diff --git a/DISCLAIMER b/DISCLAIMER-WIP similarity index 100% rename from DISCLAIMER rename to DISCLAIMER-WIP diff --git a/NOTICE b/NOTICE index 43c4b92efb0..646a3d4ae06 100644 --- a/NOTICE +++ b/NOTICE @@ -21,3 +21,7 @@ This product also includes the following third-party components: * search-ui Downloaded from: https://gitlab.com/antora/antora-lunr-extension License: Mozilla Public License 2.0 + +* JavaParser, JavaLexer + Downloaded from: https://github.com/antlr/grammars-v4/tree/master/java/java + License: BSD License \ No newline at end of file diff --git a/drools-compiler/src/main/java/org/drools/compiler/builder/impl/KnowledgeBuilderRulesConfigurationImpl.java b/drools-compiler/src/main/java/org/drools/compiler/builder/impl/KnowledgeBuilderRulesConfigurationImpl.java index 0c90262aa28..48e3e4971f1 100644 --- a/drools-compiler/src/main/java/org/drools/compiler/builder/impl/KnowledgeBuilderRulesConfigurationImpl.java +++ b/drools-compiler/src/main/java/org/drools/compiler/builder/impl/KnowledgeBuilderRulesConfigurationImpl.java @@ -127,7 +127,6 @@ public KnowledgeBuilderRulesConfigurationImpl(CompositeConfiguration + + + + 4.0.0 + + org.drools + drools-drl + 999-SNAPSHOT + + + org.drools + drools-drl-parser-tests + + Drools :: DRL :: Parser :: Tests + + + org.drools.drl.parser.tests + + + + + + org.assertj + assertj-core + test + + + org.junit.jupiter + junit-jupiter-api + test + + + org.junit.jupiter + junit-jupiter-engine + test + + + org.junit.jupiter + junit-jupiter-params + test + + + ch.qos.logback + logback-classic + test + + + + org.drools + drools-drl-parser + test + + + org.drools + drools-compiler + test + + + org.drools + drools-mvel + test + + + + + + default + + true + + + + + org.apache.maven.plugins + maven-surefire-plugin + + + + default-test + + + true + + + + + old-parser-test + + + false + + + + test + + + + + + + + + diff --git a/drools-drl/drools-drl-parser-tests/src/test/java/org/drools/drl/parser/antlr4/DRLExprParserTest.java b/drools-drl/drools-drl-parser-tests/src/test/java/org/drools/drl/parser/antlr4/DRLExprParserTest.java new file mode 100644 index 00000000000..0baeac61ff1 --- /dev/null +++ b/drools-drl/drools-drl-parser-tests/src/test/java/org/drools/drl/parser/antlr4/DRLExprParserTest.java @@ -0,0 +1,581 @@ +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you 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 + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.drools.drl.parser.antlr4; + +import java.util.Arrays; +import java.util.List; + +import org.drools.drl.ast.descr.AtomicExprDescr; +import org.drools.drl.ast.descr.BindingDescr; +import org.drools.drl.ast.descr.ConnectiveType; +import org.drools.drl.ast.descr.ConstraintConnectiveDescr; +import org.drools.drl.ast.descr.RelationalExprDescr; +import org.drools.drl.parser.DrlExprParser; +import org.drools.drl.parser.DrlExprParserFactory; +import org.drools.drl.parser.DrlParser; +import org.drools.drl.parser.DroolsParserException; +import org.drools.drl.parser.impl.Operator; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.Timeout; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.EnumSource; +import org.junit.jupiter.params.provider.ValueSource; +import org.kie.internal.builder.conf.LanguageLevelOption; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.junit.jupiter.api.Assumptions.assumeFalse; + +/** + * DRLExprTreeTest + */ +class DRLExprParserTest { + + DrlExprParser parser; + + @BeforeEach + void setUp() { + this.parser = DrlExprParserFactory.getDrlExprParser(LanguageLevelOption.DRL6); + } + + @AfterEach + void tearDown() { + this.parser = null; + } + + @Test + void simpleExpression() { + String source = "a > b"; + ConstraintConnectiveDescr result = parser.parse( source ); + assertThat(parser.hasErrors()).as(parser.getErrors().toString()).isFalse(); + + assertThat(result.getConnective()).isEqualTo(ConnectiveType.AND); + assertThat(result.getDescrs()).hasSize(1); + + RelationalExprDescr expr = (RelationalExprDescr) result.getDescrs().get( 0 ); + assertThat(expr.getOperator()).isEqualTo(">"); + + AtomicExprDescr left = (AtomicExprDescr) expr.getLeft(); + AtomicExprDescr right = (AtomicExprDescr) expr.getRight(); + + assertThat(left.getExpression()).isEqualTo("a"); + assertThat(right.getExpression()).isEqualTo("b"); + } + + @Test + void andConnective() { + String source = "a > b && 10 != 20"; + ConstraintConnectiveDescr result = parser.parse( source ); + assertThat(parser.hasErrors()).as(parser.getErrors().toString()).isFalse(); + + assertThat(result.getConnective()).isEqualTo(ConnectiveType.AND); + assertThat(result.getDescrs()).hasSize(2); + + RelationalExprDescr expr = (RelationalExprDescr) result.getDescrs().get( 0 ); + assertThat(expr.getOperator()).isEqualTo(">"); + AtomicExprDescr left = (AtomicExprDescr) expr.getLeft(); + AtomicExprDescr right = (AtomicExprDescr) expr.getRight(); + assertThat(left.getExpression()).isEqualTo("a"); + assertThat(right.getExpression()).isEqualTo("b"); + + expr = (RelationalExprDescr) result.getDescrs().get( 1 ); + assertThat(expr.getOperator()).isEqualTo("!="); + left = (AtomicExprDescr) expr.getLeft(); + right = (AtomicExprDescr) expr.getRight(); + assertThat(left.getExpression()).isEqualTo("10"); + assertThat(right.getExpression()).isEqualTo("20"); + } + + @Test + void connective2() { + String source = "(a > b || 10 != 20) && someMethod(10) == 20"; + ConstraintConnectiveDescr result = parser.parse( source ); + assertThat(parser.hasErrors()).as(parser.getErrors().toString()).isFalse(); + + assertThat(result.getConnective()).isEqualTo(ConnectiveType.AND); + assertThat(result.getDescrs()).hasSize(2); + + ConstraintConnectiveDescr or = (ConstraintConnectiveDescr) result.getDescrs().get( 0 ); + assertThat(or.getConnective()).isEqualTo(ConnectiveType.OR); + assertThat(or.getDescrs()).hasSize(2); + + RelationalExprDescr expr = (RelationalExprDescr) or.getDescrs().get( 0 ); + assertThat(expr.getOperator()).isEqualTo(">"); + AtomicExprDescr left = (AtomicExprDescr) expr.getLeft(); + AtomicExprDescr right = (AtomicExprDescr) expr.getRight(); + assertThat(left.getExpression()).isEqualTo("a"); + assertThat(right.getExpression()).isEqualTo("b"); + + expr = (RelationalExprDescr) or.getDescrs().get( 1 ); + assertThat(expr.getOperator()).isEqualTo("!="); + left = (AtomicExprDescr) expr.getLeft(); + right = (AtomicExprDescr) expr.getRight(); + assertThat(left.getExpression()).isEqualTo("10"); + assertThat(right.getExpression()).isEqualTo("20"); + + expr = (RelationalExprDescr) result.getDescrs().get( 1 ); + assertThat(expr.getOperator()).isEqualTo("=="); + left = (AtomicExprDescr) expr.getLeft(); + right = (AtomicExprDescr) expr.getRight(); + assertThat(left.getExpression()).isEqualTo("someMethod(10)"); + assertThat(right.getExpression()).isEqualTo("20"); + + } + + @Test + void binding() { + String source = "$x : property"; + ConstraintConnectiveDescr result = parser.parse( source ); + assertThat(parser.hasErrors()).as(parser.getErrors().toString()).isFalse(); + + assertThat(result.getConnective()).isEqualTo(ConnectiveType.AND); + assertThat(result.getDescrs()).hasSize(1); + + BindingDescr bind = (BindingDescr) result.getDescrs().get( 0 ); + assertThat(bind.getVariable()).isEqualTo("$x"); + assertThat(bind.getExpression()).isEqualTo("property"); + } + + @Test + void bindingConstraint() { + String source = "$x : property > value"; + ConstraintConnectiveDescr result = parser.parse( source ); + assertThat(parser.hasErrors()).as(parser.getErrors().toString()).isFalse(); + + assertThat(result.getConnective()).isEqualTo(ConnectiveType.AND); + assertThat(result.getDescrs()).hasSize(1); + + RelationalExprDescr rel = (RelationalExprDescr) result.getDescrs().get( 0 ); + assertThat(rel.getOperator()).isEqualTo(">"); + + BindingDescr bind = (BindingDescr) rel.getLeft(); + assertThat(bind.getVariable()).isEqualTo("$x"); + assertThat(bind.getExpression()).isEqualTo("property"); + + AtomicExprDescr right = (AtomicExprDescr) rel.getRight(); + assertThat(right.getExpression()).isEqualTo("value"); + } + + @Test + void bindingWithRestrictions() { + String source = "$x : property > value && < 20"; + ConstraintConnectiveDescr result = parser.parse( source ); + assertThat(parser.hasErrors()).as(parser.getErrors().toString()).isFalse(); + + assertThat(result.getConnective()).isEqualTo(ConnectiveType.AND); + assertThat(result.getDescrs()).hasSize(2); + + RelationalExprDescr rel = (RelationalExprDescr) result.getDescrs().get( 0 ); + assertThat(rel.getOperator()).isEqualTo(">"); + + BindingDescr bind = (BindingDescr) rel.getLeft(); + assertThat(bind.getVariable()).isEqualTo("$x"); + assertThat(bind.getExpression()).isEqualTo("property"); + + AtomicExprDescr right = (AtomicExprDescr) rel.getRight(); + assertThat(right.getExpression()).isEqualTo("value"); + + rel = (RelationalExprDescr) result.getDescrs().get( 1 ); + assertThat(rel.getOperator()).isEqualTo("<"); + + AtomicExprDescr left = (AtomicExprDescr) rel.getLeft(); + assertThat(left.getExpression()).isEqualTo("property"); + + right = (AtomicExprDescr) rel.getRight(); + assertThat(right.getExpression()).isEqualTo("20"); + } + + @Test + void doubleBinding() { + String source = "$x : x.m( 1, a ) && $y : y[z].foo"; + ConstraintConnectiveDescr result = parser.parse( source ); + assertThat(parser.hasErrors()).as(parser.getErrors().toString()).isFalse(); + + assertThat(result.getConnective()).isEqualTo(ConnectiveType.AND); + assertThat(result.getDescrs()).hasSize(2); + + BindingDescr bind = (BindingDescr) result.getDescrs().get( 0 ); + assertThat(bind.getVariable()).isEqualTo("$x"); + assertThat(bind.getExpression()).isEqualTo("x.m( 1, a )"); + + bind = (BindingDescr) result.getDescrs().get( 1 ); + assertThat(bind.getVariable()).isEqualTo("$y"); + assertThat(bind.getExpression()).isEqualTo("y[z].foo"); + } + + private static final List nonKeywordBuiltInOperators = Arrays.asList( + Operator.BuiltInOperator.EQUAL, + Operator.BuiltInOperator.NOT_EQUAL, + Operator.BuiltInOperator.LESS, + Operator.BuiltInOperator.LESS_OR_EQUAL, + Operator.BuiltInOperator.GREATER, + Operator.BuiltInOperator.GREATER_OR_EQUAL + ); + + @ParameterizedTest + @EnumSource(Operator.BuiltInOperator.class) + void drlKeywordMethodCall(Operator.BuiltInOperator operator) { + // Skip operators that cannot be used as method names (==, !=, <, etc.). + assumeFalse(nonKeywordBuiltInOperators.contains(operator)); + + String source = String.format("x.%s( 1, a )", operator.getSymbol()); + ConstraintConnectiveDescr result = parser.parse( source ); + assertThat(parser.hasErrors()).as(parser.getErrors().toString()).isFalse(); + + assertThat(result.getConnective()).isEqualTo(ConnectiveType.AND); + assertThat(result.getDescrs()).hasSize(1); + + AtomicExprDescr descr = (AtomicExprDescr) result.getDescrs().get( 0 ); + assertThat(descr.getExpression()).isEqualTo(source); + } + + @ParameterizedTest + @EnumSource(Operator.BuiltInOperator.class) + void drlKeywordInChainedMethodCallWithBinding(Operator.BuiltInOperator operator) { + // Skip operators that cannot be used as method names (==, !=, <, etc.). + assumeFalse(nonKeywordBuiltInOperators.contains(operator)); + + String expressionSource = String.format("x.%s( 1, a ).%s(\"\")", operator.getSymbol(), operator.getSymbol()); + String bindingVariableSource = "$x"; + String source = bindingVariableSource + " : " + expressionSource; + ConstraintConnectiveDescr result = parser.parse( source ); + assertThat(parser.hasErrors()).as(parser.getErrors().toString()).isFalse(); + + assertThat(result.getConnective()).isEqualTo(ConnectiveType.AND); + assertThat(result.getDescrs()).hasSize(1); + + BindingDescr bind = (BindingDescr) result.getDescrs().get( 0 ); + assertThat(bind.getVariable()).isEqualTo(bindingVariableSource); + assertThat(bind.getExpression()).isEqualTo(expressionSource); + } + + @Test + void deepBinding() { + String source = "($a : a > $b : b[10].prop || 10 != 20) && $x : someMethod(10) == 20"; + ConstraintConnectiveDescr result = parser.parse( source ); + assertThat(parser.hasErrors()).as(parser.getErrors().toString()).isFalse(); + + assertThat(result.getConnective()).isEqualTo(ConnectiveType.AND); + assertThat(result.getDescrs()).hasSize(2); + + ConstraintConnectiveDescr or = (ConstraintConnectiveDescr) result.getDescrs().get( 0 ); + assertThat(or.getConnective()).isEqualTo(ConnectiveType.OR); + assertThat(or.getDescrs()).hasSize(2); + + RelationalExprDescr expr = (RelationalExprDescr) or.getDescrs().get( 0 ); + assertThat(expr.getOperator()).isEqualTo(">"); + BindingDescr leftBind = (BindingDescr) expr.getLeft(); + BindingDescr rightBind = (BindingDescr) expr.getRight(); + assertThat(leftBind.getVariable()).isEqualTo("$a"); + assertThat(leftBind.getExpression()).isEqualTo("a"); + assertThat(rightBind.getVariable()).isEqualTo("$b"); + assertThat(rightBind.getExpression()).isEqualTo("b[10].prop"); + + expr = (RelationalExprDescr) or.getDescrs().get( 1 ); + assertThat(expr.getOperator()).isEqualTo("!="); + AtomicExprDescr leftExpr = (AtomicExprDescr) expr.getLeft(); + AtomicExprDescr rightExpr = (AtomicExprDescr) expr.getRight(); + assertThat(leftExpr.getExpression()).isEqualTo("10"); + assertThat(rightExpr.getExpression()).isEqualTo("20"); + + expr = (RelationalExprDescr) result.getDescrs().get( 1 ); + assertThat(expr.getOperator()).isEqualTo("=="); + leftBind = (BindingDescr) expr.getLeft(); + rightExpr = (AtomicExprDescr) expr.getRight(); + assertThat(leftBind.getVariable()).isEqualTo("$x"); + assertThat(leftBind.getExpression()).isEqualTo("someMethod(10)"); + assertThat(rightExpr.getExpression()).isEqualTo("20"); + + } + + @Test + @Timeout(10000L) + void nestedExpression() { + // DROOLS-982 + String source = "(((((((((((((((((((((((((((((((((((((((((((((((((( a > b ))))))))))))))))))))))))))))))))))))))))))))))))))"; + ConstraintConnectiveDescr result = parser.parse( source ); + assertThat(parser.hasErrors()).as(parser.getErrors().toString()).isFalse(); + + assertThat(result.getConnective()).isEqualTo(ConnectiveType.AND); + assertThat(result.getDescrs()).hasSize(1); + + RelationalExprDescr expr = (RelationalExprDescr) result.getDescrs().get( 0 ); + assertThat(expr.getOperator()).isEqualTo(">"); + + AtomicExprDescr left = (AtomicExprDescr) expr.getLeft(); + AtomicExprDescr right = (AtomicExprDescr) expr.getRight(); + + assertThat(left.getExpression()).isEqualTo("a"); + assertThat(right.getExpression()).isEqualTo("b"); + } + + /** + * Each test input is a simple expression covering one of the existing keywords. The test is successful if the parser has + * no errors and the descriptor's expression string is equal to the input. + * + * @param source expression using a keyword + */ + @ParameterizedTest + @ValueSource(strings = { + "(X) x", + "SomeClass.super.getData()", + "(boolean) b", + "(char) c", + "(byte) b", + "(short) s", + "(int) i", + "(long) l", + "(float) f", + "(double) d", + "this", + "this()", + "Object[][].class.getName()", + "newArrayList()" + }) + void keywords(String source) { + ConstraintConnectiveDescr result = parser.parse( source ); + assertThat(parser.hasErrors()).as(parser.getErrors().toString()).isFalse(); + + assertThat(result.getConnective()).isEqualTo(ConnectiveType.AND); + assertThat(result.getDescrs()).hasSize(1); + + AtomicExprDescr expr = (AtomicExprDescr) result.getDescrs().get( 0 ); + + assertThat(expr.getExpression()).isEqualTo(source); + } + + @Test + void keywordInstanceof() { + String source = "a instanceof A"; + ConstraintConnectiveDescr result = parser.parse( source ); + assertThat(parser.hasErrors()).as(parser.getErrors().toString()).isFalse(); + + assertThat(result.getConnective()).isEqualTo(ConnectiveType.AND); + assertThat(result.getDescrs()).hasSize(1); + + // Unlike the other keywords, instanceof can only be used in a relational expression, + // so it needs to be tested differently. + RelationalExprDescr expr = (RelationalExprDescr) result.getDescrs().get( 0 ); + assertThat(expr.getOperator()).isEqualTo("instanceof"); + + AtomicExprDescr left = (AtomicExprDescr) expr.getLeft(); + AtomicExprDescr right = (AtomicExprDescr) expr.getRight(); + + assertThat(left.getExpression()).isEqualTo("a"); + assertThat(right.getExpression()).isEqualTo("A"); + } + + @Test + void mismatchedInput() { + String source = "+"; + parser.parse(source); + assertThat(parser.hasErrors()).isTrue(); + assertThat(parser.getErrors()).hasSize(1); + DroolsParserException exception = parser.getErrors().get(0); + + // Backward Compatibility Notes: + // Antlr4 gives a different error code/message from antlr3 for this case. + // Backward compatibility doesn't seem to be required in this case. + if (DrlParser.ANTLR4_PARSER_ENABLED) { + assertThat(exception.getErrorCode()).isEqualTo("ERR 102"); + assertThat(exception.getLineNumber()).isEqualTo(1); + assertThat(exception.getColumn()).isEqualTo(1); + assertThat(exception.getOffset()).isEqualTo(1); + assertThat(exception.getMessage()) + .startsWithIgnoringCase("[ERR 102] Line 1:1 mismatched input '' expecting ") + .contains("TIME_INTERVAL", "DRL_STRING_LITERAL", "?/", "boolean", "byte", "char", "double", "float", "int", "long", "new", "short", "super", "DECIMAL_LITERAL", "HEX_LITERAL", "FLOAT_LITERAL", "BOOL_LITERAL", "STRING_LITERAL", "null", "(", "[", ".", "<", "!", "~", "++", "--", "+", "-", "*", "/", "IDENTIFIER"); + } else { + assertThat(exception.getErrorCode()).isEqualTo("ERR 101"); + assertThat(exception.getLineNumber()).isEqualTo(1); + assertThat(exception.getColumn()).isEqualTo(1); + assertThat(exception.getOffset()).isEqualTo(1); + assertThat(exception.getMessage()) + .isEqualToIgnoringCase("[ERR 101] Line 1:1 no viable alternative at input ''"); + } + } + + @Test + void extraneousInput() { + String source = "a +; b"; + parser.parse(source); + assertThat(parser.hasErrors()).isTrue(); + assertThat(parser.getErrors()).hasSize(1); + DroolsParserException exception = parser.getErrors().get(0); + + // Backward Compatibility Notes: + // Antlr4 gives a different error code/message from antlr3 for this case. + // Backward compatibility doesn't seem to be required in this case. + if (DrlParser.ANTLR4_PARSER_ENABLED) { + assertThat(exception.getErrorCode()).isEqualTo("ERR 109"); + assertThat(exception.getLineNumber()).isEqualTo(1); + assertThat(exception.getColumn()).isEqualTo(3); + assertThat(exception.getOffset()).isEqualTo(3); + assertThat(exception.getMessage()) + .startsWithIgnoringCase("[ERR 109] Line 1:3 extraneous input ';' expecting ") + .contains("TIME_INTERVAL", "DRL_STRING_LITERAL", "?/", "boolean", "byte", "char", "double", "float", "int", "long", "new", "short", "super", "DECIMAL_LITERAL", "HEX_LITERAL", "FLOAT_LITERAL", "BOOL_LITERAL", "STRING_LITERAL", "null", "(", "[", ".", "<", "!", "~", "++", "--", "+", "-", "*", "/", "IDENTIFIER"); + } else { + assertThat(exception.getErrorCode()).isEqualTo("ERR 101"); + assertThat(exception.getLineNumber()).isEqualTo(1); + assertThat(exception.getColumn()).isEqualTo(3); + assertThat(exception.getOffset()).isEqualTo(3); + assertThat(exception.getMessage()) + .isEqualToIgnoringCase("[ERR 101] Line 1:3 no viable alternative at input ';'"); + } + } + + @Test + void noViableAlt() { + String source = "a~a"; + parser.parse(source); + + // Backward Compatibility Notes: + // Old expr parser (DRL6Expressions) allows this expression and only takes "a" ignoring the invalid part "~a" without emitting an error. + // This is rather a bug in the old parser, and the new parser (ANTLR4) correctly emits an error for this case. + // Backward compatibility doesn't seem to be required in this case. + if (DrlParser.ANTLR4_PARSER_ENABLED) { + assertThat(parser.hasErrors()).isTrue(); + assertThat(parser.getErrors()).hasSize(1); + DroolsParserException exception = parser.getErrors().get(0); + assertThat(exception.getErrorCode()).isEqualTo("ERR 101"); + assertThat(exception.getLineNumber()).isEqualTo(1); + assertThat(exception.getColumn()).isEqualTo(2); + assertThat(exception.getOffset()).isEqualTo(2); + assertThat(exception.getMessage()) + .isEqualToIgnoringCase("[ERR 101] Line 1:2 no viable alternative at input 'a'"); + } else { + assertThat(parser.hasErrors()).isFalse(); + } + } + + @Test + void orWithMethodCall() { + String source = "value == 10 || someMethod() == 4"; + ConstraintConnectiveDescr result = parser.parse(source); + assertThat(parser.hasErrors()).as(parser.getErrors().toString()).isFalse(); + + assertThat(result.getConnective()).isEqualTo(ConnectiveType.AND); // root is AND + assertThat(result.getDescrs()).hasSize(1); + ConstraintConnectiveDescr or = (ConstraintConnectiveDescr) result.getDescrs().get(0); + assertThat(or.getConnective()).isEqualTo(ConnectiveType.OR); + assertThat(or.getDescrs()).hasSize(2); + + RelationalExprDescr expr = (RelationalExprDescr) or.getDescrs().get(0); + assertThat(expr.getOperator()).isEqualTo("=="); + AtomicExprDescr left = (AtomicExprDescr) expr.getLeft(); + AtomicExprDescr right = (AtomicExprDescr) expr.getRight(); + assertThat(left.getExpression()).isEqualTo("value"); + assertThat(right.getExpression()).isEqualTo("10"); + + expr = (RelationalExprDescr) or.getDescrs().get(1); + assertThat(expr.getOperator()).isEqualTo("=="); + left = (AtomicExprDescr) expr.getLeft(); + right = (AtomicExprDescr) expr.getRight(); + assertThat(left.getExpression()).isEqualTo("someMethod()"); + assertThat(right.getExpression()).isEqualTo("4"); + } + + @Test + void orWithMethodCallWithArg() { + String source = "value == 10 || someMethod(value) == 4"; + ConstraintConnectiveDescr result = parser.parse(source); + assertThat(parser.hasErrors()).as(parser.getErrors().toString()).isFalse(); + + assertThat(result.getConnective()).isEqualTo(ConnectiveType.AND); // root is AND + assertThat(result.getDescrs()).hasSize(1); + ConstraintConnectiveDescr or = (ConstraintConnectiveDescr) result.getDescrs().get(0); + assertThat(or.getConnective()).isEqualTo(ConnectiveType.OR); + assertThat(or.getDescrs()).hasSize(2); + + RelationalExprDescr expr = (RelationalExprDescr) or.getDescrs().get(0); + assertThat(expr.getOperator()).isEqualTo("=="); + AtomicExprDescr left = (AtomicExprDescr) expr.getLeft(); + AtomicExprDescr right = (AtomicExprDescr) expr.getRight(); + assertThat(left.getExpression()).isEqualTo("value"); + assertThat(right.getExpression()).isEqualTo("10"); + + expr = (RelationalExprDescr) or.getDescrs().get(1); + assertThat(expr.getOperator()).isEqualTo("=="); + left = (AtomicExprDescr) expr.getLeft(); + right = (AtomicExprDescr) expr.getRight(); + assertThat(left.getExpression()).isEqualTo("someMethod(value)"); + assertThat(right.getExpression()).isEqualTo("4"); + } + + @Test + void andWithMethodCall() { + String source = "value == 10 && someMethod() == 4"; + ConstraintConnectiveDescr result = parser.parse(source); + assertThat(parser.hasErrors()).as(parser.getErrors().toString()).isFalse(); + + assertThat(result.getConnective()).isEqualTo(ConnectiveType.AND); + assertThat(result.getDescrs()).hasSize(2); + + RelationalExprDescr expr = (RelationalExprDescr) result.getDescrs().get(0); + assertThat(expr.getOperator()).isEqualTo("=="); + AtomicExprDescr left = (AtomicExprDescr) expr.getLeft(); + AtomicExprDescr right = (AtomicExprDescr) expr.getRight(); + assertThat(left.getExpression()).isEqualTo("value"); + assertThat(right.getExpression()).isEqualTo("10"); + + expr = (RelationalExprDescr) result.getDescrs().get(1); + assertThat(expr.getOperator()).isEqualTo("=="); + left = (AtomicExprDescr) expr.getLeft(); + right = (AtomicExprDescr) expr.getRight(); + assertThat(left.getExpression()).isEqualTo("someMethod()"); + assertThat(right.getExpression()).isEqualTo("4"); + } + + @Test + void andWithMethodCallWithArg() { + String source = "value == 10 && someMethod(value) == 4"; + ConstraintConnectiveDescr result = parser.parse(source); + assertThat(parser.hasErrors()).as(parser.getErrors().toString()).isFalse(); + + assertThat(result.getConnective()).isEqualTo(ConnectiveType.AND); + assertThat(result.getDescrs()).hasSize(2); + + RelationalExprDescr expr = (RelationalExprDescr) result.getDescrs().get(0); + assertThat(expr.getOperator()).isEqualTo("=="); + AtomicExprDescr left = (AtomicExprDescr) expr.getLeft(); + AtomicExprDescr right = (AtomicExprDescr) expr.getRight(); + assertThat(left.getExpression()).isEqualTo("value"); + assertThat(right.getExpression()).isEqualTo("10"); + + expr = (RelationalExprDescr) result.getDescrs().get(1); + assertThat(expr.getOperator()).isEqualTo("=="); + left = (AtomicExprDescr) expr.getLeft(); + right = (AtomicExprDescr) expr.getRight(); + assertThat(left.getExpression()).isEqualTo("someMethod(value)"); + assertThat(right.getExpression()).isEqualTo("4"); + } + + @Test + void newBigDecimal() { + String source = "$bd : new BigDecimal(30)"; + ConstraintConnectiveDescr result = parser.parse(source); + assertThat(parser.hasErrors()).as(parser.getErrors().toString()).isFalse(); + + assertThat(result.getDescrs()).hasSize(1); + + BindingDescr bind = (BindingDescr) result.getDescrs().get(0); + assertThat(bind.getVariable()).isEqualTo("$bd"); + assertThat(bind.getExpression()).isEqualTo("new BigDecimal(30)"); + } +} diff --git a/drools-drl/drools-drl-parser-tests/src/test/java/org/drools/drl/parser/antlr4/DRLParserIdentifierTest.java b/drools-drl/drools-drl-parser-tests/src/test/java/org/drools/drl/parser/antlr4/DRLParserIdentifierTest.java new file mode 100644 index 00000000000..cd982fc001e --- /dev/null +++ b/drools-drl/drools-drl-parser-tests/src/test/java/org/drools/drl/parser/antlr4/DRLParserIdentifierTest.java @@ -0,0 +1,325 @@ +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you 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 + *

+ * http://www.apache.org/licenses/LICENSE-2.0 + *

+ * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.drools.drl.parser.antlr4; + +import org.drools.drl.ast.descr.AccumulateDescr; +import org.drools.drl.ast.descr.AccumulateImportDescr; +import org.drools.drl.ast.descr.AnnotationDescr; +import org.drools.drl.ast.descr.BehaviorDescr; +import org.drools.drl.ast.descr.ExprConstraintDescr; +import org.drools.drl.ast.descr.FunctionDescr; +import org.drools.drl.ast.descr.GlobalDescr; +import org.drools.drl.ast.descr.PackageDescr; +import org.drools.drl.ast.descr.PatternDescr; +import org.drools.drl.ast.descr.RuleDescr; +import org.drools.drl.ast.descr.WindowDeclarationDescr; +import org.drools.drl.ast.descr.WindowReferenceDescr; +import org.drools.drl.parser.DrlParser; +import org.drools.drl.parser.DroolsParserException; +import org.drools.drl.parser.impl.Operator; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.Test; + +import static org.assertj.core.api.Assertions.assertThat; + +/* + * This test class is to test parse rules to accept drlIdentifier insteadof IDENTIFIER. (e.g. drl keyword like "contains") + */ +class DRLParserIdentifierTest { + + private DrlParser parser; + + @BeforeEach + void setUp() { + parser = ParserTestUtils.getParser(); + } + + private PackageDescr parseAndGetPackageDescr(String drl) { + try { + PackageDescr pkg = parser.parse(null, drl); + assertThat(parser.hasErrors()).as(parser.getErrors().toString()).isFalse(); + return pkg; + } catch (DroolsParserException e) { + throw new RuntimeException(e); + } + } + + private RuleDescr parseAndGetFirstRuleDescr(String drl) { + PackageDescr pkg = parseAndGetPackageDescr(drl); + assertThat(pkg.getRules()).isNotEmpty(); + return pkg.getRules().get(0); + } + + @Test + void importAccumulate() { + final String source = "import accumulate org.example.MyFunction contains;"; + final PackageDescr pkg = parseAndGetPackageDescr(source); + AccumulateImportDescr accumulateImportDescr = pkg.getAccumulateImports().get(0); + assertThat(accumulateImportDescr.getTarget()).isEqualTo("org.example.MyFunction"); + assertThat(accumulateImportDescr.getFunctionName()).isEqualTo("contains"); + } + + @Test + void windowDeclaration() { + final String text = + "declare window contains\n" + + " $s : StockTick( source == \"NYSE\" )\n" + + " over window:length( 10 )\n" + + "end"; + PackageDescr pkg = parseAndGetPackageDescr(text); + WindowDeclarationDescr windowDeclarationDescr = pkg.getWindowDeclarations().iterator().next(); + assertThat(windowDeclarationDescr.getName()).isEqualTo("contains"); + } + + @Test + void nestedConstraint() { + final String text = + "rule R\n" + + "when\n" + + " Person( contains.matches.( city == \"london\", country == \"uk\"))\n" + + "then\n" + + "end"; + RuleDescr rule = parseAndGetFirstRuleDescr(text); + assertThat(rule.getLhs().getDescrs().get(0)).isInstanceOfSatisfying(PatternDescr.class, patternDescr -> { + assertThat(patternDescr.getConstraint().getDescrs().get(0)).isInstanceOfSatisfying(ExprConstraintDescr.class, exprConstraintDescr -> { + assertThat(exprConstraintDescr.getExpression()).isEqualTo("contains.matches.city == \"london\""); + }); + assertThat(patternDescr.getConstraint().getDescrs().get(1)).isInstanceOfSatisfying(ExprConstraintDescr.class, exprConstraintDescr -> { + assertThat(exprConstraintDescr.getExpression()).isEqualTo("contains.matches.country == \"uk\""); + }); + }); + } + + @Test + void function() { + final String text = "function boolean contains(String s) { return true; }"; + PackageDescr packageDescr = parseAndGetPackageDescr(text); + FunctionDescr function = packageDescr.getFunctions().get(0); + assertThat(function.getName()).isEqualTo("contains"); + } + + @Test + void patternFilter() { + final String text = "rule X when StockTick( symbol==\"ACME\") over window:contains(10) then end"; + RuleDescr rule = parseAndGetFirstRuleDescr(text); + PatternDescr pattern = (PatternDescr) rule.getLhs().getDescrs().get(0); + BehaviorDescr behavior = pattern.getBehaviors().get(0); + assertThat(behavior.getType()).isEqualTo("window"); + assertThat(behavior.getSubType()).isEqualTo("contains"); + assertThat(behavior.getParameters().get(0)).isEqualTo("10"); + } + + @Test + void accumulateFunction() { + final String text = "rule R1\n" + + "when\n" + + " accumulate( Person( $age : age > 21 ), $ave : contains( $age ) );\n" + + "then\n" + + "end"; + RuleDescr rule = parseAndGetFirstRuleDescr(text); + final PatternDescr out = (PatternDescr) rule.getLhs().getDescrs().get(0); + final AccumulateDescr accumulate = (AccumulateDescr) out.getSource(); + assertThat(accumulate.getFunctions().get(0).getFunction()).isEqualToIgnoringWhitespace("contains"); + } + + @Test + void fromWindow() { + final String text = + "rule X\n" + + "when\n" + + " StockTick() from window contains\n" + + "then\n" + + "end\n"; + RuleDescr rule = parseAndGetFirstRuleDescr(text); + PatternDescr pattern = (PatternDescr) rule.getLhs().getDescrs().get(0); + assertThat(pattern.getSource()).isInstanceOfSatisfying(WindowReferenceDescr.class, windowReferenceDescr -> { + assertThat(windowReferenceDescr.getName()).isEqualTo("contains"); + }); + } + + @Test + void type() { + final String text = "global contains.matches bbb"; + PackageDescr pkg = parseAndGetPackageDescr(text); + GlobalDescr global = pkg.getGlobals().get(0); + assertThat(global.getType()).isEqualTo("contains.matches"); + assertThat(global.getIdentifier()).isEqualTo("bbb"); + } + + @Test + void unification() { + final String text = "rule X\n" + + "when\n" + + " contains := Person()\n" + + "then\n" + + "end"; + PatternDescr pattern = (PatternDescr) parseAndGetFirstRuleDescr(text).getLhs().getDescrs().get(0); + assertThat(pattern.getIdentifier()).isEqualTo("contains"); + assertThat(pattern.isUnification()).isTrue(); + } + + @Test + void annotation() { + final String text = "rule R\n" + + "@contains.matches(soundslike=\"abc\")\n" + + "when\n" + + "then\n" + + "end"; + RuleDescr rule = parseAndGetFirstRuleDescr(text); + AnnotationDescr annotation = rule.getAnnotation("contains.matches"); + assertThat(annotation.getValue("soundslike")).isEqualTo("\"abc\""); + } + + @Test + void constraintBoundVariable() { + final String text = "rule X\n" + + "when\n" + + " Person( contains : age > 20)\n" + + "then\n" + + "end"; + PatternDescr pattern = (PatternDescr) parseAndGetFirstRuleDescr(text).getLhs().getDescrs().get(0); + ExprConstraintDescr exprConstraintDescr = (ExprConstraintDescr) pattern.getConstraint().getDescrs().get(0); + assertThat(exprConstraintDescr.getExpression()).isEqualTo("contains : age > 20"); + } + + @Test + void constraintBoundVariableUnify() { + final String text = "rule X\n" + + "when\n" + + " Person( contains := age > 20)\n" + + "then\n" + + "end"; + PatternDescr pattern = (PatternDescr) parseAndGetFirstRuleDescr(text).getLhs().getDescrs().get(0); + ExprConstraintDescr exprConstraintDescr = (ExprConstraintDescr) pattern.getConstraint().getDescrs().get(0); + assertThat(exprConstraintDescr.getExpression()).isEqualTo("contains := age > 20"); + } + + @Test + void xpathChunk() { + final String text = + "rule R when\n" + + " $man: Man( /contains.matches#soundslike[memberOf > 10] )\n" + + "then\n" + + "end\n"; + PatternDescr pattern = (PatternDescr) parseAndGetFirstRuleDescr(text).getLhs().getDescrs().get(0); + ExprConstraintDescr exprConstraintDescr = (ExprConstraintDescr) pattern.getConstraint().getDescrs().get(0); + assertThat(exprConstraintDescr.getExpression()).isEqualTo("/contains.matches#soundslike[memberOf > 10]"); + } + + @Test + void createdName() { + final String text = + "rule X\n" + + "when\n" + + " Person( age > new contains.matches(10))\n" + + "then\n" + + "end"; + PatternDescr pattern = (PatternDescr) parseAndGetFirstRuleDescr(text).getLhs().getDescrs().get(0); + ExprConstraintDescr exprConstraintDescr = (ExprConstraintDescr) pattern.getConstraint().getDescrs().get(0); + assertThat(exprConstraintDescr.getExpression()).isEqualTo("age > new contains.matches(10)"); + } + + @Test + void explicitGenericInvocationSuffix() { + final String text = + "rule X\n" + + "when\n" + + " Person( name == contains())\n" + + "then\n" + + "end"; + PatternDescr pattern = (PatternDescr) parseAndGetFirstRuleDescr(text).getLhs().getDescrs().get(0); + ExprConstraintDescr exprConstraintDescr = (ExprConstraintDescr) pattern.getConstraint().getDescrs().get(0); + assertThat(exprConstraintDescr.getExpression()).isEqualTo("name == contains()"); + } + + @Disabled("Old parser does not support this syntax") + @Test + void innerCreator() { + final String text = + "rule X\n" + + "when\n" + + " Person( outer.new contains() != null )\n" + + "then\n" + + "end"; + PatternDescr pattern = (PatternDescr) parseAndGetFirstRuleDescr(text).getLhs().getDescrs().get(0); + ExprConstraintDescr exprConstraintDescr = (ExprConstraintDescr) pattern.getConstraint().getDescrs().get(0); + assertThat(exprConstraintDescr.getExpression()).isEqualTo("outer.new contains() != null"); + } + + @Test + void superSuffix() { + final String text = + "rule X\n" + + "when\n" + + " Person( address.super.contains() == 10 )\n" + + "then\n" + + "end"; + PatternDescr pattern = (PatternDescr) parseAndGetFirstRuleDescr(text).getLhs().getDescrs().get(0); + ExprConstraintDescr exprConstraintDescr = (ExprConstraintDescr) pattern.getConstraint().getDescrs().get(0); + assertThat(exprConstraintDescr.getExpression()).isEqualTo("address.super.contains() == 10"); + } + + @Disabled("To be done by https://github.com/apache/incubator-kie-drools/issues/5874") + @Test + void operator_key() { + final String text = + "rule X\n" + + "when\n" + + " Person( age provides 10 )\n" + + "then\n" + + "end"; + // PROVIDES is not IDENTIFIER, but included in drlIdentifier + Operator.addOperatorToRegistry("provides", false); + PatternDescr pattern = (PatternDescr) parseAndGetFirstRuleDescr(text).getLhs().getDescrs().get(0); + ExprConstraintDescr exprConstraintDescr = (ExprConstraintDescr) pattern.getConstraint().getDescrs().get(0); + assertThat(exprConstraintDescr.getExpression()).isEqualTo("age provides 10"); + } + + @Disabled("To be done by https://github.com/apache/incubator-kie-drools/issues/5874") + @Test + void neg_operator_key() { + final String text = + "rule X\n" + + "when\n" + + " Person( age not provides 10 )\n" + + "then\n" + + "end"; + // PROVIDES is not IDENTIFIER, but included in drlIdentifier + Operator.addOperatorToRegistry("provides", true); + PatternDescr pattern = (PatternDescr) parseAndGetFirstRuleDescr(text).getLhs().getDescrs().get(0); + ExprConstraintDescr exprConstraintDescr = (ExprConstraintDescr) pattern.getConstraint().getDescrs().get(0); + assertThat(exprConstraintDescr.getExpression()).isEqualTo("age not provides 10"); + } + + @Test + void operator_key_temporal() { + // This test (and MiscDRLParserTest.parse_PluggableOperators) fails when adapting drlIdentifier to operator_key and neg_operator_key in DRL6Expressions.g4 + // See https://github.com/apache/incubator-kie-drools/issues/5874 + final String text = + "rule X\n" + + "when\n" + + " Person( this after[1,10] $a || this not after[15,20] $a )\n" + + "then\n" + + "end"; + PatternDescr pattern = (PatternDescr) parseAndGetFirstRuleDescr(text).getLhs().getDescrs().get(0); + ExprConstraintDescr exprConstraintDescr = (ExprConstraintDescr) pattern.getConstraint().getDescrs().get(0); + assertThat(exprConstraintDescr.getExpression()).isEqualTo("this after[1,10] $a || this not after[15,20] $a"); + } +} diff --git a/drools-drl/drools-drl-parser-tests/src/test/java/org/drools/drl/parser/antlr4/DRLParserTest.java b/drools-drl/drools-drl-parser-tests/src/test/java/org/drools/drl/parser/antlr4/DRLParserTest.java new file mode 100644 index 00000000000..b760f5f75b4 --- /dev/null +++ b/drools-drl/drools-drl-parser-tests/src/test/java/org/drools/drl/parser/antlr4/DRLParserTest.java @@ -0,0 +1,116 @@ +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you 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 + *

+ * http://www.apache.org/licenses/LICENSE-2.0 + *

+ * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.drools.drl.parser.antlr4; + +import java.util.List; + +import org.drools.drl.ast.descr.AnnotationDescr; +import org.drools.drl.ast.descr.AttributeDescr; +import org.drools.drl.ast.descr.BaseDescr; +import org.drools.drl.ast.descr.ExprConstraintDescr; +import org.drools.drl.ast.descr.GlobalDescr; +import org.drools.drl.ast.descr.PackageDescr; +import org.drools.drl.ast.descr.PatternDescr; +import org.drools.drl.ast.descr.RuleDescr; +import org.junit.jupiter.api.Test; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.drools.drl.parser.antlr4.DRLParserHelper.computeTokenIndex; +import static org.drools.drl.parser.antlr4.DRLParserHelper.createDrlParser; +import static org.drools.drl.parser.antlr4.DRLParserHelper.parse; + +/** + * This test class is specific to new antlr4 parser. + */ +class DRLParserTest { + + private static final String drl = + "package org.test;\n" + + "import org.test.model.Person;\n" + + "global String result;\n" + + "rule TestRule @Test(true) no-loop salience 15 when \n" + + " $p:Person( age >= 18 )\n" + + "then\n" + + " int a = 4;\n" + + " System.out.println($p.getName());\n" + + "end\n"; + + @Test + void parse_basicRule() { + PackageDescr packageDescr = parse(drl); + assertThat(packageDescr.getName()).isEqualTo("org.test"); + + assertThat(packageDescr.getImports()).hasSize(1); + assertThat(packageDescr.getImports().get(0).getTarget()).isEqualTo("org.test.model.Person"); + + assertThat(packageDescr.getGlobals()).hasSize(1); + GlobalDescr globalDescr = packageDescr.getGlobals().get(0); + assertThat(globalDescr.getType()).isEqualTo("String"); + assertThat(globalDescr.getIdentifier()).isEqualTo("result"); + + assertThat(packageDescr.getRules()).hasSize(1); + RuleDescr ruleDescr = packageDescr.getRules().get(0); + + AnnotationDescr annotationDescr = ruleDescr.getAnnotation("Test"); + assertThat(annotationDescr).isNotNull(); + assertThat(annotationDescr.getValue()).isEqualTo("true"); + + assertThat(ruleDescr.getAttributes()).hasSize(2); + assertThat(ruleDescr.getAttributes().get("no-loop")).isNotNull(); + AttributeDescr salience = ruleDescr.getAttributes().get("salience"); + assertThat(salience).isNotNull(); + assertThat(salience.getValue()).isEqualTo("15"); + + assertThat(ruleDescr.getName()).isEqualTo("TestRule"); + + assertThat(ruleDescr.getLhs().getDescrs()).hasSize(1); + PatternDescr patternDescr = (PatternDescr) ruleDescr.getLhs().getDescrs().get(0); + assertThat(patternDescr.getIdentifier()).isEqualTo("$p"); + assertThat(patternDescr.getObjectType()).isEqualTo("Person"); + + List constraints = patternDescr.getConstraint().getDescrs(); + assertThat(constraints).hasSize(1); + ExprConstraintDescr expr = (ExprConstraintDescr) constraints.get(0); + assertThat(expr.getExpression()).isEqualTo("age >= 18"); + + assertThat(ruleDescr.getConsequence().toString()).isEqualToIgnoringWhitespace("int a = 4; System.out.println($p.getName());"); + } + + @Test + void computeTokenIndex_basicRule() { + DRLParser parser = createDrlParser(drl); + parser.compilationUnit(); + + assertThat((int) computeTokenIndex(parser, 1, 0)).isEqualTo(0); + assertThat((int) computeTokenIndex(parser, 1, 1)).isEqualTo(0); + assertThat((int) computeTokenIndex(parser, 1, 7)).isEqualTo(0); + assertThat((int) computeTokenIndex(parser, 1, 8)).isEqualTo(1); + assertThat((int) computeTokenIndex(parser, 1, 9)).isEqualTo(2); + assertThat((int) computeTokenIndex(parser, 1, 9)).isEqualTo(2); + assertThat((int) computeTokenIndex(parser, 1, 12)).isEqualTo(3); + assertThat((int) computeTokenIndex(parser, 1, 13)).isEqualTo(4); + assertThat((int) computeTokenIndex(parser, 1, 17)).isEqualTo(5); + assertThat((int) computeTokenIndex(parser, 1, 18)).isEqualTo(6); + assertThat((int) computeTokenIndex(parser, 2, 0)).isEqualTo(6); + assertThat((int) computeTokenIndex(parser, 2, 1)).isEqualTo(7); + assertThat((int) computeTokenIndex(parser, 2, 6)).isEqualTo(7); + assertThat((int) computeTokenIndex(parser, 2, 7)).isEqualTo(8); + // Skip RHS token assertion as it is fluid part at the moment. + } +} diff --git a/drools-drl/drools-drl-parser-tests/src/test/java/org/drools/drl/parser/antlr4/DescrCommonPropertyTest.java b/drools-drl/drools-drl-parser-tests/src/test/java/org/drools/drl/parser/antlr4/DescrCommonPropertyTest.java new file mode 100644 index 00000000000..2e1a0e8564e --- /dev/null +++ b/drools-drl/drools-drl-parser-tests/src/test/java/org/drools/drl/parser/antlr4/DescrCommonPropertyTest.java @@ -0,0 +1,480 @@ +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you 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 + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.drools.drl.parser.antlr4; + +import java.io.ByteArrayInputStream; +import java.io.IOException; +import java.io.InputStream; +import java.nio.charset.StandardCharsets; + +import org.drools.drl.ast.descr.AccumulateDescr; +import org.drools.drl.ast.descr.AccumulateImportDescr; +import org.drools.drl.ast.descr.AndDescr; +import org.drools.drl.ast.descr.AnnotationDescr; +import org.drools.drl.ast.descr.BaseDescr; +import org.drools.drl.ast.descr.BehaviorDescr; +import org.drools.drl.ast.descr.CollectDescr; +import org.drools.drl.ast.descr.EntryPointDeclarationDescr; +import org.drools.drl.ast.descr.EntryPointDescr; +import org.drools.drl.ast.descr.EvalDescr; +import org.drools.drl.ast.descr.ExistsDescr; +import org.drools.drl.ast.descr.ExprConstraintDescr; +import org.drools.drl.ast.descr.ForallDescr; +import org.drools.drl.ast.descr.FromDescr; +import org.drools.drl.ast.descr.FunctionDescr; +import org.drools.drl.ast.descr.FunctionImportDescr; +import org.drools.drl.ast.descr.GlobalDescr; +import org.drools.drl.ast.descr.ImportDescr; +import org.drools.drl.ast.descr.NotDescr; +import org.drools.drl.ast.descr.OrDescr; +import org.drools.drl.ast.descr.PackageDescr; +import org.drools.drl.ast.descr.PatternDescr; +import org.drools.drl.ast.descr.QueryDescr; +import org.drools.drl.ast.descr.RuleDescr; +import org.drools.drl.ast.descr.TypeDeclarationDescr; +import org.drools.drl.ast.descr.TypeFieldDescr; +import org.drools.drl.ast.descr.UnitDescr; +import org.drools.drl.ast.descr.WindowDeclarationDescr; +import org.drools.drl.ast.descr.WindowReferenceDescr; +import org.drools.drl.parser.DrlParser; +import org.drools.drl.parser.DroolsParserException; +import org.drools.io.InputStreamResource; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.kie.api.io.Resource; + +import static org.assertj.core.api.Assertions.assertThat; + +/* + * This test class is to assert Descr common properties + */ +class DescrCommonPropertyTest { + + private DrlParser parser; + + private Resource resource; + + @BeforeEach + void setUp() { + parser = ParserTestUtils.getParser(); + } + + private PackageDescr parseAndGetPackageDescr(String drl) { + try (InputStream inputStream = new ByteArrayInputStream(drl.getBytes(StandardCharsets.UTF_8))) { + resource = new InputStreamResource(inputStream); + PackageDescr pkg = parser.parse(resource); + assertThat(parser.hasErrors()).as(parser.getErrors().toString()).isFalse(); + return pkg; + } catch (DroolsParserException | IOException e) { + throw new RuntimeException(e); + } + } + + private void assertProperties(BaseDescr descr, int startCharacter, int endCharacter, int line, int column, int endLine, int endColumn) { + assertThat(descr.getStartCharacter()).isEqualTo(startCharacter); // first character of the start token. character is 0-based + assertThat(descr.getEndCharacter()).isEqualTo(endCharacter); // last character of the end token. character is 0-based + assertThat(descr.getLine()).isEqualTo(line); // line of the start token. line is 1-based + assertThat(descr.getColumn()).isEqualTo(column); // first column of the start token. column is 0-based + assertThat(descr.getEndLine()).isEqualTo(endLine); // line of the end token. line is 1-based + assertThat(descr.getEndColumn()).isEqualTo(endColumn); // last column of the end token. column is 0-based + assertThat(descr.getResource()).isEqualTo(resource); + } + + @Test + void packageDescr() { + final String source = "package foo.bar.baz"; + final PackageDescr pkg = parseAndGetPackageDescr(source); + assertProperties(pkg, 0, 19, 1, 0, 1, 18); + } + + @Test + void ruleDescr() { + final String source = "rule \"MyRule\"\n" + + " when\n" + + " then\n" + + "end"; + final PackageDescr pkg = parseAndGetPackageDescr(source); + final RuleDescr rule = pkg.getRules().get(0); + assertProperties(rule, 0, 31, 1, 0, 4, 2); + } + + @Test + void unitDescr() { + final String source = "package abc;\n" + + "unit Foo;"; + final PackageDescr pkg = parseAndGetPackageDescr(source); + final UnitDescr unit = pkg.getUnit(); + assertProperties(unit, 13, 22, 2, 0, 2, 8); + } + + @Test + void queryDescr() { + final String source = "query \"MyQuery\"\n" + + " Foo()\n" + + "end"; + final PackageDescr pkg = parseAndGetPackageDescr(source); + final QueryDescr query = (QueryDescr) pkg.getRules().get(0); + assertProperties(query, 0, 27, 1, 0, 3, 2); + } + + @Test + void functionDescr() { + final String source = "function void myFunction(String data) {\n" + + " foo();\n" + + "}"; + final PackageDescr pkg = parseAndGetPackageDescr(source); + final FunctionDescr function = pkg.getFunctions().get(0); + assertProperties(function, 0, 50, 1, 0, 3, 0); + } + + @Test + void globalDescr() { + final String source = "global java.util.List myList"; + final PackageDescr pkg = parseAndGetPackageDescr(source); + final GlobalDescr global = pkg.getGlobals().get(0); + assertProperties(global, 0, 28, 1, 0, 1, 27); + } + + @Test + void functionImportDescr() { + final String source = "import function org.drools.core.util.DateUtils.*"; + final PackageDescr pkg = parseAndGetPackageDescr(source); + final FunctionImportDescr functionImport = pkg.getFunctionImports().get(0); + assertProperties(functionImport, 0, 48, 1, 0, 1, 47); + } + + @Test + void importDescr() { + final String source = "import org.drools.core.util.DateUtils"; + final PackageDescr pkg = parseAndGetPackageDescr(source); + final ImportDescr importDescr = pkg.getImports().get(0); + assertProperties(importDescr, 0, 37, 1, 0, 1, 36); + } + + @Test + void accumulateImportDescr() { + final String source = "import accumulate org.example.MyAccUtils.sum mySum"; + final PackageDescr pkg = parseAndGetPackageDescr(source); + final AccumulateImportDescr accumulateImport = pkg.getAccumulateImports().get(0); + assertProperties(accumulateImport, 0, 50, 1, 0, 1, 49); + } + + @Test + void typeDeclarationDescr() { + final String source = "declare MyType\n" + + " name : String\n" + + "end"; + final PackageDescr pkg = parseAndGetPackageDescr(source); + final TypeDeclarationDescr typeDeclaration = pkg.getTypeDeclarations().get(0); + + // startCharacter = 8 looks a little odd ("declare" is not included in the Descr), but it keeps the same as the old implementation. We may change it in the future. + assertProperties(typeDeclaration, 8, 34, 1, 8, 3, 2); + } + + @Test + void entryPointDeclarationDescr() { + final String source = "declare entry-point MyEntryPoint\n" + + " @foo( true )\n" + + "end"; + final PackageDescr pkg = parseAndGetPackageDescr(source); + final EntryPointDeclarationDescr entryPointDeclaration = pkg.getEntryPointDeclarations().stream().findFirst().get(); + assertProperties(entryPointDeclaration, 8, 51, 1, 8, 3, 2); + } + + @Test + void windowDeclarationDescr() { + final String source = "declare window MyWindow\n" + + " $s : StockTick( source == \"NYSE\" )\n" + + " over window:length( 10, $s.symbol )\n" + + " from entry-point stStream\n" + + "end"; + final PackageDescr pkg = parseAndGetPackageDescr(source); + final WindowDeclarationDescr windowDeclaration = pkg.getWindowDeclarations().stream().findFirst().get(); + assertProperties(windowDeclaration, 8, 140, 1, 8, 5, 2); + } + + @Test + void annotationDescr() { + final String source = "package org.drools\n" + + "rule R1\n" + + "when\n" + + " $p : Person( name == \"Mario\" ) @watch(!*, age)\n" + + "then\n" + + "end\n"; + final PackageDescr pkg = parseAndGetPackageDescr(source); + final RuleDescr rule = pkg.getRules().get(0); + AnnotationDescr annotation = rule.getLhs().getAllPatternDescr().get(0).getAnnotations().stream().findFirst().get(); + assertProperties(annotation, 65, 80, 4, 33, 4, 47); + } + + @Test + void typeFieldDescr() { + final String source = "declare MyType\n" + + " name : String\n" + + "end"; + final PackageDescr pkg = parseAndGetPackageDescr(source); + final TypeDeclarationDescr typeDeclaration = pkg.getTypeDeclarations().get(0); + TypeFieldDescr typeField = typeDeclaration.getFields().get("name"); + // Backward Compatibility Notes: + // The old DRL6Parser uses only the attribute value token for common properties (seem to be wrong), so startCharacter and column are different between old and new parser. + // Backward compatibility doesn't seem to be required in this case. + if (DrlParser.ANTLR4_PARSER_ENABLED) { + assertProperties(typeField, 17, 30, 2, 2, 2, 14); + } else { + assertProperties(typeField, 24, 30, 2, 9, 2, 14); + } + } + + @Test + void attributeDescr() { + final String source = "rule R1\n" + + " salience 42\n" + + " agenda-group \"my_group\"\n" + + " when\n" + + " then\n" + + "end"; + final PackageDescr pkg = parseAndGetPackageDescr(source); + final RuleDescr rule = pkg.getRules().get(0); + + // Backward Compatibility Notes: + // The old DRL6Parser uses only the attribute value token for common properties (seem to be wrong), so startCharacter and column are different between old and new parser. + // Backward compatibility doesn't seem to be required in this case. (If do it, the code would be unnecessarily complicated.) + if (DrlParser.ANTLR4_PARSER_ENABLED) { + assertProperties(rule.getAttributes().get("salience"), 10, 21, 2, 2, 2, 12); + assertProperties(rule.getAttributes().get("agenda-group"), 24, 47, 3, 2, 3, 24); + } else { + assertProperties(rule.getAttributes().get("salience"), 19, 21, 2, 11, 2, 12); + assertProperties(rule.getAttributes().get("agenda-group"), 37, 47, 3, 15, 3, 24); + } + } + + @Test + void patternDescr() { + final String source = "rule R1\n" + + " when\n" + + " $p : Person( name == \"Mario\" )\n" + + " then\n" + + "end"; + final PackageDescr pkg = parseAndGetPackageDescr(source); + final RuleDescr rule = pkg.getRules().get(0); + PatternDescr pattern = (PatternDescr) rule.getLhs().getDescrs().get(0); + assertProperties(pattern, 19, 49, 3, 4, 3, 33); + } + + @Test + void orDescr() { + final String source = "rule R1\n" + + " when\n" + + " ( $p : Person( name == \"Mario\" ) or $p : Person( name == \"Luigi\" ) )\n" + + " then\n" + + "end"; + final PackageDescr pkg = parseAndGetPackageDescr(source); + final RuleDescr rule = pkg.getRules().get(0); + OrDescr or = (OrDescr) rule.getLhs().getDescrs().get(0); + assertProperties(or, 21, 85, 3, 6, 3, 69); + } + + @Test + void andDescr() { + final String source = "rule R1\n" + + " when\n" + + " ( $p1 : Person( name == \"Mario\" ) and $p2 : Person( name == \"Luigi\" ) )\n" + + " then\n" + + "end"; + final PackageDescr pkg = parseAndGetPackageDescr(source); + final RuleDescr rule = pkg.getRules().get(0); + AndDescr and = rule.getLhs(); + assertProperties(and, 19, 90, 3, 4, 3, 74); + } + + @Test + void forallDescr() { + final String source = "rule R1\n" + + " when\n" + + " forall( $p : Person( name == \"Mario\" ) )\n" + + " then\n" + + "end"; + final PackageDescr pkg = parseAndGetPackageDescr(source); + final RuleDescr rule = pkg.getRules().get(0); + ForallDescr forall = (ForallDescr) rule.getLhs().getDescrs().get(0); + assertProperties(forall, 19, 59, 3, 4, 3, 43); + } + + @Test + void accumulateDescr() { + final String source = "rule R1\n" + + " when\n" + + " accumulate( $p : Person( name == \"Mario\" ), $sum : sum($p.getAge()) )\n" + + " then\n" + + "end"; + final PackageDescr pkg = parseAndGetPackageDescr(source); + final RuleDescr rule = pkg.getRules().get(0); + PatternDescr pattern = (PatternDescr) rule.getLhs().getDescrs().get(0); + AccumulateDescr accumulate = (AccumulateDescr) pattern.getSource(); + assertProperties(accumulate, 19, 88, 3, 4, 3, 72); + } + + @Test + void behaviorDescr() { + final String source = "rule X when StockTick( symbol==\"ACME\") over window:length(10) then end"; + final PackageDescr pkg = parseAndGetPackageDescr(source); + final RuleDescr rule = pkg.getRules().get(0); + PatternDescr pattern = (PatternDescr) rule.getLhs().getDescrs().get(0); + BehaviorDescr behavior = pattern.getBehaviors().get(0); + + // "over" is not included in BehaviorDescr + assertProperties(behavior, 44, 61, 1, 44, 1, 60); + } + + @Test + void fromDescr() { + final String source = "rule X\n" + + " when\n" + + " Adult( $children : children)\n" + + " Child() from $children\n" + + " then\n" + + "end"; + ; + final PackageDescr pkg = parseAndGetPackageDescr(source); + final RuleDescr rule = pkg.getRules().get(0); + PatternDescr pattern = (PatternDescr) rule.getLhs().getDescrs().get(1); + FromDescr from = (FromDescr) pattern.getSource(); + + // Backward Compatibility Notes: + // The old DRL6Parser doesn't populate common properties of FromDescr (seem to be wrong). + // Backward compatibility doesn't seem to be required in this case. + if (DrlParser.ANTLR4_PARSER_ENABLED) { + // "from" is not included in FromDescr + assertProperties(from, 64, 73, 4, 17, 4, 25); + } else { + assertProperties(from, -1, -1, -1, -1, -1, -1); + } + } + + @Test + void collectDescr() { + final String source = "rule X\n" + + " when\n" + + " ArrayList() from collect( Person( age > 21 ) );\n" + + " then\n" + + "end"; + final PackageDescr pkg = parseAndGetPackageDescr(source); + final RuleDescr rule = pkg.getRules().get(0); + PatternDescr pattern = (PatternDescr) rule.getLhs().getDescrs().get(0); + CollectDescr collect = (CollectDescr) pattern.getSource(); + + assertProperties(collect, 35, 64, 3, 21, 3, 49); + } + + @Test + void entryPointDescr() { + final String source = "rule X\n" + + " when\n" + + " StockTick() from entry-point \"stream\"\n" + + " then\n" + + "end"; + final PackageDescr pkg = parseAndGetPackageDescr(source); + final RuleDescr rule = pkg.getRules().get(0); + PatternDescr pattern = (PatternDescr) rule.getLhs().getDescrs().get(0); + EntryPointDescr entryPoint = (EntryPointDescr) pattern.getSource(); + + // Backward Compatibility Notes: + // The old DRL6Parser doesn't populate common properties of EntryPointDescr (seem to be wrong). + // Backward compatibility doesn't seem to be required in this case. + if (DrlParser.ANTLR4_PARSER_ENABLED) { + assertProperties(entryPoint, 35, 55, 3, 21, 3, 40); + } else { + assertProperties(entryPoint, -1, -1, -1, -1, -1, -1); + } + } + + @Test + void windowReferenceDescr() { + final String source = "rule X\n" + + " when\n" + + " StockTick() from window MyWindow\n" + + " then\n" + + "end"; + final PackageDescr pkg = parseAndGetPackageDescr(source); + final RuleDescr rule = pkg.getRules().get(0); + PatternDescr pattern = (PatternDescr) rule.getLhs().getDescrs().get(0); + WindowReferenceDescr windowReference = (WindowReferenceDescr) pattern.getSource(); + // Backward Compatibility Notes: + // The old DRL6Parser doesn't populate common properties of WindowReferenceDescr (seem to be wrong). + // Backward compatibility doesn't seem to be required in this case. + if (DrlParser.ANTLR4_PARSER_ENABLED) { + assertProperties(windowReference, 35, 50, 3, 21, 3, 35); + } else { + assertProperties(windowReference, -1, -1, -1, -1, -1, -1); + } + } + + @Test + void exprConstraintDescr() { + final String source = "rule X\n" + + " when\n" + + " Person( age > 21 )\n" + + " then\n" + + "end"; + final PackageDescr pkg = parseAndGetPackageDescr(source); + final RuleDescr rule = pkg.getRules().get(0); + PatternDescr pattern = (PatternDescr) rule.getLhs().getDescrs().get(0); + ExprConstraintDescr exprConstraint = (ExprConstraintDescr) pattern.getDescrs().get(0); + assertProperties(exprConstraint, 26, 33, 3, 12, 3, 18); + } + + @Test + void existDescr() { + final String source = "rule X\n" + + " when\n" + + " exists( Person( age > 21 ) )\n" + + " then\n" + + "end"; + final PackageDescr pkg = parseAndGetPackageDescr(source); + final RuleDescr rule = pkg.getRules().get(0); + ExistsDescr exists = (ExistsDescr) rule.getLhs().getDescrs().get(0); + assertProperties(exists, 18, 46, 3, 4, 3, 31); + } + + @Test + void notDescr() { + final String source = "rule X\n" + + " when\n" + + " not( Person( age > 21 ) )\n" + + " then\n" + + "end"; + final PackageDescr pkg = parseAndGetPackageDescr(source); + final RuleDescr rule = pkg.getRules().get(0); + NotDescr not = (NotDescr) rule.getLhs().getDescrs().get(0); + assertProperties(not, 18, 43, 3, 4, 3, 28); + } + + @Test + void evalDescr() { + final String source = "rule X\n" + + " when\n" + + " eval( 1 + 1 == 2 )\n" + + " then\n" + + "end"; + final PackageDescr pkg = parseAndGetPackageDescr(source); + final RuleDescr rule = pkg.getRules().get(0); + EvalDescr eval = (EvalDescr) rule.getLhs().getDescrs().get(0); + assertProperties(eval, 18, 36, 3, 4, 3, 21); + } +} diff --git a/drools-drl/drools-drl-parser-tests/src/test/java/org/drools/drl/parser/antlr4/DescrDumperTest.java b/drools-drl/drools-drl-parser-tests/src/test/java/org/drools/drl/parser/antlr4/DescrDumperTest.java new file mode 100644 index 00000000000..76f750ff215 --- /dev/null +++ b/drools-drl/drools-drl-parser-tests/src/test/java/org/drools/drl/parser/antlr4/DescrDumperTest.java @@ -0,0 +1,369 @@ +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you 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 + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.drools.drl.parser.antlr4; + +import org.drools.compiler.lang.DescrDumper; +import org.drools.compiler.lang.DumperContext; +import org.drools.drl.ast.descr.AtomicExprDescr; +import org.drools.drl.ast.descr.BindingDescr; +import org.drools.drl.ast.descr.ConstraintConnectiveDescr; +import org.drools.drl.parser.DrlExprParser; +import org.drools.drl.parser.DrlExprParserFactory; +import org.drools.mvel.evaluators.MatchesEvaluatorsDefinition; +import org.drools.mvel.evaluators.SetEvaluatorsDefinition; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.Test; +import org.kie.internal.builder.conf.LanguageLevelOption; + +import static org.assertj.core.api.Assertions.assertThat; + +public class DescrDumperTest { + + private DescrDumper dumper; + + @BeforeEach + void setUp() { + // configure operators + new SetEvaluatorsDefinition(); + new MatchesEvaluatorsDefinition(); + + dumper = new DescrDumper(); + } + + @Test + void dump() { + String input = "price > 10 && < 20 || == $val || == 30"; + String expected = "( price > 10 && price < 20 || price == $val || price == 30 )"; + + ConstraintConnectiveDescr descr = parse(input); + String result = dumper.dump(descr); + + assertThat(result).isEqualTo(expected); + } + + @Test + void dumpMatches() { + String input = "type.toString matches \"something\\swith\\tsingle escapes\""; + String expected = "type.toString ~= \"something\\swith\\tsingle escapes\""; + + ConstraintConnectiveDescr descr = parse(input); + String result = dumper.dump(descr); + + assertThat(result).isEqualTo(expected); + } + + @Test + void dumpMatches2() { + String input = "type.toString matches 'something\\swith\\tsingle escapes'"; + String expected = "type.toString ~= \"something\\swith\\tsingle escapes\""; + + ConstraintConnectiveDescr descr = parse(input); + String result = dumper.dump(descr); + + assertThat(result).isEqualTo(expected); + } + + @Test + void dumpMatches3() { + String input = "this[\"content\"] matches \"hello ;=\""; + String expected = "this[\"content\"] ~= \"hello ;=\""; + + ConstraintConnectiveDescr descr = parse(input); + String result = dumper.dump(descr); + + assertThat(result).isEqualTo(expected); + } + + @Test + void dumpContains() { + String input = "list contains \"b\""; + String expected = "list contains \"b\""; + + ConstraintConnectiveDescr descr = parse(input); + String result = dumper.dump(descr); + + assertThat(result).isEqualTo(expected); + } + + @Test + void dumpContains2() { + String input = "list not contains \"b\""; + String expected = "!( list contains \"b\" )"; + + ConstraintConnectiveDescr descr = parse(input); + String result = dumper.dump(descr); + + assertThat(result).isEqualTo(expected); + } + + @Test + void dumpExcludes() { + String input = "list excludes \"b\""; + String expected = "!( list contains \"b\" )"; + + ConstraintConnectiveDescr descr = parse(input); + String result = dumper.dump(descr); + + assertThat(result).isEqualTo(expected); + } + + @Test + void dumpExcludes2() { + String input = "list not excludes \"b\""; + String expected = "list contains \"b\""; + + ConstraintConnectiveDescr descr = parse(input); + String result = dumper.dump(descr); + + assertThat(result).isEqualTo(expected); + } + + @Test + @Disabled + void dumpWithDateAttr() { + String input = "son.birthDate == \"01-jan-2000\""; + String expected = "son.birthDate == org.drools.util.DateUtils.parseDate( \"01-jan-2000\" )"; + + ConstraintConnectiveDescr descr = parse(input); + String result = dumper.dump(descr); + + assertThat(result).isEqualTo(expected); + } + + @Test + void dumpComplex() { + String input = "a ( > 60 && < 70 ) || ( > 50 && < 55 ) && a3 == \"black\" || a == 40 && a3 == \"pink\" || a == 12 && a3 == \"yellow\" || a3 == \"blue\""; + String expected = "( ( a > 60 && a < 70 || a > 50 && a < 55 ) && a3 == \"black\" || a == 40 && a3 == \"pink\" || a == 12 && a3 == \"yellow\" || a3 == \"blue\" )"; + + ConstraintConnectiveDescr descr = parse(input); + String result = dumper.dump(descr); + + assertThat(result).isEqualTo(expected); + } + + @Test + void dumpBindings() { + String input = "$x : property > value"; + String expected = "property > value"; + + ConstraintConnectiveDescr descr = parse(input); + DumperContext ctx = new DumperContext(); + String result = dumper.dump(descr, + ctx); + + assertThat(result).isEqualTo(expected); + assertThat(ctx.getBindings()).hasSize(1); + BindingDescr bind = ctx.getBindings().get(0); + assertThat(bind.getVariable()).isEqualTo("$x"); + assertThat(bind.getExpression()).isEqualTo("property"); + } + + @Test + void dumpBindings2() { + String input = "( $a : a > $b : b[10].prop || 10 != 20 ) && $x : someMethod(10) == 20"; + String expected = "( a > b[10].prop || 10 != 20 ) && someMethod(10) == 20"; + + ConstraintConnectiveDescr descr = parse(input); + DumperContext ctx = new DumperContext(); + String result = dumper.dump(descr, + ctx); + + assertThat(result).isEqualTo(expected); + assertThat(ctx.getBindings()).hasSize(3); + BindingDescr bind = ctx.getBindings().get(0); + assertThat(bind.getVariable()).isEqualTo("$a"); + assertThat(bind.getExpression()).isEqualTo("a"); + bind = ctx.getBindings().get(1); + assertThat(bind.getVariable()).isEqualTo("$b"); + assertThat(bind.getExpression()).isEqualTo("b[10].prop"); + bind = ctx.getBindings().get(2); + assertThat(bind.getVariable()).isEqualTo("$x"); + assertThat(bind.getExpression()).isEqualTo("someMethod(10)"); + } + + @Test + void dumpBindings3() { + String input = "( $a : a > $b : b[10].prop || 10 != 20 ) && $x : someMethod(10)"; + String expected = "( a > b[10].prop || 10 != 20 )"; + + ConstraintConnectiveDescr descr = parse(input); + String result = dumper.dump(descr); + + assertThat(result).isEqualTo(expected); + } + + @Test + void dumpBindings4() { + String input = "( $a : a > $b : b[10].prop || $x : someMethod(10) ) && 10 != 20"; + String expected = "( a > b[10].prop ) && 10 != 20"; + + ConstraintConnectiveDescr descr = parse(input); + String result = dumper.dump(descr); + + assertThat(result).isEqualTo(expected); + } + + @Test + void dumpBindingsWithRestriction() { + String input = "$x : age > 10 && < 20 || > 30"; + String expected = "( age > 10 && age < 20 || age > 30 )"; + + ConstraintConnectiveDescr descr = parse(input); + DumperContext ctx = new DumperContext(); + String result = dumper.dump(descr, + ctx); + + assertThat(result).isEqualTo(expected); + assertThat(ctx.getBindings()).hasSize(1); + BindingDescr bind = ctx.getBindings().get(0); + assertThat(bind.getVariable()).isEqualTo("$x"); + assertThat(bind.getExpression()).isEqualTo("age"); + } + + @Test + void dumpBindingsComplexOp() { + String input = "$x : age in (10, 20, $someVal)"; + String expected = "( age == 10 || age == 20 || age == $someVal )"; + + ConstraintConnectiveDescr descr = parse(input); + DumperContext ctx = new DumperContext(); + String result = dumper.dump(descr, + ctx); + + assertThat(result).isEqualTo(expected); + assertThat(ctx.getBindings()).hasSize(1); + BindingDescr bind = ctx.getBindings().get(0); + assertThat(bind.getVariable()).isEqualTo("$x"); + assertThat(bind.getExpression()).isEqualTo("age"); + } + + @Test + void dumpBindingsComplexOp2() { + String input = "$x : age not in (10, 20, $someVal)"; + String expected = "age != 10 && age != 20 && age != $someVal"; + + ConstraintConnectiveDescr descr = parse(input); + DumperContext ctx = new DumperContext(); + String result = dumper.dump(descr, + ctx); + + assertThat(result).isEqualTo(expected); + assertThat(ctx.getBindings()).hasSize(1); + BindingDescr bind = ctx.getBindings().get(0); + assertThat(bind.getVariable()).isEqualTo("$x"); + assertThat(bind.getExpression()).isEqualTo("age"); + } + + @Test + void processInlineCast() { + String expr = "field1#Class.field2"; + String expectedInstanceof = "field1 instanceof Class"; + String expectedcasted = "((Class)field1).field2"; + AtomicExprDescr atomicExpr = new AtomicExprDescr(expr); + ConstraintConnectiveDescr ccd = new ConstraintConnectiveDescr(); + ccd.addDescr(atomicExpr); + String[] instanceofAndCastedExpr = dumper.processImplicitConstraints(expr, atomicExpr, ccd, ccd.getDescrs().indexOf(atomicExpr), null); + assertThat(ccd.getDescrs()).hasSize(2); + assertThat(ccd.getDescrs().get(0).toString()).isEqualTo(expectedInstanceof); + assertThat(atomicExpr.getRewrittenExpression()).isEqualTo(expectedcasted); + + expr = "field1#Class1.field2#Class2.field3"; + String expectedInstanceof1 = "field1 instanceof Class1"; + String expectedInstanceof2 = "((Class1)field1).field2 instanceof Class2"; + expectedcasted = "((Class2)((Class1)field1).field2).field3"; + atomicExpr = new AtomicExprDescr(expr); + ccd = new ConstraintConnectiveDescr(); + instanceofAndCastedExpr = dumper.processImplicitConstraints(expr, atomicExpr, ccd, ccd.getDescrs().indexOf(atomicExpr), null); + assertThat(ccd.getDescrs().get(0).toString()).isEqualTo(expectedInstanceof1); + assertThat(ccd.getDescrs().get(1).toString()).isEqualTo(expectedInstanceof2); + assertThat(instanceofAndCastedExpr[1]).isEqualTo(expectedcasted); + assertThat(atomicExpr.getRewrittenExpression()).isEqualTo(expectedcasted); + } + + @Test + void processNullSafeDereferencing() { + String expr = "field1!.field2"; + String expectedNullCheck = "field1 != null"; + String expectedExpr = "field1.field2"; + AtomicExprDescr atomicExpr = new AtomicExprDescr(expr); + ConstraintConnectiveDescr ccd = new ConstraintConnectiveDescr(); + String[] nullCheckAndExpr = dumper.processImplicitConstraints(expr, atomicExpr, ccd, ccd.getDescrs().indexOf(atomicExpr), null); + assertThat(ccd.getDescrs().get(0).toString()).isEqualTo(expectedNullCheck); + assertThat(nullCheckAndExpr[1]).isEqualTo(expectedExpr); + assertThat(atomicExpr.getRewrittenExpression()).isEqualTo(expectedExpr); + + expr = "field1!.field2!.field3"; + String expectedNullCheck1 = "field1 != null"; + String expectedNullCheck2 = "field1.field2 != null"; + expectedExpr = "field1.field2.field3"; + atomicExpr = new AtomicExprDescr(expr); + ccd = new ConstraintConnectiveDescr(); + nullCheckAndExpr = dumper.processImplicitConstraints(expr, atomicExpr, ccd, ccd.getDescrs().indexOf(atomicExpr), null); + assertThat(ccd.getDescrs().get(0).toString()).isEqualTo(expectedNullCheck1); + assertThat(ccd.getDescrs().get(1).toString()).isEqualTo(expectedNullCheck2); + assertThat(nullCheckAndExpr[1]).isEqualTo(expectedExpr); + assertThat(atomicExpr.getRewrittenExpression()).isEqualTo(expectedExpr); + } + + @Test + void processImplicitConstraints() { + String expr = "field1#Class!.field2"; + String expectedConstraints = "field1 instanceof Class"; + String expectedExpr = "((Class)field1).field2"; + AtomicExprDescr atomicExpr = new AtomicExprDescr(expr); + ConstraintConnectiveDescr ccd = new ConstraintConnectiveDescr(); + String[] constraintsAndExpr = dumper.processImplicitConstraints(expr, atomicExpr, ccd, ccd.getDescrs().indexOf(atomicExpr), null); + assertThat(ccd.getDescrs().get(0).toString()).isEqualTo(expectedConstraints); + assertThat(constraintsAndExpr[1]).isEqualTo(expectedExpr); + assertThat(atomicExpr.getRewrittenExpression()).isEqualTo(expectedExpr); + + expr = "field1!.field2#Class.field3"; + String expectedConstraints1 = "field1 != null"; + String expectedConstraints2 = "field1.field2 instanceof Class"; + expectedExpr = "((Class)field1.field2).field3"; + atomicExpr = new AtomicExprDescr(expr); + ccd = new ConstraintConnectiveDescr(); + constraintsAndExpr = dumper.processImplicitConstraints(expr, atomicExpr, ccd, ccd.getDescrs().indexOf(atomicExpr), null); + assertThat(ccd.getDescrs().get(0).toString()).isEqualTo(expectedConstraints1); + assertThat(ccd.getDescrs().get(1).toString()).isEqualTo(expectedConstraints2); + assertThat(constraintsAndExpr[1]).isEqualTo(expectedExpr); + assertThat(atomicExpr.getRewrittenExpression()).isEqualTo(expectedExpr); + + expr = "field1#Class.field2!.field3"; + expectedConstraints1 = "field1 instanceof Class"; + expectedConstraints2 = "((Class)field1).field2 != null"; + expectedExpr = "((Class)field1).field2.field3"; + atomicExpr = new AtomicExprDescr(expr); + ccd = new ConstraintConnectiveDescr(); + constraintsAndExpr = dumper.processImplicitConstraints(expr, atomicExpr, ccd, ccd.getDescrs().indexOf(atomicExpr), null); + assertThat(ccd.getDescrs().get(0).toString()).isEqualTo(expectedConstraints1); + assertThat(ccd.getDescrs().get(1).toString()).isEqualTo(expectedConstraints2); + assertThat(constraintsAndExpr[1]).isEqualTo(expectedExpr); + assertThat(atomicExpr.getRewrittenExpression()).isEqualTo(expectedExpr); + } + + public ConstraintConnectiveDescr parse(final String constraint) { + DrlExprParser parser = DrlExprParserFactory.getDrlExprParser(LanguageLevelOption.DRL6); + ConstraintConnectiveDescr result = parser.parse(constraint); + assertThat(parser.hasErrors()).as(parser.getErrors().toString()).isFalse(); + + return result; + } +} diff --git a/drools-drl/drools-drl-parser-tests/src/test/java/org/drools/drl/parser/antlr4/MiscDRLParserTest.java b/drools-drl/drools-drl-parser-tests/src/test/java/org/drools/drl/parser/antlr4/MiscDRLParserTest.java new file mode 100644 index 00000000000..3fc2cdbca39 --- /dev/null +++ b/drools-drl/drools-drl-parser-tests/src/test/java/org/drools/drl/parser/antlr4/MiscDRLParserTest.java @@ -0,0 +1,5274 @@ +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you 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 + *

+ * http://www.apache.org/licenses/LICENSE-2.0 + *

+ * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.drools.drl.parser.antlr4; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; +import java.io.UncheckedIOException; +import java.net.URISyntaxException; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.util.Collection; +import java.util.Collections; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.regex.Pattern; +import java.util.stream.Stream; + +import org.drools.drl.ast.descr.AccumulateDescr; +import org.drools.drl.ast.descr.AccumulateImportDescr; +import org.drools.drl.ast.descr.AndDescr; +import org.drools.drl.ast.descr.AnnotationDescr; +import org.drools.drl.ast.descr.AttributeDescr; +import org.drools.drl.ast.descr.BaseDescr; +import org.drools.drl.ast.descr.BehaviorDescr; +import org.drools.drl.ast.descr.CollectDescr; +import org.drools.drl.ast.descr.ConditionalBranchDescr; +import org.drools.drl.ast.descr.EntryPointDeclarationDescr; +import org.drools.drl.ast.descr.EntryPointDescr; +import org.drools.drl.ast.descr.EnumDeclarationDescr; +import org.drools.drl.ast.descr.EnumLiteralDescr; +import org.drools.drl.ast.descr.EvalDescr; +import org.drools.drl.ast.descr.ExistsDescr; +import org.drools.drl.ast.descr.ExprConstraintDescr; +import org.drools.drl.ast.descr.ForallDescr; +import org.drools.drl.ast.descr.FromDescr; +import org.drools.drl.ast.descr.FunctionDescr; +import org.drools.drl.ast.descr.GlobalDescr; +import org.drools.drl.ast.descr.GroupByDescr; +import org.drools.drl.ast.descr.ImportDescr; +import org.drools.drl.ast.descr.MVELExprDescr; +import org.drools.drl.ast.descr.NamedConsequenceDescr; +import org.drools.drl.ast.descr.NotDescr; +import org.drools.drl.ast.descr.OrDescr; +import org.drools.drl.ast.descr.PackageDescr; +import org.drools.drl.ast.descr.PatternDescr; +import org.drools.drl.ast.descr.QualifiedName; +import org.drools.drl.ast.descr.QueryDescr; +import org.drools.drl.ast.descr.RuleDescr; +import org.drools.drl.ast.descr.TypeDeclarationDescr; +import org.drools.drl.ast.descr.TypeFieldDescr; +import org.drools.drl.ast.descr.WindowDeclarationDescr; +import org.drools.drl.parser.DrlParser; +import org.drools.drl.parser.DroolsError; +import org.drools.drl.parser.DroolsParserException; +import org.drools.drl.parser.impl.Operator; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.Arguments; +import org.junit.jupiter.params.provider.MethodSource; +import org.junit.jupiter.params.provider.ValueSource; + +import static org.assertj.core.api.Assertions.assertThat; + +/* + * This test class is ported from org.drools.mvel.compiler.lang.RuleParserTest + */ +class MiscDRLParserTest { + + private DrlParser parser; + + @BeforeEach + void setUp() { + parser = ParserTestUtils.getParser(); + } + + private String readResource(final String filename) { + Path path; + try { + path = Paths.get(getClass().getResource(filename).toURI()); + } catch (URISyntaxException e) { + throw new RuntimeException(e); + } + final StringBuilder sb = new StringBuilder(); + try (BufferedReader br = Files.newBufferedReader(path, StandardCharsets.UTF_8)) { + for (String line; (line = br.readLine()) != null; ) { + sb.append(line); + sb.append("\n"); + } + } catch (IOException e) { + throw new UncheckedIOException(e); + } + return sb.toString(); + } + + private PackageDescr parseAndGetPackageDescr(String drl) { + try { + PackageDescr pkg = parser.parse(null, drl); + assertThat(parser.hasErrors()).as(parser.getErrors().toString()).isFalse(); + return pkg; + } catch (DroolsParserException e) { + throw new RuntimeException(e); + } + } + + private PackageDescr parseAndGetPackageDescrWithoutErrorCheck(String drl) { + try { + return parser.parse(null, drl); + } catch (DroolsParserException e) { + throw new RuntimeException(e); + } + } + + private PackageDescr parseAndGetPackageDescrWithDsl(String dslrFileName, String dslFileName) { + try (InputStreamReader dslr = new InputStreamReader(getClass().getResourceAsStream(dslrFileName)); + InputStreamReader dsl = new InputStreamReader(getClass().getResourceAsStream(dslFileName))) { + PackageDescr pkg = parser.parse(dslr, dsl); + assertThat(parser.hasErrors()).as(parser.getErrors().toString()).isFalse(); + return pkg; + } catch (DroolsParserException | IOException e) { + throw new RuntimeException(e); + } + } + + private RuleDescr parseAndGetFirstRuleDescr(String drl) { + PackageDescr pkg = parseAndGetPackageDescr(drl); + assertThat(pkg.getRules()).isNotEmpty(); + return pkg.getRules().get(0); + } + + private ExprConstraintDescr parseAndGetFirstConstraintDescr(String drl) { + RuleDescr rule = parseAndGetFirstRuleDescr(drl); + assertThat(rule.getLhs().getDescrs().get(0)).isInstanceOf(PatternDescr.class); + PatternDescr patternDescr = (PatternDescr) rule.getLhs().getDescrs().get(0); + assertThat(patternDescr.getConstraint().getDescrs().get(0)).isInstanceOf(ExprConstraintDescr.class); + return (ExprConstraintDescr) patternDescr.getConstraint().getDescrs().get(0); + } + + private PackageDescr parseAndGetPackageDescrFromFile(String filename) { + return parseAndGetPackageDescr(readResource(filename)); + } + + private RuleDescr parseAndGetFirstRuleDescrFromFile(String filename) { + return parseAndGetFirstRuleDescr(readResource(filename)); + } + + private QueryDescr parseAndGetFirstQueryDescr(String drl) { + PackageDescr pkg = parseAndGetPackageDescr(drl); + assertThat(pkg.getRules()).isNotEmpty(); + Optional optQuery = pkg.getRules().stream().filter(QueryDescr.class::isInstance).map(QueryDescr.class::cast).findFirst(); + assertThat(optQuery).isPresent(); + return optQuery.get(); + } + + private QueryDescr parseAndGetFirstQueryDescrFromFile(String filename) { + return parseAndGetFirstQueryDescr(readResource(filename)); + } + + @Test + void emptySource() { + final String source = ""; + final PackageDescr pkg = parseAndGetPackageDescr(source); + assertThat(pkg.getName()).isEmpty(); + } + + @Test + void validPackage() { + final String source = "package foo.bar.baz"; + final PackageDescr pkg = parseAndGetPackageDescr(source); + assertThat(pkg.getName()).isEqualTo("foo.bar.baz"); + } + + @Test + void packageWithErrorNode() { + final String source = "package 12 foo.bar.baz"; + final PackageDescr pkg = parseAndGetPackageDescrWithoutErrorCheck(source); + assertThat(parser.hasErrors()).isTrue(); + assertThat(pkg).isNull(); + } + + @Test + void packageWithAllErrorNode() { + final String source = "package 12 12312 231"; + final PackageDescr pkg = parseAndGetPackageDescrWithoutErrorCheck(source); + assertThat(parser.hasErrors()).isTrue(); + assertThat(pkg).isNull(); + } + + @Test + void importDef() { + final String source = "package foo; import com.foo.Bar; import com.foo.Baz;"; + PackageDescr pkg = parseAndGetPackageDescr(source); + assertThat(pkg.getName()).isEqualTo("foo"); + assertThat(pkg.getImports()).hasSize(2); + ImportDescr impdescr = pkg.getImports().get(0); + assertThat(impdescr.getTarget()).isEqualTo("com.foo.Bar"); + assertThat(impdescr.getStartCharacter()).isEqualTo(source.indexOf("import " + impdescr.getTarget())); + assertThat(impdescr.getEndCharacter()).isEqualTo(source.indexOf("import " + impdescr.getTarget()) + ("import " + impdescr.getTarget()).length()); + + impdescr = pkg.getImports().get(1); + assertThat(impdescr.getTarget()).isEqualTo("com.foo.Baz"); + assertThat(impdescr.getStartCharacter()).isEqualTo(source.indexOf("import " + impdescr.getTarget())); + assertThat(impdescr.getEndCharacter()).isEqualTo(source.indexOf("import " + impdescr.getTarget()) + ("import " + impdescr.getTarget()).length()); + } + + @Test + void functionImport() { + final String source = "package foo\n" + + "import function java.lang.Math.max\n" + + "import function java.lang.Math.min;\n" + + "import foo.bar.*\n" + + "import baz.Baz"; + PackageDescr pkg = parseAndGetPackageDescr(source); + assertThat(pkg.getName()).isEqualTo("foo"); + assertThat(pkg.getImports()).hasSize(2); + ImportDescr impdescr = pkg.getImports().get(0); + assertThat(impdescr.getTarget()).isEqualTo("foo.bar.*"); + assertThat(impdescr.getStartCharacter()).isEqualTo(source.indexOf("import " + impdescr.getTarget())); + + assertThat(impdescr.getEndCharacter()).isEqualTo(source.indexOf("import " + impdescr.getTarget()) + ("import " + impdescr.getTarget()).length()); + + impdescr = pkg.getImports().get(1); + assertThat(impdescr.getTarget()).isEqualTo("baz.Baz"); + assertThat(impdescr.getStartCharacter()).isEqualTo(source.indexOf("import " + impdescr.getTarget())); + assertThat(impdescr.getEndCharacter()).isEqualTo(source.indexOf("import " + impdescr.getTarget()) + ("import " + impdescr.getTarget()).length()); + + assertThat(pkg.getFunctionImports()).hasSize(2); + impdescr = pkg.getFunctionImports().get(0); + assertThat(impdescr.getTarget()).isEqualTo("java.lang.Math.max"); + assertThat(impdescr.getStartCharacter()).isEqualTo(source.indexOf("import function " + impdescr.getTarget())); + assertThat(impdescr.getEndCharacter()).isEqualTo(source.indexOf("import function " + impdescr.getTarget()) + ("import function " + impdescr.getTarget()).length()); + + impdescr = pkg.getFunctionImports().get(1); + assertThat(impdescr.getTarget()).isEqualTo("java.lang.Math.min"); + assertThat(impdescr.getStartCharacter()).isEqualTo(source.indexOf("import function " + impdescr.getTarget())); + assertThat(impdescr.getEndCharacter()).isEqualTo(source.indexOf("import function " + impdescr.getTarget()) + ("import function " + impdescr.getTarget()).length()); + } + + @Test + void globalWithComplexType() { + final String source = "package foo.bar.baz\n" + + "import com.foo.Bar\n" + + "global java.util.List> aList;\n" + + "global Integer aNumber"; + PackageDescr pkg = parseAndGetPackageDescr(source); + assertThat(pkg.getName()).isEqualTo("foo.bar.baz"); + assertThat(pkg.getImports()).hasSize(1); + + ImportDescr impdescr = pkg.getImports().get(0); + assertThat(impdescr.getTarget()).isEqualTo("com.foo.Bar"); + assertThat(impdescr.getStartCharacter()).isEqualTo(source.indexOf("import " + impdescr.getTarget())); + assertThat(impdescr.getEndCharacter()).isEqualTo(source.indexOf("import " + impdescr.getTarget()) + ("import " + impdescr.getTarget()).length()); + + assertThat(pkg.getGlobals()).hasSize(2); + + GlobalDescr global = pkg.getGlobals().get(0); + assertThat(global.getType()).isEqualTo("java.util.List>"); + assertThat(global.getIdentifier()).isEqualTo("aList"); + assertThat(global.getStartCharacter()).isEqualTo(source.indexOf("global " + global.getType())); + assertThat(global.getEndCharacter()).isEqualTo(source.indexOf("global " + global.getType() + " " + global.getIdentifier()) + + ("global " + global.getType() + " " + global.getIdentifier()).length()); + + global = pkg.getGlobals().get(1); + assertThat(global.getType()).isEqualTo("Integer"); + assertThat(global.getIdentifier()).isEqualTo("aNumber"); + assertThat(global.getStartCharacter()).isEqualTo(source.indexOf("global " + global.getType())); + assertThat(global.getEndCharacter()).isEqualTo(source.indexOf("global " + global.getType() + " " + global.getIdentifier()) + + ("global " + global.getType() + " " + global.getIdentifier()).length()); + } + + @Test + void globalWithOrWithoutSemi() { + String source = readResource("globals.drl"); + PackageDescr pkg = parseAndGetPackageDescr(source); + + assertThat(pkg.getRules()).hasSize(1); + + final RuleDescr rule = pkg.getRules().get(0); + assertThat(rule.getLhs().getDescrs()).hasSize(1); + + assertThat(pkg.getImports()).hasSize(1); + assertThat(pkg.getGlobals()).hasSize(2); + + final GlobalDescr foo = pkg.getGlobals().get(0); + assertThat(foo.getType()).isEqualTo("java.lang.String"); + assertThat(foo.getIdentifier()).isEqualTo("foo"); + final GlobalDescr bar = pkg.getGlobals().get(1); + assertThat(bar.getType()).isEqualTo("java.lang.Integer"); + assertThat(bar.getIdentifier()).isEqualTo("bar"); + } + + @Test + void functionImportWithNotExist() { + String source = readResource("test_FunctionImport.drl"); + PackageDescr pkg = parseAndGetPackageDescr(source); + + assertThat(pkg.getFunctionImports()).hasSize(2); + + assertThat(pkg.getFunctionImports().get(0).getTarget()).isEqualTo("abd.def.x"); + assertThat(pkg.getFunctionImports().get(0).getStartCharacter()).isNotSameAs(-1); + assertThat(pkg.getFunctionImports().get(0).getEndCharacter()).isNotSameAs(-1); + assertThat(pkg.getFunctionImports().get(1).getTarget()).isEqualTo("qed.wah.*"); + assertThat(pkg.getFunctionImports().get(1).getStartCharacter()).isNotSameAs(-1); + assertThat(pkg.getFunctionImports().get(1).getEndCharacter()).isNotSameAs(-1); + } + + @Test + void fromComplexAccessor() { + String source = "rule \"Invalid customer id\" ruleflow-group \"validate\" lock-on-active true \n" + + " when \n" + + " o: Order( ) \n" + + " not( Customer( ) from customerService.getCustomer(o.getCustomerId()) ) \n" + + " then \n" + + " System.err.println(\"Invalid customer id found!\"); " + + "\n" + + " o.addError(\"Invalid customer id\"); \n" + + "end \n"; + PackageDescr pkg = parseAndGetPackageDescr(source); + + RuleDescr rule = pkg.getRules().get(0); + assertThat(rule.getName()).isEqualTo("Invalid customer id"); + + assertThat(rule.getLhs().getDescrs()).hasSize(2); + + NotDescr not = (NotDescr) rule.getLhs().getDescrs().get(1); + PatternDescr customer = (PatternDescr) not.getDescrs().get(0); + + assertThat(customer.getObjectType()).isEqualTo("Customer"); + assertThat(((FromDescr) customer.getSource()).getDataSource().getText()).isEqualTo("customerService.getCustomer(o.getCustomerId())"); + } + + @Test + void fromWithInlineList() { + String source = "rule XYZ \n" + + " when \n" + + " o: Order( ) \n" + + " not( Number( ) from [1, 2, 3] ) \n" + + " then \n" + + " System.err.println(\"Invalid customer id found!\"); \n" + + " o.addError(\"Invalid customer id\"); \n" + + "end \n"; + PackageDescr pkg = parseAndGetPackageDescr(source); + + RuleDescr rule = pkg.getRules().get(0); + assertThat(rule.getName()).isEqualTo("XYZ"); + + PatternDescr number = (PatternDescr) ((NotDescr) rule.getLhs().getDescrs().get(1)).getDescrs().get(0); + assertThat(((FromDescr) number.getSource()).getDataSource().toString()).isEqualToIgnoringWhitespace("[1, 2, 3]"); + } + + @Test + void fromWithInlineListMethod() { + String source = "rule XYZ \n" + + " when \n" + + " o: Order( ) \n" + + " Number( ) from [1, 2, 3].sublist(1, 2) \n" + + " then \n" + + " System.err.println(\"Invalid customer id found!\"); \n" + + " o.addError(\"Invalid customer id\"); \n" + + "end \n"; + PackageDescr pkg = parseAndGetPackageDescr(source); + + RuleDescr rule = pkg.getRules().get(0); + assertThat(rule.getName()).isEqualTo("XYZ"); + + PatternDescr number = (PatternDescr) rule.getLhs().getDescrs().get(1); + + assertThat(((FromDescr) number.getSource()).getDataSource().toString()).isEqualToIgnoringWhitespace("[1, 2, 3].sublist(1, 2)"); + } + + @Test + void fromWithInlineListIndex() { + String source = "rule XYZ \n" + + " when \n" + + " o: Order( ) \n" + + " Number( ) from [1, 2, 3][1] \n" + + " then \n" + + " System.err.println(\"Invalid customer id found!\"); \n" + + " o.addError(\"Invalid customer id\"); \n" + + "end \n"; + PackageDescr pkg = parseAndGetPackageDescr(source); + + RuleDescr rule = pkg.getRules().get(0); + assertThat(rule.getName()).isEqualTo("XYZ"); + + PatternDescr number = (PatternDescr) rule.getLhs().getDescrs().get(1); + assertThat(((FromDescr) number.getSource()).getDataSource().toString()).isEqualToIgnoringWhitespace("[1, 2, 3][1]"); + } + + @Test + void ruleWithoutEnd() { + String source = "rule \"Invalid customer id\" \n" + + " when \n" + + " o: Order( ) \n" + + " then \n" + + " System.err.println(\"Invalid customer id found!\"); \n"; + parseAndGetPackageDescrWithoutErrorCheck(source); + assertThat(parser.hasErrors()).isTrue(); + } + + @Test + void orWithSpecialBind() { + String source = "rule \"A and (B or C or D)\" \n" + + " when \n" + + " pdo1 : ParametricDataObject( paramID == 101, stringValue == \"1000\" ) and \n" + + " pdo2 :(ParametricDataObject( paramID == 101, stringValue == \"1001\" ) or \n" + + " ParametricDataObject( paramID == 101, stringValue == \"1002\" ) or \n" + + " ParametricDataObject( paramID == 101, stringValue == \"1003\" )) \n" + + " then \n" + + " System.out.println( \"Rule: A and (B or C or D) Fired. pdo1: \" + pdo1 + \" pdo2: \"+ pdo2); \n" + + "end\n"; + PackageDescr pkg = parseAndGetPackageDescr(source); + + RuleDescr rule = pkg.getRules().get(0); + AndDescr lhs = rule.getLhs(); + assertThat(lhs.getDescrs()).hasSize(2); + + PatternDescr pdo1 = (PatternDescr) lhs.getDescrs().get(0); + assertThat(pdo1.getIdentifier()).isEqualTo("pdo1"); + + OrDescr or = (OrDescr) rule.getLhs().getDescrs().get(1); + assertThat(or.getDescrs()).hasSize(3); + for (BaseDescr pdo2 : or.getDescrs()) { + assertThat(((PatternDescr) pdo2).getIdentifier()).isEqualTo("pdo2"); + } + } + + @Test + void compatibleRestriction() { + String source = "package com.sample rule test when Test( ( text == null || text2 matches \"\" ) ) then end"; + PackageDescr pkg = parseAndGetPackageDescr(source); + + assertThat(pkg.getName()).isEqualTo("com.sample"); + RuleDescr rule = pkg.getRules().get(0); + assertThat(rule.getName()).isEqualTo("test"); + ExprConstraintDescr expr = (ExprConstraintDescr) ((PatternDescr) rule.getLhs().getDescrs().get(0)).getDescrs().get(0); + assertThat(expr.getText()).isEqualTo("( text == null || text2 matches \"\" )"); + } + + @Test + void simpleConstraint() { + String source = "package com.sample rule test when Cheese( type == 'stilton', price > 10 ) then end"; + PackageDescr pkg = parseAndGetPackageDescr(source); + + assertThat(pkg.getName()).isEqualTo("com.sample"); + RuleDescr rule = pkg.getRules().get(0); + assertThat(rule.getName()).isEqualTo("test"); + + assertThat(rule.getLhs().getDescrs()).hasSize(1); + PatternDescr pattern = (PatternDescr) rule.getLhs().getDescrs().get(0); + + AndDescr constraint = (AndDescr) pattern.getConstraint(); + assertThat(constraint.getDescrs()).hasSize(2); + assertThat(constraint.getDescrs().get(0)).hasToString("type == \"stilton\""); + assertThat(constraint.getDescrs().get(1)).hasToString("price > 10"); + } + + @Test + void stringEscapes() { + String source = "package com.sample rule test when Cheese( type matches \"\\..*\\\\.\" ) then end"; + PackageDescr pkg = parseAndGetPackageDescr(source); + assertThat(pkg.getName()).isEqualTo("com.sample"); + RuleDescr rule = pkg.getRules().get(0); + assertThat(rule.getName()).isEqualTo("test"); + + assertThat(rule.getLhs().getDescrs()).hasSize(1); + PatternDescr pattern = (PatternDescr) rule.getLhs().getDescrs().get(0); + + AndDescr constraint = (AndDescr) pattern.getConstraint(); + assertThat(constraint.getDescrs()).hasSize(1); + assertThat(constraint.getDescrs().get(0)).hasToString("type matches \"\\..*\\\\.\""); + } + + @Test + void dialectWithSingleQuotation() { + final String source = "dialect 'mvel'"; + PackageDescr pkg = parseAndGetPackageDescr(source); + AttributeDescr attr = pkg.getAttributes().get(0); + assertThat(attr.getName()).isEqualTo("dialect"); + assertThat(attr.getValue()).isEqualTo("mvel"); + } + + @Test + void dialectWithDoubleQuotation() { + final String source = "dialect \"mvel\""; + PackageDescr pkg = parseAndGetPackageDescr(source); + AttributeDescr attr = pkg.getAttributes().get(0); + assertThat(attr.getName()).isEqualTo("dialect"); + assertThat(attr.getValue()).isEqualTo("mvel"); + } + + @Test + void emptyRuleWithoutWhen() { + String source = readResource("empty_rule.drl"); // without WHEN + RuleDescr ruleDescr = parseAndGetFirstRuleDescr(source); + + assertThat(ruleDescr).isNotNull(); + + assertThat(ruleDescr.getName()).isEqualTo("empty"); + assertThat(ruleDescr.getLhs()).isNotNull(); + assertThat(ruleDescr.getConsequence()).isNotNull(); + } + + @Test + void keywordCollisions() { + String source = readResource("eol_funny_business.drl"); // keywords everywhere + + // Note: eol_funny_business.drl is modified from the one under drools-test-coverage to be more realistic. + // e.g. "package" is not allowed in a package value in Java, so it doesn't make sense to test. (Right to raise a parser error) + + PackageDescr pkg = parseAndGetPackageDescr(source); + + assertThat(pkg.getRules()).hasSize(1); + } + + @Test + void ternaryExpression() { + String source = readResource("ternary_expression.drl"); + PackageDescr pkg = parseAndGetPackageDescr(source); + + final RuleDescr rule = pkg.getRules().get(0); + assertThat(pkg.getRules()).hasSize(1); + + assertThat((String) rule.getConsequence()).isEqualToIgnoringWhitespace("if (speed > speedLimit ? true : false;) pullEmOver();"); + } + + @Test + void functionWithArrays() { + String source = readResource("function_arrays.drl"); + + // Note: function_arrays.drl is modified from the one under drools-test-coverage to be more realistic. + // new String[3] {"a","b","c"} is invalid in Java (Cannot define dimension expressions when an array initializer is provided) + // , so it doesn't make sense to test. (Right to raise a parser error) + + PackageDescr pkg = parseAndGetPackageDescr(source); + + assertThat(pkg.getName()).isEqualTo("foo"); + assertThat(pkg.getRules()).hasSize(1); + + final RuleDescr rule = pkg.getRules().get(0); + + assertThat((String) rule.getConsequence()).isEqualToIgnoringWhitespace("yourFunction(new String[] {\"a\",\"b\",\"c\"});"); + + final FunctionDescr func = pkg.getFunctions().get(0); + + assertThat(func.getReturnType()).isEqualTo("String[]"); + assertThat(func.getParameterNames().get(0)).isEqualTo("args[]"); + assertThat(func.getParameterTypes().get(0)).isEqualTo("String"); + } + + @Test + void almostEmptyRule() { + String source = readResource("almost_empty_rule.drl"); + PackageDescr pkg = parseAndGetPackageDescr(source); + + assertThat(pkg).isNotNull(); + + RuleDescr rule = pkg.getRules().get(0); + + assertThat(rule.getName()).isEqualTo("almost_empty"); + assertThat(rule.getLhs()).isNotNull(); + assertThat(((String) rule.getConsequence())).isBlank(); + } + + @Test + void quotedStringNameRule() { + String source = readResource("quoted_string_name_rule.drl"); + PackageDescr pkg = parseAndGetPackageDescr(source); + + RuleDescr rule = pkg.getRules().get(0); + assertThat(rule).isNotNull(); + + assertThat(rule.getName()).isEqualTo("quoted string name"); + assertThat(rule.getLhs()).isNotNull(); + assertThat(((String) rule.getConsequence())).isBlank(); + } + + @Test + void noLoop() { + String source = readResource("no-loop.drl"); + PackageDescr pkg = parseAndGetPackageDescr(source); + + RuleDescr rule = pkg.getRules().get(0); + assertThat(rule).isNotNull(); + + assertThat(rule.getName()).isEqualTo("rule1"); + final AttributeDescr att = rule.getAttributes().get("no-loop"); + assertThat(att.getValue()).isEqualTo("false"); + assertThat(att.getName()).isEqualTo("no-loop"); + } + + @Test + void autofocus() { + String source = readResource("autofocus.drl"); + PackageDescr pkg = parseAndGetPackageDescr(source); + + RuleDescr rule = pkg.getRules().get(0); + assertThat(rule).isNotNull(); + + assertThat(rule.getName()).isEqualTo("rule1"); + final AttributeDescr att = rule.getAttributes().get("auto-focus"); + assertThat(att.getValue()).isEqualTo("true"); + assertThat(att.getName()).isEqualTo("auto-focus"); + } + + @Test + void ruleFlowGroup() { + String source = readResource("ruleflowgroup.drl"); + PackageDescr pkg = parseAndGetPackageDescr(source); + + RuleDescr rule = pkg.getRules().get(0); + assertThat(rule).isNotNull(); + + assertThat(rule.getName()).isEqualTo("rule1"); + final AttributeDescr att = rule.getAttributes().get("ruleflow-group"); + assertThat(att.getValue()).isEqualTo("a group"); + assertThat(att.getName()).isEqualTo("ruleflow-group"); + } + + @Test + void consequenceWithDeclaration() { + String source = readResource("declaration-in-consequence.drl"); + PackageDescr pkg = parseAndGetPackageDescr(source); + + // Note : Removed "i\i;" from the original declaration-in-consequence.drl under drools-test-coverage + // because it's not a valid java expression and doesn't make sense to test. (Right to raise a parser error) + + RuleDescr rule = pkg.getRules().get(0); + assertThat(rule).isNotNull(); + + assertThat(rule.getName()).isEqualTo("myrule"); + + final String expected = "int i = 0; i = 1; i / 1; i == 1; i(i); i = 'i'; i.i.i; ii; i=\"i\"; ++i;" + + "i++; --i; i--; i += i; i -= i; i *= i; i /= i;" + + "int i = 5;" + "for(int j; j 0).isTrue(); + assertThat(((String) rule.getConsequence()).indexOf("--") > 0).isTrue(); + assertThat(((String) rule.getConsequence()).indexOf("+=") > 0).isTrue(); + assertThat(((String) rule.getConsequence()).indexOf("==") > 0).isTrue(); + assertThat(((String) rule.getConsequence()).indexOf("i++") > 0).isTrue(); + // note, need to assert that "i++" is preserved as is, no extra spaces. + } + + @Test + void or() { + final String text = "rule X when Person(age < 42, location==\"atlanta\") \nor\nPerson(name==\"bob\") then end"; + PackageDescr pkg = parseAndGetPackageDescr(text); + RuleDescr rule = pkg.getRules().get(0); + + assertThat(rule).isNotNull(); + + AndDescr lhs = rule.getLhs(); + assertThat(lhs.getDescrs()).hasSize(1); + assertThat(((OrDescr) lhs.getDescrs().get(0)).getDescrs()).hasSize(2); + } + + @Test + void lhsWithStringQuotes() { + final String text = "rule X when Person( location==\"atlanta\\\"\") then end\n"; + PackageDescr pkg = parseAndGetPackageDescr(text); + RuleDescr rule = pkg.getRules().get(0); + + assertThat(rule).isNotNull(); + + AndDescr lhs = rule.getLhs(); + ExprConstraintDescr constr = (ExprConstraintDescr) ((PatternDescr) lhs.getDescrs().get(0)).getDescrs().get(0); + + assertThat(constr.getText()).isEqualToIgnoringWhitespace("location==\"atlanta\\\"\""); + } + + @Test + void lhsWithStringQuotesEscapeChars() { + final String text = "rule X when Cheese( $x: type, type == \"s\\tti\\\"lto\\nn\" ) then end\n"; + PackageDescr pkg = parseAndGetPackageDescr(text); + RuleDescr rule = pkg.getRules().get(0); + + assertThat(rule).isNotNull(); + + AndDescr lhs = rule.getLhs(); + ExprConstraintDescr constr = (ExprConstraintDescr) ((PatternDescr) lhs.getDescrs().get(0)).getDescrs().get(1); + + assertThat(constr.getText()).isEqualToIgnoringWhitespace("type == \"s\\tti\\\"lto\\nn\""); + } + + @Test + void literalBoolAndNegativeNumbersRule() { + RuleDescr rule = parseAndGetFirstRuleDescrFromFile("literal_bool_and_negative.drl"); + + assertThat(rule).isNotNull(); + + assertThat(rule.getName()).isEqualTo("simple_rule"); + assertThat(rule.getLhs()).isNotNull(); + + assertThat((String) rule.getConsequence()).isEqualToIgnoringWhitespace("cons();"); + + final AndDescr lhs = rule.getLhs(); + assertThat(lhs.getDescrs()).hasSize(3); + + PatternDescr pattern = (PatternDescr) lhs.getDescrs().get(0); + assertThat(pattern.getConstraint().getDescrs()).hasSize(1); + AndDescr fieldAnd = (AndDescr) pattern.getConstraint(); + ExprConstraintDescr fld = (ExprConstraintDescr) fieldAnd.getDescrs().get(0); + assertThat(fld.getExpression()).isEqualToIgnoringWhitespace("bar == false"); + + pattern = (PatternDescr) lhs.getDescrs().get(1); + assertThat(pattern.getConstraint().getDescrs()).hasSize(1); + + fieldAnd = (AndDescr) pattern.getConstraint(); + fld = (ExprConstraintDescr) fieldAnd.getDescrs().get(0); + + assertThat(fld.getText()).isEqualToIgnoringWhitespace("boo > -42"); + + pattern = (PatternDescr) lhs.getDescrs().get(2); + assertThat(pattern.getConstraint().getDescrs()).hasSize(1); + + fieldAnd = (AndDescr) pattern.getConstraint(); + fld = (ExprConstraintDescr) fieldAnd.getDescrs().get(0); + + assertThat(fld.getText()).isEqualToIgnoringWhitespace("boo > -42.42"); + } + + @Test + void emptyPattern() { + String source = readResource("test_EmptyPattern.drl"); + PackageDescr pkg = parseAndGetPackageDescr(source); + + assertThat(pkg.getRules()).hasSize(1); + final RuleDescr ruleDescr = pkg.getRules().get(0); + assertThat(ruleDescr.getName()).isEqualTo("simple rule"); + assertThat(ruleDescr.getLhs()).isNotNull(); + assertThat(ruleDescr.getLhs().getDescrs()).hasSize(1); + final PatternDescr patternDescr = (PatternDescr) ruleDescr.getLhs().getDescrs().get(0); + assertThat(patternDescr.getConstraint().getDescrs()).isEmpty(); // this + assertThat(patternDescr.getObjectType()).isEqualTo("Cheese"); + } + + @Test + void simpleMethodCallWithFrom() { + RuleDescr rule = parseAndGetFirstRuleDescrFromFile("test_SimpleMethodCallWithFrom.drl"); + final PatternDescr pattern = (PatternDescr) rule.getLhs().getDescrs().get(0); + final FromDescr from = (FromDescr) pattern.getSource(); + final MVELExprDescr method = (MVELExprDescr) from.getDataSource(); + + assertThat(method.getExpression()).isEqualToIgnoringWhitespace("something.doIt( foo,bar,42,\"hello\",[ a : \"b\", \"something\" : 42, \"a\" : foo, x : [x:y]],\"end\", [a, \"b\", 42] )"); + } + + @Test + void simpleFunctionCallWithFrom() { + RuleDescr rule = parseAndGetFirstRuleDescrFromFile("test_SimpleFunctionCallWithFrom.drl"); + final PatternDescr pattern = (PatternDescr) rule.getLhs().getDescrs().get(0); + final FromDescr from = (FromDescr) pattern.getSource(); + final MVELExprDescr func = (MVELExprDescr) from.getDataSource(); + + assertThat(func.getExpression()).isEqualToIgnoringWhitespace("doIt( foo,bar,42,\"hello\",[ a : \"b\", \"something\" : 42, \"a\" : foo, x : [x:y]],\"end\", [a, \"b\", 42] )"); + } + + @Test + void simpleAccessorWithFrom() { + RuleDescr rule = parseAndGetFirstRuleDescrFromFile("test_SimpleAccessorWithFrom.drl"); + final PatternDescr pattern = (PatternDescr) rule.getLhs().getDescrs().get(0); + final FromDescr from = (FromDescr) pattern.getSource(); + final MVELExprDescr accessor = (MVELExprDescr) from.getDataSource(); + + assertThat(accessor.getExpression()).isEqualTo("something.doIt"); + } + + @Test + void simpleAccessorAndArgWithFrom() { + RuleDescr rule = parseAndGetFirstRuleDescrFromFile("test_SimpleAccessorArgWithFrom.drl"); + final PatternDescr pattern = (PatternDescr) rule.getLhs().getDescrs().get(0); + final FromDescr from = (FromDescr) pattern.getSource(); + final MVELExprDescr accessor = (MVELExprDescr) from.getDataSource(); + + assertThat(accessor.getExpression()).isEqualTo("something.doIt[\"key\"]"); + } + + @Test + void complexChainedAccessor() { + RuleDescr rule = parseAndGetFirstRuleDescrFromFile("test_ComplexChainedCallWithFrom.drl"); + + final PatternDescr pattern = (PatternDescr) rule.getLhs().getDescrs().get(0); + final FromDescr from = (FromDescr) pattern.getSource(); + final MVELExprDescr accessor = (MVELExprDescr) from.getDataSource(); + + assertThat(accessor.getExpression()).isEqualToIgnoringWhitespace("doIt1( foo,bar,42,\"hello\",[ a : \"b\"], [a, \"b\", 42] ).doIt2(bar, [a, \"b\", 42]).field[\"key\"]"); + } + + @Test + void from() { + RuleDescr rule = parseAndGetFirstRuleDescrFromFile("from.drl"); + assertThat(rule).isNotNull(); + + assertThat(rule.getName()).isEqualTo("using_from"); + + assertThat(rule.getLhs().getDescrs()).hasSize(9); + } + + @Test + void simpleRuleWithBindings() { + RuleDescr rule = parseAndGetFirstRuleDescrFromFile("simple_rule.drl"); + assertThat(rule).isNotNull(); + + assertThat(rule.getName()).isEqualTo("simple_rule"); + + assertThat(rule.getStartCharacter()).isEqualTo(803); + assertThat(rule.getEndCharacter()).isEqualTo(996); + + assertThat(rule.getConsequenceLine()).isEqualTo(22); + assertThat(rule.getConsequencePattern()).isEqualTo(2); + + final AndDescr lhs = rule.getLhs(); + + assertThat(lhs).isNotNull(); + + assertThat(lhs.getDescrs()).hasSize(3); + + // Check first pattern + final PatternDescr first = (PatternDescr) lhs.getDescrs().get(0); + assertThat(first.getIdentifier()).isEqualTo("foo3"); + assertThat(first.getObjectType()).isEqualTo("Bar"); + + assertThat(first.getConstraint().getDescrs()).hasSize(1); + + AndDescr fieldAnd = (AndDescr) first.getConstraint(); + ExprConstraintDescr constraint = (ExprConstraintDescr) fieldAnd.getDescrs().get(0); + assertThat(constraint).isNotNull(); + + assertThat(constraint.getExpression()).isEqualToIgnoringWhitespace("a==3"); + + // Check second pattern + final PatternDescr second = (PatternDescr) lhs.getDescrs().get(1); + assertThat(second.getIdentifier()).isEqualTo("foo4"); + assertThat(second.getObjectType()).isEqualTo("Bar"); + + // no constraints, only a binding + fieldAnd = (AndDescr) second.getConstraint(); + assertThat(fieldAnd.getDescrs()).hasSize(1); + + final ExprConstraintDescr binding = (ExprConstraintDescr) second.getConstraint().getDescrs().get(0); + assertThat(binding.getExpression()).isEqualToIgnoringWhitespace("a4:a==4"); + + // Check third pattern + final PatternDescr third = (PatternDescr) lhs.getDescrs().get(2); + assertThat(third.getIdentifier()).isNull(); + assertThat(third.getObjectType()).isEqualTo("Baz"); + + assertThat((String) rule.getConsequence()).isEqualToIgnoringWhitespace("if ( a == b ) { " + " assert( foo3 );" + "} else {" + " retract( foo4 );" + "}" + " System.out.println( a4 );"); + } + + @Test + void multipleRestrictionsConstraint() { + RuleDescr rule = parseAndGetFirstRuleDescrFromFile("restrictions_test.drl"); + assertThat(rule).isNotNull(); + + assertThat((String) rule.getConsequence()).isEqualToIgnoringWhitespace("consequence();"); + assertThat(rule.getName()).isEqualTo("simple_rule"); + assertThat(rule.getLhs().getDescrs()).hasSize(2); + + // The first pattern, with 2 restrictions on a single field (plus a + // connective) + PatternDescr pattern = (PatternDescr) rule.getLhs().getDescrs().get(0); + assertThat(pattern.getObjectType()).isEqualTo("Person"); + assertThat(pattern.getConstraint().getDescrs()).hasSize(1); + + AndDescr and = (AndDescr) pattern.getConstraint(); + ExprConstraintDescr fld = (ExprConstraintDescr) and.getDescrs().get(0); + assertThat(fld.getExpression()).isEqualTo("age > 30 && < 40"); + + // the second col, with 2 fields, the first with 2 restrictions, the + // second field with one + pattern = (PatternDescr) rule.getLhs().getDescrs().get(1); + assertThat(pattern.getObjectType()).isEqualTo("Vehicle"); + assertThat(pattern.getConstraint().getDescrs()).hasSize(2); + + and = (AndDescr) pattern.getConstraint(); + fld = (ExprConstraintDescr) and.getDescrs().get(0); + assertThat(fld.getExpression()).isEqualToIgnoringWhitespace("type == \"sedan\" || == \"wagon\""); + + // now the second field + fld = (ExprConstraintDescr) and.getDescrs().get(1); + assertThat(fld.getExpression()).isEqualToIgnoringWhitespace("age < 3"); + } + + @Test + void lineNumberInAST() { + // also see testSimpleExpander to see how this works with an expander + // (should be the same). + + final RuleDescr rule = parseAndGetFirstRuleDescrFromFile( + "simple_rule.drl"); + + assertThat(rule).isNotNull(); + + assertThat(rule.getName()).isEqualTo("simple_rule"); + + assertThat(rule.getConsequenceLine()).isEqualTo(22); + assertThat(rule.getConsequencePattern()).isEqualTo(2); + + final AndDescr lhs = rule.getLhs(); + + assertThat(lhs).isNotNull(); + + assertThat(lhs.getDescrs()).hasSize(3); + + // Check first pattern + final PatternDescr first = (PatternDescr) lhs.getDescrs().get(0); + assertThat(first.getIdentifier()).isEqualTo("foo3"); + assertThat(first.getObjectType()).isEqualTo("Bar"); + assertThat(first.getConstraint().getDescrs()).hasSize(1); + + // Check second pattern + final PatternDescr second = (PatternDescr) lhs.getDescrs().get(1); + assertThat(second.getIdentifier()).isEqualTo("foo4"); + assertThat(second.getObjectType()).isEqualTo("Bar"); + + final PatternDescr third = (PatternDescr) lhs.getDescrs().get(2); + assertThat(third.getObjectType()).isEqualTo("Baz"); + + assertThat(first.getLine()).isEqualTo(19); + assertThat(second.getLine()).isEqualTo(20); + assertThat(third.getLine()).isEqualTo(21); + } + + @Test + void lineNumberIncludingCommentsInRHS() { + PackageDescr pkg = parseAndGetPackageDescrFromFile( + "test_CommentLineNumbersInConsequence.drl"); + + final String rhs = (String) ((RuleDescr) pkg.getRules().get(0)).getConsequence(); + String expected = "\\s*//woot$\\s*first;$\\s*$\\s*//$\\s*$\\s*/\\* lala$\\s*$\\s*\\*/$\\s*second;$\\s*"; + assertThat(Pattern.compile(expected, + Pattern.DOTALL | Pattern.MULTILINE).matcher(rhs).matches()).isTrue(); + } + + @Test + void lhsSemicolonDelim() { + final RuleDescr rule = parseAndGetFirstRuleDescrFromFile( + "lhs_semicolon_delim.drl"); + + assertThat(rule).isNotNull(); + + assertThat(rule.getName()).isEqualTo("simple_rule"); + + final AndDescr lhs = rule.getLhs(); + + assertThat(lhs).isNotNull(); + + assertThat(lhs.getDescrs()).hasSize(3); + + // System.err.println( lhs.getDescrs() ); + + // Check first pattern + final PatternDescr first = (PatternDescr) lhs.getDescrs().get(0); + assertThat(first.getIdentifier()).isEqualTo("foo3"); + assertThat(first.getObjectType()).isEqualTo("Bar"); + + assertThat(first.getConstraint().getDescrs()).hasSize(1); + + // LiteralDescr constraint = (LiteralDescr) first.getDescrs().get( 0 ); + AndDescr and = (AndDescr) first.getConstraint(); + ExprConstraintDescr fld = (ExprConstraintDescr) and.getDescrs().get(0); + assertThat(fld).isNotNull(); + + assertThat(fld.getExpression()).isEqualTo("a==3"); + + // Check second pattern + final PatternDescr second = (PatternDescr) lhs.getDescrs().get(1); + assertThat(second.getIdentifier()).isEqualTo("foo4"); + assertThat(second.getObjectType()).isEqualTo("Bar"); + + assertThat(second.getDescrs()).hasSize(1); + + final ExprConstraintDescr fieldBindingDescr = (ExprConstraintDescr) second.getDescrs().get(0); + assertThat(fieldBindingDescr.getExpression()).isEqualTo("a4:a==4"); + + // Check third pattern + final PatternDescr third = (PatternDescr) lhs.getDescrs().get(2); + assertThat(third.getIdentifier()).isNull(); + assertThat(third.getObjectType()).isEqualTo("Baz"); + + assertThat((String) rule.getConsequence()).isEqualToIgnoringWhitespace("if ( a == b ) { " + " assert( foo3 );" + "} else {" + " retract( foo4 );" + "}" + " System.out.println( a4 );"); + } + + @Test + void notNode() { + final RuleDescr rule = parseAndGetFirstRuleDescrFromFile( + "rule_not.drl"); + + assertThat(rule).isNotNull(); + assertThat(rule.getName()).isEqualTo("simple_rule"); + + final AndDescr lhs = rule.getLhs(); + assertThat(lhs.getDescrs()).hasSize(1); + final NotDescr not = (NotDescr) lhs.getDescrs().get(0); + assertThat(not.getDescrs()).hasSize(1); + final PatternDescr pattern = (PatternDescr) not.getDescrs().get(0); + + assertThat(pattern.getObjectType()).isEqualTo("Cheese"); + assertThat(pattern.getConstraint().getDescrs()).hasSize(1); + + final AndDescr and = (AndDescr) pattern.getConstraint(); + final ExprConstraintDescr fld = (ExprConstraintDescr) and.getDescrs().get(0); + + assertThat(fld.getExpression()).isEqualTo("type == \"stilton\""); + } + + @Test + void notExistWithBrackets() { + + final PackageDescr pkg = parseAndGetPackageDescrFromFile( + "not_exist_with_brackets.drl"); + + final RuleDescr rule = (RuleDescr) pkg.getRules().get(0); + + assertThat(rule).isNotNull(); + assertThat(rule.getName()).isEqualTo("simple_rule"); + + final AndDescr lhs = rule.getLhs(); + assertThat(lhs.getDescrs()).hasSize(2); + final NotDescr not = (NotDescr) lhs.getDescrs().get(0); + assertThat(not.getDescrs()).hasSize(1); + final PatternDescr pattern = (PatternDescr) not.getDescrs().get(0); + + assertThat(pattern.getObjectType()).isEqualTo("Cheese"); + + final ExistsDescr ex = (ExistsDescr) lhs.getDescrs().get(1); + assertThat(ex.getDescrs()).hasSize(1); + final PatternDescr exPattern = (PatternDescr) ex.getDescrs().get(0); + assertThat(exPattern.getObjectType()).isEqualTo("Foo"); + } + + @Test + void simpleQuery() { + final QueryDescr query = parseAndGetFirstQueryDescrFromFile( + "simple_query.drl"); + + assertThat(query).isNotNull(); + + assertThat(query.getName()).isEqualTo("simple_query"); + + final AndDescr lhs = query.getLhs(); + + assertThat(lhs).isNotNull(); + + assertThat(lhs.getDescrs()).hasSize(3); + + // Check first pattern + final PatternDescr first = (PatternDescr) lhs.getDescrs().get(0); + assertThat(first.getIdentifier()).isEqualTo("foo3"); + assertThat(first.getObjectType()).isEqualTo("Bar"); + + assertThat(first.getConstraint().getDescrs()).hasSize(1); + + AndDescr and = (AndDescr) first.getConstraint(); + ExprConstraintDescr fld = (ExprConstraintDescr) and.getDescrs().get(0); + assertThat(fld).isNotNull(); + + assertThat(fld.getExpression()).isEqualTo("a==3"); + + // Check second pattern + final PatternDescr second = (PatternDescr) lhs.getDescrs().get(1); + assertThat(second.getIdentifier()).isEqualTo("foo4"); + assertThat(second.getObjectType()).isEqualTo("Bar"); + + assertThat(second.getDescrs()).hasSize(1); + // check it has field bindings. + final ExprConstraintDescr bindingDescr = (ExprConstraintDescr) second.getDescrs().get(0); + assertThat(bindingDescr.getExpression()).isEqualTo("a4:a==4"); + } + + @Test + void queryRuleMixed() { + final PackageDescr pkg = parseAndGetPackageDescrFromFile( + "query_and_rule.drl"); + + assertThat(pkg.getRules()).hasSize(4); // as queries are rules + RuleDescr rule = (RuleDescr) pkg.getRules().get(0); + assertThat(rule.getName()).isEqualTo("bar"); + + QueryDescr query = (QueryDescr) pkg.getRules().get(1); + assertThat(query.getName()).isEqualTo("simple_query"); + + rule = (RuleDescr) pkg.getRules().get(2); + assertThat(rule.getName()).isEqualTo("bar2"); + + query = (QueryDescr) pkg.getRules().get(3); + assertThat(query.getName()).isEqualTo("simple_query2"); + } + + @Test + void multipleRules() { + final PackageDescr pkg = parseAndGetPackageDescrFromFile( + "multiple_rules.drl"); + + final List rules = pkg.getRules(); + + assertThat(rules).hasSize(2); + + final RuleDescr rule0 = rules.get(0); + assertThat(rule0.getName()).isEqualTo("Like Stilton"); + + final RuleDescr rule1 = rules.get(1); + assertThat(rule1.getName()).isEqualTo("Like Cheddar"); + + // checkout the first rule + AndDescr lhs = rule1.getLhs(); + assertThat(lhs).isNotNull(); + assertThat(lhs.getDescrs()).hasSize(1); + assertThat((String) rule0.getConsequence()).isEqualToIgnoringWhitespace("System.out.println(\"I like \" + t);"); + + // Check first pattern + PatternDescr first = (PatternDescr) lhs.getDescrs().get(0); + assertThat(first.getObjectType()).isEqualTo("Cheese"); + + // checkout the second rule + lhs = rule1.getLhs(); + assertThat(lhs).isNotNull(); + assertThat(lhs.getDescrs()).hasSize(1); + assertThat((String) rule1.getConsequence()).isEqualToIgnoringWhitespace("System.out.println(\"I like \" + t);"); + + // Check first pattern + first = (PatternDescr) lhs.getDescrs().get(0); + assertThat(first.getObjectType()).isEqualTo("Cheese"); + } + + @Test + void expanderLineSpread() { + final PackageDescr pkg = parseAndGetPackageDescrWithDsl("expander_spread_lines.dslr", "complex.dsl"); + + final RuleDescr rule = pkg.getRules().get(0); + assertThat(rule.getLhs().getDescrs()).hasSize(1); + + final OrDescr or = (OrDescr) rule.getLhs().getDescrs().get(0); + assertThat(or.getDescrs()).hasSize(2); + assertThat((String) rule.getConsequence()).isNotNull(); + } + + @Test + void expanderMultipleConstraints() { + final PackageDescr pkg = parseAndGetPackageDescrWithDsl("expander_multiple_constraints.dslr", "multiple_constraints.dsl"); + + final RuleDescr rule = pkg.getRules().get(0); + assertThat(rule.getLhs().getDescrs()).hasSize(2); + + PatternDescr pattern = (PatternDescr) rule.getLhs().getDescrs().get(0); + assertThat(pattern.getObjectType()).isEqualTo("Person"); + + assertThat(pattern.getConstraint().getDescrs()).hasSize(2); + assertThat(((ExprConstraintDescr) pattern.getConstraint().getDescrs().get(0)).getExpression()).isEqualTo("age < 42"); + assertThat(((ExprConstraintDescr) pattern.getConstraint().getDescrs().get(1)).getExpression()).isEqualTo("location==atlanta"); + + pattern = (PatternDescr) rule.getLhs().getDescrs().get(1); + assertThat(pattern.getObjectType()).isEqualTo("Bar"); + + assertThat((String) rule.getConsequence()).isNotNull(); + } + + @Test + void expanderMultipleConstraintsFlush() { + // this is similar to the other test, but it requires a flush to add the + // constraints + final PackageDescr pkg = parseAndGetPackageDescrWithDsl("expander_multiple_constraints_flush.dslr", "multiple_constraints.dsl"); + + final RuleDescr rule = pkg.getRules().get(0); + assertThat(rule.getLhs().getDescrs()).hasSize(1); + + final PatternDescr pattern = (PatternDescr) rule.getLhs().getDescrs().get(0); + assertThat(pattern.getObjectType()).isEqualTo("Person"); + + assertThat(pattern.getConstraint().getDescrs()).hasSize(2); + assertThat(((ExprConstraintDescr) pattern.getConstraint().getDescrs().get(0)).getExpression()).isEqualTo("age < 42"); + assertThat(((ExprConstraintDescr) pattern.getConstraint().getDescrs().get(1)).getExpression()).isEqualTo("location==atlanta"); + + assertThat((String) rule.getConsequence()).isNotNull(); + } + + @Test + void basicBinding() { + final PackageDescr pkg = parseAndGetPackageDescrFromFile( + "basic_binding.drl"); + + final RuleDescr ruleDescr = (RuleDescr) pkg.getRules().get(0); + + final AndDescr lhs = ruleDescr.getLhs(); + assertThat(lhs.getDescrs()).hasSize(1); + final PatternDescr cheese = (PatternDescr) lhs.getDescrs().get(0); + assertThat(cheese.getObjectType()).isEqualTo("Cheese"); + assertThat(cheese.getConstraint().getDescrs()).hasSize(1); + final ExprConstraintDescr fieldBinding = (ExprConstraintDescr) cheese.getDescrs().get(0); + assertThat(fieldBinding.getExpression()).isEqualToIgnoringWhitespace("$type:type"); + } + + @Test + void boundVariables() { + final PackageDescr pkg = parseAndGetPackageDescrFromFile( + "bindings.drl"); + + final RuleDescr ruleDescr = (RuleDescr) pkg.getRules().get(0); + + final AndDescr lhs = ruleDescr.getLhs(); + assertThat(lhs.getDescrs()).hasSize(2); + final PatternDescr cheese = (PatternDescr) lhs.getDescrs().get(0); + assertThat(cheese.getObjectType()).isEqualTo("Cheese"); + assertThat(cheese.getDescrs()).hasSize(1); + ExprConstraintDescr fieldBinding = (ExprConstraintDescr) cheese.getDescrs().get(0); + assertThat(fieldBinding.getExpression()).isEqualTo("$type : type == \"stilton\""); + + final PatternDescr person = (PatternDescr) lhs.getDescrs().get(1); + assertThat(person.getDescrs()).hasSize(2); + fieldBinding = (ExprConstraintDescr) person.getDescrs().get(0); + assertThat(fieldBinding.getExpression()).isEqualTo("$name : name == \"bob\""); + + ExprConstraintDescr fld = (ExprConstraintDescr) person.getDescrs().get(1); + assertThat(fld.getExpression()).isEqualTo("likes == $type"); + } + + @Test + void orNesting() { + final PackageDescr pkg = parseAndGetPackageDescrFromFile( + "or_nesting.drl"); + + assertThat(pkg).isNotNull(); + assertThat(pkg.getRules()).hasSize(1); + final RuleDescr rule = (RuleDescr) pkg.getRules().get(0); + assertThat(rule.getName()).isEqualTo("simple_rule"); + + assertThat(rule.getLhs().getDescrs()).hasSize(1); + + final OrDescr or = (OrDescr) rule.getLhs().getDescrs().get(0); + assertThat(or.getDescrs()).hasSize(2); + + final PatternDescr first = (PatternDescr) or.getDescrs().get(0); + assertThat(first.getObjectType()).isEqualTo("Person"); + + final AndDescr and = (AndDescr) or.getDescrs().get(1); + assertThat(and.getDescrs()).hasSize(2); + + final PatternDescr left = (PatternDescr) and.getDescrs().get(0); + assertThat(left.getObjectType()).isEqualTo("Person"); + + final PatternDescr right = (PatternDescr) and.getDescrs().get(1); + assertThat(right.getObjectType()).isEqualTo("Cheese"); + } + + /** + * Test that explicit "&&", "||" works as expected + */ + @Test + void andOrRules() { + final PackageDescr pkg = parseAndGetPackageDescrFromFile( + "and_or_rule.drl"); + + assertThat(pkg).isNotNull(); + assertThat(pkg.getRules()).hasSize(1); + final RuleDescr rule = (RuleDescr) pkg.getRules().get(0); + assertThat(rule.getName()).isEqualTo("simple_rule"); + + // we will have 3 children under the main And node + final AndDescr and = rule.getLhs(); + assertThat(and.getDescrs()).hasSize(3); + + PatternDescr left = (PatternDescr) and.getDescrs().get(0); + PatternDescr right = (PatternDescr) and.getDescrs().get(1); + assertThat(left.getObjectType()).isEqualTo("Person"); + assertThat(right.getObjectType()).isEqualTo("Cheese"); + + assertThat(left.getConstraint().getDescrs()).hasSize(1); + + ExprConstraintDescr fld = (ExprConstraintDescr) left.getConstraint().getDescrs().get(0); + + assertThat(fld.getExpression()).isEqualTo("name == \"mark\""); + + assertThat(right.getConstraint().getDescrs()).hasSize(1); + + fld = (ExprConstraintDescr) right.getConstraint().getDescrs().get(0); + + assertThat(fld.getExpression()).isEqualTo("type == \"stilton\""); + + // now the "||" part + final OrDescr or = (OrDescr) and.getDescrs().get(2); + assertThat(or.getDescrs()).hasSize(2); + left = (PatternDescr) or.getDescrs().get(0); + right = (PatternDescr) or.getDescrs().get(1); + assertThat(left.getObjectType()).isEqualTo("Person"); + assertThat(right.getObjectType()).isEqualTo("Cheese"); + assertThat(left.getConstraint().getDescrs()).hasSize(1); + + fld = (ExprConstraintDescr) left.getConstraint().getDescrs().get(0); + + assertThat(fld.getExpression()).isEqualTo("name == \"mark\""); + + assertThat(right.getConstraint().getDescrs()).hasSize(1); + + fld = (ExprConstraintDescr) right.getConstraint().getDescrs().get(0); + + assertThat(fld.getExpression()).isEqualTo("type == \"stilton\""); + + assertThat((String) rule.getConsequence()).isEqualToIgnoringWhitespace("System.out.println( \"Mark and Michael\" );"); + } + + /** + * test basic foo : Fact() || Fact() stuff + */ + @Test + void orWithBinding() { + final PackageDescr pkg = parseAndGetPackageDescrFromFile( + "or_binding.drl"); + + assertThat(pkg.getRules()).hasSize(1); + final RuleDescr rule = (RuleDescr) pkg.getRules().get(0); + assertThat(rule.getLhs().getDescrs()).hasSize(2); + + final OrDescr or = (OrDescr) rule.getLhs().getDescrs().get(0); + assertThat(or.getDescrs()).hasSize(2); + + final PatternDescr leftPattern = (PatternDescr) or.getDescrs().get(0); + assertThat(leftPattern.getObjectType()).isEqualTo("Person"); + assertThat(leftPattern.getIdentifier()).isEqualTo("foo"); + + final PatternDescr rightPattern = (PatternDescr) or.getDescrs().get(1); + assertThat(rightPattern.getObjectType()).isEqualTo("Person"); + assertThat(rightPattern.getIdentifier()).isEqualTo("foo"); + + final PatternDescr cheeseDescr = (PatternDescr) rule.getLhs().getDescrs().get(1); + assertThat(cheeseDescr.getObjectType()).isEqualTo("Cheese"); + assertThat(cheeseDescr.getIdentifier()).isEqualTo(null); + + assertThat((String) rule.getConsequence()).isEqualToIgnoringWhitespace("System.out.println( \"Mark and Michael\" + bar );"); + } + + /** + * test basic foo : Fact() || Fact() stuff binding to an "or" + */ + @Test + void orBindingComplex() { + final PackageDescr pkg = parseAndGetPackageDescrFromFile( + "or_binding_complex.drl"); + + assertThat(pkg.getRules()).hasSize(1); + final RuleDescr rule = (RuleDescr) pkg.getRules().get(0); + assertThat(rule.getLhs().getDescrs()).hasSize(1); + + assertThat(rule.getLhs().getDescrs()).hasSize(1); + + final OrDescr or = (OrDescr) rule.getLhs().getDescrs().get(0); + assertThat(or.getDescrs()).hasSize(2); + + // first fact + final PatternDescr firstFact = (PatternDescr) or.getDescrs().get(0); + assertThat(firstFact.getObjectType()).isEqualTo("Person"); + assertThat(firstFact.getIdentifier()).isEqualTo("foo"); + + // second "option" + final PatternDescr secondFact = (PatternDescr) or.getDescrs().get(1); + assertThat(secondFact.getObjectType()).isEqualTo("Person"); + assertThat(secondFact.getConstraint().getDescrs()).hasSize(1); + assertThat(secondFact.getIdentifier()).isEqualTo("foo"); + + assertThat((String) rule.getConsequence()).isEqualToIgnoringWhitespace("System.out.println( \"Mark and Michael\" + bar );"); + } + + @Test + void orBindingWithBrackets() { + final PackageDescr pkg = parseAndGetPackageDescrFromFile( + "or_binding_with_brackets.drl"); + + assertThat(pkg.getRules()).hasSize(1); + final RuleDescr rule = (RuleDescr) pkg.getRules().get(0); + assertThat(rule.getLhs().getDescrs()).hasSize(1); + + assertThat(rule.getLhs().getDescrs()).hasSize(1); + + final OrDescr or = (OrDescr) rule.getLhs().getDescrs().get(0); + assertThat(or.getDescrs()).hasSize(2); + + // first fact + final PatternDescr firstFact = (PatternDescr) or.getDescrs().get(0); + assertThat(firstFact.getObjectType()).isEqualTo("Person"); + assertThat(firstFact.getIdentifier()).isEqualTo("foo"); + + // second "option" + final PatternDescr secondFact = (PatternDescr) or.getDescrs().get(0); + assertThat(secondFact.getObjectType()).isEqualTo("Person"); + assertThat(secondFact.getIdentifier()).isEqualTo("foo"); + + assertThat((String) rule.getConsequence()).isEqualToIgnoringWhitespace("System.out.println( \"Mark and Michael\" + bar );"); + } + + @Test + void parenthesesOrAndOr() { + final PackageDescr pkg = parseAndGetPackageDescrFromFile( + "brackets_precedence.drl"); + + assertThat(pkg.getRules()).hasSize(1); + final RuleDescr rule = (RuleDescr) pkg.getRules().get(0); + + final AndDescr rootAnd = (AndDescr) rule.getLhs(); + + assertThat(rootAnd.getDescrs()).hasSize(2); + + final OrDescr leftOr = (OrDescr) rootAnd.getDescrs().get(0); + + assertThat(leftOr.getDescrs()).hasSize(2); + final NotDescr not = (NotDescr) leftOr.getDescrs().get(0); + final PatternDescr foo1 = (PatternDescr) not.getDescrs().get(0); + assertThat(foo1.getObjectType()).isEqualTo("Foo"); + final PatternDescr foo2 = (PatternDescr) leftOr.getDescrs().get(1); + assertThat(foo2.getObjectType()).isEqualTo("Foo"); + + final OrDescr rightOr = (OrDescr) rootAnd.getDescrs().get(1); + + assertThat(rightOr.getDescrs()).hasSize(2); + final PatternDescr shoes = (PatternDescr) rightOr.getDescrs().get(0); + assertThat(shoes.getObjectType()).isEqualTo("Shoes"); + final PatternDescr butt = (PatternDescr) rightOr.getDescrs().get(1); + assertThat(butt.getObjectType()).isEqualTo("Butt"); + } + + @Test + void parenthesesAndOrOr() { + final String drl = "rule and_or_or\n" + + " when\n" + + " (Foo(x == 1) and Bar(x == 2)) or (Foo(x == 3) or Bar(x == 4))\n" + + " then\n" + + "end"; + PackageDescr pkg = parseAndGetPackageDescr(drl); + + assertThat(pkg.getRules()).hasSize(1); + final RuleDescr rule = (RuleDescr) pkg.getRules().get(0); + final AndDescr rootAnd = (AndDescr) rule.getLhs(); + assertThat(rootAnd.getDescrs()).hasSize(1); + + final OrDescr topOr = (OrDescr) rootAnd.getDescrs().get(0); + assertThat(topOr.getDescrs()).hasSize(2); + + final AndDescr leftAnd = (AndDescr) topOr.getDescrs().get(0); + assertThat(leftAnd.getDescrs()).hasSize(2); + final PatternDescr foo1 = (PatternDescr) leftAnd.getDescrs().get(0); + assertThat(foo1.getObjectType()).isEqualTo("Foo"); + final PatternDescr bar1 = (PatternDescr) leftAnd.getDescrs().get(1); + assertThat(bar1.getObjectType()).isEqualTo("Bar"); + + final OrDescr rightOr = (OrDescr) topOr.getDescrs().get(1); + assertThat(rightOr.getDescrs()).hasSize(2); + final PatternDescr foo2 = (PatternDescr) rightOr.getDescrs().get(0); + assertThat(foo2.getObjectType()).isEqualTo("Foo"); + final PatternDescr bar2 = (PatternDescr) rightOr.getDescrs().get(1); + assertThat(bar2.getObjectType()).isEqualTo("Bar"); + } + + @Test + void parenthesesOrAndAnd() { + final String drl = "rule or_and_and\n" + + " when\n" + + " (Foo(x == 1) or Bar(x == 2)) and (Foo(x == 3) and Bar(x == 4))\n" + + " then\n" + + "end"; + PackageDescr pkg = parseAndGetPackageDescr(drl); + + assertThat(pkg.getRules()).hasSize(1); + final RuleDescr rule = (RuleDescr) pkg.getRules().get(0); + final AndDescr rootAnd = (AndDescr) rule.getLhs(); + assertThat(rootAnd.getDescrs()).hasSize(2); + + final OrDescr leftOr = (OrDescr) rootAnd.getDescrs().get(0); + assertThat(leftOr.getDescrs()).hasSize(2); + final PatternDescr foo1 = (PatternDescr) leftOr.getDescrs().get(0); + assertThat(foo1.getObjectType()).isEqualTo("Foo"); + final PatternDescr bar1 = (PatternDescr) leftOr.getDescrs().get(1); + assertThat(bar1.getObjectType()).isEqualTo("Bar"); + + final AndDescr rightAnd = (AndDescr) rootAnd.getDescrs().get(1); + assertThat(rightAnd.getDescrs()).hasSize(2); + final PatternDescr foo2 = (PatternDescr) rightAnd.getDescrs().get(0); + assertThat(foo2.getObjectType()).isEqualTo("Foo"); + final PatternDescr bar2 = (PatternDescr) rightAnd.getDescrs().get(1); + assertThat(bar2.getObjectType()).isEqualTo("Bar"); + } + + @Test + void multipleLevelNestAndOrOrOrAnd() { + final String drl = "rule and_or_or_or_and\n" + + " when\n" + + " (Foo(x == 1) and (Bar(x == 2) or Foo(x == 3))) or (Bar(x == 4) or (Foo(x == 5) and Bar(x == 6)))\n" + + " then\n" + + "end"; + PackageDescr pkg = parseAndGetPackageDescr(drl); + + assertThat(pkg.getRules()).hasSize(1); + final RuleDescr rule = (RuleDescr) pkg.getRules().get(0); + final AndDescr rootAnd = (AndDescr) rule.getLhs(); + assertThat(rootAnd.getDescrs()).hasSize(1); + + final OrDescr topOr = (OrDescr) rootAnd.getDescrs().get(0); + assertThat(topOr.getDescrs()).hasSize(2); + + final AndDescr leftAnd = (AndDescr) topOr.getDescrs().get(0); + assertThat(leftAnd.getDescrs()).hasSize(2); + final PatternDescr foo1 = (PatternDescr) leftAnd.getDescrs().get(0); + assertThat(foo1.getObjectType()).isEqualTo("Foo"); + final OrDescr leftOr = (OrDescr) leftAnd.getDescrs().get(1); + assertThat(leftOr.getDescrs()).hasSize(2); + final PatternDescr bar1 = (PatternDescr) leftOr.getDescrs().get(0); + assertThat(bar1.getObjectType()).isEqualTo("Bar"); + final PatternDescr foo2 = (PatternDescr) leftOr.getDescrs().get(1); + assertThat(foo2.getObjectType()).isEqualTo("Foo"); + + final OrDescr rightOr = (OrDescr) topOr.getDescrs().get(1); + assertThat(rightOr.getDescrs()).hasSize(2); + final PatternDescr bar2 = (PatternDescr) rightOr.getDescrs().get(0); + assertThat(bar2.getObjectType()).isEqualTo("Bar"); + final AndDescr rightAnd = (AndDescr) rightOr.getDescrs().get(1); + assertThat(rightAnd.getDescrs()).hasSize(2); + final PatternDescr foo3 = (PatternDescr) rightAnd.getDescrs().get(0); + assertThat(foo3.getObjectType()).isEqualTo("Foo"); + final PatternDescr bar3 = (PatternDescr) rightAnd.getDescrs().get(1); + assertThat(bar3.getObjectType()).isEqualTo("Bar"); + } + + @Test + void multipleLevelNestWithThreeOrSiblings() { + final String drl = "rule nest_or_siblings\n" + + " when\n" + + " (A() or (B() or C() or (D() and E())))\n" + + " then\n" + + "end"; + PackageDescr pkg = parseAndGetPackageDescr(drl); + + assertThat(pkg.getRules()).hasSize(1); + final RuleDescr rule = (RuleDescr) pkg.getRules().get(0); + final AndDescr rootAnd = (AndDescr) rule.getLhs(); + assertThat(rootAnd.getDescrs()).hasSize(1); + + final OrDescr topOr = (OrDescr) rootAnd.getDescrs().get(0); + assertThat(topOr.getDescrs()).hasSize(2); + + final PatternDescr leftPattern = (PatternDescr) topOr.getDescrs().get(0); + assertThat(leftPattern.getObjectType()).isEqualTo("A"); + + final OrDescr rightOr = (OrDescr) topOr.getDescrs().get(1); + assertThat(rightOr.getDescrs()).as("top level Or has 3 sibling children").hasSize(3); + final PatternDescr bPattern = (PatternDescr) rightOr.getDescrs().get(0); + assertThat(bPattern.getObjectType()).isEqualTo("B"); + final PatternDescr cPattern = (PatternDescr) rightOr.getDescrs().get(1); + assertThat(cPattern.getObjectType()).isEqualTo("C"); + final AndDescr deAnd = (AndDescr) rightOr.getDescrs().get(2); + assertThat(deAnd.getDescrs()).hasSize(2); + + final PatternDescr dPattern = (PatternDescr) deAnd.getDescrs().get(0); + assertThat(dPattern.getObjectType()).isEqualTo("D"); + final PatternDescr ePattern = (PatternDescr) deAnd.getDescrs().get(1); + assertThat(ePattern.getObjectType()).isEqualTo("E"); + } + + @Test + void existsMultipleLevelNestWithThreeOrSiblings() { + final String drl = "rule nest_or_siblings\n" + + " when\n" + + " exists(A() or (B() or C() or (D() and E())))\n" + + " then\n" + + "end"; + PackageDescr pkg = parseAndGetPackageDescr(drl); + + assertThat(pkg.getRules()).hasSize(1); + final RuleDescr rule = (RuleDescr) pkg.getRules().get(0); + final AndDescr rootAnd = (AndDescr) rule.getLhs(); + assertThat(rootAnd.getDescrs()).hasSize(1); + + final ExistsDescr topExists = (ExistsDescr) rootAnd.getDescrs().get(0); + assertThat(topExists.getDescrs()).hasSize(1); + + final OrDescr topOr = (OrDescr) topExists.getDescrs().get(0); + assertThat(topOr.getDescrs()).hasSize(2); + + final PatternDescr leftPattern = (PatternDescr) topOr.getDescrs().get(0); + assertThat(leftPattern.getObjectType()).isEqualTo("A"); + + final OrDescr rightOr = (OrDescr) topOr.getDescrs().get(1); + assertThat(rightOr.getDescrs()).hasSize(3); + final PatternDescr bPattern = (PatternDescr) rightOr.getDescrs().get(0); + assertThat(bPattern.getObjectType()).isEqualTo("B"); + final PatternDescr cPattern = (PatternDescr) rightOr.getDescrs().get(1); + assertThat(cPattern.getObjectType()).isEqualTo("C"); + final AndDescr deAnd = (AndDescr) rightOr.getDescrs().get(2); + assertThat(deAnd.getDescrs()).hasSize(2); + + final PatternDescr dPattern = (PatternDescr) deAnd.getDescrs().get(0); + assertThat(dPattern.getObjectType()).isEqualTo("D"); + final PatternDescr ePattern = (PatternDescr) deAnd.getDescrs().get(1); + assertThat(ePattern.getObjectType()).isEqualTo("E"); + } + + @Test + void evalMultiple() { + final PackageDescr pkg = parseAndGetPackageDescrFromFile( + "eval_multiple.drl"); + + assertThat(pkg.getRules()).hasSize(1); + final RuleDescr rule = (RuleDescr) pkg.getRules().get(0); + assertThat(rule.getLhs().getDescrs()).hasSize(4); + + final EvalDescr eval = (EvalDescr) rule.getLhs().getDescrs().get(0); + assertThat((String) eval.getContent()).isEqualToIgnoringWhitespace("abc(\"foo\") + 5"); + + final PatternDescr pattern = (PatternDescr) rule.getLhs().getDescrs().get(1); + assertThat(pattern.getObjectType()).isEqualTo("Foo"); + } + + @Test + void withEval() { + final PackageDescr pkg = parseAndGetPackageDescrFromFile( + "with_eval.drl"); + + assertThat(pkg.getRules()).hasSize(1); + final RuleDescr rule = (RuleDescr) pkg.getRules().get(0); + assertThat(rule.getLhs().getDescrs()).hasSize(3); + PatternDescr pattern = (PatternDescr) rule.getLhs().getDescrs().get(0); + assertThat(pattern.getObjectType()).isEqualTo("Foo"); + pattern = (PatternDescr) rule.getLhs().getDescrs().get(1); + assertThat(pattern.getObjectType()).isEqualTo("Bar"); + + final EvalDescr eval = (EvalDescr) rule.getLhs().getDescrs().get(2); + assertThat((String) eval.getContent()).isEqualToIgnoringWhitespace("abc(\"foo\")"); + assertThat((String) rule.getConsequence()).isEqualToIgnoringWhitespace("Kapow"); + } + + @Test + void withRetval() { + final PackageDescr pkg = parseAndGetPackageDescrFromFile( + "with_retval.drl"); + + assertThat(pkg.getRules()).hasSize(1); + + final RuleDescr rule = (RuleDescr) pkg.getRules().get(0); + assertThat(rule.getLhs().getDescrs()).hasSize(1); + final PatternDescr col = (PatternDescr) rule.getLhs().getDescrs().get(0); + assertThat(col.getConstraint().getDescrs()).hasSize(1); + assertThat(col.getObjectType()).isEqualTo("Foo"); + final ExprConstraintDescr fld = (ExprConstraintDescr) col.getConstraint().getDescrs().get(0); + + assertThat(fld.getExpression()).isEqualToIgnoringWhitespace("name== (a + b)"); + } + + @Test + void withPredicate() { + final PackageDescr pkg = parseAndGetPackageDescrFromFile( + "with_predicate.drl"); + + assertThat(pkg.getRules()).hasSize(1); + + final RuleDescr rule = (RuleDescr) pkg.getRules().get(0); + assertThat(rule.getLhs().getDescrs()).hasSize(1); + final PatternDescr col = (PatternDescr) rule.getLhs().getDescrs().get(0); + AndDescr and = (AndDescr) col.getConstraint(); + assertThat(and.getDescrs()).hasSize(2); + + final ExprConstraintDescr field = (ExprConstraintDescr) col.getDescrs().get(0); + final ExprConstraintDescr pred = (ExprConstraintDescr) and.getDescrs().get(1); + assertThat(field.getExpression()).isEqualToIgnoringWhitespace("$age2:age"); + assertThat(pred.getExpression()).isEqualToIgnoringWhitespace("$age2 == $age1+2"); + } + + @Test + void notWithConstraint() { + final PackageDescr pkg = parseAndGetPackageDescrFromFile( + "not_with_constraint.drl"); + + assertThat(pkg.getRules()).hasSize(1); + + final RuleDescr rule = (RuleDescr) pkg.getRules().get(0); + assertThat(rule.getLhs().getDescrs()).hasSize(2); + + PatternDescr pattern = (PatternDescr) rule.getLhs().getDescrs().get(0); + final ExprConstraintDescr fieldBinding = (ExprConstraintDescr) pattern.getDescrs().get(0); + assertThat(fieldBinding.getExpression()).isEqualToIgnoringWhitespace("$likes:like"); + + final NotDescr not = (NotDescr) rule.getLhs().getDescrs().get(1); + pattern = (PatternDescr) not.getDescrs().get(0); + + final ExprConstraintDescr fld = (ExprConstraintDescr) pattern.getConstraint().getDescrs().get(0); + + assertThat(fld.getExpression()).isEqualToIgnoringWhitespace("type == $likes"); + } + + @Test + void functions() { + final PackageDescr pkg = parseAndGetPackageDescrFromFile( + "functions.drl"); + + assertThat(pkg.getRules()).hasSize(2); + + final List functions = pkg.getFunctions(); + assertThat(functions).hasSize(2); + + FunctionDescr func = functions.get(0); + assertThat(func.getName()).isEqualTo("functionA"); + assertThat(func.getReturnType()).isEqualTo("String"); + assertThat(func.getParameterNames()).hasSize(2); + assertThat(func.getParameterTypes()).hasSize(2); + assertThat(func.getLine()).isEqualTo(21); + assertThat(func.getColumn()).isEqualTo(0); + + assertThat(func.getParameterTypes().get(0)).isEqualTo("String"); + assertThat(func.getParameterNames().get(0)).isEqualTo("s"); + + assertThat(func.getParameterTypes().get(1)).isEqualTo("Integer"); + assertThat(func.getParameterNames().get(1)).isEqualTo("i"); + + assertThat(func.getBody()).isEqualToIgnoringWhitespace("foo();"); + + func = functions.get(1); + assertThat(func.getName()).isEqualTo("functionB"); + assertThat(func.getText()).isEqualToIgnoringWhitespace("bar();"); + } + + @Test + void comment() { + final PackageDescr pkg = parseAndGetPackageDescrFromFile( + "comment.drl"); + + assertThat(pkg).isNotNull(); + + assertThat(pkg.getName()).isEqualTo("foo.bar"); + } + + @Test + void attributes() { + final RuleDescr rule = parseAndGetFirstRuleDescrFromFile( + "rule_attributes.drl"); + assertThat(rule.getName()).isEqualTo("simple_rule"); + assertThat((String) rule.getConsequence()).isEqualToIgnoringWhitespace("bar();"); + + final Map attrs = rule.getAttributes(); + assertThat(attrs).hasSize(6); + + AttributeDescr at = (AttributeDescr) attrs.get("salience"); + assertThat(at.getName()).isEqualTo("salience"); + assertThat(at.getValue()).isEqualTo("42"); + + at = (AttributeDescr) attrs.get("agenda-group"); + assertThat(at.getName()).isEqualTo("agenda-group"); + assertThat(at.getValue()).isEqualTo("my_group"); + + at = (AttributeDescr) attrs.get("no-loop"); + assertThat(at.getName()).isEqualTo("no-loop"); + assertThat(at.getValue()).isEqualTo("true"); + + at = (AttributeDescr) attrs.get("duration"); + assertThat(at.getName()).isEqualTo("duration"); + assertThat(at.getValue()).isEqualTo("42"); + + at = (AttributeDescr) attrs.get("activation-group"); + assertThat(at.getName()).isEqualTo("activation-group"); + assertThat(at.getValue()).isEqualTo("my_activation_group"); + + at = (AttributeDescr) attrs.get("lock-on-active"); + assertThat(at.getName()).isEqualTo("lock-on-active"); + assertThat(at.getValue()).isEqualTo("true"); + } + + @Test + void attributes2() { + final PackageDescr pkg = parseAndGetPackageDescrFromFile( + "rule_attributes2.drl"); + + List rules = pkg.getRules(); + assertThat(rules).hasSize(3); + + RuleDescr rule = rules.get(0); + assertThat(rule.getName()).isEqualTo("rule1"); + Map attrs = rule.getAttributes(); + assertThat(attrs).hasSize(2); + AttributeDescr at = (AttributeDescr) attrs.get("salience"); + assertThat(at.getName()).isEqualTo("salience"); + assertThat(at.getValue()).isEqualTo("(42)"); + at = (AttributeDescr) attrs.get("agenda-group"); + assertThat(at.getName()).isEqualTo("agenda-group"); + assertThat(at.getValue()).isEqualTo("my_group"); + + rule = rules.get(1); + assertThat(rule.getName()).isEqualTo("rule2"); + attrs = rule.getAttributes(); + assertThat(attrs).hasSize(2); + at = (AttributeDescr) attrs.get("salience"); + assertThat(at.getName()).isEqualTo("salience"); + assertThat(at.getValue()).isEqualTo("(Integer.MIN_VALUE)"); + at = (AttributeDescr) attrs.get("no-loop"); + assertThat(at.getName()).isEqualTo("no-loop"); + + rule = rules.get(2); + assertThat(rule.getName()).isEqualTo("rule3"); + attrs = rule.getAttributes(); + assertThat(attrs).hasSize(2); + at = (AttributeDescr) attrs.get("enabled"); + assertThat(at.getName()).isEqualTo("enabled"); + assertThat(at.getValue()).isEqualTo("(Boolean.TRUE)"); + at = (AttributeDescr) attrs.get("activation-group"); + assertThat(at.getName()).isEqualTo("activation-group"); + assertThat(at.getValue()).isEqualTo("my_activation_group"); + } + + @Test + void attributeRefract() { + final String source = "rule Test refract when Person() then end"; + + PackageDescr pkg = parseAndGetPackageDescr( + source); + + RuleDescr rule = (RuleDescr) pkg.getRules().get(0); + + assertThat(rule.getName()).isEqualTo("Test"); + Map attributes = rule.getAttributes(); + assertThat(attributes).hasSize(1); + AttributeDescr refract = attributes.get("refract"); + assertThat(refract).isNotNull(); + assertThat(refract.getValue()).isEqualTo("true"); + } + + @Test + void enabledExpression() { + final RuleDescr rule = parseAndGetFirstRuleDescrFromFile( + "rule_enabled_expression.drl"); + assertThat(rule.getName()).isEqualTo("simple_rule"); + assertThat((String) rule.getConsequence()).isEqualToIgnoringWhitespace("bar();"); + + final Map attrs = rule.getAttributes(); + assertThat(attrs).hasSize(3); + + AttributeDescr at = (AttributeDescr) attrs.get("enabled"); + assertThat(at.getName()).isEqualTo("enabled"); + assertThat(at.getValue()).isEqualTo("( 1 + 1 == 2 )"); + + at = (AttributeDescr) attrs.get("salience"); + assertThat(at.getName()).isEqualTo("salience"); + assertThat(at.getValue()).isEqualTo("( 1+2 )"); + + at = (AttributeDescr) attrs.get("lock-on-active"); + assertThat(at.getName()).isEqualTo("lock-on-active"); + assertThat(at.getValue()).isEqualTo("true"); + } + + @Test + void durationExpression() { + final RuleDescr rule = parseAndGetFirstRuleDescrFromFile( + "rule_duration_expression.drl"); + assertThat(rule.getName()).isEqualTo("simple_rule"); + assertThat((String) rule.getConsequence()).isEqualToIgnoringWhitespace("bar();"); + + final Map attrs = rule.getAttributes(); + assertThat(attrs).hasSize(2); + + AttributeDescr at = (AttributeDescr) attrs.get("duration"); + assertThat(at.getName()).isEqualTo("duration"); + assertThat(at.getValue()).isEqualTo("1h30m"); + + at = (AttributeDescr) attrs.get("lock-on-active"); + assertThat(at.getName()).isEqualTo("lock-on-active"); + assertThat(at.getValue()).isEqualTo("true"); + } + + @Test + void calendars() { + final RuleDescr rule = parseAndGetFirstRuleDescrFromFile( + "rule_calendars_attribute.drl"); + assertThat(rule.getName()).isEqualTo("simple_rule"); + assertThat((String) rule.getConsequence()).isEqualToIgnoringWhitespace("bar();"); + + final Map attrs = rule.getAttributes(); + assertThat(attrs).hasSize(2); + + AttributeDescr at = (AttributeDescr) attrs.get("calendars"); + assertThat(at.getName()).isEqualTo("calendars"); + assertThat(at.getValue()).isEqualTo("[ \"cal1\" ]"); + + at = (AttributeDescr) attrs.get("lock-on-active"); + assertThat(at.getName()).isEqualTo("lock-on-active"); + assertThat(at.getValue()).isEqualTo("true"); + } + + @Test + void calendars2() { + final RuleDescr rule = parseAndGetFirstRuleDescrFromFile( + "rule_calendars_attribute2.drl"); + + assertThat(rule.getName()).isEqualTo("simple_rule"); + assertThat((String) rule.getConsequence()).isEqualToIgnoringWhitespace("bar();"); + + final Map attrs = rule.getAttributes(); + assertThat(attrs).hasSize(2); + + AttributeDescr at = (AttributeDescr) attrs.get("calendars"); + assertThat(at.getName()).isEqualTo("calendars"); + assertThat(at.getValue()).isEqualTo("[ \"cal 1\", \"cal 2\", \"cal 3\" ]"); + + at = (AttributeDescr) attrs.get("lock-on-active"); + assertThat(at.getName()).isEqualTo("lock-on-active"); + assertThat(at.getValue()).isEqualTo("true"); + } + + @Test + void timer() { + final RuleDescr rule = parseAndGetFirstRuleDescrFromFile("rule_timer_attribute.drl"); + assertThat(rule.getName()).isEqualTo("simple_rule"); + assertThat((String) rule.getConsequence()).isEqualToIgnoringWhitespace("bar();"); + + final Map attrs = rule.getAttributes(); + assertThat(attrs).hasSize(2); + + AttributeDescr at = (AttributeDescr) attrs.get("timer"); + assertThat(at.getName()).isEqualTo("timer"); + assertThat(at.getValue()).isEqualTo("int: 0 1; start=1_000_000, repeat-limit=0"); + + at = (AttributeDescr) attrs.get("lock-on-active"); + assertThat(at.getName()).isEqualTo("lock-on-active"); + assertThat(at.getValue()).isEqualTo("true"); + } + + @Test + void attributes_alternateSyntax() { + final RuleDescr rule = parseAndGetFirstRuleDescrFromFile( + "rule_attributes_alt.drl"); + assertThat(rule.getName()).isEqualTo("simple_rule"); + assertThat((String) rule.getConsequence()).isEqualToIgnoringWhitespace("bar();"); + + final Map attrs = rule.getAttributes(); + assertThat(attrs).hasSize(6); + + AttributeDescr at = attrs.get("salience"); + assertThat(at.getName()).isEqualTo("salience"); + assertThat(at.getValue()).isEqualTo("42"); + + at = attrs.get("agenda-group"); + assertThat(at.getName()).isEqualTo("agenda-group"); + assertThat(at.getValue()).isEqualTo("my_group"); + + at = attrs.get("no-loop"); + assertThat(at.getName()).isEqualTo("no-loop"); + assertThat(at.getValue()).isEqualTo("true"); + + at = attrs.get("lock-on-active"); + assertThat(at.getName()).isEqualTo("lock-on-active"); + assertThat(at.getValue()).isEqualTo("true"); + + at = attrs.get("duration"); + assertThat(at.getName()).isEqualTo("duration"); + assertThat(at.getValue()).isEqualTo("42"); + + at = attrs.get("activation-group"); + assertThat(at.getName()).isEqualTo("activation-group"); + assertThat(at.getValue()).isEqualTo("my_activation_group"); + } + + @Test + void enumeration() { + final RuleDescr rule = parseAndGetFirstRuleDescrFromFile( + "enumeration.drl"); + assertThat(rule.getName()).isEqualTo("simple_rule"); + assertThat(rule.getLhs().getDescrs()).hasSize(1); + final PatternDescr col = (PatternDescr) rule.getLhs().getDescrs().get(0); + assertThat(col.getObjectType()).isEqualTo("Foo"); + assertThat(col.getConstraint().getDescrs()).hasSize(1); + final ExprConstraintDescr fld = (ExprConstraintDescr) col.getConstraint().getDescrs().get(0); + + assertThat(fld.getExpression()).isEqualToIgnoringWhitespace("bar == Foo.BAR"); + } + + @Test + void extraLhsNewline() { + final PackageDescr pkg = parseAndGetPackageDescrFromFile( + "extra_lhs_newline.drl"); + } + + @Test + void soundsLike() { + final PackageDescr pkg = parseAndGetPackageDescrFromFile( + "soundslike_operator.drl"); + + RuleDescr rule = (RuleDescr) pkg.getRules().get(0); + PatternDescr pat = (PatternDescr) rule.getLhs().getDescrs().get(0); + + pat.getConstraint(); + } + + @Test + void packageAttributes() { + final PackageDescr pkg = parseAndGetPackageDescrFromFile( + "package_attributes.drl"); + + AttributeDescr at = (AttributeDescr) pkg.getAttributes().get(0); + assertThat(at.getName()).isEqualTo("agenda-group"); + assertThat(at.getValue()).isEqualTo("x"); + at = (AttributeDescr) pkg.getAttributes().get(1); + assertThat(at.getName()).isEqualTo("dialect"); + assertThat(at.getValue()).isEqualTo("java"); + + assertThat(pkg.getRules()).hasSize(2); + + assertThat(pkg.getImports()).hasSize(2); + + RuleDescr rule = (RuleDescr) pkg.getRules().get(0); + assertThat(rule.getName()).isEqualTo("bar"); + at = (AttributeDescr) rule.getAttributes().get("agenda-group"); + assertThat(at.getName()).isEqualTo("agenda-group"); + assertThat(at.getValue()).isEqualTo("x"); + at = (AttributeDescr) rule.getAttributes().get("dialect"); + assertThat(at.getName()).isEqualTo("dialect"); + assertThat(at.getValue()).isEqualTo("java"); + + rule = (RuleDescr) pkg.getRules().get(1); + assertThat(rule.getName()).isEqualTo("baz"); + at = (AttributeDescr) rule.getAttributes().get("dialect"); + assertThat(at.getName()).isEqualTo("dialect"); + assertThat(at.getValue()).isEqualTo("mvel"); + at = (AttributeDescr) rule.getAttributes().get("agenda-group"); + assertThat(at.getName()).isEqualTo("agenda-group"); + assertThat(at.getValue()).isEqualTo("x"); + } + + @Test + void statementOrdering1() { + final PackageDescr pkg = parseAndGetPackageDescrFromFile( + "statement_ordering_1.drl"); + + assertThat(pkg.getRules()).hasSize(2); + + assertThat(((RuleDescr) pkg.getRules().get(0)).getName()).isEqualTo("foo"); + assertThat(((RuleDescr) pkg.getRules().get(1)).getName()).isEqualTo("bar"); + + assertThat(pkg.getFunctions()).hasSize(2); + + assertThat(((FunctionDescr) pkg.getFunctions().get(0)).getName()).isEqualTo("cheeseIt"); + assertThat(((FunctionDescr) pkg.getFunctions().get(1)).getName()).isEqualTo("uncheeseIt"); + + assertThat(pkg.getImports()).hasSize(4); + assertThat(((ImportDescr) pkg.getImports().get(0)).getTarget()).isEqualTo("im.one"); + assertThat(((ImportDescr) pkg.getImports().get(1)).getTarget()).isEqualTo("im.two"); + assertThat(((ImportDescr) pkg.getImports().get(2)).getTarget()).isEqualTo("im.three"); + assertThat(((ImportDescr) pkg.getImports().get(3)).getTarget()).isEqualTo("im.four"); + } + + @Test + void ruleNamesStartingWithNumbers() { + final PackageDescr pkg = parseAndGetPackageDescrFromFile( + "rule_names_number_prefix.drl"); + + assertThat(pkg.getRules()).hasSize(2); + + assertThat(((RuleDescr) pkg.getRules().get(0)).getName()).isEqualTo("1. Do Stuff!"); + assertThat(((RuleDescr) pkg.getRules().get(1)).getName()).isEqualTo("2. Do More Stuff!"); + } + + @Test + void evalWithNewline() { + final PackageDescr pkg = parseAndGetPackageDescrFromFile( + "eval_with_newline.drl"); + } + + @Test + void endPosition() { + final PackageDescr pkg = parseAndGetPackageDescrFromFile( + "test_EndPosition.drl"); + final RuleDescr rule = (RuleDescr) pkg.getRules().get(0); + final PatternDescr col = (PatternDescr) rule.getLhs().getDescrs().get(0); + assertThat(col.getLine()).isEqualTo(23); + assertThat(col.getEndLine()).isEqualTo(25); + } + + @Test + void groupBy() { + final PackageDescr pkg = parseAndGetPackageDescrFromFile("groupBy.drl"); + + assertThat(pkg.getRules()).hasSize(1); + final RuleDescr rule = pkg.getRules().get(0); + assertThat(rule.getLhs().getDescrs()).hasSize(1); + + final PatternDescr outPattern = (PatternDescr) rule.getLhs().getDescrs().get(0); + final GroupByDescr groupBy = (GroupByDescr) outPattern.getSource(); + assertThat(groupBy.getGroupingKey()).isEqualToIgnoringWhitespace("$initial"); + assertThat(groupBy.getGroupingFunction()).isEqualToIgnoringWhitespace("$p.getName().substring(0, 1)"); + assertThat(groupBy.getActionCode()).isNull(); + assertThat(groupBy.getReverseCode()).isNull(); + assertThat(groupBy.getFunctions()).hasSize(2); + assertThat(groupBy.getFunctions().get(0).getFunction()).isEqualToIgnoringWhitespace("sum"); + assertThat(groupBy.getFunctions().get(1).getFunction()).isEqualToIgnoringWhitespace("count"); + + assertThat(groupBy.getFunctions().get(0).getParams()).hasSize(1); + assertThat(groupBy.getFunctions().get(0).getParams()[0]).isEqualToIgnoringWhitespace("$age"); + + assertThat(groupBy.getFunctions().get(1).getParams()).hasSize(0); + + assertThat(groupBy.isExternalFunction()).isTrue(); + + final PatternDescr pattern = groupBy.getInputPattern(); + assertThat(pattern.getObjectType()).isEqualTo("Person"); + assertThat(pattern.getConstraint().getDescrs()).hasSize(1); + assertThat(pattern.getConstraint().getDescrs().get(0).getText()).isEqualToIgnoringWhitespace("$age : age < 30"); + + assertThat(pattern.getConstraint().getDescrs()).hasSize(1); + assertThat(pattern.getConstraint().getDescrs().get(0).getText()).isEqualToIgnoringWhitespace("$age : age < 30"); + + assertThat(outPattern.getConstraint().getDescrs()).hasSize(1); + assertThat(outPattern.getConstraint().getDescrs().get(0).getText()).isEqualToIgnoringWhitespace("$sumOfAges > 10"); + } + + @Test + void qualifiedClassname() { + final PackageDescr pkg = parseAndGetPackageDescrFromFile( + "qualified_classname.drl"); + + final RuleDescr rule = (RuleDescr) pkg.getRules().get(0); + + final PatternDescr p = (PatternDescr) rule.getLhs().getDescrs().get(0); + + assertThat(p.getObjectType()).isEqualTo("com.cheeseco.Cheese"); + } + + @Test + void accumulate() { + final String drl = "rule R\n" + + "when\n" + + " accumulate( Person( $age : age );\n" + + " $avg : average( $age ) );\n" + + "then\n" + + "end"; + RuleDescr rule = parseAndGetFirstRuleDescr(drl); + + PatternDescr out = (PatternDescr) rule.getLhs().getDescrs().get(0); + assertThat(out.getObjectType()).isEqualTo("Object"); + AccumulateDescr accum = (AccumulateDescr) out.getSource(); + assertThat(accum.isExternalFunction()).isTrue(); + + List functions = accum.getFunctions(); + assertThat(functions).hasSize(1); + assertThat(functions.get(0).getFunction()).isEqualTo("average"); + assertThat(functions.get(0).getBind()).isEqualTo("$avg"); + assertThat(functions.get(0).getParams()[0]).isEqualTo("$age"); + + final PatternDescr pattern = accum.getInputPattern(); + assertThat(pattern.getObjectType()).isEqualTo("Person"); + + // accum.getInput() is always AndDescr + assertThat(accum.getInput()).isInstanceOfSatisfying(AndDescr.class, and -> { + assertThat(and.getDescrs()).hasSize(1); + assertThat(and.getDescrs().get(0)).isInstanceOfSatisfying(PatternDescr.class, patternDescr -> { + assertThat(patternDescr.getObjectType()).isEqualTo("Person"); + }); + }); + } + + @Test + void fromAccumulate() { + final PackageDescr pkg = parseAndGetPackageDescrFromFile("from_accumulate.drl"); + + assertThat(pkg.getRules()).hasSize(1); + final RuleDescr rule = pkg.getRules().get(0); + assertThat(rule.getLhs().getDescrs()).hasSize(1); + + final PatternDescr outPattern = (PatternDescr) rule.getLhs().getDescrs().get(0); + final AccumulateDescr accum = (AccumulateDescr) outPattern.getSource(); + assertThat(accum.getInitCode()).isEqualTo("int x = 0;"); + assertThat(accum.getActionCode()).isEqualTo("x++;"); + assertThat(accum.getReverseCode()).isNull(); + assertThat(accum.getResultCode()).isEqualTo("new Integer(x)"); + + assertThat(accum.isExternalFunction()).isFalse(); + + final PatternDescr pattern = accum.getInputPattern(); + assertThat(pattern.getObjectType()).isEqualTo("Person"); + + // accum.getInput() is always AndDescr + assertThat(accum.getInput()).isInstanceOfSatisfying(AndDescr.class, and -> { + assertThat(and.getDescrs()).hasSize(1); + assertThat(and.getDescrs().get(0)).isInstanceOfSatisfying(PatternDescr.class, patternDescr -> { + assertThat(patternDescr.getObjectType()).isEqualTo("Person"); + }); + }); + } + + @Test + void accumulateWithBindings() { + final PackageDescr pkg = parseAndGetPackageDescrFromFile( + "accumulate_with_bindings.drl"); + + assertThat(pkg.getRules()).hasSize(1); + final RuleDescr rule = (RuleDescr) pkg.getRules().get(0); + assertThat(rule.getLhs().getDescrs()).hasSize(1); + + final PatternDescr outPattern = (PatternDescr) rule.getLhs().getDescrs().get(0); + final AccumulateDescr accum = (AccumulateDescr) outPattern.getSource(); + assertThat(outPattern.getIdentifier()).isEqualTo("$counter"); + assertThat(accum.getInitCode()).isEqualTo("int x = 0;"); + assertThat(accum.getActionCode()).isEqualTo("x++;"); + assertThat(accum.getResultCode()).isEqualTo("new Integer(x)"); + + final PatternDescr pattern = (PatternDescr) accum.getInputPattern(); + assertThat(pattern.getObjectType()).isEqualTo("Person"); + } + + /** + * - Optional semicolon at the end of statements (int x = 0). + * - Optional comma delimiting init, action, and result. + */ + @Test + void accumulateWithoutOptionalDelimiters() { + String source = "rule \"AccumulateParserTest\"\n" + + "when\n" + + " $counter:Integer() from accumulate( $person : Person( age > 21 ),\n" + + " init( int x = 0 )\n" + + " action( x++ )\n" + + " result( new Integer(x) ) );\n" + + "then\n" + + "end\n"; + final PackageDescr pkg = parseAndGetPackageDescr(source); + + assertThat(pkg.getRules()).hasSize(1); + final RuleDescr rule = (RuleDescr) pkg.getRules().get(0); + assertThat(rule.getLhs().getDescrs()).hasSize(1); + + final PatternDescr outPattern = (PatternDescr) rule.getLhs().getDescrs().get(0); + final AccumulateDescr accum = (AccumulateDescr) outPattern.getSource(); + assertThat(outPattern.getIdentifier()).isEqualTo("$counter"); + assertThat(accum.getInitCode()).isEqualTo("int x = 0"); + assertThat(accum.getActionCode()).isEqualTo("x++"); + assertThat(accum.getResultCode()).isEqualTo("new Integer(x)"); + + final PatternDescr pattern = (PatternDescr) accum.getInputPattern(); + assertThat(pattern.getObjectType()).isEqualTo("Person"); + } + + /** + * When the accumulate function (e.g. count()) has no arguments. + */ + @Test + void accumulateCount() { + String source = "rule R when\n" + + " accumulate (\n" + + " Person(), $result : count() " + + " )" + + "then\n" + + "end"; + final PackageDescr pkg = parseAndGetPackageDescr(source); + + assertThat(pkg.getRules()).hasSize(1); + final RuleDescr rule = (RuleDescr) pkg.getRules().get(0); + assertThat(rule.getLhs().getDescrs()).hasSize(1); + + final PatternDescr outPattern = (PatternDescr) rule.getLhs().getDescrs().get(0); + final AccumulateDescr accum = (AccumulateDescr) outPattern.getSource(); + assertThat(accum).isNotNull(); + + final PatternDescr pattern = (PatternDescr) accum.getInputPattern(); + assertThat(pattern.getObjectType()).isEqualTo("Person"); + + assertThat(accum.getFunctions()).hasSize(1); + AccumulateDescr.AccumulateFunctionCallDescr accumulateFunction = accum.getFunctions().get(0); + assertThat(accumulateFunction.getBind()).isEqualTo("$result"); + assertThat(accumulateFunction.getFunction()).isEqualTo("count"); + assertThat(accumulateFunction.getParams()).isEmpty(); + } + + @Test + void collect() { + final PackageDescr pkg = parseAndGetPackageDescrFromFile( + "collect.drl"); + + assertThat(pkg.getRules()).hasSize(1); + final RuleDescr rule = (RuleDescr) pkg.getRules().get(0); + assertThat(rule.getLhs().getDescrs()).hasSize(1); + + final PatternDescr outPattern = (PatternDescr) rule.getLhs().getDescrs().get(0); + final CollectDescr collect = (CollectDescr) outPattern.getSource(); + + final PatternDescr pattern = (PatternDescr) collect.getInputPattern(); + assertThat(pattern.getObjectType()).isEqualTo("Person"); + } + + @Test + void predicate2() { + // predicates are also prefixed by the eval keyword + final RuleDescr rule = parseAndGetFirstRuleDescr( + "rule X when Foo(eval( $var.equals(\"xyz\") )) then end"); + + final PatternDescr pattern = (PatternDescr) rule.getLhs().getDescrs().get(0); + final List constraints = pattern.getConstraint().getDescrs(); + assertThat(constraints).hasSize(1); + + final ExprConstraintDescr predicate = (ExprConstraintDescr) constraints.get(0); + assertThat(predicate.getExpression()).isEqualToIgnoringWhitespace("eval( $var.equals(\"xyz\") )"); + } + + @Test + void escapedStrings() { + final RuleDescr rule = parseAndGetFirstRuleDescrFromFile( + "escaped-string.drl"); + + assertThat(rule).isNotNull(); + + assertThat(rule.getName()).isEqualTo("test_Quotes"); + + final String expected = "String s = \"\\\"\\n\\t\\\\\";"; + + assertThat((String) rule.getConsequence()).isEqualToIgnoringWhitespace(expected); + } + + @Test + void nestedCEs() { + final RuleDescr rule = parseAndGetFirstRuleDescrFromFile( + "nested_conditional_elements.drl"); + + assertThat(rule).isNotNull(); + + final AndDescr root = rule.getLhs(); + final NotDescr not1 = (NotDescr) root.getDescrs().get(0); + final AndDescr and1 = (AndDescr) not1.getDescrs().get(0); + + final PatternDescr state = (PatternDescr) and1.getDescrs().get(0); + final NotDescr not2 = (NotDescr) and1.getDescrs().get(1); + final AndDescr and2 = (AndDescr) not2.getDescrs().get(0); + final PatternDescr person = (PatternDescr) and2.getDescrs().get(0); + final PatternDescr cheese = (PatternDescr) and2.getDescrs().get(1); + + final PatternDescr person2 = (PatternDescr) root.getDescrs().get(1); + final OrDescr or = (OrDescr) root.getDescrs().get(2); + final PatternDescr cheese2 = (PatternDescr) or.getDescrs().get(0); + final PatternDescr cheese3 = (PatternDescr) or.getDescrs().get(1); + + assertThat("State").isEqualTo(state.getObjectType()); + assertThat("Person").isEqualTo(person.getObjectType()); + assertThat("Cheese").isEqualTo(cheese.getObjectType()); + assertThat("Person").isEqualTo(person2.getObjectType()); + assertThat("Cheese").isEqualTo(cheese2.getObjectType()); + assertThat("Cheese").isEqualTo(cheese3.getObjectType()); + } + + @Test + void forall() { + final PackageDescr pkg = parseAndGetPackageDescrFromFile( + "forall.drl"); + + assertThat(pkg.getRules()).hasSize(1); + final RuleDescr rule = (RuleDescr) pkg.getRules().get(0); + assertThat(rule.getLhs().getDescrs()).hasSize(1); + + final ForallDescr forall = (ForallDescr) rule.getLhs().getDescrs().get(0); + + assertThat(forall.getDescrs()).hasSize(2); + final PatternDescr pattern = forall.getBasePattern(); + assertThat(pattern.getObjectType()).isEqualTo("Person"); + final List remaining = forall.getRemainingPatterns(); + assertThat(remaining).hasSize(1); + final PatternDescr cheese = (PatternDescr) remaining.get(0); + assertThat(cheese.getObjectType()).isEqualTo("Cheese"); + } + + @Test + void forallWithFrom() { + final PackageDescr pkg = parseAndGetPackageDescrFromFile( + "forallwithfrom.drl"); + + assertThat(pkg.getRules()).hasSize(1); + final RuleDescr rule = (RuleDescr) pkg.getRules().get(0); + assertThat(rule.getLhs().getDescrs()).hasSize(1); + + final ForallDescr forall = (ForallDescr) rule.getLhs().getDescrs().get(0); + + assertThat(forall.getDescrs()).hasSize(2); + final PatternDescr pattern = forall.getBasePattern(); + assertThat(pattern.getObjectType()).isEqualTo("Person"); + assertThat(((FromDescr) pattern.getSource()).getDataSource().toString()).isEqualTo("$village"); + final List remaining = forall.getRemainingPatterns(); + assertThat(remaining).hasSize(1); + final PatternDescr cheese = (PatternDescr) remaining.get(0); + assertThat(cheese.getObjectType()).isEqualTo("Cheese"); + assertThat(((FromDescr) cheese.getSource()).getDataSource().toString()).isEqualTo("$cheesery"); + } + + @Test + void memberof() { + final String text = "rule X when Country( $cities : city )\nPerson( city memberOf $cities )\n then end"; + AndDescr descrs = parseAndGetFirstRuleDescr( + text).getLhs(); + + assertThat(descrs.getDescrs()).hasSize(2); + PatternDescr pat = (PatternDescr) descrs.getDescrs().get(1); + ExprConstraintDescr fieldConstr = (ExprConstraintDescr) pat.getConstraint().getDescrs().get(0); + + assertThat(fieldConstr.getExpression()).isEqualTo("city memberOf $cities"); + } + + @Test + void notMemberof() { + final String text = "rule X when Country( $cities : city )\nPerson( city not memberOf $cities ) then end\n"; + AndDescr descrs = parseAndGetFirstRuleDescr( + text).getLhs(); + + assertThat(descrs.getDescrs()).hasSize(2); + PatternDescr pat = (PatternDescr) descrs.getDescrs().get(1); + ExprConstraintDescr fieldConstr = (ExprConstraintDescr) pat.getConstraint().getDescrs().get(0); + + assertThat(fieldConstr.getExpression()).isEqualTo("city not memberOf $cities"); + } + + @Test + void inOperator() { + final RuleDescr rule = parseAndGetFirstRuleDescrFromFile( + "in_operator_test.drl"); + + assertThat(rule).isNotNull(); + + assertThat((String) rule.getConsequence()).isEqualToIgnoringWhitespace("consequence();"); + assertThat(rule.getName()).isEqualTo("simple_rule"); + assertThat(rule.getLhs().getDescrs()).hasSize(2); + + // The first pattern, with 2 restrictions on a single field (plus a + // connective) + PatternDescr pattern = (PatternDescr) rule.getLhs().getDescrs().get(0); + assertThat(pattern.getObjectType()).isEqualTo("Person"); + assertThat(pattern.getConstraint().getDescrs()).hasSize(1); + + ExprConstraintDescr fld = (ExprConstraintDescr) pattern.getConstraint().getDescrs().get(0); + assertThat(fld.getExpression()).isEqualTo("age > 30 && < 40"); + + // the second col, with 2 fields, the first with 2 restrictions, the + // second field with one + pattern = (PatternDescr) rule.getLhs().getDescrs().get(1); + assertThat(pattern.getObjectType()).isEqualTo("Vehicle"); + assertThat(pattern.getConstraint().getDescrs()).hasSize(2); + + fld = (ExprConstraintDescr) pattern.getConstraint().getDescrs().get(0); + assertThat(fld.getExpression()).isEqualToIgnoringWhitespace("type in ( \"sedan\", \"wagon\" )"); + + // now the second field + fld = (ExprConstraintDescr) pattern.getConstraint().getDescrs().get(1); + assertThat(fld.getExpression()).isEqualTo("age < 3"); + } + + @Test + void notInOperator() { + final RuleDescr rule = parseAndGetFirstRuleDescrFromFile( + "notin_operator_test.drl"); + + assertThat(rule).isNotNull(); + + assertThat((String) rule.getConsequence()).isEqualToIgnoringWhitespace("consequence();"); + assertThat(rule.getName()).isEqualTo("simple_rule"); + assertThat(rule.getLhs().getDescrs()).hasSize(2); + + // The first pattern, with 2 restrictions on a single field (plus a + // connective) + PatternDescr pattern = (PatternDescr) rule.getLhs().getDescrs().get(0); + assertThat(pattern.getObjectType()).isEqualTo("Person"); + assertThat(pattern.getConstraint().getDescrs()).hasSize(1); + + ExprConstraintDescr fld = (ExprConstraintDescr) pattern.getConstraint().getDescrs().get(0); + assertThat(fld.getExpression()).isEqualTo("age > 30 && < 40"); + + // the second col, with 2 fields, the first with 2 restrictions, the + // second field with one + pattern = (PatternDescr) rule.getLhs().getDescrs().get(1); + assertThat(pattern.getObjectType()).isEqualTo("Vehicle"); + assertThat(pattern.getConstraint().getDescrs()).hasSize(2); + + fld = (ExprConstraintDescr) pattern.getConstraint().getDescrs().get(0); + assertThat(fld.getExpression()).isEqualToIgnoringWhitespace("type not in ( \"sedan\", \"wagon\" )"); + + // now the second field + fld = (ExprConstraintDescr) pattern.getConstraint().getDescrs().get(1); + assertThat(fld.getExpression()).isEqualTo("age < 3"); + } + + @Test + void checkOrDescr() { + final String text = "rule X when Person( eval( age == 25 ) || ( eval( name.equals( \"bob\" ) ) && eval( age == 30 ) ) ) then end"; + PatternDescr pattern = (PatternDescr) parseAndGetFirstRuleDescr( + text).getLhs().getDescrs().get(0); + + assertThat(pattern.getDescrs()).hasSize(1); + assertThat(AndDescr.class).isEqualTo(pattern.getConstraint().getClass()); + + assertThat(pattern.getConstraint().getDescrs().get(0).getClass()).isEqualTo(ExprConstraintDescr.class); + } + + @Test + void constraintAndConnective() { + final String text = "rule X when Person( age < 42 && location==\"atlanta\") then end"; + PatternDescr pattern = (PatternDescr) parseAndGetFirstRuleDescr( + text).getLhs().getDescrs().get(0); + + assertThat(pattern.getDescrs()).hasSize(1); + ExprConstraintDescr fcd = (ExprConstraintDescr) pattern.getDescrs().get(0); + assertThat(fcd.getExpression()).isEqualToIgnoringWhitespace("age < 42 && location==\"atlanta\""); + } + + @Test + void constraintOrConnective() { + final String text = "rule X when Person( age < 42 || location==\"atlanta\") then end"; + PatternDescr pattern = (PatternDescr) parseAndGetFirstRuleDescr( + text).getLhs().getDescrs().get(0); + + assertThat(pattern.getDescrs()).hasSize(1); + ExprConstraintDescr fcd = (ExprConstraintDescr) pattern.getDescrs().get(0); + assertThat(fcd.getExpression()).isEqualToIgnoringWhitespace("age < 42 || location==\"atlanta\""); + } + + @Test + void restrictions() { + final String text = "rule X when Foo( bar > 1 || == 1 ) then end\n"; + + AndDescr descrs = (AndDescr) parseAndGetFirstRuleDescr( + text).getLhs(); + + assertThat(descrs.getDescrs()).hasSize(1); + PatternDescr pat = (PatternDescr) descrs.getDescrs().get(0); + ExprConstraintDescr fieldConstr = (ExprConstraintDescr) pat.getConstraint().getDescrs().get(0); + + assertThat(fieldConstr.getExpression()).isEqualTo("bar > 1 || == 1"); + } + + @Test + void semicolon() { + final PackageDescr pkg = parseAndGetPackageDescrFromFile( + "semicolon.drl"); + + assertThat(pkg.getName()).isEqualTo("org.drools.mvel.compiler"); + assertThat(pkg.getGlobals()).hasSize(1); + assertThat(pkg.getRules()).hasSize(3); + + final RuleDescr rule1 = (RuleDescr) pkg.getRules().get(0); + assertThat(rule1.getLhs().getDescrs()).hasSize(2); + + final RuleDescr query1 = (RuleDescr) pkg.getRules().get(1); + assertThat(query1.getLhs().getDescrs()).hasSize(3); + + final RuleDescr rule2 = (RuleDescr) pkg.getRules().get(2); + assertThat(rule2.getLhs().getDescrs()).hasSize(2); + } + + @Test + void eval() { + final PackageDescr pkg = parseAndGetPackageDescrFromFile( + "eval_parsing.drl"); + + assertThat(pkg.getName()).isEqualTo("org.drools.mvel.compiler"); + assertThat(pkg.getRules()).hasSize(1); + + final RuleDescr rule1 = (RuleDescr) pkg.getRules().get(0); + assertThat(rule1.getLhs().getDescrs()).hasSize(1); + } + + @Test + void accumulateReverse() { + final PackageDescr pkg = parseAndGetPackageDescrFromFile( + "accumulateReverse.drl"); + + assertThat(pkg.getRules()).hasSize(1); + final RuleDescr rule = (RuleDescr) pkg.getRules().get(0); + assertThat(rule.getLhs().getDescrs()).hasSize(1); + + final PatternDescr out = (PatternDescr) rule.getLhs().getDescrs().get(0); + final AccumulateDescr accum = (AccumulateDescr) out.getSource(); + assertThat(accum.getInitCode()).isEqualToIgnoringWhitespace("int x = 0 ;" + ); + assertThat(accum.getActionCode()).isEqualToIgnoringWhitespace("x++;" + ); + assertThat(accum.getReverseCode()).isEqualToIgnoringWhitespace("x--;" + ); + assertThat(accum.getResultCode()).isEqualToIgnoringWhitespace("new Integer(x)" + ); + assertThat(accum.isExternalFunction()).isFalse(); + + final PatternDescr pattern = (PatternDescr) accum.getInputPattern(); + assertThat(pattern.getObjectType()).isEqualTo("Person"); + } + + @Test + void accumulateExternalFunction() { + final PackageDescr pkg = parseAndGetPackageDescrFromFile( + "accumulateExternalFunction.drl"); + + assertThat(pkg.getRules()).hasSize(1); + final RuleDescr rule = (RuleDescr) pkg.getRules().get(0); + assertThat(rule.getLhs().getDescrs()).hasSize(1); + + final PatternDescr out = (PatternDescr) rule.getLhs().getDescrs().get(0); + final AccumulateDescr accum = (AccumulateDescr) out.getSource(); + assertThat(accum.getFunctions().get(0).getParams()[0]).isEqualToIgnoringWhitespace("$age" + ); + assertThat(accum.getFunctions().get(0).getFunction()).isEqualToIgnoringWhitespace("average" + ); + assertThat(accum.isExternalFunction()).isTrue(); + + final PatternDescr pattern = (PatternDescr) accum.getInputPattern(); + assertThat(pattern.getObjectType()).isEqualTo("Person"); + } + + @Test + void collectWithNestedFrom() { + final PackageDescr pkg = parseAndGetPackageDescrFromFile( + "collect_with_nested_from.drl"); + + assertThat(pkg.getRules()).hasSize(1); + final RuleDescr rule = (RuleDescr) pkg.getRules().get(0); + assertThat(rule.getLhs().getDescrs()).hasSize(1); + + final PatternDescr out = (PatternDescr) rule.getLhs().getDescrs().get(0); + final CollectDescr collect = (CollectDescr) out.getSource(); + + PatternDescr person = (PatternDescr) collect.getInputPattern(); + assertThat(person.getObjectType()).isEqualTo("Person"); + + final CollectDescr collect2 = (CollectDescr) person.getSource(); + + final PatternDescr people = collect2.getInputPattern(); + assertThat(people.getObjectType()).isEqualTo("People"); + } + + @Test + void accumulateWithNestedFrom() { + final PackageDescr pkg = parseAndGetPackageDescrFromFile( + "accumulate_with_nested_from.drl"); + + assertThat(pkg.getRules()).hasSize(1); + final RuleDescr rule = (RuleDescr) pkg.getRules().get(0); + assertThat(rule.getLhs().getDescrs()).hasSize(1); + + final PatternDescr out = (PatternDescr) rule.getLhs().getDescrs().get(0); + final AccumulateDescr accumulate = (AccumulateDescr) out.getSource(); + + PatternDescr person = (PatternDescr) accumulate.getInputPattern(); + assertThat(person.getObjectType()).isEqualTo("Person"); + + final CollectDescr collect2 = (CollectDescr) person.getSource(); + + final PatternDescr people = collect2.getInputPattern(); + assertThat(people.getObjectType()).isEqualTo("People"); + } + + @Test + void accumulateMultipleFunctions() { + final PackageDescr pkg = parseAndGetPackageDescrFromFile( + "accumulateMultipleFunctions.drl"); + + assertThat(pkg.getRules()).hasSize(1); + + RuleDescr rule = (RuleDescr) pkg.getRules().get(0); + assertThat(rule.getLhs().getDescrs()).hasSize(1); + + PatternDescr out = (PatternDescr) rule.getLhs().getDescrs().get(0); + assertThat(out.getObjectType()).isEqualTo("Object"); + AccumulateDescr accum = (AccumulateDescr) out.getSource(); + assertThat(accum.isExternalFunction()).isTrue(); + + List functions = accum.getFunctions(); + assertThat(functions).hasSize(3); + assertThat(functions.get(0).getFunction()).isEqualTo("average"); + assertThat(functions.get(0).getBind()).isEqualTo("$a1"); + assertThat(functions.get(0).getParams()[0]).isEqualTo("$price"); + + assertThat(functions.get(1).getFunction()).isEqualTo("min"); + assertThat(functions.get(1).getBind()).isEqualTo("$m1"); + assertThat(functions.get(1).getParams()[0]).isEqualTo("$price"); + + assertThat(functions.get(2).getFunction()).isEqualTo("max"); + assertThat(functions.get(2).getBind()).isEqualTo("$M1"); + assertThat(functions.get(2).getParams()[0]).isEqualTo("$price"); + + final PatternDescr pattern = (PatternDescr) accum.getInputPattern(); + assertThat(pattern.getObjectType()).isEqualTo("Cheese"); + } + + @Test + void accumulateMnemonic() { + String drl = "package org.drools.mvel.compiler\n" + + "rule \"Accumulate 1\"\n" + + "when\n" + + " acc( Cheese( $price : price ),\n" + + " $a1 : average( $price ) )\n" + + "then\n" + + "end\n"; + PackageDescr pkg = parseAndGetPackageDescr( + drl); + + assertThat(pkg.getRules()).hasSize(1); + + RuleDescr rule = (RuleDescr) pkg.getRules().get(0); + assertThat(rule.getLhs().getDescrs()).hasSize(1); + + PatternDescr out = (PatternDescr) rule.getLhs().getDescrs().get(0); + assertThat(out.getObjectType()).isEqualTo("Object"); + AccumulateDescr accum = (AccumulateDescr) out.getSource(); + assertThat(accum.isExternalFunction()).isTrue(); + + List functions = accum.getFunctions(); + assertThat(functions).hasSize(1); + assertThat(functions.get(0).getFunction()).isEqualTo("average"); + assertThat(functions.get(0).getBind()).isEqualTo("$a1"); + assertThat(functions.get(0).getParams()[0]).isEqualTo("$price"); + + final PatternDescr pattern = (PatternDescr) accum.getInputPattern(); + assertThat(pattern.getObjectType()).isEqualTo("Cheese"); + } + + @Test + void accumulateMnemonic2() { + String drl = "package org.drools.mvel.compiler\n" + + "rule \"Accumulate 1\"\n" + + "when\n" + + " Number() from acc( Cheese( $price : price ),\n" + + " average( $price ) )\n" + + "then\n" + + "end\n"; + PackageDescr pkg = parseAndGetPackageDescr( + drl); + + assertThat(pkg.getRules()).hasSize(1); + + RuleDescr rule = (RuleDescr) pkg.getRules().get(0); + assertThat(rule.getLhs().getDescrs()).hasSize(1); + + PatternDescr out = (PatternDescr) rule.getLhs().getDescrs().get(0); + assertThat(out.getObjectType()).isEqualTo("Number"); + AccumulateDescr accum = (AccumulateDescr) out.getSource(); + assertThat(accum.isExternalFunction()).isTrue(); + + List functions = accum.getFunctions(); + assertThat(functions).hasSize(1); + assertThat(functions.get(0).getFunction()).isEqualTo("average"); + assertThat(functions.get(0).getParams()[0]).isEqualTo("$price"); + + final PatternDescr pattern = (PatternDescr) accum.getInputPattern(); + assertThat(pattern.getObjectType()).isEqualTo("Cheese"); + } + + @Test + void importAccumulate() { + String drl = "package org.drools.mvel.compiler\n" + + "import acc foo.Bar baz\n" + + "import accumulate foo.Bar2 baz2\n" + + "rule \"Accumulate 1\"\n" + + "when\n" + + " acc( Cheese( $price : price ),\n" + + " $v1 : baz( $price ), \n" + + " $v2 : baz2( $price ) )\n" + + "then\n" + + "end\n"; + PackageDescr pkg = parseAndGetPackageDescr( + drl); + + assertThat(pkg.getAccumulateImports()).hasSize(2); + AccumulateImportDescr imp = (AccumulateImportDescr) pkg.getAccumulateImports().get(0); + assertThat(imp.getTarget()).isEqualTo("foo.Bar"); + assertThat(imp.getFunctionName()).isEqualTo("baz"); + + imp = (AccumulateImportDescr) pkg.getAccumulateImports().get(1); + assertThat(imp.getTarget()).isEqualTo("foo.Bar2"); + assertThat(imp.getFunctionName()).isEqualTo("baz2"); + + assertThat(pkg.getRules()).hasSize(1); + + RuleDescr rule = (RuleDescr) pkg.getRules().get(0); + assertThat(rule.getLhs().getDescrs()).hasSize(1); + + PatternDescr out = (PatternDescr) rule.getLhs().getDescrs().get(0); + assertThat(out.getObjectType()).isEqualTo("Object"); + AccumulateDescr accum = (AccumulateDescr) out.getSource(); + assertThat(accum.isExternalFunction()).isTrue(); + + List functions = accum.getFunctions(); + assertThat(functions).hasSize(2); + assertThat(functions.get(0).getFunction()).isEqualTo("baz"); + assertThat(functions.get(0).getBind()).isEqualTo("$v1"); + assertThat(functions.get(0).getParams()[0]).isEqualTo("$price"); + + assertThat(functions.get(1).getFunction()).isEqualTo("baz2"); + assertThat(functions.get(1).getBind()).isEqualTo("$v2"); + assertThat(functions.get(1).getParams()[0]).isEqualTo("$price"); + + final PatternDescr pattern = (PatternDescr) accum.getInputPattern(); + assertThat(pattern.getObjectType()).isEqualTo("Cheese"); + } + + @Test + void accumulateMultipleFunctionsConstraint() { + final PackageDescr pkg = parseAndGetPackageDescrFromFile( + "accumulateMultipleFunctionsConstraint.drl"); + + assertThat(pkg.getRules()).hasSize(1); + + RuleDescr rule = (RuleDescr) pkg.getRules().get(0); + assertThat(rule.getLhs().getDescrs()).hasSize(1); + + PatternDescr out = (PatternDescr) rule.getLhs().getDescrs().get(0); + assertThat(out.getObjectType()).isEqualTo("Object"); + assertThat(out.getConstraint().getDescrs()).hasSize(2); + assertThat(out.getConstraint().getDescrs().get(0).toString()).isEqualTo("$a1 > 10 && $M1 <= 100"); + assertThat(out.getConstraint().getDescrs().get(1).toString()).isEqualTo("$m1 == 5"); + AccumulateDescr accum = (AccumulateDescr) out.getSource(); + assertThat(accum.isExternalFunction()).isTrue(); + + List functions = accum.getFunctions(); + assertThat(functions).hasSize(3); + assertThat(functions.get(0).getFunction()).isEqualTo("average"); + assertThat(functions.get(0).getBind()).isEqualTo("$a1"); + assertThat(functions.get(0).getParams()[0]).isEqualTo("$price"); + + assertThat(functions.get(1).getFunction()).isEqualTo("min"); + assertThat(functions.get(1).getBind()).isEqualTo("$m1"); + assertThat(functions.get(1).getParams()[0]).isEqualTo("$price"); + + assertThat(functions.get(2).getFunction()).isEqualTo("max"); + assertThat(functions.get(2).getBind()).isEqualTo("$M1"); + assertThat(functions.get(2).getParams()[0]).isEqualTo("$price"); + + final PatternDescr pattern = (PatternDescr) accum.getInputPattern(); + assertThat(pattern.getObjectType()).isEqualTo("Cheese"); + } + + @Test + void orCE() { + final PackageDescr pkg = parseAndGetPackageDescrFromFile( + "or_ce.drl"); + + assertThat(pkg.getRules()).hasSize(1); + final RuleDescr rule = (RuleDescr) pkg.getRules().get(0); + assertThat(rule.getLhs().getDescrs()).hasSize(2); + + final PatternDescr person = (PatternDescr) rule.getLhs().getDescrs().get(0); + assertThat(person.getObjectType()).isEqualTo("Person"); + assertThat(person.getIdentifier()).isEqualTo("$p"); + + final OrDescr or = (OrDescr) rule.getLhs().getDescrs().get(1); + assertThat(or.getDescrs()).hasSize(2); + + final PatternDescr cheese1 = (PatternDescr) or.getDescrs().get(0); + assertThat(cheese1.getObjectType()).isEqualTo("Cheese"); + assertThat(cheese1.getIdentifier()).isEqualTo("$c"); + final PatternDescr cheese2 = (PatternDescr) or.getDescrs().get(1); + assertThat(cheese2.getObjectType()).isEqualTo("Cheese"); + assertThat(cheese2.getIdentifier()).isNull(); + } + + @Test + void ruleSingleLine() { + final String text = "rule \"another test\" salience 10 when eval( true ) then System.out.println(1); end"; + RuleDescr rule = parseAndGetFirstRuleDescr( + text); + + assertThat(rule.getName()).isEqualTo("another test"); + assertThat((String) rule.getConsequence()).isEqualToIgnoringWhitespace("System.out.println(1); "); + } + + @Test + void ruleTwoLines() { + final String text = "rule \"another test\" salience 10 when eval( true ) then System.out.println(1);\n end"; + RuleDescr rule = parseAndGetFirstRuleDescr( + text); + + assertThat(rule.getName()).isEqualTo("another test"); + assertThat((String) rule.getConsequence()).isEqualToIgnoringWhitespace("System.out.println(1);\n "); + } + + @Test + void ruleParseLhs3() { + final String text = "rule X when (or\nnot Person()\n(and Cheese()\nMeat()\nWine())) then end"; + AndDescr pattern = parseAndGetFirstRuleDescr( + text).getLhs(); + + assertThat(pattern.getDescrs()).hasSize(1); + OrDescr or = (OrDescr) pattern.getDescrs().get(0); + assertThat(or.getDescrs()).hasSize(2); + NotDescr not = (NotDescr) or.getDescrs().get(0); + AndDescr and = (AndDescr) or.getDescrs().get(1); + assertThat(not.getDescrs()).hasSize(1); + PatternDescr person = (PatternDescr) not.getDescrs().get(0); + assertThat(person.getObjectType()).isEqualTo("Person"); + assertThat(and.getDescrs()).hasSize(3); + PatternDescr cheese = (PatternDescr) and.getDescrs().get(0); + assertThat(cheese.getObjectType()).isEqualTo("Cheese"); + PatternDescr meat = (PatternDescr) and.getDescrs().get(1); + assertThat(meat.getObjectType()).isEqualTo("Meat"); + PatternDescr wine = (PatternDescr) and.getDescrs().get(2); + assertThat(wine.getObjectType()).isEqualTo("Wine"); + } + + @Test + void accumulateMultiPattern() { + final PackageDescr pkg = parseAndGetPackageDescrFromFile( + "accumulate_multi_pattern.drl"); + + assertThat(pkg.getRules()).hasSize(1); + final RuleDescr rule = (RuleDescr) pkg.getRules().get(0); + assertThat(rule.getLhs().getDescrs()).hasSize(1); + + final PatternDescr outPattern = (PatternDescr) rule.getLhs().getDescrs().get(0); + final AccumulateDescr accum = (AccumulateDescr) outPattern.getSource(); + assertThat(outPattern.getIdentifier()).isEqualToIgnoringWhitespace("$counter" + ); + assertThat(accum.getInitCode()).isEqualToIgnoringWhitespace("int x = 0 ;" + ); + assertThat(accum.getActionCode()).isEqualToIgnoringWhitespace("x++;" + ); + assertThat(accum.getResultCode()).isEqualToIgnoringWhitespace("new Integer(x)" + ); + + final AndDescr and = (AndDescr) accum.getInput(); + assertThat(and.getDescrs()).hasSize(2); + final PatternDescr person = (PatternDescr) and.getDescrs().get(0); + final PatternDescr cheese = (PatternDescr) and.getDescrs().get(1); + assertThat(person.getObjectType()).isEqualTo("Person"); + assertThat(cheese.getObjectType()).isEqualTo("Cheese"); + } + + @Test + void pluggableOperators() { + + final PackageDescr pkg = parseAndGetPackageDescrFromFile( + "pluggable_operators.drl"); + + assertThat(pkg.getRules()).hasSize(1); + final RuleDescr rule = (RuleDescr) pkg.getRules().get(0); + assertThat(rule.getLhs().getDescrs()).hasSize(5); + + final PatternDescr eventA = (PatternDescr) rule.getLhs().getDescrs().get(0); + assertThat(eventA.getIdentifier()).isEqualTo("$a"); + assertThat(eventA.getObjectType()).isEqualTo("EventA"); + + final PatternDescr eventB = (PatternDescr) rule.getLhs().getDescrs().get(1); + assertThat(eventB.getIdentifier()).isEqualTo("$b"); + assertThat(eventB.getObjectType()).isEqualTo("EventB"); + assertThat(eventB.getConstraint().getDescrs()).hasSize(1); + assertThat(eventB.getConstraint().getDescrs()).hasSize(1); + + final ExprConstraintDescr fcdB = (ExprConstraintDescr) eventB.getConstraint().getDescrs().get(0); + assertThat(fcdB.getExpression()).isEqualTo("this after[1,10] $a || this not after[15,20] $a"); + + final PatternDescr eventC = (PatternDescr) rule.getLhs().getDescrs().get(2); + assertThat(eventC.getIdentifier()).isEqualTo("$c"); + assertThat(eventC.getObjectType()).isEqualTo("EventC"); + assertThat(eventC.getConstraint().getDescrs()).hasSize(1); + final ExprConstraintDescr fcdC = (ExprConstraintDescr) eventC.getConstraint().getDescrs().get(0); + assertThat(fcdC.getExpression()).isEqualTo("this finishes $b"); + + final PatternDescr eventD = (PatternDescr) rule.getLhs().getDescrs().get(3); + assertThat(eventD.getIdentifier()).isEqualTo("$d"); + assertThat(eventD.getObjectType()).isEqualTo("EventD"); + assertThat(eventD.getConstraint().getDescrs()).hasSize(1); + final ExprConstraintDescr fcdD = (ExprConstraintDescr) eventD.getConstraint().getDescrs().get(0); + assertThat(fcdD.getExpression()).isEqualTo("this not starts $a"); + + final PatternDescr eventE = (PatternDescr) rule.getLhs().getDescrs().get(4); + assertThat(eventE.getIdentifier()).isEqualTo("$e"); + assertThat(eventE.getObjectType()).isEqualTo("EventE"); + assertThat(eventE.getConstraint().getDescrs()).hasSize(1); + + ExprConstraintDescr fcdE = (ExprConstraintDescr) eventE.getConstraint().getDescrs().get(0); + assertThat(fcdE.getExpression()).isEqualTo("this not before[1, 10] $b || after[1, 10] $c && this after[1, 5] $d"); + } + + @Test + void ruleMetadata() { + final PackageDescr pkg = parseAndGetPackageDescrFromFile( + "Rule_with_Metadata.drl"); + + // @fooAttribute(barValue) + // @fooAtt2(barVal2) + RuleDescr rule = pkg.getRules().get(0); + assertThat(rule.getAnnotationNames()).contains("fooMeta1"); + assertThat(rule.getAnnotation("fooMeta1").getValue()).isEqualTo("barVal1"); + assertThat(rule.getAnnotationNames()).contains("fooMeta2"); + assertThat(rule.getAnnotation("fooMeta2").getValue()).isEqualTo("barVal2"); + assertThat((String) rule.getConsequence()).isEqualToIgnoringWhitespace("System.out.println(\"Consequence\");" + ); + } + + @Test + void ruleExtends() { + final PackageDescr pkg = parseAndGetPackageDescrFromFile( + "Rule_with_Extends.drl"); + + RuleDescr rule = pkg.getRules().get(0); + assertThat(rule.getParentName() != null).isTrue(); + assertThat(rule.getParentName()).isEqualTo("rule1"); + + AndDescr lhs = rule.getLhs(); + assertThat(lhs).isNotNull(); + assertThat(lhs.getDescrs()).hasSize(1); + + PatternDescr pattern = (PatternDescr) lhs.getDescrs().get(0); + assertThat(pattern.getObjectType()).isEqualTo("foo"); + assertThat(pattern.getIdentifier()).isEqualTo("$foo"); + } + + @Test + void typeDeclarationWithFields() { + final PackageDescr pkg = parseAndGetPackageDescrFromFile( + "declare_type_with_fields.drl"); + + List td = pkg.getTypeDeclarations(); + assertThat(td).hasSize(3); + + TypeDeclarationDescr d = td.get(0); + assertThat(d.getTypeName()).isEqualTo("SomeFact"); + assertThat(d.getFields()).hasSize(2); + assertThat(d.getFields()).containsKey("name"); + assertThat(d.getFields()).containsKey("age"); + + TypeFieldDescr f = d.getFields().get("name"); + assertThat(f.getPattern().getObjectType()).isEqualTo("String"); + + f = d.getFields().get("age"); + assertThat(f.getPattern().getObjectType()).isEqualTo("Integer"); + + d = td.get(1); + assertThat(d.getTypeName()).isEqualTo("AnotherFact"); + + TypeDeclarationDescr type = td.get(2); + assertThat(type.getTypeName()).isEqualTo("Person"); + + assertThat(type.getAnnotation("role").getValue()).isEqualTo("fact"); + assertThat(type.getAnnotation("doc").getValue("descr")).isEqualTo("\"Models a person\""); + assertThat(type.getAnnotation("doc").getValue("author")).isEqualTo("\"Bob\""); + assertThat(type.getAnnotation("doc").getValue("date")).isEqualTo("Calendar.getInstance().getDate()"); + + assertThat(type.getFields()).hasSize(2); + TypeFieldDescr field = type.getFields().get("name"); + assertThat(field.getFieldName()).isEqualTo("name"); + assertThat(field.getPattern().getObjectType()).isEqualTo("String"); + assertThat(field.getInitExpr()).isEqualTo("\"John Doe\""); + assertThat(field.getAnnotation("length").getValue("max")).isEqualTo("50"); + assertThat(field.getAnnotation("key")).isNotNull(); + + field = type.getFields().get("age"); + assertThat(field.getFieldName()).isEqualTo("age"); + assertThat(field.getPattern().getObjectType()).isEqualTo("int"); + assertThat(field.getInitExpr()).isEqualTo("-1"); + assertThat(field.getAnnotation("ranged").getValue("min")).isEqualTo("0"); + assertThat(field.getAnnotation("ranged").getValue("max")).isEqualTo("150"); + assertThat(field.getAnnotation("ranged").getValue("unknown")).isEqualTo("-1"); + } + + @Test + void qualifiedTypeDeclaration() { + final PackageDescr pkg = parseAndGetPackageDescrFromFile( + "qualified_type_declaration.drl"); + + TypeDeclarationDescr someFact = pkg.getTypeDeclarations().get(0); + assertThat(someFact.getTypeName()).isEqualTo("SomeFact"); + assertThat(someFact.getNamespace()).isEqualTo("com.sample1"); + + EnumDeclarationDescr color = pkg.getEnumDeclarations().get(0); + assertThat(color.getTypeName()).isEqualTo("Color"); + assertThat(color.getNamespace()).isEqualTo("com.sample2"); + } + + @Test + void parenthesesOneLevelNestWithThreeSiblings() { + final PackageDescr pkg = parseAndGetPackageDescrFromFile("Rule_with_nested_LHS.drl"); + + RuleDescr rule = pkg.getRules().get(0); + assertThat(rule.getName()).isEqualTo("test"); + + AndDescr lhs = rule.getLhs(); + assertThat(lhs).isNotNull(); + assertThat(lhs.getDescrs()).hasSize(2); + + PatternDescr a = (PatternDescr) lhs.getDescrs().get(0); + assertThat(a.getObjectType()).isEqualTo("A"); + + OrDescr or = (OrDescr) lhs.getDescrs().get(1); + assertThat(or.getDescrs()).hasSize(3); + + AndDescr and1 = (AndDescr) or.getDescrs().get(0); + assertThat(and1.getDescrs()).hasSize(2); + PatternDescr b = (PatternDescr) and1.getDescrs().get(0); + PatternDescr c = (PatternDescr) and1.getDescrs().get(1); + assertThat(b.getObjectType()).isEqualTo("B"); + assertThat(c.getObjectType()).isEqualTo("C"); + + AndDescr and2 = (AndDescr) or.getDescrs().get(1); + assertThat(and2.getDescrs()).hasSize(2); + PatternDescr d = (PatternDescr) and2.getDescrs().get(0); + PatternDescr e = (PatternDescr) and2.getDescrs().get(1); + assertThat(d.getObjectType()).isEqualTo("D"); + assertThat(e.getObjectType()).isEqualTo("E"); + + AndDescr and3 = (AndDescr) or.getDescrs().get(2); + assertThat(and3.getDescrs()).hasSize(2); + PatternDescr f = (PatternDescr) and3.getDescrs().get(0); + PatternDescr g = (PatternDescr) and3.getDescrs().get(1); + assertThat(f.getObjectType()).isEqualTo("F"); + assertThat(g.getObjectType()).isEqualTo("G"); + } + + @Test + void entryPoint() { + final String text = "rule X when StockTick( symbol==\"ACME\") from entry-point StreamA then end"; + + PackageDescr pkg = parseAndGetPackageDescr( + text); + + RuleDescr rule = pkg.getRules().get(0); + PatternDescr pattern = (PatternDescr) rule.getLhs().getDescrs().get(0); + + assertThat(pattern.getDescrs()).hasSize(1); + ExprConstraintDescr fcd = (ExprConstraintDescr) pattern.getDescrs().get(0); + assertThat(fcd.getExpression()).isEqualTo("symbol==\"ACME\""); + + assertThat(pattern.getSource()).isNotNull(); + EntryPointDescr entry = (EntryPointDescr) pattern.getSource(); + assertThat(entry.getEntryId()).isEqualTo("StreamA"); + } + + @Test + void entryPoint2() { + final String text = "rule X when StockTick( symbol==\"ACME\") from entry-point \"StreamA\" then end"; + + PackageDescr pkg = parseAndGetPackageDescr( + text); + + RuleDescr rule = pkg.getRules().get(0); + PatternDescr pattern = (PatternDescr) rule.getLhs().getDescrs().get(0); + + assertThat(pattern.getDescrs()).hasSize(1); + ExprConstraintDescr fcd = (ExprConstraintDescr) pattern.getDescrs().get(0); + assertThat(fcd.getExpression()).isEqualTo("symbol==\"ACME\""); + + assertThat(pattern.getSource()).isNotNull(); + EntryPointDescr entry = (EntryPointDescr) pattern.getSource(); + assertThat(entry.getEntryId()).isEqualTo("StreamA"); + } + + @Test + void slidingWindow() { + final String text = "rule X when StockTick( symbol==\"ACME\") over window:length(10) then end"; + + PackageDescr pkg = parseAndGetPackageDescr(text); + + RuleDescr rule = pkg.getRules().get(0); + PatternDescr pattern = (PatternDescr) rule.getLhs().getDescrs().get(0); + + assertThat(pattern.getDescrs()).hasSize(1); + ExprConstraintDescr fcd = (ExprConstraintDescr) pattern.getDescrs().get(0); + assertThat(fcd.getExpression()).isEqualTo("symbol==\"ACME\""); + + List behaviors = pattern.getBehaviors(); + assertThat(behaviors).isNotNull(); + assertThat(behaviors).hasSize(1); + BehaviorDescr descr = behaviors.get(0); + assertThat(descr.getType()).isEqualTo("window"); + assertThat(descr.getSubType()).isEqualTo("length"); + assertThat(descr.getParameters().get(0)).isEqualTo("10"); + } + + @Test + void ruleOldSyntax1() { + final String source = "rule \"Test\" when ( not $r :LiteralRestriction( operator == Operator.EQUAL ) ) then end"; + + PackageDescr pkg = parseAndGetPackageDescr( + source); + + RuleDescr rule = (RuleDescr) pkg.getRules().get(0); + + assertThat(rule.getName()).isEqualTo("Test"); + assertThat(rule.getLhs().getDescrs()).hasSize(1); + assertThat(((NotDescr) rule.getLhs().getDescrs().get(0)).getDescrs()).hasSize(1); + NotDescr notDescr = (NotDescr) rule.getLhs().getDescrs().get(0); + PatternDescr patternDescr = (PatternDescr) notDescr.getDescrs().get(0); + assertThat(patternDescr.getIdentifier()).isEqualTo("$r"); + assertThat(patternDescr.getDescrs()).hasSize(1); + ExprConstraintDescr fieldConstraintDescr = (ExprConstraintDescr) patternDescr.getDescrs().get(0); + assertThat(fieldConstraintDescr.getExpression()).isEqualToIgnoringWhitespace("operator == Operator.EQUAL"); + } + + @Test + void ruleOldSyntax2() { + final String source = "rule \"Test\" when ( $r :LiteralRestriction( operator == Operator.EQUAL ) ) then end"; + + PackageDescr pkg = parseAndGetPackageDescr( + source); + + RuleDescr rule = (RuleDescr) pkg.getRules().get(0); + + assertThat(rule.getName()).isEqualTo("Test"); + assertThat(rule.getLhs().getDescrs()).hasSize(1); + PatternDescr patternDescr = (PatternDescr) rule.getLhs().getDescrs().get(0); + assertThat(patternDescr.getIdentifier()).isEqualTo("$r"); + assertThat(patternDescr.getDescrs()).hasSize(1); + ExprConstraintDescr fieldConstraintDescr = (ExprConstraintDescr) patternDescr.getDescrs().get(0); + assertThat(fieldConstraintDescr.getExpression()).isEqualToIgnoringWhitespace("operator == Operator.EQUAL"); + } + + @Test + void typeWithMetaData() { + + PackageDescr pkg = parseAndGetPackageDescrFromFile( + "type_with_meta.drl"); + + final List declarations = pkg.getTypeDeclarations(); + + assertThat(declarations).hasSize(3); + } + + @Test + void nullConstraints() { + final String text = "rule X when Person( name == null ) then end"; + PatternDescr pattern = (PatternDescr) parseAndGetFirstRuleDescr( + text).getLhs().getDescrs().get(0); + + assertThat(pattern.getDescrs()).hasSize(1); + ExprConstraintDescr fcd = (ExprConstraintDescr) pattern.getDescrs().get(0); + assertThat(fcd.getExpression()).isEqualTo("name == null"); + assertThat(fcd.getPosition()).isEqualTo(0); + assertThat(fcd.getType()).isEqualTo(ExprConstraintDescr.Type.NAMED); + } + + @Test + void positionalConstraintsOnly() { + final String text = "rule X when Person( \"Mark\", 42; ) then end"; + PatternDescr pattern = (PatternDescr) parseAndGetFirstRuleDescr( + text).getLhs().getDescrs().get(0); + + assertThat(pattern.getDescrs()).hasSize(2); + ExprConstraintDescr fcd = (ExprConstraintDescr) pattern.getDescrs().get(0); + assertThat(fcd.getExpression()).isEqualTo("\"Mark\""); + assertThat(fcd.getPosition()).isEqualTo(0); + assertThat(fcd.getType()).isEqualTo(ExprConstraintDescr.Type.POSITIONAL); + fcd = (ExprConstraintDescr) pattern.getDescrs().get(1); + assertThat(fcd.getExpression()).isEqualTo("42"); + assertThat(fcd.getPosition()).isEqualTo(1); + assertThat(fcd.getType()).isEqualTo(ExprConstraintDescr.Type.POSITIONAL); + } + + @Test + void isQuery() { + final String text = "rule X when ?person( \"Mark\", 42; ) then end"; + PatternDescr pattern = (PatternDescr) parseAndGetFirstRuleDescr( + text).getLhs().getDescrs().get(0); + + assertThat(pattern.isQuery()).isTrue(); + + assertThat(pattern.getDescrs()).hasSize(2); + ExprConstraintDescr fcd = (ExprConstraintDescr) pattern.getDescrs().get(0); + assertThat(fcd.getExpression()).isEqualTo("\"Mark\""); + assertThat(fcd.getPosition()).isEqualTo(0); + assertThat(fcd.getType()).isEqualTo(ExprConstraintDescr.Type.POSITIONAL); + fcd = (ExprConstraintDescr) pattern.getDescrs().get(1); + assertThat(fcd.getExpression()).isEqualTo("42"); + assertThat(fcd.getPosition()).isEqualTo(1); + assertThat(fcd.getType()).isEqualTo(ExprConstraintDescr.Type.POSITIONAL); + } + + @Test + void fromFollowedByQuery() { + // the 'from' expression requires a ";" to disambiguate the "?" + // prefix for queries from the ternary operator "? :" + final String text = "rule X when Cheese() from $cheesery ?person( \"Mark\", 42; ) then end"; + RuleDescr rule = parseAndGetFirstRuleDescr( + text); + + PatternDescr pattern = (PatternDescr) rule.getLhs().getDescrs().get(0); + assertThat(pattern.getObjectType()).isEqualTo("Cheese"); + assertThat(pattern.getSource().getText()).isEqualTo("from $cheesery"); + assertThat(pattern.isQuery()).isFalse(); + + pattern = (PatternDescr) rule.getLhs().getDescrs().get(1); + assertThat(pattern.getObjectType()).isEqualTo("person"); + assertThat(pattern.isQuery()).isTrue(); + } + + @Test + void fromWithTernaryFollowedByQuery() { + // the 'from' expression requires a ";" to disambiguate the "?" + // prefix for queries from the ternary operator "? :" + final String text = "rule X when Cheese() from (isFull ? $cheesery : $market) ?person( \"Mark\", 42; ) then end"; + RuleDescr rule = parseAndGetFirstRuleDescr( + text); + + PatternDescr pattern = (PatternDescr) rule.getLhs().getDescrs().get(0); + assertThat(pattern.getObjectType()).isEqualTo("Cheese"); + assertThat(pattern.getSource().getText()).isEqualToIgnoringWhitespace("from (isFull ? $cheesery : $market)"); + assertThat(pattern.isQuery()).isFalse(); + + pattern = (PatternDescr) rule.getLhs().getDescrs().get(1); + assertThat(pattern.getObjectType()).isEqualTo("person"); + assertThat(pattern.isQuery()).isTrue(); + } + + @Test + void multiValueAnnotationsBackwardCompatibility() { + // multiple values with no keys are parsed as a single value + final String text = "rule X @ann1( val1, val2 ) @ann2( \"val1\", \"val2\" ) when then end"; + RuleDescr rule = parseAndGetFirstRuleDescr( + text); + + AnnotationDescr ann = rule.getAnnotation("ann1"); + assertThat(ann).isNotNull(); + assertThat(ann.getValue()).isEqualTo("val1, val2"); + + ann = rule.getAnnotation("ann2"); + assertThat(ann).isNotNull(); + assertThat(ann.getValue()).isEqualTo("\"val1\", \"val2\""); + assertThat(ann.getSingleValueAsString()).isEqualTo("\"val1\", \"val2\""); + } + + @Test + void positionalsAndNamedConstraints() { + final String text = "rule X when Person( \"Mark\", 42; location == \"atlanta\" ) then end"; + PatternDescr pattern = (PatternDescr) parseAndGetFirstRuleDescr( + text).getLhs().getDescrs().get(0); + + assertThat(pattern.getDescrs()).hasSize(3); + ExprConstraintDescr fcd = (ExprConstraintDescr) pattern.getDescrs().get(0); + assertThat(fcd.getExpression()).isEqualTo("\"Mark\""); + assertThat(fcd.getPosition()).isEqualTo(0); + assertThat(fcd.getType()).isEqualTo(ExprConstraintDescr.Type.POSITIONAL); + fcd = (ExprConstraintDescr) pattern.getDescrs().get(1); + assertThat(fcd.getExpression()).isEqualTo("42"); + assertThat(fcd.getPosition()).isEqualTo(1); + assertThat(fcd.getType()).isEqualTo(ExprConstraintDescr.Type.POSITIONAL); + + fcd = (ExprConstraintDescr) pattern.getDescrs().get(2); + assertThat(fcd.getExpression()).isEqualTo("location == \"atlanta\""); + assertThat(fcd.getPosition()).isEqualTo(2); + assertThat(fcd.getType()).isEqualTo(ExprConstraintDescr.Type.NAMED); + } + + @Test + void unificationBinding() { + final String text = "rule X when $p := Person( $name := name, $loc : location ) then end"; + PatternDescr pattern = (PatternDescr) parseAndGetFirstRuleDescr( + text).getLhs().getDescrs().get(0); + + assertThat(pattern.getIdentifier()).isEqualTo("$p"); + assertThat(pattern.isUnification()).isTrue(); + + assertThat(pattern.getDescrs()).hasSize(2); + ExprConstraintDescr bindingDescr = (ExprConstraintDescr) pattern.getDescrs().get(0); + assertThat(bindingDescr.getExpression()).isEqualTo("$name := name"); + + bindingDescr = (ExprConstraintDescr) pattern.getDescrs().get(1); + assertThat(bindingDescr.getExpression()).isEqualTo("$loc : location"); + } + + @Test + void bigLiterals() { + final String text = "rule X when Primitives( bigInteger == (10I), " + + " bigDecimal == (10B), " + + " bigInteger < 50I, " + + " bigDecimal < 50.2B ) then end"; + PatternDescr pattern = (PatternDescr) parseAndGetFirstRuleDescr( + text).getLhs().getDescrs().get(0); + + assertThat(pattern.getDescrs()).hasSize(4); + ExprConstraintDescr ecd = (ExprConstraintDescr) pattern.getDescrs().get(0); + assertThat(ecd.getExpression()).isEqualTo("bigInteger == (10I)"); + + ecd = (ExprConstraintDescr) pattern.getDescrs().get(1); + assertThat(ecd.getExpression()).isEqualTo("bigDecimal == (10B)"); + + ecd = (ExprConstraintDescr) pattern.getDescrs().get(2); + assertThat(ecd.getExpression()).isEqualTo("bigInteger < 50I"); + + ecd = (ExprConstraintDescr) pattern.getDescrs().get(3); + assertThat(ecd.getExpression()).isEqualTo("bigDecimal < 50.2B"); + } + + @Test + void bindingComposite() { + final String text = "rule X when Person( $name : name == \"Bob\" || $loc : location == \"Montreal\" ) then end"; + PatternDescr pattern = (PatternDescr) parseAndGetFirstRuleDescr( + text).getLhs().getDescrs().get(0); + + assertThat(pattern.getObjectType()).isEqualTo("Person"); + assertThat(pattern.isUnification()).isFalse(); + + // embedded bindings are extracted at compile time + List constraints = pattern.getDescrs(); + assertThat(constraints).hasSize(1); + assertThat(((ExprConstraintDescr) constraints.get(0)).getExpression()).isEqualTo("$name : name == \"Bob\" || $loc : location == \"Montreal\""); + } + + @Test + void bindingCompositeWithMethods() { + final String text = "rule X when Person( $name : name.toUpperCase() == \"Bob\" || $loc : location[0].city == \"Montreal\" ) then end"; + PatternDescr pattern = (PatternDescr) parseAndGetFirstRuleDescr( + text).getLhs().getDescrs().get(0); + + assertThat(pattern.getObjectType()).isEqualTo("Person"); + assertThat(pattern.isUnification()).isFalse(); + + // embedded bindings are extracted at compile time + List constraints = pattern.getDescrs(); + assertThat(constraints).hasSize(1); + assertThat(((ExprConstraintDescr) constraints.get(0)).getExpression()).isEqualTo("$name : name.toUpperCase() == \"Bob\" || $loc : location[0].city == \"Montreal\""); + } + + @Test + void pluggableOperators2() { + final String text = "rule \"tt\"\n" + + " dialect \"mvel\"\n" + + "when\n" + + " exists (TelephoneCall( this finishes [1m] \"25-May-2011\" ))\n" + + "then\n" + + "end"; + PatternDescr pattern = (PatternDescr) ((ExistsDescr) parseAndGetFirstRuleDescr( + text).getLhs().getDescrs().get(0)).getDescrs().get(0); + + assertThat(pattern.getObjectType()).isEqualTo("TelephoneCall"); + ExprConstraintDescr constr = (ExprConstraintDescr) pattern.getConstraint().getDescrs().get(0); + assertThat(constr.getText()).isEqualTo("this finishes [1m] \"25-May-2011\""); + } + + @Test + void inlineEval() { + final String text = "rule \"inline eval\"\n" + + "when\n" + + " Person( eval( name.startsWith(\"b\") && name.finishesWith(\"b\")) )\n" + + "then\n" + + "end"; + PatternDescr pattern = (PatternDescr) parseAndGetFirstRuleDescr( + text).getLhs().getDescrs().get(0); + + assertThat(pattern.getObjectType()).isEqualTo("Person"); + ExprConstraintDescr constr = (ExprConstraintDescr) pattern.getConstraint().getDescrs().get(0); + assertThat(constr.getText()).isEqualToIgnoringWhitespace("eval( name.startsWith(\"b\") && name.finishesWith(\"b\"))"); + } + + @Test + void infinityLiteral() { + final String text = "rule \"infinity\"\n" + + "when\n" + + " StockTick( this after[-*,*] $another )\n" + + "then\n" + + "end"; + PatternDescr pattern = (PatternDescr) parseAndGetFirstRuleDescr( + text).getLhs().getDescrs().get(0); + + assertThat(pattern.getObjectType()).isEqualTo("StockTick"); + ExprConstraintDescr constr = (ExprConstraintDescr) pattern.getConstraint().getDescrs().get(0); + assertThat(constr.getText()).isEqualTo("this after[-*,*] $another"); + } + + static Stream entryPointIds() { + return Stream.of( + Arguments.of("eventStream", "eventStream"), + Arguments.of("\"My entry-point 'ID'\"", "My entry-point 'ID'") + ); + } + + @ParameterizedTest + @MethodSource("entryPointIds") + void parse_EntryPointDeclaration(String sourceId, String expectedId) { + final String text = "package org.drools\n" + + "declare entry-point " + sourceId + "\n" + + " @source(\"jndi://queues/events\")\n" + + " @foo( true )\n" + + "end"; + PackageDescr pkg = parseAndGetPackageDescr( + text); + + assertThat(pkg.getName()).isEqualTo("org.drools"); + assertThat(pkg.getEntryPointDeclarations()).hasSize(1); + + EntryPointDeclarationDescr epd = pkg.getEntryPointDeclarations().iterator().next(); + + assertThat(epd.getEntryPointId()).isEqualTo(expectedId); + assertThat(epd.getAnnotations()).hasSize(2); + assertThat(epd.getAnnotation("source").getValue()).isEqualTo("\"jndi://queues/events\""); + assertThat(epd.getAnnotation("foo").getValue()).isEqualTo("true"); + } + + @Test + void windowDeclaration() { + final String text = "package org.drools\n" + + "declare window Ticks\n" + + " @doc(\"last 10 stock ticks\")\n" + + " $s : StockTick( source == \"NYSE\" )\n" + + " over window:length( 10, $s.symbol )\n" + + " from entry-point stStream\n" + + "end"; + PackageDescr pkg = parseAndGetPackageDescr( + text); + + assertThat(pkg.getName()).isEqualTo("org.drools"); + assertThat(pkg.getWindowDeclarations()).hasSize(1); + + WindowDeclarationDescr wdd = pkg.getWindowDeclarations().iterator().next(); + + assertThat(wdd.getName()).isEqualTo("Ticks"); + assertThat(wdd.getAnnotations()).hasSize(1); + assertThat(wdd.getAnnotation("doc").getValue()).isEqualTo("\"last 10 stock ticks\""); + + PatternDescr pd = wdd.getPattern(); + assertThat(pd).isNotNull(); + assertThat(pd.getIdentifier()).isEqualTo("$s"); + assertThat(pd.getObjectType()).isEqualTo("StockTick"); + assertThat(pd.getSource().getText()).isEqualTo("stStream"); + + assertThat(pd.getBehaviors()).hasSize(1); + BehaviorDescr bd = pd.getBehaviors().get(0); + assertThat(bd.getType()).isEqualTo("window"); + assertThat(bd.getSubType()).isEqualTo("length"); + assertThat(bd.getParameters()).hasSize(2); + assertThat(bd.getParameters().get(0)).isEqualTo("10"); + assertThat(bd.getParameters().get(1)).isEqualTo("$s.symbol"); + } + + @Test + void windowUsage() { + final String text = "package org.drools\n" + + "rule X\n" + + "when\n" + + " StockTick() from window Y\n" + + "then\n" + + "end\n"; + PackageDescr pkg = parseAndGetPackageDescr( + text); + + assertThat(pkg.getName()).isEqualTo("org.drools"); + assertThat(pkg.getRules()).hasSize(1); + + RuleDescr rd = pkg.getRules().get(0); + + assertThat(rd.getName()).isEqualTo("X"); + assertThat(rd.getLhs().getDescrs()).hasSize(1); + + PatternDescr pd = (PatternDescr) rd.getLhs().getDescrs().get(0); + assertThat(pd).isNotNull(); + assertThat(pd.getObjectType()).isEqualTo("StockTick"); + assertThat(pd.getSource().getText()).isEqualTo("Y"); + } + + @Test + void endInRhs() { + final String text = "package org.drools\n" + + "rule X\n" + + "when\n" + + " $s : String()\n" + + "then\n" + + " System.out.println($s.endsWith(\"xyz\"));\n" + + "end\n"; + PackageDescr packageDescr = parseAndGetPackageDescr(text); + + RuleDescr ruleDescr = packageDescr.getRules().get(0); + assertThat(ruleDescr.getConsequence().toString()).isEqualToIgnoringWhitespace("System.out.println($s.endsWith(\"xyz\"));"); + } + + @Test + void endTokenInRhs() { + final String text = "package org.drools\n" + + "rule X\n" + + "when\n" + + " $s : String()\n" + + "then\n" + + " int end = 10;\n" + + "end\n"; + PackageDescr packageDescr = parseAndGetPackageDescr(text); + + RuleDescr ruleDescr = packageDescr.getRules().get(0); + assertThat(ruleDescr.getConsequence().toString()).isEqualToIgnoringWhitespace("int end = 10;"); + } + + @Test + void ruleTokenInRhs() { + final String text = "package org.drools\n" + + "rule X\n" + + "when\n" + + " $s : String()\n" + + "then\n" + + " int rule = 10;\n" + + "end\n"; + PackageDescr packageDescr = parseAndGetPackageDescr(text); + + RuleDescr ruleDescr = packageDescr.getRules().get(0); + assertThat(ruleDescr.getConsequence().toString()).isEqualToIgnoringWhitespace("int rule = 10;"); + } + + @Test + void semicolonEnd() { + final String text = "package org.drools\n" + + "rule X\n" + + "when\n" + + " $s : String()\n" + + "then\n" + + " delete($s);end\n"; // no space after semicolon + PackageDescr packageDescr = parseAndGetPackageDescr(text); + + RuleDescr ruleDescr = packageDescr.getRules().get(0); + assertThat(ruleDescr.getConsequence().toString()).isEqualToIgnoringWhitespace("delete($s);"); + } + + @Test + void braceEnd() { + final String text = "package org.drools\n" + + "rule X\n" + + "when\n" + + " $p : Person()\n" + + "then\n" + + " modify($p) { setAge(2) }end\n"; // no space after right brace + PackageDescr packageDescr = parseAndGetPackageDescr(text); + + RuleDescr ruleDescr = packageDescr.getRules().get(0); + assertThat(ruleDescr.getConsequence().toString()).isEqualToIgnoringWhitespace("modify($p) { setAge(2) }"); + } + + @Test + void parenthesisEnd() { + final String text = "package org.drools\n" + + "rule X\n" + + "when\n" + + " $p : Person()\n" + + "then\n" + + " retract($p)end\n"; // no space after right parenthesis + PackageDescr packageDescr = parseAndGetPackageDescr(text); + + RuleDescr ruleDescr = packageDescr.getRules().get(0); + assertThat(ruleDescr.getConsequence().toString()).isEqualToIgnoringWhitespace("retract($p)"); + } + + @Test + void endAndRuleInSameLine() { + final String text = "package org.drools\n" + + "rule R1\n" + + "when\n" + + " $p : Person()\n" + + "then\n" + + " retract($p)\n" + + "end rule R2 when Person() then end"; // 'rule' after 'end' in the same line + PackageDescr packageDescr = parseAndGetPackageDescr(text); + + List ruleDescrList = packageDescr.getRules(); + assertThat(ruleDescrList).hasSize(2); + assertThat(ruleDescrList.get(0).getName()).isEqualTo("R1"); + assertThat(ruleDescrList.get(1).getName()).isEqualTo("R2"); + } + + @Test + void endAndAttributeAndRuleInSameLine() { + final String text = "package org.drools\n" + + "rule R1\n" + + "when\n" + + " $p : Person()\n" + + "then\n" + + " retract($p)\n" + + "end no-loop true rule R2 when Person() then end"; // 'end', attribute, 'rule' in the same line + PackageDescr packageDescr = parseAndGetPackageDescr(text); + + List ruleDescrList = packageDescr.getRules(); + assertThat(ruleDescrList).hasSize(2); + assertThat(ruleDescrList.get(0).getName()).isEqualTo("R1"); + assertThat(ruleDescrList.get(1).getName()).isEqualTo("R2"); + assertThat(packageDescr.getAttributes().get(0).getName()).isEqualTo("no-loop"); // package level attribute + } + + @Test + void endAndSingleLineCommentAndRule() { + final String text = "package org.drools\n" + + "rule R1\n" + + "when\n" + + " $p : Person()\n" + + "then\n" + + " retract($p)\n" + + "end\n" + + "// comment\n" + + "rule R2 when Person() then end"; + PackageDescr packageDescr = parseAndGetPackageDescr(text); + + List ruleDescrList = packageDescr.getRules(); + assertThat(ruleDescrList).hasSize(2); + assertThat(ruleDescrList.get(0).getName()).isEqualTo("R1"); + assertThat(ruleDescrList.get(1).getName()).isEqualTo("R2"); + } + + @Test + void endAndMultiLineCommentAndRule() { + final String text = "package org.drools\n" + + "rule R1\n" + + "when\n" + + " $p : Person()\n" + + "then\n" + + " retract($p)\n" + + "end\n" + + "/* comment\n" + + "comment */\n" + + "rule R2 when Person() then end"; + PackageDescr packageDescr = parseAndGetPackageDescr(text); + + List ruleDescrList = packageDescr.getRules(); + assertThat(ruleDescrList).hasSize(2); + assertThat(ruleDescrList.get(0).getName()).isEqualTo("R1"); + assertThat(ruleDescrList.get(1).getName()).isEqualTo("R2"); + } + + @Test + void endAndNonPairingDoubleQuoteInSingleLineCommentInRHS() { + final String text = "package org.drools\n" + + "rule R1\n" + + "when\n" + + " $p : Person()\n" + + "then\n" + + " //System.out.println(\");\n" + // non-pairing double quote in comment + " retract($p)\n" + + "end\n" + + "rule \"R2\" when Person() then end"; + PackageDescr packageDescr = parseAndGetPackageDescr(text); + + List ruleDescrList = packageDescr.getRules(); + assertThat(ruleDescrList).hasSize(2); + assertThat(ruleDescrList.get(0).getName()).isEqualTo("R1"); + assertThat(ruleDescrList.get(1).getName()).isEqualTo("R2"); + } + + @Test + void endAndNonPairingDoubleQuoteInMultiLineCommentInRHS() { + final String text = "package org.drools\n" + + "rule R1\n" + + "when\n" + + " $p : Person()\n" + + "then\n" + + " /*System.out.println\n" + + " (\");*/\n" + // non-pairing double quote in comment + " retract($p)\n" + + "end\n" + + "rule \"R2\" when Person() then end"; + PackageDescr packageDescr = parseAndGetPackageDescr(text); + + List ruleDescrList = packageDescr.getRules(); + assertThat(ruleDescrList).hasSize(2); + assertThat(ruleDescrList.get(0).getName()).isEqualTo("R1"); + assertThat(ruleDescrList.get(1).getName()).isEqualTo("R2"); + } + + @Test + void endAndDoubleQuotationsInRHS() { + final String text = "package org.drools\n" + + "rule R1\n" + + "when\n" + + " $p : Person()\n" + + "then\n" + + " System.out.println(\"Draw \"+$p1+\" \"+$p2);\n" + + " retract($p)\n" + + "end\n" + + "rule \"R2\" when Person() then end"; + PackageDescr packageDescr = parseAndGetPackageDescr(text); + + List ruleDescrList = packageDescr.getRules(); + assertThat(ruleDescrList).hasSize(2); + assertThat(ruleDescrList.get(0).getName()).isEqualTo("R1"); + assertThat(ruleDescrList.get(1).getName()).isEqualTo("R2"); + } + + @Test + void endAndSingleQuotationsInRHS() { + final String text = "package org.drools\n" + + "rule R1\n" + + "when\n" + + " $p : Person()\n" + + "then\n" + + " System.out.println('Draw '+$p1+' '+$p2);\n" + + " retract($p)\n" + + "end\n" + + "rule \"R2\" when Person() then end"; + PackageDescr packageDescr = parseAndGetPackageDescr(text); + + List ruleDescrList = packageDescr.getRules(); + assertThat(ruleDescrList).hasSize(2); + assertThat(ruleDescrList.get(0).getName()).isEqualTo("R1"); + assertThat(ruleDescrList.get(1).getName()).isEqualTo("R2"); + } + + @Test + void singleQuoteInRhsWithSpace() { + String consequence = getResultConsequence(" System.out.println( 'singleQuoteInRhs' );\n"); + assertThat(consequence) + .as("Single quote should be converted to double quote") + .isEqualToIgnoringWhitespace("System.out.println( \"singleQuoteInRhs\" );"); + } + + @Test + void singleQuoteInRhsWithoutSpace() { + String consequence = getResultConsequence(" System.out.println('singleQuoteInRhs');\n"); + assertThat(consequence) + .as("Single quote should be converted to double quote") + .isEqualToIgnoringWhitespace("System.out.println( \"singleQuoteInRhs\" );"); + } + + @Test + void singleQuoteInDoubleQuoteInRhsWithoutSpace() { + String consequence = getResultConsequence(" System.out.println(\"There is '\" + $s + \"' in the workspace.\");\n"); + assertThat(consequence) + .as("Single quote should not be converted to double quote in case of inside double quotes") + .isEqualToIgnoringWhitespace("System.out.println(\"There is '\" + $s + \"' in the workspace.\");"); + } + + private String getResultConsequence(String rhs) { + final String text = "package org.drools\n" + + "rule X\n" + + "when\n" + + " $s : String()\n" + + "then\n" + + rhs + + "end\n"; + PackageDescr packageDescr = parseAndGetPackageDescr(text); + + RuleDescr ruleDescr = packageDescr.getRules().get(0); + return ruleDescr.getConsequence().toString(); + } + + @Test + void ruleDescrProperties() { + final String text = "package org.drools\n" + + "rule R1\n" + + "when\n" + + " $p : Person()\n" + + "then\n" + + " retract($p);\n" + + "end\n"; + + PackageDescr packageDescr = parseAndGetPackageDescr(text); + + RuleDescr ruleDescr = packageDescr.getRules().get(0); + + assertThat(ruleDescr.getName()).isEqualTo("R1"); + assertThat(ruleDescr.getNamespace()).isEqualTo("org.drools"); + } + + /** + * Each test input is a constraint expression covering one of the existing DRL operators. The test is successful if the parser has + * no errors and the descriptor's expression string is equal to the input. + * + * @param constraint expression using an operator + */ + @ParameterizedTest + @ValueSource(strings = { + "country matches \"[a-z]*\"", + "country not matches \"[a-z]*\"", + "person memberOf $europeanDescendants", + "person not memberOf $europeanDescendants", + "countries contains \"UK\"", + "countries not contains \"UK\"", + "countries excludes \"UK\"", + "countries not excludes \"UK\"", + "firstName soundslike \"John\"", + "firstName not soundslike \"John\"", + "routingValue str[startsWith] \"R1\"", + "routingValue not str[startsWith] \"R1\"" + }) + void constraintOperators(String constraint) { + final String text = "package org.drools\n" + + "rule R1\n" + + "when\n" + + " $p : Person(" + constraint + ")\n" + + "then\n" + + "end\n"; + + PackageDescr packageDescr = parseAndGetPackageDescr(text); + + RuleDescr ruleDescr = packageDescr.getRules().get(0); + AndDescr lhs = ruleDescr.getLhs(); + PatternDescr patternDescr = (PatternDescr) lhs.getDescrs().get(0); + ExprConstraintDescr exprConstraintDescr = (ExprConstraintDescr) patternDescr.getConstraint().getDescrs().get(0); + assertThat(exprConstraintDescr.getExpression()).isEqualToIgnoringWhitespace(constraint); + } + + @ParameterizedTest + @ValueSource(strings = { + "country matches \"[a-z]*\" || matches \"[A-Z]*\"", + "country not matches \"[a-z]*\" || not matches \"[A-Z]*\"", + "person memberOf $europeanDescendants || memberOf $africanDescendants", + "person not memberOf $europeanDescendants || not memberOf $africanDescendants", + "countries contains \"UK\" || contains \"US\"", + "countries not contains \"UK\" || not contains \"US\"", + "countries excludes \"UK\" || excludes \"US\"", + "countries not excludes \"UK\" || not excludes \"US\"", + "firstName soundslike \"John\" || soundslike \"Paul\"", + "firstName not soundslike \"John\" && not soundslike \"Paul\"", + "routingValue str[startsWith] \"R1\" || str[startsWith] \"R2\"", + "routingValue not str[startsWith] \"R1\" && not str[startsWith] \"R2\"" + }) + void halfConstraintOperators(String constraint) { + final String text = "package org.drools\n" + + "rule R1\n" + + "when\n" + + " $p : Person(" + constraint + ")\n" + + "then\n" + + "end\n"; + + PackageDescr packageDescr = parseAndGetPackageDescr(text); + + RuleDescr ruleDescr = packageDescr.getRules().get(0); + AndDescr lhs = ruleDescr.getLhs(); + PatternDescr patternDescr = (PatternDescr) lhs.getDescrs().get(0); + ExprConstraintDescr exprConstraintDescr = (ExprConstraintDescr) patternDescr.getConstraint().getDescrs().get(0); + assertThat(exprConstraintDescr.getExpression()).isEqualToIgnoringWhitespace(constraint); + } + + @Test + void nullSafeDereferencing() { + final String text = "package org.drools\n" + + "rule R1\n" + + "when\n" + + " $p : Person(address!.city == $city)\n" + + "then\n" + + "end\n"; + PackageDescr packageDescr = parseAndGetPackageDescr(text); + ExprConstraintDescr constraintDescr = getFirstExprConstraintDescr(packageDescr); + assertThat(constraintDescr.toString()).isEqualToIgnoringWhitespace("address!.city == $city"); + } + + @Test + void nullSafeDereferencingMethodCall() { + final String text = "package org.drools\n" + + "rule R1\n" + + "when\n" + + " $p : Person(address!.city!.startsWith(\"M\"))\n" + + "then\n" + + "end\n"; + PackageDescr packageDescr = parseAndGetPackageDescr(text); + ExprConstraintDescr constraintDescr = getFirstExprConstraintDescr(packageDescr); + assertThat(constraintDescr.toString()).isEqualToIgnoringWhitespace("address!.city!.startsWith(\"M\")"); + } + + @Test + void nullSafeDereferencingMethodCallBindVariable() { + final String text = "package org.drools\n" + + "rule R1\n" + + "when\n" + + " $p : Person( $containsL : address!.city.contains(\"L\") )\n" + + "then\n" + + "end\n"; + PackageDescr packageDescr = parseAndGetPackageDescr(text); + ExprConstraintDescr constraintDescr = getFirstExprConstraintDescr(packageDescr); + assertThat(constraintDescr.toString()).isEqualToIgnoringWhitespace("$containsL : address!.city.contains(\"L\")"); + } + + @Test + void groupedConstraints() { + final String text = "package org.drools\n" + + "rule R1\n" + + "when\n" + + " $p : Person( address.(city.startsWith(\"I\") && city.length() == 5 ) )\n" + + "then\n" + + "end\n"; + PackageDescr packageDescr = parseAndGetPackageDescr(text); + ExprConstraintDescr constraintDescr = getFirstExprConstraintDescr(packageDescr); + assertThat(constraintDescr.toString()) + .as("prefix should be appended to each element") + .isEqualToIgnoringWhitespace("address.city.startsWith(\"I\") && address.city.length() == 5"); + } + + @Test + void groupedConstraintsWithNullSafeDereferencing() { + final String text = "package org.drools\n" + + "rule R1\n" + + "when\n" + + " $p : Person( address!.(city!.startsWith(\"I\") && city!.length() == 5 ) )\n" + + "then\n" + + "end\n"; + PackageDescr packageDescr = parseAndGetPackageDescr(text); + ExprConstraintDescr constraintDescr = getFirstExprConstraintDescr(packageDescr); + assertThat(constraintDescr.toString()) + .as("prefix should be appended to each element") + .isEqualToIgnoringWhitespace("address!.city!.startsWith(\"I\") && address!.city!.length() == 5"); + } + + @Test + void functionWithStringLiteral() { + final String text = "function String star(String s) { return \"*\"; }"; + PackageDescr packageDescr = parseAndGetPackageDescr(text); + + FunctionDescr function = packageDescr.getFunctions().get(0); + + assertThat(function.getName()).isEqualTo("star"); + assertThat(function.getReturnType()).isEqualTo("String"); + assertThat(function.getParameterTypes().get(0)).isEqualTo("String"); + assertThat(function.getParameterNames().get(0)).isEqualTo("s"); + assertThat(function.getBody()).isEqualToIgnoringWhitespace("return \"*\";"); + } + + @Test + void functionWithStringLiteralAddition() { + final String text = "function String addStar(String s) { return s + \"*\"; }"; + PackageDescr packageDescr = parseAndGetPackageDescr(text); + + FunctionDescr function = packageDescr.getFunctions().get(0); + + assertThat(function.getName()).isEqualTo("addStar"); + assertThat(function.getReturnType()).isEqualTo("String"); + assertThat(function.getParameterTypes().get(0)).isEqualTo("String"); + assertThat(function.getParameterNames().get(0)).isEqualTo("s"); + assertThat(function.getBody()).isEqualToIgnoringWhitespace("return s + \"*\";"); + } + + @Test + void functionWithMultipleBlockStatements() { + final String text = "function String star(String s) {\n" + + " String result = s + \"*\";\n" + + " return result;\n" + + "}"; + PackageDescr packageDescr = parseAndGetPackageDescr(text); + + FunctionDescr function = packageDescr.getFunctions().get(0); + + assertThat(function.getName()).isEqualTo("star"); + assertThat(function.getReturnType()).isEqualTo("String"); + assertThat(function.getParameterTypes().get(0)).isEqualTo("String"); + assertThat(function.getParameterNames().get(0)).isEqualTo("s"); + assertThat(function.getBody()).isEqualToIgnoringWhitespace("String result = s + \"*\"; return result;"); + } + + @Test + void lhsPatternAnnotation() { + final String text = "package org.drools\n" + + "rule R1\n" + + "when\n" + + " $p : Person( name == \"Mario\" ) @watch(!*, age)\n" + + "then\n" + + "end\n"; + PackageDescr packageDescr = parseAndGetPackageDescr(text); + + RuleDescr ruleDescr = packageDescr.getRules().get(0); + PatternDescr patternDescr = (PatternDescr) ruleDescr.getLhs().getDescrs().get(0); + AnnotationDescr annotationDescr = patternDescr.getAnnotations().iterator().next(); + + assertThat(annotationDescr.getName()).isEqualTo("watch"); + assertThat(annotationDescr.getValue()).isEqualTo("!*, age"); + assertThat(annotationDescr.getSingleValueAsString()).isEqualTo("!*, age"); + } + + @Test + void prefixAndDescrAnnotation() { + final String text = + "rule R\n" + + " when\n" + + " ( and @Annot \n" + + " String() \n" + + " Integer() ) \n" + + " then\n" + + "end\n"; + PackageDescr packageDescr = parseAndGetPackageDescr(text); + + RuleDescr ruleDescr = packageDescr.getRules().get(0); + AndDescr andDescr = ruleDescr.getLhs(); + AnnotationDescr annotationDescr = andDescr.getAnnotations().iterator().next(); + assertThat(annotationDescr.getName()).isEqualTo("Annot"); + assertThat(annotationDescr.hasValue()).isFalse(); + + assertThat(andDescr.getDescrs()).hasSize(2); + } + + @Test + void prefixOrDescrAnnotation() { + final String text = + "rule R\n" + + " when\n" + + " ( or @Annot \n" + + " String() \n" + + " Integer() ) \n" + + " then\n" + + "end\n"; + PackageDescr packageDescr = parseAndGetPackageDescr(text); + + RuleDescr ruleDescr = packageDescr.getRules().get(0); + OrDescr orDescr = (OrDescr) ruleDescr.getLhs().getDescrs().get(0); + AnnotationDescr annotationDescr = orDescr.getAnnotations().iterator().next(); + + assertThat(annotationDescr.getName()).isEqualTo("Annot"); + assertThat(annotationDescr.hasValue()).isFalse(); + + assertThat(orDescr.getDescrs()).hasSize(2); + } + + @Test + void infixAndDescrAnnotation() { + final String text = + "rule R\n" + + " when\n" + + " ( Double() \n" + + " and @Annot1 String() \n" + + " and @Annot2 Integer() ) " + + " then\n" + + "end\n"; + PackageDescr packageDescr = parseAndGetPackageDescr(text); + + RuleDescr ruleDescr = packageDescr.getRules().get(0); + AndDescr andDescr = ruleDescr.getLhs(); + Collection annotationDescrs = andDescr.getAnnotations(); + assertThat(annotationDescrs).extracting(AnnotationDescr::getName).containsExactlyInAnyOrder("Annot1", "Annot2"); + + assertThat(andDescr.getDescrs()).hasSize(3); + } + + @Test + void infixOrDescrAnnotation() { + final String text = + "rule R\n" + + " when\n" + + " ( Double() \n" + + " or @Annot1 String() \n" + + " or @Annot2 Integer() ) " + + " then\n" + + "end\n"; + PackageDescr packageDescr = parseAndGetPackageDescr(text); + + RuleDescr ruleDescr = packageDescr.getRules().get(0); + OrDescr orDescr = (OrDescr) ruleDescr.getLhs().getDescrs().get(0); + Collection annotationDescrs = orDescr.getAnnotations(); + assertThat(annotationDescrs).extracting(AnnotationDescr::getName).containsExactlyInAnyOrder("Annot1", "Annot2"); + + assertThat(orDescr.getDescrs()).hasSize(3); + } + + @Test + void annotationWithEmptyParentheses() { + final String text = "package org.drools;\n" + + "import java.util.*;\n" + + "import org.drools.base.factmodel.traits.*;\n" + + "declare HashMap @Traitable() end \n" + + "declare trait PersonMap\n" + + "@propertyReactive \n" + + " age : Integer @Alias( \"years\" ) \n" + + "end\n"; + PackageDescr packageDescr = parseAndGetPackageDescr(text); + + AnnotationDescr annotationDescr = packageDescr.getTypeDeclarations().get(0).getAnnotations().iterator().next(); + + assertThat(annotationDescr.getName()).isEqualTo("Traitable"); + assertThat(annotationDescr.getValue()).isEqualTo(Collections.emptyMap()); + assertThat(annotationDescr.getSingleValueAsString()).isNull(); + } + + @Test + void fromNew() { + final String text = "package org.drools\n" + + "rule R1\n" + + "when\n" + + " $p : Person() from new Person(\"John\", 30)\n" + + "then\n" + + "end\n"; + PackageDescr packageDescr = parseAndGetPackageDescr(text); + RuleDescr ruleDescr = packageDescr.getRules().get(0); + PatternDescr patternDescr = (PatternDescr) ruleDescr.getLhs().getDescrs().get(0); + FromDescr fromDescr = (FromDescr) patternDescr.getSource(); + assertThat(fromDescr.getDataSource().toString()).isEqualTo("new Person(\"John\", 30)"); + } + + @Test + void expiresWithTimeLiteralValue() { + String text = "package org.drools\n" + + "declare StockFact\n" + + " @role( value = event )\n" + + " @expires( value = 2s, policy = TIME_SOFT )\n" + + "end"; + + PackageDescr packageDescr = parseAndGetPackageDescr(text); + + AnnotationDescr annotationDescr = packageDescr + .getTypeDeclarations().get(0) + .getAnnotation("expires"); + + assertThat(annotationDescr.getSingleValueAsString()).isEqualTo("2s"); + assertThat(annotationDescr.getValueAsString("value")).isEqualTo("2s"); + assertThat(annotationDescr.getValueAsString("policy")).isEqualTo("TIME_SOFT"); + } + + @Test + void ooPath() { + final String text = "package org.drools\n" + + "rule R when\n" + + " $man: Man( /wife/children[age > 10] )\n" + + "then\n" + + "end\n"; + PackageDescr packageDescr = parseAndGetPackageDescr(text); + ExprConstraintDescr constraintDescr = getFirstExprConstraintDescr(packageDescr); + assertThat(constraintDescr.toString()) + .isEqualToIgnoringWhitespace("/wife/children[age > 10]"); + } + + private static ExprConstraintDescr getFirstExprConstraintDescr(PackageDescr packageDescr) { + RuleDescr ruleDescr = packageDescr.getRules().get(0); + PatternDescr patternDescr = (PatternDescr) ruleDescr.getLhs().getDescrs().get(0); + ExprConstraintDescr constraintDescr = (ExprConstraintDescr) patternDescr.getConstraint().getDescrs().get(0); + return constraintDescr; + } + + @Test + void ooPathWithBindingInBrackets() { + final String text = "package org.drools\n" + + "rule R when\n" + + " Man( /wife[$age : age] )\n" + + "then\n" + + "end\n"; + PackageDescr packageDescr = parseAndGetPackageDescr(text); + ExprConstraintDescr constraintDescr = getFirstExprConstraintDescr(packageDescr); + assertThat(constraintDescr.toString()) + .isEqualToIgnoringWhitespace("/wife[$age : age]"); + } + + @Test + void ooPathWithBindingInParentheses() { + final String text = "package org.drools\n" + + "rule R when\n" + + " Man( $toy: /wife/children[age > 10]/toys )\n" + + "then\n" + + "end\n"; + PackageDescr packageDescr = parseAndGetPackageDescr(text); + ExprConstraintDescr constraintDescr = getFirstExprConstraintDescr(packageDescr); + assertThat(constraintDescr.toString()) + .isEqualToIgnoringWhitespace("$toy: /wife/children[age > 10]/toys"); + } + + @Test + void ooPathWithBackReference() { + final String text = "package org.drools\n" + + "rule R when\n" + + " Man( $toy: /wife/children/toys[ name.length == ../name.length ] )\n" + + "then\n" + + "end\n"; + + PackageDescr packageDescr = parseAndGetPackageDescr(text); + ExprConstraintDescr constraintDescr = getFirstExprConstraintDescr(packageDescr); + assertThat(constraintDescr.toString()) + .isEqualToIgnoringWhitespace("$toy: /wife/children/toys[ name.length == ../name.length ]"); + } + + @Test + void ooPathMixedWithStandardConstraint() { + final String text = "package org.drools\n" + + "rule R when\n" + + " Man( /wife[$age : age] && age > $age )\n" + + "then\n" + + "end\n"; + + PackageDescr packageDescr = parseAndGetPackageDescr(text); + ExprConstraintDescr constraintDescr = getFirstExprConstraintDescr(packageDescr); + assertThat(constraintDescr.toString()) + .isEqualToIgnoringWhitespace("/wife[$age : age] && age > $age"); + } + + @Test + void ooPathLhsPattern() { + final String text = "package org.drools\n" + + "rule PlainNot when\n" + + " not( /strings [ this == \"It Does Work\" ] )\n" + + "then\n" + + "end\n"; + PackageDescr packageDescr = parseAndGetPackageDescr(text); + RuleDescr ruleDescr = packageDescr.getRules().get(0); + assertThat(ruleDescr.getLhs().getDescrs().get(0)).isInstanceOfSatisfying(NotDescr.class, notDescr -> { + assertThat(notDescr.getDescrs()).hasSize(1); + assertThat(notDescr.getDescrs().get(0)).isInstanceOfSatisfying(PatternDescr.class, patternDescr -> { + assertThat(patternDescr.getConstraint().getDescrs()).hasSize(1); + assertThat(patternDescr.getConstraint().getDescrs().get(0)).isInstanceOfSatisfying(ExprConstraintDescr.class, exprConstraintDescr -> { + assertThat(exprConstraintDescr.getExpression()).isEqualTo("/strings [ this == \"It Does Work\" ]"); + assertThat(exprConstraintDescr.getType()).isEqualTo(ExprConstraintDescr.Type.NAMED); + assertThat(exprConstraintDescr.getPosition()).isEqualTo(0); + }); + }); + }); + } + + @Test + void inlineCast() { + final String text = "package org.drools\n" + + "rule R1\n" + + "when\n" + + " $a : ICA( someB#ICB.onlyConcrete() == \"Hello\" )\n" + + "then\n" + + "end\n"; + PackageDescr packageDescr = parseAndGetPackageDescr(text); + ExprConstraintDescr constraintDescr = getFirstExprConstraintDescr(packageDescr); + assertThat(constraintDescr.toString()).isEqualToIgnoringWhitespace("someB#ICB.onlyConcrete() == \"Hello\""); + } + + @Test + void inlineCastMultiple() { + final String text = "package org.drools\n" + + "rule R1\n" + + "when\n" + + " $a : ICA( someB#ICB.someC#ICC.onlyConcrete() == \"Hello\" )\n" + + "then\n" + + "end\n"; + PackageDescr packageDescr = parseAndGetPackageDescr(text); + ExprConstraintDescr constraintDescr = getFirstExprConstraintDescr(packageDescr); + assertThat(constraintDescr.toString()).isEqualToIgnoringWhitespace("someB#ICB.someC#ICC.onlyConcrete() == \"Hello\""); + } + + @Test + void inlineCastThis() { + final String text = "package org.drools\n" + + "rule R1\n" + + "when\n" + + " $o : Object( this#Person.name == \"Mark\" )\n" + + "then\n" + + "end\n"; + PackageDescr packageDescr = parseAndGetPackageDescr(text); + ExprConstraintDescr constraintDescr = getFirstExprConstraintDescr(packageDescr); + assertThat(constraintDescr.toString()).isEqualToIgnoringWhitespace("this#Person.name == \"Mark\""); + } + + @Test + void queryArgumentWithoutType() { + final String text = "package org.drools\n" + + "query olderThan( $age )\n" + + " $p : Person(age > (Integer)$age)\n" + + "end "; + final QueryDescr query = parseAndGetFirstQueryDescr(text); + + assertThat(query).isNotNull(); + assertThat(query.getName()).isEqualTo("olderThan"); + assertThat(query.getParameterTypes()).containsExactly("Object"); + assertThat(query.getParameters()).containsExactly("$age"); + } + + @Test + void queryMultipleArguments() { + final String text = "package org.drools\n" + + "query olderThan( String $name, int $age )\n" + + " $p : Person(age > $age)\n" + + "end "; + final QueryDescr query = parseAndGetFirstQueryDescr(text); + + assertThat(query).isNotNull(); + assertThat(query.getName()).isEqualTo("olderThan"); + assertThat(query.getParameterTypes()).containsExactly("String", "int"); + assertThat(query.getParameters()).containsExactly("$name", "$age"); + } + + @Test + void queryArrayArgument() { + final String text = "package org.drools\n" + + "query olderThan( int[] $ages )\n" + + " $p : Person(age > $ages[0])\n" + + "end "; + final QueryDescr query = parseAndGetFirstQueryDescr(text); + + assertThat(query).isNotNull(); + assertThat(query.getName()).isEqualTo("olderThan"); + assertThat(query.getParameterTypes()).containsExactly("int[]"); + assertThat(query.getParameters()).containsExactly("$ages"); + } + + @Test + void queryZeroArgument() { + final String text = "package org.drools\n" + + "query olderThan()\n" + + " $p : Person()\n" + + "end "; + final QueryDescr query = parseAndGetFirstQueryDescr(text); + + assertThat(query).isNotNull(); + assertThat(query.getName()).isEqualTo("olderThan"); + assertThat(query.getParameterTypes()).isEmpty(); + assertThat(query.getParameters()).isEmpty(); + } + + @Test + void queryNoArgument() { + final String text = "package org.drools\n" + + "query olderThan\n" + + " $p : Person()\n" + + "end "; + final QueryDescr query = parseAndGetFirstQueryDescr(text); + + assertThat(query).isNotNull(); + assertThat(query.getName()).isEqualTo("olderThan"); + assertThat(query.getParameterTypes()).isEmpty(); + assertThat(query.getParameters()).isEmpty(); + } + + @Test + void traitExtendsMultiple() { + final String source = "declare trait FatherTrait extends com.sample.ParentTrait, UncleTrait, org.test.GrandParentTrait end"; + + PackageDescr pkg = parseAndGetPackageDescr(source); + + final List declarations = pkg.getTypeDeclarations(); + + assertThat(declarations).hasSize(1); + TypeDeclarationDescr trait = declarations.get(0); + assertThat(trait.getSuperTypeName()).isEqualTo("ParentTrait"); + assertThat(trait.getSuperTypeNamespace()).isEqualTo("com.sample"); + assertThat(trait.getSuperTypes()) + .map(QualifiedName::getFullName) + .containsExactlyInAnyOrder("com.sample.ParentTrait", "UncleTrait", "org.test.GrandParentTrait"); + } + + @Test + void pluggableEvaluator() { + final String source = "package org.drools\n" + + "rule R\n" + + "when\n" + + " $t : Thing( $c : core, this not isA t.x.E.class, this isA t.x.D.class )\n" + + "then\n" + + " list.add( \"E\" ); \n" + + " don( $t, E.class ); \n" + + "end\n"; + + Operator.addOperatorToRegistry("isA", false); + Operator.addOperatorToRegistry("isA", true); + + PatternDescr pattern = (PatternDescr) parseAndGetFirstRuleDescr(source).getLhs().getDescrs().get(0); + assertThat(pattern.getConstraint().getDescrs()) + .extracting(Object::toString) + .containsExactly("$c : core", "this not isA t.x.E.class", "this isA t.x.D.class"); + } + + @Test + void namedConsequenceDo() { + final String text = + "rule R when\n" + + " $r : Result()\n" + + " $p1 : Person(name == \"Mark\")\n" + + " do[FoundMark]\n" + + " $p2 : Person(name != \"Mark\", age > $p1.age)\n" + + "then\n" + + " $r.addValue($p2.getName() + \" is older than \" + $p1.getName());\n" + + "then[FoundMark]\n" + + " $r.addValue(\"Found \" + $p1.getName());\n" + + "end"; + PackageDescr packageDescr = parseAndGetPackageDescr(text); + RuleDescr ruleDescr = packageDescr.getRules().get(0); + NamedConsequenceDescr namedConsequenceDescr = (NamedConsequenceDescr) ruleDescr.getLhs().getDescrs().get(2); + assertThat(namedConsequenceDescr.getName()).isEqualTo("FoundMark"); + + assertThat(ruleDescr.getConsequence().toString().trim()).isEqualTo("$r.addValue($p2.getName() + \" is older than \" + $p1.getName());"); + assertThat(ruleDescr.getNamedConsequences().get("FoundMark").toString().trim()).isEqualTo("$r.addValue(\"Found \" + $p1.getName());"); + } + + @Test + void namedConsequenceIfElse() { + final String text = + "rule R1 dialect \"mvel\" when\n" + + " $a: Cheese ( type == \"stilton\" )\n" + + " if ( $a.price > Cheese.BASE_PRICE ) do[t1] else do[t2]\n" + + " $b: Cheese ( type == \"cheddar\" )\n" + + "then\n" + + " results.add( $b.getType() );\n" + + "then[t1]\n" + + " results.add( $a.getType() );\n" + + "then[t2]\n" + + " results.add( $a.getType().toUpperCase() );\n" + + "end\n"; + PackageDescr packageDescr = parseAndGetPackageDescr(text); + RuleDescr ruleDescr = packageDescr.getRules().get(0); + ConditionalBranchDescr conditionalBranchDescr = (ConditionalBranchDescr) ruleDescr.getLhs().getDescrs().get(1); + assertThat(conditionalBranchDescr.getCondition().getContent().toString()).isEqualTo("$a.price > Cheese.BASE_PRICE"); + assertThat(conditionalBranchDescr.getConsequence().getName()).isEqualTo("t1"); + assertThat(conditionalBranchDescr.getElseBranch().getConsequence().getName()).isEqualTo("t2"); + } + + @Test + void namedConsequenceIfElseBreak() { + final String text = + "rule R1 dialect \"mvel\" when\n" + + " $a: Cheese ( type == \"stilton\" )\n" + + " if ( $a.price > Cheese.BASE_PRICE ) break[t1] else break[t2]\n" + + " $b: Cheese ( type == \"cheddar\" )\n" + + "then\n" + + " results.add( $b.getType() );\n" + + "then[t1]\n" + + " results.add( $a.getType() );\n" + + "then[t2]\n" + + " results.add( $a.getType().toUpperCase() );\n" + + "end\n"; + PackageDescr packageDescr = parseAndGetPackageDescr(text); + RuleDescr ruleDescr = packageDescr.getRules().get(0); + ConditionalBranchDescr conditionalBranchDescr = (ConditionalBranchDescr) ruleDescr.getLhs().getDescrs().get(1); + assertThat(conditionalBranchDescr.getCondition().getContent().toString()).isEqualTo("$a.price > Cheese.BASE_PRICE"); + assertThat(conditionalBranchDescr.getConsequence().getName()).isEqualTo("t1"); + assertThat(conditionalBranchDescr.getElseBranch().getConsequence().getName()).isEqualTo("t2"); + } + + @Test + void namedConsequenceNestedIf() { + final String text = + "rule R1 dialect \"mvel\" when\n" + + " $a: Cheese ( type == \"stilton\" )\n" + + " if ( $a.price > Cheese.BASE_PRICE ) do[t1] else if ($a.price == Cheese.BASE_PRICE ) do[t2]\n" + + " $b: Cheese ( type == \"cheddar\" )\n" + + "then\n" + + " results.add( $b.getType() );\n" + + "then[t1]\n" + + " results.add( $a.getType() );\n" + + "then[t2]\n" + + " results.add( $a.getType().toUpperCase() );\n" + + "end\n"; + PackageDescr packageDescr = parseAndGetPackageDescr(text); + RuleDescr ruleDescr = packageDescr.getRules().get(0); + ConditionalBranchDescr conditionalBranchDescr = (ConditionalBranchDescr) ruleDescr.getLhs().getDescrs().get(1); + assertThat(conditionalBranchDescr.getCondition().getContent().toString()).isEqualTo("$a.price > Cheese.BASE_PRICE"); + assertThat(conditionalBranchDescr.getConsequence().getName()).isEqualTo("t1"); + ConditionalBranchDescr elseBranch = conditionalBranchDescr.getElseBranch(); + assertThat(elseBranch.getCondition().getContent().toString()).isEqualTo("$a.price == Cheese.BASE_PRICE"); + assertThat(elseBranch.getConsequence().getName()).isEqualTo("t2"); + } + + @Test + void namedConsequenceAfterExists() { + final String text = + "rule R when\n" + + " $r : Result()\n" + + " exists( Person(name == \"Mark\") )\n" + + " do[FoundMark]\n" + + " $p2 : Person(name != \"Mark\", age > $p1.age)\n" + + "then\n" + + " $r.addValue($p2.getName() + \" is older than \" + $p1.getName());\n" + + "then[FoundMark]\n" + + " $r.addValue(\"Found \" + $p1.getName());\n" + + "end"; + PackageDescr packageDescr = parseAndGetPackageDescr(text); + RuleDescr ruleDescr = packageDescr.getRules().get(0); + NamedConsequenceDescr namedConsequenceDescr = (NamedConsequenceDescr) ruleDescr.getLhs().getDescrs().get(2); + assertThat(namedConsequenceDescr.getName()).isEqualTo("FoundMark"); + } + + @Test + void namedConsequenceAfterNot() { + final String text = + "rule R when\n" + + " $r : Result()\n" + + " not( Person(name == \"Mark\") )\n" + + " do[NotFoundMark]\n" + + " $p2 : Person(name != \"Mark\", age > $p1.age)\n" + + "then\n" + + " $r.addValue($p2.getName() + \" is older than \" + $p1.getName());\n" + + "then[FoundMark]\n" + + " $r.addValue(\"NotFound \" + $p1.getName());\n" + + "end"; + PackageDescr packageDescr = parseAndGetPackageDescr(text); + RuleDescr ruleDescr = packageDescr.getRules().get(0); + NamedConsequenceDescr namedConsequenceDescr = (NamedConsequenceDescr) ruleDescr.getLhs().getDescrs().get(2); + assertThat(namedConsequenceDescr.getName()).isEqualTo("NotFoundMark"); + } + + @Test + void namedConsequenceIfElseAfterEval() { + final String text = + "rule R1 dialect \"mvel\" when\n" + + " $a: Cheese ( type == \"stilton\" )\n" + + " eval($a.price > 0) if ( $a.price > Cheese.BASE_PRICE ) do[t1] else do[t2]\n" + + " $b: Cheese ( type == \"cheddar\" )\n" + + "then\n" + + " results.add( $b.getType() );\n" + + "then[t1]\n" + + " results.add( $a.getType() );\n" + + "then[t2]\n" + + " results.add( $a.getType().toUpperCase() );\n" + + "end\n"; + PackageDescr packageDescr = parseAndGetPackageDescr(text); + RuleDescr ruleDescr = packageDescr.getRules().get(0); + ConditionalBranchDescr conditionalBranchDescr = (ConditionalBranchDescr) ruleDescr.getLhs().getDescrs().get(2); + assertThat(conditionalBranchDescr.getCondition().getContent().toString()).isEqualTo("$a.price > Cheese.BASE_PRICE"); + assertThat(conditionalBranchDescr.getConsequence().getName()).isEqualTo("t1"); + assertThat(conditionalBranchDescr.getElseBranch().getConsequence().getName()).isEqualTo("t2"); + } + + @Test + void namedConsequenceAfterEnclosed() { + final String text = + "rule R when\n" + + " $r : Result()\n" + + " ( Person(name == \"Mark\") or Person(name == \"Mario\") )\n" + + " do[FoundMarkOrMario]\n" + + " $p2 : Person(name != \"Mark\", age > $p1.age)\n" + + "then\n" + + " $r.addValue($p2.getName() + \" is older than \" + $p1.getName());\n" + + "then[FoundMark]\n" + + " $r.addValue(\"Found \" + $p1.getName());\n" + + "end"; + PackageDescr packageDescr = parseAndGetPackageDescr(text); + RuleDescr ruleDescr = packageDescr.getRules().get(0); + NamedConsequenceDescr namedConsequenceDescr = (NamedConsequenceDescr) ruleDescr.getLhs().getDescrs().get(2); + assertThat(namedConsequenceDescr.getName()).isEqualTo("FoundMarkOrMario"); + } + + @Test + void namedConsequenceOrWithBindVariables() { + final String text = + "rule R when\n" + + " $r : Result()\n" + + " ( $p1 : Person(name == \"Mark\") or $p1 : Person(name == \"Mario\") )\n" + + " do[FoundMarkOrMario]\n" + + " $p2 : Person(name != \"Mark\", age > $p1.age)\n" + + "then\n" + + " $r.addValue($p2.getName() + \" is older than \" + $p1.getName());\n" + + "then[FoundMark]\n" + + " $r.addValue(\"Found \" + $p1.getName());\n" + + "end"; + PackageDescr packageDescr = parseAndGetPackageDescr(text); + RuleDescr ruleDescr = packageDescr.getRules().get(0); + + OrDescr orDescr = (OrDescr) ruleDescr.getLhs().getDescrs().get(1); + PatternDescr patternDescr1 = (PatternDescr) orDescr.getDescrs().get(0); + assertThat(patternDescr1.getIdentifier()).isEqualTo("$p1"); + assertThat(((ExprConstraintDescr) patternDescr1.getConstraint().getDescrs().get(0)).getExpression()).isEqualTo("name == \"Mark\""); + PatternDescr patternDescr2 = (PatternDescr) orDescr.getDescrs().get(1); + assertThat(patternDescr2.getIdentifier()).isEqualTo("$p1"); + assertThat(((ExprConstraintDescr) patternDescr2.getConstraint().getDescrs().get(0)).getExpression()).isEqualTo("name == \"Mario\""); + + NamedConsequenceDescr namedConsequenceDescr = (NamedConsequenceDescr) ruleDescr.getLhs().getDescrs().get(2); + assertThat(namedConsequenceDescr.getName()).isEqualTo("FoundMarkOrMario"); + } + + @Test + void namedConsequencesInsideOR1() { + final String text = + "import org.drools.mvel.compiler.Cheese;\n " + + "global java.util.List results;\n" + + "\n" + + "rule R1 when\n" + + " ( $a: Cheese ( type == \"stilton\" ) do[t1]\n" + + " or\n" + + " $b: Cheese ( type == \"gorgonzola\" ) )\n" + + " $c: Cheese ( type == \"cheddar\" )\n" + + "then\n" + + " results.add( $c.getType() );\n" + + "then[t1]\n" + + " results.add( $a.getType() );\n" + + "end\n"; + PackageDescr packageDescr = parseAndGetPackageDescr(text); + RuleDescr ruleDescr = packageDescr.getRules().get(0); + + assertThat(ruleDescr.getLhs().getDescrs()).hasSize(2); + assertThat(ruleDescr.getLhs().getDescrs()).first().isInstanceOfSatisfying(OrDescr.class, stiltonOrGorgonzola -> { + assertThat(stiltonOrGorgonzola.getDescrs()).hasSize(2); + assertThat(stiltonOrGorgonzola.getDescrs()).first().isInstanceOfSatisfying(AndDescr.class, andDescr -> { + assertThat(andDescr.getDescrs()).hasSize(2); + assertThat(andDescr.getDescrs()).first().isInstanceOfSatisfying(PatternDescr.class, stilton -> { + assertThat(stilton.getIdentifier()).isEqualTo("$a"); + assertThat(stilton.getObjectType()).isEqualTo("Cheese"); + assertThat(stilton.getConstraint().toString()).contains("stilton"); + }); + assertThat(andDescr.getDescrs()).last().isInstanceOfSatisfying(NamedConsequenceDescr.class, namedConsequenceDescr -> { + assertThat(namedConsequenceDescr.getName()).isEqualTo("t1"); + }); + }); + assertThat(stiltonOrGorgonzola.getDescrs()).last().isInstanceOfSatisfying(PatternDescr.class, gorgonzola -> { + assertThat(gorgonzola.getIdentifier()).isEqualTo("$b"); + assertThat(gorgonzola.getObjectType()).isEqualTo("Cheese"); + assertThat(gorgonzola.getConstraint().toString()).contains("gorgonzola"); + }); + }); + assertThat(ruleDescr.getLhs().getDescrs()).last().isInstanceOfSatisfying(PatternDescr.class, cheddar -> { + assertThat(cheddar.getIdentifier()).isEqualTo("$c"); + assertThat(cheddar.getObjectType()).isEqualTo("Cheese"); + assertThat(cheddar.getConstraint().toString()).contains("cheddar"); + }); + } + + @Test + void namedConsequencesInsideOR2() { + final String text = + "import org.drools.mvel.compiler.Cheese;\n " + + "global java.util.List results;\n" + + "\n" + + "rule R1 when\n" + + " ( $a: Cheese ( type == \"stilton\" )\n" + + " or\n" + + " $b: Cheese ( type == \"gorgonzola\" ) do[t1] )\n" + + " $c: Cheese ( type == \"cheddar\" )\n" + + "then\n" + + " results.add( $c.getType() );\n" + + "then[t1]\n" + + " results.add( $b.getType() );\n" + + "end\n"; + PackageDescr packageDescr = parseAndGetPackageDescr(text); + RuleDescr ruleDescr = packageDescr.getRules().get(0); + + assertThat(ruleDescr.getLhs().getDescrs()).hasSize(2); + assertThat(ruleDescr.getLhs().getDescrs()).first().isInstanceOfSatisfying(OrDescr.class, stiltonOrGorgonzola -> { + assertThat(stiltonOrGorgonzola.getDescrs()).hasSize(2); + assertThat(stiltonOrGorgonzola.getDescrs()).first().isInstanceOfSatisfying(PatternDescr.class, stilton -> { + assertThat(stilton.getIdentifier()).isEqualTo("$a"); + assertThat(stilton.getObjectType()).isEqualTo("Cheese"); + assertThat(stilton.getConstraint().toString()).contains("stilton"); + }); + assertThat(stiltonOrGorgonzola.getDescrs()).last().isInstanceOfSatisfying(AndDescr.class, andDescr -> { + assertThat(andDescr.getDescrs()).hasSize(2); + assertThat(andDescr.getDescrs()).first().isInstanceOfSatisfying(PatternDescr.class, gorgonzola -> { + assertThat(gorgonzola.getIdentifier()).isEqualTo("$b"); + assertThat(gorgonzola.getObjectType()).isEqualTo("Cheese"); + assertThat(gorgonzola.getConstraint().toString()).contains("gorgonzola"); + }); + assertThat(andDescr.getDescrs()).last().isInstanceOfSatisfying(NamedConsequenceDescr.class, namedConsequenceDescr -> { + assertThat(namedConsequenceDescr.getName()).isEqualTo("t1"); + }); + }); + }); + assertThat(ruleDescr.getLhs().getDescrs()).last().isInstanceOfSatisfying(PatternDescr.class, cheddar -> { + assertThat(cheddar.getIdentifier()).isEqualTo("$c"); + assertThat(cheddar.getObjectType()).isEqualTo("Cheese"); + assertThat(cheddar.getConstraint().toString()).contains("cheddar"); + }); + } + + @Test + void queryComplexLhs() { + final String text = "query isContainedIn(String x, String y)\n" + + " Location (x, y;)\n" + + " or\n" + + " ( Location (z, y;) and ?isContainedIn(x, z;))\n" + + "end\n"; + final QueryDescr query = parseAndGetFirstQueryDescr(text); + + assertThat(query).isNotNull(); + AndDescr lhs = query.getLhs(); + assertThat(lhs.getDescrs()).hasSize(1); + + assertThat(lhs.getDescrs().get(0)) + .as("Top level node is OR") + .isInstanceOfSatisfying(OrDescr.class, orDescr -> { + assertThat(orDescr.getDescrs()).hasSize(2); + assertThat(orDescr.getDescrs().get(0)) + .as("Left node of OR is Pattern") + .isInstanceOfSatisfying(PatternDescr.class, patternDescr -> { + assertThat(patternDescr.getObjectType()).isEqualTo("Location"); + assertThat(patternDescr.getConstraint().getDescrs().get(0)) + .isInstanceOfSatisfying(ExprConstraintDescr.class, constraint -> { + assertThat(constraint.getExpression()).isEqualTo("x"); + assertThat(constraint.getType()).isEqualTo(ExprConstraintDescr.Type.POSITIONAL); + assertThat(constraint.getPosition()).isEqualTo(0); + }); + assertThat(patternDescr.getConstraint().getDescrs().get(1)) + .isInstanceOfSatisfying(ExprConstraintDescr.class, constraint -> { + assertThat(constraint.getExpression()).isEqualTo("y"); + assertThat(constraint.getType()).isEqualTo(ExprConstraintDescr.Type.POSITIONAL); + assertThat(constraint.getPosition()).isEqualTo(1); + }); + }); + assertThat(orDescr.getDescrs().get(1)) + .as("Right node of OR is AND") + .isInstanceOfSatisfying(AndDescr.class, andDescr -> { + assertThat(andDescr.getDescrs().get(0)) + .as("Left node of AND is Pattern") + .isInstanceOfSatisfying(PatternDescr.class, patternDescr -> { + assertThat(patternDescr.getObjectType()).isEqualTo("Location"); + assertThat(patternDescr.getConstraint().getDescrs().get(0)) + .isInstanceOfSatisfying(ExprConstraintDescr.class, constraint -> { + assertThat(constraint.getExpression()).isEqualTo("z"); + assertThat(constraint.getType()).isEqualTo(ExprConstraintDescr.Type.POSITIONAL); + assertThat(constraint.getPosition()).isEqualTo(0); + }); + assertThat(patternDescr.getConstraint().getDescrs().get(1)) + .isInstanceOfSatisfying(ExprConstraintDescr.class, constraint -> { + assertThat(constraint.getExpression()).isEqualTo("y"); + assertThat(constraint.getType()).isEqualTo(ExprConstraintDescr.Type.POSITIONAL); + assertThat(constraint.getPosition()).isEqualTo(1); + }); + }); + assertThat(andDescr.getDescrs().get(1)) + .as("Right node of AND is Query Pattern") + .isInstanceOfSatisfying(PatternDescr.class, patternDescr -> { + assertThat(patternDescr.isQuery()).isTrue(); + assertThat(patternDescr.getObjectType()).isEqualTo("isContainedIn"); + assertThat(patternDescr.getConstraint().getDescrs().get(0)) + .isInstanceOfSatisfying(ExprConstraintDescr.class, constraint -> { + assertThat(constraint.getExpression()).isEqualTo("x"); + assertThat(constraint.getType()).isEqualTo(ExprConstraintDescr.Type.POSITIONAL); + assertThat(constraint.getPosition()).isEqualTo(0); + }); + assertThat(patternDescr.getConstraint().getDescrs().get(1)) + .isInstanceOfSatisfying(ExprConstraintDescr.class, constraint -> { + assertThat(constraint.getExpression()).isEqualTo("z"); + assertThat(constraint.getType()).isEqualTo(ExprConstraintDescr.Type.POSITIONAL); + assertThat(constraint.getPosition()).isEqualTo(1); + }); + }); + }); + }); + } + + @Test + void notWithPrefixAnd() { + final String text = + "package org.drools.compiler\n" + + "rule R when\n" + + " (not (and Integer( $i : intValue )\n" + + " String( length > $i ) \n" + + " )\n" + + " )\n" + + "then\n" + + "end"; + PackageDescr packageDescr = parseAndGetPackageDescr(text); + RuleDescr ruleDescr = packageDescr.getRules().get(0); + assertThat(ruleDescr.getLhs().getDescrs().get(0)).isInstanceOfSatisfying(NotDescr.class, notDescr -> { + assertThat(notDescr.getDescrs().get(0)).isInstanceOfSatisfying(AndDescr.class, andDescr -> { + assertThat(andDescr.getDescrs()).hasSize(2); + assertThat(andDescr.getDescrs().get(0)).isInstanceOfSatisfying(PatternDescr.class, patternDescr -> { + assertThat(patternDescr.getObjectType()).isEqualTo("Integer"); + assertThat(patternDescr.getConstraint().getDescrs().get(0)).isInstanceOfSatisfying(ExprConstraintDescr.class, exprConstraintDescr -> { + assertThat(exprConstraintDescr.getExpression()).isEqualTo("$i : intValue"); + }); + }); + assertThat(andDescr.getDescrs().get(1)).isInstanceOfSatisfying(PatternDescr.class, patternDescr -> { + assertThat(patternDescr.getObjectType()).isEqualTo("String"); + assertThat(patternDescr.getConstraint().getDescrs().get(0)).isInstanceOfSatisfying(ExprConstraintDescr.class, exprConstraintDescr -> { + assertThat(exprConstraintDescr.getExpression()).isEqualTo("length > $i"); + }); + }); + }); + }); + } + + @Test + void existsWithPrefixAnd() { + final String text = + "package org.drools.compiler\n" + + "rule R when\n" + + " (exists (and Integer( $i : intValue )\n" + + " String( length > $i ) \n" + + " )\n" + + " )\n" + + "then\n" + + "end"; + PackageDescr packageDescr = parseAndGetPackageDescr(text); + RuleDescr ruleDescr = packageDescr.getRules().get(0); + assertThat(ruleDescr.getLhs().getDescrs().get(0)).isInstanceOfSatisfying(ExistsDescr.class, existsDescr -> { + assertThat(existsDescr.getDescrs().get(0)).isInstanceOfSatisfying(AndDescr.class, andDescr -> { + assertThat(andDescr.getDescrs()).hasSize(2); + assertThat(andDescr.getDescrs().get(0)).isInstanceOfSatisfying(PatternDescr.class, patternDescr -> { + assertThat(patternDescr.getObjectType()).isEqualTo("Integer"); + assertThat(patternDescr.getConstraint().getDescrs().get(0)).isInstanceOfSatisfying(ExprConstraintDescr.class, exprConstraintDescr -> { + assertThat(exprConstraintDescr.getExpression()).isEqualTo("$i : intValue"); + }); + }); + assertThat(andDescr.getDescrs().get(1)).isInstanceOfSatisfying(PatternDescr.class, patternDescr -> { + assertThat(patternDescr.getObjectType()).isEqualTo("String"); + assertThat(patternDescr.getConstraint().getDescrs().get(0)).isInstanceOfSatisfying(ExprConstraintDescr.class, exprConstraintDescr -> { + assertThat(exprConstraintDescr.getExpression()).isEqualTo("length > $i"); + }); + }); + }); + }); + } + + @Test + void enumDeclaration() { + final String text = + "declare enum PersonAge\n" + + " @doc(author=\"Bob\")\n" + + " ELEVEN(11, \"XI\"), TWELVE(12, \"XII\");\n" + + "\n" + + " key: int\n" + + " romanStr : String\n" + + "end"; + PackageDescr pkg = parseAndGetPackageDescr(text); + + List descrList = pkg.getEnumDeclarations(); + EnumDeclarationDescr enumDeclarationDescr = descrList.get(0); + assertThat(enumDeclarationDescr.getTypeName()).isEqualTo("PersonAge"); + + assertThat(enumDeclarationDescr.getAnnotation("doc").getValue("author")).isEqualTo("\"Bob\""); + + List literals = enumDeclarationDescr.getLiterals(); + EnumLiteralDescr enumLiteralDescr0 = literals.get(0); + assertThat(enumLiteralDescr0.getName()).isEqualTo("ELEVEN"); + assertThat(enumLiteralDescr0.getConstructorArgs()).containsExactly("11", "\"XI\""); + EnumLiteralDescr enumLiteralDescr1 = literals.get(1); + assertThat(enumLiteralDescr1.getName()).isEqualTo("TWELVE"); + assertThat(enumLiteralDescr1.getConstructorArgs()).containsExactly("12", "\"XII\""); + + TypeFieldDescr key = enumDeclarationDescr.getFields().get("key"); + assertThat(key.getPattern().getObjectType()).isEqualTo("int"); + + TypeFieldDescr romanStr = enumDeclarationDescr.getFields().get("romanStr"); + assertThat(romanStr.getPattern().getObjectType()).isEqualTo("String"); + } + + @Test + void packageChildrenNamespaceAndUnitProperties() { + String namespace = "org.drools.compiler.test"; + String source = readResource("package_children.drl"); + PackageDescr pkg = parseAndGetPackageDescr(source); + + // Package and Rule Unit's namespace. + assertThat(pkg.getName()).isEqualTo(namespace); + assertThat(pkg.getUnit().getNamespace()).isEqualTo(namespace); + + // Children that are expected to have the package name as their namespace. + assertNamespace(pkg.getImports(), namespace); + assertNamespace(pkg.getFunctionImports(), namespace); + assertNamespace(pkg.getAccumulateImports(), namespace); + assertNamespace(pkg.getGlobals(), namespace); + assertNamespace(pkg.getFunctions(), namespace); + assertNamespace(pkg.getRules(), namespace); + assertNamespace(pkg.getAttributes(), namespace); + + // Children that are expected to have no namespace. + assertNamespace(pkg.getTypeDeclarations(), ""); + assertNamespace(pkg.getEnumDeclarations(), ""); + assertNamespace(pkg.getEntryPointDeclarations(), ""); + assertNamespace(pkg.getWindowDeclarations(), ""); + + assertThat(pkg.getRules()) + .allSatisfy(ruleDescr -> assertThat(ruleDescr.getUnit()).isNotNull()) + .allSatisfy(ruleDescr -> assertThat(ruleDescr.getUnit().getTarget()).isEqualTo("TestUnit")); + + assertThat(pkg.getRules().get(0).getUnitQualifiedName()).isEqualTo("TestUnit.MyQuery"); + assertThat(pkg.getRules().get(1).getUnitQualifiedName()).isEqualTo("TestUnit.My Rule"); + } + + static void assertNamespace(Collection children, String namespace) { + assertThat(children).isNotEmpty(); // Make sure that every child type is represented. + assertThat(children).allSatisfy(baseDescr -> assertThat(baseDescr.getNamespace()).isEqualTo(namespace)); + } + + @Test + void noWhitespaceBetweenRuleKeywordAndName() { + final String text = "rule X when then end rule\"Y\" when then end rule'Z'when then end"; + + PackageDescr pkg = parseAndGetPackageDescr(text); + + assertThat(pkg.getRules()) + .map(RuleDescr::getName) + .containsExactly("X", "Y", "Z"); + } + + @Test + void orWithMethodCall() { + final String text = + "rule R1\n" + + "when\n" + + " MyFact( value == 10 || someMethod() == 4 )\n" + + "then\n" + + "end"; + ExprConstraintDescr exprConstraintDescr = parseAndGetFirstConstraintDescr(text); + assertThat(exprConstraintDescr.getExpression()).isEqualTo("value == 10 || someMethod() == 4"); + } + + @Test + void orWithMethodCallWithArg() { + final String text = + "rule R1\n" + + "when\n" + + " MyFact( value == 10 || someMethod(value) == 4 )\n" + + "then\n" + + "end"; + ExprConstraintDescr exprConstraintDescr = parseAndGetFirstConstraintDescr(text); + assertThat(exprConstraintDescr.getExpression()).isEqualTo("value == 10 || someMethod(value) == 4"); + } + + @Test + void andWithMethodCall() { + final String text = + "rule R1\n" + + "when\n" + + " MyFact( value == 10 && someMethod() == 4 )\n" + + "then\n" + + "end"; + ExprConstraintDescr exprConstraintDescr = parseAndGetFirstConstraintDescr(text); + assertThat(exprConstraintDescr.getExpression()).isEqualTo("value == 10 && someMethod() == 4"); + } + + @Test + void andWithMethodCallWithArg() { + final String text = + "rule R1\n" + + "when\n" + + " MyFact( value == 10 && someMethod(value) == 4 )\n" + + "then\n" + + "end"; + ExprConstraintDescr exprConstraintDescr = parseAndGetFirstConstraintDescr(text); + assertThat(exprConstraintDescr.getExpression()).isEqualTo("value == 10 && someMethod(value) == 4"); + } + + @Test + void unificationInAccumulateRule() { + final String text = + "rule R\n" + + "when\n" + + " MyFact($i : currentValue)\n" + + " accumulate( $p : Person( name == \"John\" ),\n" + + " $i := min( $p.getAge() ) )\n" + + "then\n" + + "end"; + RuleDescr rule = parseAndGetFirstRuleDescr(text); + assertThat(rule.getLhs().getDescrs()).hasSize(2); + + final PatternDescr outPattern = (PatternDescr) rule.getLhs().getDescrs().get(1); + AccumulateDescr accumulateDescr = (AccumulateDescr) outPattern.getSource(); + assertThat(accumulateDescr.getInputPattern()).isInstanceOfSatisfying(PatternDescr.class, patternDescr -> { + assertThat(patternDescr.getIdentifier()).isEqualTo("$p"); + assertThat(patternDescr.getObjectType()).isEqualTo("Person"); + }); + + AccumulateDescr.AccumulateFunctionCallDescr accumulateFunction = accumulateDescr.getFunctions().get(0); + assertThat(accumulateFunction.getBind()).isEqualTo("$i"); + assertThat(accumulateFunction.isUnification()).isTrue(); + assertThat(accumulateFunction.getFunction()).isEqualTo("min"); + assertThat(accumulateFunction.getParams()).containsExactly("$p.getAge()"); + } + + @Test + void existsOrNot() { + final String text = + "rule R\n" + + "when\n" + + " exists(not(Integer()) or not(Double()))\n" + + "then\n" + + "end"; + RuleDescr rule = parseAndGetFirstRuleDescr(text); + assertThat(rule.getLhs().getDescrs().get(0)).isInstanceOfSatisfying(ExistsDescr.class, existsDescr -> { + assertThat(existsDescr.getDescrs().get(0)).isInstanceOfSatisfying(OrDescr.class, orDescr -> { + assertThat(orDescr.getDescrs()).hasSize(2); + assertThat(orDescr.getDescrs().get(0)).isInstanceOfSatisfying(NotDescr.class, notDescr -> { + assertThat(notDescr.getDescrs().get(0)).isInstanceOfSatisfying(PatternDescr.class, patternDescr -> { + assertThat(patternDescr.getObjectType()).isEqualTo("Integer"); + }); + }); + assertThat(orDescr.getDescrs().get(1)).isInstanceOfSatisfying(NotDescr.class, notDescr -> { + assertThat(notDescr.getDescrs().get(0)).isInstanceOfSatisfying(PatternDescr.class, patternDescr -> { + assertThat(patternDescr.getObjectType()).isEqualTo("Double"); + }); + }); + }); + }); + } + + @Test + void nestedNot() { + final String text = + "rule R\n" + + "when\n" + + " not ( not ( Cheese() ) )\n" + + "then\n" + + "end"; + RuleDescr rule = parseAndGetFirstRuleDescr(text); + assertThat(rule.getLhs().getDescrs().get(0)).isInstanceOfSatisfying(NotDescr.class, notDescr -> { + assertThat(notDescr.getDescrs().get(0)).isInstanceOfSatisfying(NotDescr.class, nestedNotDescr -> { + assertThat(nestedNotDescr.getDescrs().get(0)).isInstanceOfSatisfying(PatternDescr.class, patternDescr -> { + assertThat(patternDescr.getObjectType()).isEqualTo("Cheese"); + }); + }); + }); + } + + @Test + void errorMessage_shouldNotContainEmptyString() { + final String text = + "rule R\n" + + "when\n" + + " foo\n" + // parse error + "then\n" + + "end"; + PackageDescr pkg = parseAndGetPackageDescrWithoutErrorCheck(text); + assertThat(pkg).isNull(); + assertThat(parser.hasErrors()).isTrue(); + assertThat(parser.getErrors()).extracting(DroolsError::getMessage).doesNotContain(""); + } + + @ParameterizedTest + @MethodSource("org.drools.drl.parser.antlr4.ParserTestUtils#javaKeywords") + void javaKeywordsInPackage(String keyword) { + String pkgName = "org.drools." + keyword; + String text = "package " + pkgName + "\n" + + "rule R\n" + + "when\n" + + " $p : Person()\n" + + "then\n" + + "end\n"; + + PackageDescr pkg = parseAndGetPackageDescr(text); + + assertThat(pkg.getName()).isEqualTo(pkgName); + assertThat(pkg.getRules()).hasSize(1); + + assertThat(pkg.getRules().get(0).getName()).isEqualTo("R"); + } + + @Test + void accumulateEmptyChunks() { + String text = "rule R\n" + + "when\n" + + " $totalAmount : Number() from accumulate( Cheese( $price : price ),\n" + + " init( ),\n" + + " action( ),\n" + + " result( null ) );\n" + + "then\n" + + "end"; + RuleDescr rule = parseAndGetFirstRuleDescr(text); + + final PatternDescr outPattern = (PatternDescr) rule.getLhs().getDescrs().get(0); + final AccumulateDescr accumulateDescr = (AccumulateDescr) outPattern.getSource(); + assertThat(accumulateDescr.getInitCode()).isEmpty(); + assertThat(accumulateDescr.getActionCode()).isEmpty(); + assertThat(accumulateDescr.getReverseCode()).isNull(); + assertThat(accumulateDescr.getResultCode()).isEqualTo("null"); + } + + @Test + void doublePipeInfixOr() { + final String text = + "rule R\n" + + "when\n" + + " Person()\n" + + " ||\n" + + " Address()\n" + + "then\n" + + "end"; + RuleDescr rule = parseAndGetFirstRuleDescr(text); + assertThat(rule.getLhs().getDescrs().get(0)).isInstanceOfSatisfying(OrDescr.class, orDescr -> { + assertThat(orDescr.getDescrs().get(0)).isInstanceOfSatisfying(PatternDescr.class, patternDescr -> { + assertThat(patternDescr.getObjectType()).isEqualTo("Person"); + }); + assertThat(orDescr.getDescrs().get(1)).isInstanceOfSatisfying(PatternDescr.class, patternDescr -> { + assertThat(patternDescr.getObjectType()).isEqualTo("Address"); + }); + }); + } + + @Test + void doubleAmpersandInfixAnd() { + final String text = + "rule R\n" + + "when\n" + + " Person()\n" + + " &&\n" + + " Address()\n" + + "then\n" + + "end"; + RuleDescr rule = parseAndGetFirstRuleDescr(text); + assertThat(rule.getLhs().getDescrs().get(0)).isInstanceOfSatisfying(PatternDescr.class, patternDescr -> { + assertThat(patternDescr.getObjectType()).isEqualTo("Person"); + }); + assertThat(rule.getLhs().getDescrs().get(1)).isInstanceOfSatisfying(PatternDescr.class, patternDescr -> { + assertThat(patternDescr.getObjectType()).isEqualTo("Address"); + }); + } + + @Test + void doubleAmpersandInfixAndInAccumulate() { + final String text = + "rule R\n" + + "when\n" + + " accumulate( FactA($a : value) && FactB($b : value);\n" + + " $avg : average($a + $b))\n" + + "then\n" + + "end"; + RuleDescr rule = parseAndGetFirstRuleDescr(text); + final PatternDescr outPattern = (PatternDescr) rule.getLhs().getDescrs().get(0); + AccumulateDescr accumulateDescr = (AccumulateDescr) outPattern.getSource(); + assertThat(accumulateDescr.getInput()).isInstanceOfSatisfying(AndDescr.class, andDescr -> { + assertThat(andDescr.getDescrs()).hasSize(2); + assertThat(andDescr.getDescrs().get(0)).isInstanceOfSatisfying(PatternDescr.class, patternDescr -> { + assertThat(patternDescr.getObjectType()).isEqualTo("FactA"); + assertThat(patternDescr.getConstraint().getDescrs().get(0)).isInstanceOfSatisfying(ExprConstraintDescr.class, exprConstraintDescr -> { + assertThat(exprConstraintDescr.getExpression()).isEqualTo("$a : value"); + }); + }); + assertThat(andDescr.getDescrs().get(1)).isInstanceOfSatisfying(PatternDescr.class, patternDescr -> { + assertThat(patternDescr.getObjectType()).isEqualTo("FactB"); + assertThat(patternDescr.getConstraint().getDescrs().get(0)).isInstanceOfSatisfying(ExprConstraintDescr.class, exprConstraintDescr -> { + assertThat(exprConstraintDescr.getExpression()).isEqualTo("$b : value"); + }); + }); + }); + + AccumulateDescr.AccumulateFunctionCallDescr accumulateFunction = accumulateDescr.getFunctions().get(0); + assertThat(accumulateFunction.getBind()).isEqualTo("$avg"); + assertThat(accumulateFunction.getFunction()).isEqualTo("average"); + assertThat(accumulateFunction.getParams()).containsExactly("$a + $b"); + } + + @Test + void durationChunk() { + final String text = + "rule R\n" + + " duration (wrong input) \n" + + "when\n" + + "then\n" + + "end"; + RuleDescr rule = parseAndGetFirstRuleDescr(text); + assertThat(rule.getAttributes()).containsKey("duration"); + assertThat(rule.getAttributes().get("duration").getType()).isEqualTo(AttributeDescr.Type.EXPRESSION); + + // At the moment, the parser accepts any input and let the compile phase validate it. + assertThat(rule.getAttributes().get("duration").getValue()).isEqualTo("wrong input"); + } + + @Test + void accumulateWithEmptyActionAndReverse() { + final String drl = "rule R when\n" + + " Number() from accumulate( Number(),\n" + + " init( double total = 0; ),\n" + + " action( ),\n" + + " reverse( ),\n" + + " result( new Double( total ) )\n" + + " )\n" + + "then end"; + RuleDescr rule = parseAndGetFirstRuleDescr(drl); + + final PatternDescr outPattern = (PatternDescr) rule.getLhs().getDescrs().get(0); + final AccumulateDescr accum = (AccumulateDescr) outPattern.getSource(); + assertThat(accum.getInitCode()).isEqualTo("double total = 0;"); + assertThat(accum.getActionCode()).isEmpty(); + assertThat(accum.getReverseCode()).isEmpty(); + assertThat(accum.getResultCode()).isEqualTo("new Double( total )"); + + assertThat(accum.isExternalFunction()).isFalse(); + + final PatternDescr pattern = accum.getInputPattern(); + assertThat(pattern.getObjectType()).isEqualTo("Number"); + + assertThat(accum.getInput()).isInstanceOfSatisfying(AndDescr.class, and -> { + assertThat(and.getDescrs()).hasSize(1); + assertThat(and.getDescrs().get(0)).isInstanceOfSatisfying(PatternDescr.class, patternDescr -> { + assertThat(patternDescr.getObjectType()).isEqualTo("Number"); + }); + }); + } + + @Test + void functionWithAnonymousClass() { + final String text = "function Function f() {\n" + + " return new Function() {\n" + + " public Integer apply(String s) {\n" + + " return s.length();\n" + + " }\n" + + " };\n" + + "}"; + PackageDescr packageDescr = parseAndGetPackageDescr(text); + FunctionDescr function = packageDescr.getFunctions().get(0); + + assertThat(function.getName()).isEqualTo("f"); + assertThat(function.getReturnType()).isEqualToIgnoringWhitespace("Function"); + assertThat(function.getParameterTypes()).isEmpty(); + assertThat(function.getParameterNames()).isEmpty(); + assertThat(function.getBody()).isEqualToIgnoringWhitespace("return new Function() {\n" + + " public Integer apply(String s) {\n" + + " return s.length();\n" + + " }\n" + + " };"); + } + + @Test + void typeDeclarationWithTypeToken() { + final String drl = "declare type Foo\n" + // "type" is just optional + " id : int\n" + + "end"; + final PackageDescr pkg = parseAndGetPackageDescr(drl); + + TypeDeclarationDescr typeDeclarationDescr = pkg.getTypeDeclarations().get(0); + assertThat(typeDeclarationDescr.getTypeName()).isEqualTo("Foo"); + TypeFieldDescr typeFieldDescr = typeDeclarationDescr.getFields().get("id"); + assertThat(typeFieldDescr.getPattern().getObjectType()).isEqualTo("int"); + } +} diff --git a/drools-drl/drools-drl-parser-tests/src/test/java/org/drools/drl/parser/antlr4/ParserTestUtils.java b/drools-drl/drools-drl-parser-tests/src/test/java/org/drools/drl/parser/antlr4/ParserTestUtils.java new file mode 100644 index 00000000000..3419eab65e5 --- /dev/null +++ b/drools-drl/drools-drl-parser-tests/src/test/java/org/drools/drl/parser/antlr4/ParserTestUtils.java @@ -0,0 +1,61 @@ +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you 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 + *

+ * http://www.apache.org/licenses/LICENSE-2.0 + *

+ * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.drools.drl.parser.antlr4; + +import java.util.Arrays; +import java.util.List; + +import org.drools.drl.parser.DrlParser; + +public class ParserTestUtils { + + // 'new' is not included because it cannot be included in drlIdentifier. + // See https://github.com/apache/incubator-kie-drools/pull/5958 + public static List javaKeywords = + Arrays.asList( + "abstract", "assert", "boolean", "break", "byte", "case", "catch", "char", "class", "const", + "continue", "default", "do", "double", "else", "enum", "extends", "final", "finally", "float", + "for", "goto", "if", "implements", "import", "instanceof", "int", "interface", "long", "native", + "package", "private", "protected", "public", "return", "short", "static", "strictfp", + "super", "switch", "synchronized", "this", "throw", "throws", "transient", "try", "void", "volatile", + "while" + ); + + private ParserTestUtils() { + // It is a utility class, so it should not be instantiated. + } + + /** + * Returns a DrlParser which encapsulates an old or new parser depending on system property + */ + public static DrlParser getParser() { + return new DrlParser(); + } + + /** + * Enables the old parser. Just for quick testing purposes. + */ + public static void enableOldParser() { + DrlParser.ANTLR4_PARSER_ENABLED = false; + } + + public static List javaKeywords() { + return javaKeywords; + } +} diff --git a/drools-drl/drools-drl-parser-tests/src/test/resources/logback-test.xml b/drools-drl/drools-drl-parser-tests/src/test/resources/logback-test.xml new file mode 100644 index 00000000000..f44c3a48c76 --- /dev/null +++ b/drools-drl/drools-drl-parser-tests/src/test/resources/logback-test.xml @@ -0,0 +1,37 @@ + + + + + + + %date{HH:mm:ss.SSS} [%thread] %-5level %class{36}.%method:%line - %msg%n + + + + + + + + + + + \ No newline at end of file diff --git a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl/parser/antlr4/Rule_with_Extends.drl b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl/parser/antlr4/Rule_with_Extends.drl new file mode 100644 index 00000000000..74cff04d3c1 --- /dev/null +++ b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl/parser/antlr4/Rule_with_Extends.drl @@ -0,0 +1,25 @@ +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you 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 + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations + * under the License. + */ + +package org.drools.compiler + +rule test_rule extends rule1 + when + $foo : foo() + then + +end diff --git a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl/parser/antlr4/Rule_with_Metadata.drl b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl/parser/antlr4/Rule_with_Metadata.drl new file mode 100644 index 00000000000..122634a9b26 --- /dev/null +++ b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl/parser/antlr4/Rule_with_Metadata.drl @@ -0,0 +1,27 @@ +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you 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 + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations + * under the License. + */ + + +package org.drools.compiler + +rule test_rule + @fooMeta1(barVal1) + @fooMeta2(barVal2) + when + then + System.out.println("Consequence"); +end diff --git a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl/parser/antlr4/Rule_with_nested_LHS.drl b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl/parser/antlr4/Rule_with_nested_LHS.drl new file mode 100644 index 00000000000..c009e6ec210 --- /dev/null +++ b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl/parser/antlr4/Rule_with_nested_LHS.drl @@ -0,0 +1,28 @@ +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you 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 + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations + * under the License. + */ + +package org.drools.compiler + +rule test + when + A() + ( B() and C() ) or + ( D() and E() ) or + ( F() and G() ) + then + +end diff --git a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl/parser/antlr4/accumulateExternalFunction.drl b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl/parser/antlr4/accumulateExternalFunction.drl new file mode 100755 index 00000000000..43ee672e90b --- /dev/null +++ b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl/parser/antlr4/accumulateExternalFunction.drl @@ -0,0 +1,23 @@ +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you 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 + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations + * under the License. + */ + +rule "AccumulateReverseParserTest" +when + Number() from accumulate( Person( $age : age > 21 ), + average( $age ) ); +then +end \ No newline at end of file diff --git a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl/parser/antlr4/accumulateMultipleFunctions.drl b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl/parser/antlr4/accumulateMultipleFunctions.drl new file mode 100755 index 00000000000..0557d308f43 --- /dev/null +++ b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl/parser/antlr4/accumulateMultipleFunctions.drl @@ -0,0 +1,30 @@ +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you 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 + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations + * under the License. + */ + +package org.drools.compiler + +rule "Accumulate 1" +when + accumulate( Cheese( $price : price ), + $a1 : average( $price ), + $m1 : min( $price ), + $M1 : max( $price ) // binds are optional, but it makes no sense to not have a binding in this case + ) +then + // do something +end + diff --git a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl/parser/antlr4/accumulateMultipleFunctionsConstraint.drl b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl/parser/antlr4/accumulateMultipleFunctionsConstraint.drl new file mode 100755 index 00000000000..9c146f05edb --- /dev/null +++ b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl/parser/antlr4/accumulateMultipleFunctionsConstraint.drl @@ -0,0 +1,32 @@ +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you 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 + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations + * under the License. + */ + +package org.drools.compiler + +rule "Accumulate 1" +when + accumulate( Cheese( $price : price ); + $a1 : average( $price ), + $m1 : min( $price ), + $M1 : max( $price ); // binds are optional, but it makes no sense to not have a binding in this case + $a1 > 10 && $M1 <= 100, + $m1 == 5 // inline evals + ) +then + // do something +end + diff --git a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl/parser/antlr4/accumulateReverse.drl b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl/parser/antlr4/accumulateReverse.drl new file mode 100755 index 00000000000..76872623dda --- /dev/null +++ b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl/parser/antlr4/accumulateReverse.drl @@ -0,0 +1,26 @@ +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you 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 + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations + * under the License. + */ + +rule "AccumulateReverseParserTest" +when + Integer() from accumulate( Person( age > 21 ), + init( int x = 0; ), + action( x++; ), + reverse( x--; ), + result( new Integer(x) ) ); +then +end \ No newline at end of file diff --git a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl/parser/antlr4/accumulate_multi_pattern.drl b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl/parser/antlr4/accumulate_multi_pattern.drl new file mode 100755 index 00000000000..8d3f6828f50 --- /dev/null +++ b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl/parser/antlr4/accumulate_multi_pattern.drl @@ -0,0 +1,25 @@ +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you 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 + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations + * under the License. + */ + +rule "AccumulateMultiPatternParserTest" +when + $counter:Integer() from accumulate( $person : Person( age > 21 ) and Cheese( type == $person.likes ), + init( int x = 0; ), + action( x++; ), + result( new Integer(x) ) ); +then +end \ No newline at end of file diff --git a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl/parser/antlr4/accumulate_with_bindings.drl b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl/parser/antlr4/accumulate_with_bindings.drl new file mode 100755 index 00000000000..75d70816931 --- /dev/null +++ b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl/parser/antlr4/accumulate_with_bindings.drl @@ -0,0 +1,25 @@ +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you 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 + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations + * under the License. + */ + +rule "AccumulateParserTest" +when + $counter:Integer() from accumulate( $person : Person( age > 21 ), + init( int x = 0; ), + action( x++; ), + result( new Integer(x) ) ); +then +end \ No newline at end of file diff --git a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl/parser/antlr4/accumulate_with_nested_from.drl b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl/parser/antlr4/accumulate_with_nested_from.drl new file mode 100755 index 00000000000..3696836b1f2 --- /dev/null +++ b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl/parser/antlr4/accumulate_with_nested_from.drl @@ -0,0 +1,25 @@ +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you 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 + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations + * under the License. + */ + +rule "AccumulateParserTest" +when + // below statement makes no sense, but is useful to test parsing recursiveness + $personList : ArrayList() from accumulate( Person( $age : age > 21 || < 10 ) from collect( People() from $town.getPeople() ), + max( $age ) ); +then +end + diff --git a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl/parser/antlr4/almost_empty_rule.drl b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl/parser/antlr4/almost_empty_rule.drl new file mode 100644 index 00000000000..5155aa035de --- /dev/null +++ b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl/parser/antlr4/almost_empty_rule.drl @@ -0,0 +1,22 @@ +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you 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 + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations + * under the License. + */ + + +rule almost_empty + when + then +end \ No newline at end of file diff --git a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl/parser/antlr4/and_or_rule.drl b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl/parser/antlr4/and_or_rule.drl new file mode 100644 index 00000000000..e81b1d4a18f --- /dev/null +++ b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl/parser/antlr4/and_or_rule.drl @@ -0,0 +1,27 @@ +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you 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 + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations + * under the License. + */ + + +import org.drools.compiler.Person + +rule simple_rule + when + Person(name == "mark") and Cheese(type == "stilton") + Person(name == "mark") or Cheese(type == "stilton") + then + System.out.println( "Mark and Michael" ); +end diff --git a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl/parser/antlr4/autofocus.drl b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl/parser/antlr4/autofocus.drl new file mode 100644 index 00000000000..48fa4c52a19 --- /dev/null +++ b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl/parser/antlr4/autofocus.drl @@ -0,0 +1,25 @@ +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you 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 + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations + * under the License. + */ + + +rule rule1 + auto-focus true + when + not Cheese(type == "stilton") + then + funky(); +end diff --git a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl/parser/antlr4/basic_binding.drl b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl/parser/antlr4/basic_binding.drl new file mode 100644 index 00000000000..7c48ee595b5 --- /dev/null +++ b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl/parser/antlr4/basic_binding.drl @@ -0,0 +1,27 @@ +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you 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 + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations + * under the License. + */ + +package org.drools.compiler.test; + +import org.drools.compiler.Cheese; + +rule "like cheddar" + when + Cheese( $type:type ) + then + System.out.println("I like " + $type); +end \ No newline at end of file diff --git a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl/parser/antlr4/bindings.drl b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl/parser/antlr4/bindings.drl new file mode 100644 index 00000000000..6aabea7bd1b --- /dev/null +++ b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl/parser/antlr4/bindings.drl @@ -0,0 +1,29 @@ +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you 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 + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations + * under the License. + */ + +package org.drools.compiler.test; + +import org.drools.compiler.Cheese; +import org.drools.compiler.Person; + +rule "Who likes Stilton" + when + Cheese($type : type == "stilton") + $person : Person( $name : name == "bob", likes == $type) + then + System.out.println( $name + " likes " + $type); +end \ No newline at end of file diff --git a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl/parser/antlr4/brackets_precedence.drl b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl/parser/antlr4/brackets_precedence.drl new file mode 100644 index 00000000000..8259a28773c --- /dev/null +++ b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl/parser/antlr4/brackets_precedence.drl @@ -0,0 +1,23 @@ +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you 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 + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations + * under the License. + */ + + +rule simple_rule + when + ( (not Foo(x=="a") or Foo(x=="y") ) and ( Shoes() or Butt() ) ) + then +end diff --git a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl/parser/antlr4/collect.drl b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl/parser/antlr4/collect.drl new file mode 100755 index 00000000000..839e2c6c19e --- /dev/null +++ b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl/parser/antlr4/collect.drl @@ -0,0 +1,22 @@ +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you 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 + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations + * under the License. + */ + +rule "CollectParserTest" +when + $personList : ArrayList() from collect( Person( age > 21 ) ); +then +end \ No newline at end of file diff --git a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl/parser/antlr4/collect_with_nested_from.drl b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl/parser/antlr4/collect_with_nested_from.drl new file mode 100755 index 00000000000..146b9e46c6a --- /dev/null +++ b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl/parser/antlr4/collect_with_nested_from.drl @@ -0,0 +1,24 @@ +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you 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 + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations + * under the License. + */ + +rule "CollectParserTest" +when + // below statement makes no sense, but is useful to test parsing recursiveness + $personList : ArrayList() from collect( $p : Person( age > 21 || age < 10 ) from collect( People() from $town.getPeople() ) ); +then +end + diff --git a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl/parser/antlr4/comment.drl b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl/parser/antlr4/comment.drl new file mode 100644 index 00000000000..e46ecbe4601 --- /dev/null +++ b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl/parser/antlr4/comment.drl @@ -0,0 +1,32 @@ +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you 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 + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations + * under the License. + */ + +//this starts with a comment +package foo.bar + +//and another comment + +/* +yet + another + style +*/ + +rule "test" + when + then +end diff --git a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl/parser/antlr4/complex.dsl b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl/parser/antlr4/complex.dsl new file mode 100644 index 00000000000..0e7ffc0fd07 --- /dev/null +++ b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl/parser/antlr4/complex.dsl @@ -0,0 +1,24 @@ +# +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you 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 +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, +# software distributed under the License is distributed on an +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +# KIND, either express or implied. See the License for the +# specific language governing permissions and limitations +# under the License. +# + +#place your comments here - this is just a description for your own purposes. +[when]There is a Person with name of {name}=Person(name=="{name}") +[when]Person is at least {age} years old and lives in {location}=Person(age > {age}, location == "{location}") +[then]Log "{message}"=System.out.println("{message}"); +[when]Or=or diff --git a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl/parser/antlr4/declaration-in-consequence.drl b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl/parser/antlr4/declaration-in-consequence.drl new file mode 100644 index 00000000000..836a53dcd57 --- /dev/null +++ b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl/parser/antlr4/declaration-in-consequence.drl @@ -0,0 +1,48 @@ +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you 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 + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations + * under the License. + */ + + + +rule myrule + when + then + int i = 0; + i = 1; + i / 1; + i == 1; + i(i); + i = 'i'; + i.i.i; + ii; + i="i"; + ++i; + i++; + --i; + i--; + i += i; + i -= i; + i *= i; + i /= i; + int i = 5; + for(int j; j 21, $likes : likes ) + Cheese( type == $likes ) ); +then +end \ No newline at end of file diff --git a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl/parser/antlr4/forallwithfrom.drl b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl/parser/antlr4/forallwithfrom.drl new file mode 100644 index 00000000000..d387cf9c647 --- /dev/null +++ b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl/parser/antlr4/forallwithfrom.drl @@ -0,0 +1,23 @@ +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you 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 + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations + * under the License. + */ + +rule "ForallParserTest" +when + forall( Person( age > 21, $likes : likes ) from $village + Cheese( type == $likes ) from $cheesery ); +then +end \ No newline at end of file diff --git a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl/parser/antlr4/from.drl b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl/parser/antlr4/from.drl new file mode 100644 index 00000000000..47f918be139 --- /dev/null +++ b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl/parser/antlr4/from.drl @@ -0,0 +1,31 @@ +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you 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 + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations + * under the License. + */ + +rule using_from + when + Foo() from bar.baz + Foo() from bar.baz["key"] + Foo() from bar.baz[$key] + Foo() from bar.baz[1] + Whee(bar=="baz") from whee("y") + f: Foo(la==2) from bar.la(x) + Bam() from wa() + Kah() from la.wa(42, 42.42, false, null) + Bam(a=="c") + then + whee(); +end diff --git a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl/parser/antlr4/from_accumulate.drl b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl/parser/antlr4/from_accumulate.drl new file mode 100755 index 00000000000..7f3f4ce75f9 --- /dev/null +++ b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl/parser/antlr4/from_accumulate.drl @@ -0,0 +1,25 @@ +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you 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 + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations + * under the License. + */ + +rule "AccumulateParserTest" +when + Integer() from accumulate( Person( age > 21 ), + init( int x = 0; ), + action( x++; ), + result( new Integer(x) ) ); +then +end \ No newline at end of file diff --git a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl/parser/antlr4/function_arrays.drl b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl/parser/antlr4/function_arrays.drl new file mode 100644 index 00000000000..98df27bf96a --- /dev/null +++ b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl/parser/antlr4/function_arrays.drl @@ -0,0 +1,31 @@ +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you 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 + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations + * under the License. + */ + +package foo + +function String[] yourFunction(String args[]) { + baz(); +} + +rule "new rule" + + when + Something() + then + yourFunction(new String[] {"a","b","c"}); + +end diff --git a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl/parser/antlr4/functions.drl b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl/parser/antlr4/functions.drl new file mode 100644 index 00000000000..2a543650f58 --- /dev/null +++ b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl/parser/antlr4/functions.drl @@ -0,0 +1,43 @@ +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you 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 + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations + * under the License. + */ + + +import java.lang.String + +function String functionA(String s, Integer i) { + + foo(); + +} + +function void functionB() { + bar(); +} + + +rule something + when + then +end + +rule "one more thing" + when + then +end + + + diff --git a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl/parser/antlr4/globals.drl b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl/parser/antlr4/globals.drl new file mode 100644 index 00000000000..ed6d45ff31f --- /dev/null +++ b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl/parser/antlr4/globals.drl @@ -0,0 +1,30 @@ +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you 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 + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations + * under the License. + */ + +package org.drools.compiler.test; + +import org.drools.compiler.Cheese; + +global java.lang.String foo +global java.lang.Integer bar; + +rule baz + when + Cheese( ) + then + +end diff --git a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl/parser/antlr4/groupBy.drl b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl/parser/antlr4/groupBy.drl new file mode 100755 index 00000000000..9ca6ed7e834 --- /dev/null +++ b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl/parser/antlr4/groupBy.drl @@ -0,0 +1,26 @@ +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you 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 + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations + * under the License. + */ + +rule "GroupByParserTest" +when + groupby( $p: Person ( $age : age < 30 ); // SOURCE_PATTERN + $initial : $p.getName().substring(0, 1); // GROUPING_FUNCTION + $sumOfAges : sum($age), // 2 ACC_FUNCTIONS, one summing the ages of the persons in the group + $countOfPersons : count(); // and the other simply counting them + $sumOfAges > 10 ) // CONSTRAINT filtering away groups +then +end diff --git a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl/parser/antlr4/in_operator_test.drl b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl/parser/antlr4/in_operator_test.drl new file mode 100644 index 00000000000..54f5225c3e8 --- /dev/null +++ b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl/parser/antlr4/in_operator_test.drl @@ -0,0 +1,26 @@ +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you 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 + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations + * under the License. + */ + +//testing 'in' operator + +rule simple_rule + when + Person(age > 30 && < 40) + Vehicle(type in ( "sedan", "wagon" ), age < 3) + then + consequence(); +end diff --git a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl/parser/antlr4/lhs_semicolon_delim.drl b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl/parser/antlr4/lhs_semicolon_delim.drl new file mode 100644 index 00000000000..3d4d2df7c75 --- /dev/null +++ b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl/parser/antlr4/lhs_semicolon_delim.drl @@ -0,0 +1,29 @@ +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you 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 + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations + * under the License. + */ + + +rule simple_rule + when + foo3 : Bar(a==3) ; foo4 : Bar(a4:a==4) ; Baz() + then + if ( a == b ) { + assert( foo3 ); + } else { + retract( foo4 ); + } + System.out.println( a4 ); +end \ No newline at end of file diff --git a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl/parser/antlr4/literal_bool_and_negative.drl b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl/parser/antlr4/literal_bool_and_negative.drl new file mode 100644 index 00000000000..a1d01a65573 --- /dev/null +++ b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl/parser/antlr4/literal_bool_and_negative.drl @@ -0,0 +1,27 @@ +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you 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 + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations + * under the License. + */ + +//check that it can handle true/false literals, and +//negative numbers +rule simple_rule + when + Foo(bar == false) + Foo(boo > -42) + Foo(boo > -42.42) + then + cons(); +end diff --git a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl/parser/antlr4/multiple_constraints.dsl b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl/parser/antlr4/multiple_constraints.dsl new file mode 100644 index 00000000000..b56fd4bd644 --- /dev/null +++ b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl/parser/antlr4/multiple_constraints.dsl @@ -0,0 +1,25 @@ +# +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you 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 +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, +# software distributed under the License is distributed on an +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +# KIND, either express or implied. See the License for the +# specific language governing permissions and limitations +# under the License. +# + +#place your comments here - this is just a description for your own purposes. +[when]There is a Person with=Person() +[when]- age less than {age}=age < {age} +[when]- location is '{city}'=location=={city} +[when]Bar bar black sheep=Bar() +[then]Log "{message}"=System.out.println("{message}"); diff --git a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl/parser/antlr4/multiple_rules.drl b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl/parser/antlr4/multiple_rules.drl new file mode 100644 index 00000000000..067e55fdb9d --- /dev/null +++ b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl/parser/antlr4/multiple_rules.drl @@ -0,0 +1,34 @@ +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you 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 + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations + * under the License. + */ + +package org.drools.compiler.test; + +import org.drools.integrationtests.Cheese; + +rule "Like Stilton" + when + Cheese( t:type == "stilton" ) + then + System.out.println("I like " + t); +end + +rule "Like Cheddar" + when + Cheese( t:type == "cheddar" ) + then + System.out.println("I like " + t ); +end \ No newline at end of file diff --git a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl/parser/antlr4/nested_conditional_elements.drl b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl/parser/antlr4/nested_conditional_elements.drl new file mode 100755 index 00000000000..0b11f17c562 --- /dev/null +++ b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl/parser/antlr4/nested_conditional_elements.drl @@ -0,0 +1,27 @@ +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you 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 + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations + * under the License. + */ + +rule "test nested CEs" + when + not ( State( $state : state ) and + not( Person( status == $state, $likes : likes ) and + Cheese( type == $likes ) ) ) + Person( name == "Bob" ) + ( Cheese( price == 10 ) or Cheese( type == "brie" ) ) + then + results.add("OK"); +end diff --git a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl/parser/antlr4/no-loop.drl b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl/parser/antlr4/no-loop.drl new file mode 100644 index 00000000000..768fa8775c8 --- /dev/null +++ b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl/parser/antlr4/no-loop.drl @@ -0,0 +1,25 @@ +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you 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 + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations + * under the License. + */ + + +rule rule1 + no-loop false + when + not Cheese(type == "stilton") + then + funky(); +end diff --git a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl/parser/antlr4/not_exist_with_brackets.drl b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl/parser/antlr4/not_exist_with_brackets.drl new file mode 100644 index 00000000000..8ec3fd4f86e --- /dev/null +++ b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl/parser/antlr4/not_exist_with_brackets.drl @@ -0,0 +1,26 @@ +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you 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 + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations + * under the License. + */ + +package HR1 + +rule simple_rule + when + not ( Cheese(type == "stilton") ) + exists ( Foo() ) + then + funky(); +end diff --git a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl/parser/antlr4/not_with_constraint.drl b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl/parser/antlr4/not_with_constraint.drl new file mode 100644 index 00000000000..573fe4808d6 --- /dev/null +++ b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl/parser/antlr4/not_with_constraint.drl @@ -0,0 +1,31 @@ +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you 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 + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations + * under the License. + */ + +package org.drools.compiler.test; + +import org.drools.compiler.Cheese; + +global java.util.List list; +global java.lang.Integer five; + +rule "not rule test" + when + $person : Person( $likes:like ) + not Cheese( type == $likes ) + then + list.add( $person ); +end diff --git a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl/parser/antlr4/notin_operator_test.drl b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl/parser/antlr4/notin_operator_test.drl new file mode 100644 index 00000000000..a2eae254405 --- /dev/null +++ b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl/parser/antlr4/notin_operator_test.drl @@ -0,0 +1,26 @@ +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you 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 + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations + * under the License. + */ + +//testing not 'in' operator + +rule simple_rule + when + Person(age > 30 && < 40) + Vehicle(type not in ( "sedan", "wagon" ), age < 3) + then + consequence(); +end diff --git a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl/parser/antlr4/or_binding.drl b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl/parser/antlr4/or_binding.drl new file mode 100644 index 00000000000..87907a60b7a --- /dev/null +++ b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl/parser/antlr4/or_binding.drl @@ -0,0 +1,27 @@ +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you 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 + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations + * under the License. + */ + + +import org.drools.compiler.Person + +rule simple_rule + when + foo : ( Person(name == "mark") or Person(type == "fan") ) + Cheese(type == "green") + then + System.out.println( "Mark and Michael" + bar ); +end diff --git a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl/parser/antlr4/or_binding_complex.drl b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl/parser/antlr4/or_binding_complex.drl new file mode 100644 index 00000000000..2090d8f8565 --- /dev/null +++ b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl/parser/antlr4/or_binding_complex.drl @@ -0,0 +1,27 @@ +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you 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 + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations + * under the License. + */ + + + +rule simple_rule + when + foo : ( Person(name == "mark") + or + Person(type == "fan") ) + then + System.out.println( "Mark and Michael" + bar ); +end diff --git a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl/parser/antlr4/or_binding_with_brackets.drl b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl/parser/antlr4/or_binding_with_brackets.drl new file mode 100644 index 00000000000..a96bae49029 --- /dev/null +++ b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl/parser/antlr4/or_binding_with_brackets.drl @@ -0,0 +1,25 @@ +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you 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 + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations + * under the License. + */ + +rule simple_rule + when + foo : ( + Person(name == "mark") or Person(type == "fan") + ) + then + System.out.println( "Mark and Michael" + bar ); +end diff --git a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl/parser/antlr4/or_ce.drl b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl/parser/antlr4/or_ce.drl new file mode 100644 index 00000000000..3e576f091a8 --- /dev/null +++ b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl/parser/antlr4/or_ce.drl @@ -0,0 +1,26 @@ +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you 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 + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations + * under the License. + */ + +package org.drools.compiler + +rule "testing OR CE" +when + $p : Person( name == "bob" ) + $c : Cheese( type == $p.likes ) or Cheese( price == 10 ) +then + // do something +end \ No newline at end of file diff --git a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl/parser/antlr4/or_nesting.drl b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl/parser/antlr4/or_nesting.drl new file mode 100644 index 00000000000..ecf9ddb2338 --- /dev/null +++ b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl/parser/antlr4/or_nesting.drl @@ -0,0 +1,27 @@ +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you 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 + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations + * under the License. + */ + + +import org.drools.compiler.Person + +rule simple_rule + when + Person(name == "mark") or + ( Person(type == "fan") and Cheese(type == "green") ) + then + System.out.println( "Mark and Michael" + bar ); +end diff --git a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl/parser/antlr4/package_attributes.drl b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl/parser/antlr4/package_attributes.drl new file mode 100644 index 00000000000..156f5c58f6d --- /dev/null +++ b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl/parser/antlr4/package_attributes.drl @@ -0,0 +1,40 @@ +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you 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 + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations + * under the License. + */ + +package com.foo; + +agenda-group "x" + +import goo.ber +import wee.waa + + +dialect "java" + + + + +rule bar + when + then +end + +rule baz + dialect "mvel" + when + then +end \ No newline at end of file diff --git a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl/parser/antlr4/package_children.drl b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl/parser/antlr4/package_children.drl new file mode 100644 index 00000000000..f419879de3e --- /dev/null +++ b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl/parser/antlr4/package_children.drl @@ -0,0 +1,53 @@ +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you 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 + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations + * under the License. + */ + +package org.drools.compiler.test + +unit TestUnit + +import org.drools.compiler.Cheese + +import function abc.def.x + +import accumulate foo.Bar2 baz2 + +global List result + +declare Person end + +declare enum Color WHITE; end + +declare entry-point EntryPoint end + +declare window Window + Double() over window:length( 10 ) +end + +query MyQuery + Cheese() +end + +function String doSomething() {} + +enabled true; + +dialect "java" + +rule "My Rule" +when +then +end diff --git a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl/parser/antlr4/pluggable_operators.drl b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl/parser/antlr4/pluggable_operators.drl new file mode 100644 index 00000000000..59c31d2c8e7 --- /dev/null +++ b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl/parser/antlr4/pluggable_operators.drl @@ -0,0 +1,28 @@ +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you 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 + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations + * under the License. + */ + +package org.drools.compiler + +rule "test pluggable operators" +when + $a : EventA() + $b : EventB( this after[1,10] $a || this not after[15,20] $a ) + $c : EventC( this finishes $b ) + $d : EventD( this not starts $a ) + $e : EventE( this not before[1, 10] $b || after[1, 10] $c && this after[1, 5] $d ) +then +end \ No newline at end of file diff --git a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl/parser/antlr4/qualified_classname.drl b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl/parser/antlr4/qualified_classname.drl new file mode 100644 index 00000000000..9347834bbbb --- /dev/null +++ b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl/parser/antlr4/qualified_classname.drl @@ -0,0 +1,25 @@ +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you 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 + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations + * under the License. + */ + +package org.drools.compiler.test; + +rule "Who likes Stilton" + when + com.cheeseco.Cheese($type : type == "stilton") + then + System.out.println( $name + " likes " + $type); +end \ No newline at end of file diff --git a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl/parser/antlr4/qualified_type_declaration.drl b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl/parser/antlr4/qualified_type_declaration.drl new file mode 100644 index 00000000000..0eaa7067117 --- /dev/null +++ b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl/parser/antlr4/qualified_type_declaration.drl @@ -0,0 +1,27 @@ +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you 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 + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations + * under the License. + */ + +package org.drools.compiler.test; + +declare com.sample1.SomeFact + name : String + age: Integer +end + +declare enum com.sample2.Color + WHITE; +end diff --git a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl/parser/antlr4/query_and_rule.drl b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl/parser/antlr4/query_and_rule.drl new file mode 100644 index 00000000000..e9b9be3edd2 --- /dev/null +++ b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl/parser/antlr4/query_and_rule.drl @@ -0,0 +1,47 @@ +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you 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 + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations + * under the License. + */ + + +package foo + +rule bar + when + Baz() + then + Boo() +end + +query "simple_query" + foo3 : Bar(a==3) + foo4 : Bar(a4:a==4) + Baz() + +end + +rule bar2 + when + Baz() + then + Boo() +end + +query "simple_query2" + foo3 : Bar(a==3) + foo4 : Bar(a4:a==4) + Baz() + +end diff --git a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl/parser/antlr4/quoted_string_name_rule.drl b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl/parser/antlr4/quoted_string_name_rule.drl new file mode 100644 index 00000000000..9eda0358e56 --- /dev/null +++ b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl/parser/antlr4/quoted_string_name_rule.drl @@ -0,0 +1,21 @@ +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you 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 + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations + * under the License. + */ + +rule "quoted string name" + when + then +end \ No newline at end of file diff --git a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl/parser/antlr4/restrictions_test.drl b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl/parser/antlr4/restrictions_test.drl new file mode 100644 index 00000000000..edf674db5ed --- /dev/null +++ b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl/parser/antlr4/restrictions_test.drl @@ -0,0 +1,26 @@ +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you 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 + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations + * under the License. + */ + +//this is for showing off all the new multi restriction stuff + +rule simple_rule + when + Person(age > 30 && < 40) + Vehicle(type == "sedan" || == "wagon", age < 3) + then + consequence(); +end diff --git a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl/parser/antlr4/rule_attributes.drl b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl/parser/antlr4/rule_attributes.drl new file mode 100644 index 00000000000..faf0d0c3351 --- /dev/null +++ b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl/parser/antlr4/rule_attributes.drl @@ -0,0 +1,33 @@ +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you 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 + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations + * under the License. + */ + + + + +rule simple_rule + // attributes keywork (and colon) is totally optional + salience 42 + agenda-group "my_group" + no-loop + duration 42 + activation-group "my_activation_group" + lock-on-active true + when + Foo() + then + bar(); +end diff --git a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl/parser/antlr4/rule_attributes2.drl b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl/parser/antlr4/rule_attributes2.drl new file mode 100644 index 00000000000..cece840aa59 --- /dev/null +++ b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl/parser/antlr4/rule_attributes2.drl @@ -0,0 +1,46 @@ +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you 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 + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations + * under the License. + */ + +package foo.bar + + +rule rule1 + salience (42) + agenda-group "my_group" + when + Foo() + then + bar(); +end + +rule rule2 + salience (Integer.MIN_VALUE) + no-loop + when + Foo() + then + bar(); +end + +rule rule3 + enabled (Boolean.TRUE) + activation-group "my_activation_group" + when + Foo() + then + bar(); +end diff --git a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl/parser/antlr4/rule_attributes_alt.drl b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl/parser/antlr4/rule_attributes_alt.drl new file mode 100644 index 00000000000..fafc7032171 --- /dev/null +++ b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl/parser/antlr4/rule_attributes_alt.drl @@ -0,0 +1,28 @@ +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you 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 + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations + * under the License. + */ + + + + +rule simple_rule + attributes: + salience 42, agenda-group "my_group", no-loop, lock-on-active, duration 42, activation-group "my_activation_group" + when + Foo() + then + bar(); +end diff --git a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl/parser/antlr4/rule_calendars_attribute.drl b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl/parser/antlr4/rule_calendars_attribute.drl new file mode 100644 index 00000000000..2605f494aa9 --- /dev/null +++ b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl/parser/antlr4/rule_calendars_attribute.drl @@ -0,0 +1,26 @@ +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you 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 + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations + * under the License. + */ + + +rule simple_rule + calendars "cal1" + lock-on-active true + when + Foo() + then + bar(); +end diff --git a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl/parser/antlr4/rule_calendars_attribute2.drl b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl/parser/antlr4/rule_calendars_attribute2.drl new file mode 100644 index 00000000000..31040f9e95f --- /dev/null +++ b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl/parser/antlr4/rule_calendars_attribute2.drl @@ -0,0 +1,26 @@ +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you 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 + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations + * under the License. + */ + + +rule simple_rule + calendars "cal 1", "cal 2", "cal 3" + lock-on-active true + when + Foo() + then + bar(); +end diff --git a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl/parser/antlr4/rule_duration_expression.drl b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl/parser/antlr4/rule_duration_expression.drl new file mode 100644 index 00000000000..c0ca3ba4430 --- /dev/null +++ b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl/parser/antlr4/rule_duration_expression.drl @@ -0,0 +1,26 @@ +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you 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 + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations + * under the License. + */ + + +rule simple_rule + duration ( 1h30m ) + lock-on-active true + when + Foo() + then + bar(); +end diff --git a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl/parser/antlr4/rule_enabled_expression.drl b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl/parser/antlr4/rule_enabled_expression.drl new file mode 100644 index 00000000000..12550c159c7 --- /dev/null +++ b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl/parser/antlr4/rule_enabled_expression.drl @@ -0,0 +1,27 @@ +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you 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 + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations + * under the License. + */ + + +rule simple_rule + enabled ( 1 + 1 == 2 ) + salience ( 1+2 ) + lock-on-active true + when + Foo() + then + bar(); +end diff --git a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl/parser/antlr4/rule_names_number_prefix.drl b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl/parser/antlr4/rule_names_number_prefix.drl new file mode 100644 index 00000000000..cd14e5699a6 --- /dev/null +++ b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl/parser/antlr4/rule_names_number_prefix.drl @@ -0,0 +1,27 @@ +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you 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 + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations + * under the License. + */ + + +rule "1. Do Stuff!" + when + then +end + +rule "2. Do More Stuff!" + when + then +end \ No newline at end of file diff --git a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl/parser/antlr4/rule_not.drl b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl/parser/antlr4/rule_not.drl new file mode 100644 index 00000000000..96a2448ca41 --- /dev/null +++ b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl/parser/antlr4/rule_not.drl @@ -0,0 +1,24 @@ +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you 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 + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations + * under the License. + */ + + +rule simple_rule + when + not Cheese(type == "stilton") + then + funky(); +end diff --git a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl/parser/antlr4/rule_timer_attribute.drl b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl/parser/antlr4/rule_timer_attribute.drl new file mode 100644 index 00000000000..fe0377e25f0 --- /dev/null +++ b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl/parser/antlr4/rule_timer_attribute.drl @@ -0,0 +1,26 @@ +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you 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 + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations + * under the License. + */ + + +rule simple_rule + timer (int: 0 1; start=1_000_000, repeat-limit=0) + lock-on-active true + when + Foo() + then + bar(); +end diff --git a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl/parser/antlr4/ruleflowgroup.drl b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl/parser/antlr4/ruleflowgroup.drl new file mode 100755 index 00000000000..8b48eea0fe9 --- /dev/null +++ b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl/parser/antlr4/ruleflowgroup.drl @@ -0,0 +1,25 @@ +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you 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 + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations + * under the License. + */ + + +rule rule1 + ruleflow-group "a group" + when + not Cheese(type == "stilton") + then + funky(); +end diff --git a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl/parser/antlr4/semicolon.drl b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl/parser/antlr4/semicolon.drl new file mode 100644 index 00000000000..7d25f230e25 --- /dev/null +++ b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl/parser/antlr4/semicolon.drl @@ -0,0 +1,43 @@ +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you 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 + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations + * under the License. + */ + +package org.drools.mvel.compiler + +global java.util.List list; + +rule "rule1" +when + Pattern1(); + Pattern2() from x.y.z; +then + System.out.println("Test"); +end; + +query "query1" + Pattern5(); + Pattern6(); + Pattern7(); +end; + +rule "rule2" +when + Pattern3(); + Pattern4() from collect( Pattern5() ); +then + System.out.println("Test"); +end; + diff --git a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl/parser/antlr4/simple_query.drl b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl/parser/antlr4/simple_query.drl new file mode 100644 index 00000000000..2532abc0b6c --- /dev/null +++ b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl/parser/antlr4/simple_query.drl @@ -0,0 +1,25 @@ +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you 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 + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations + * under the License. + */ + + + +query "simple_query" + foo3 : Bar(a==3) + foo4 : Bar(a4:a==4) + Baz() + +end diff --git a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl/parser/antlr4/simple_rule.drl b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl/parser/antlr4/simple_rule.drl new file mode 100644 index 00000000000..afc7e6480b0 --- /dev/null +++ b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl/parser/antlr4/simple_rule.drl @@ -0,0 +1,29 @@ +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you 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 + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations + * under the License. + */ +rule simple_rule + when + foo3 : Bar(a==3) + foo4 : Bar(a4:a==4) + Baz() + then + if ( a == b ) { + assert( foo3 ); + } else { + retract( foo4 ); + } + System.out.println( a4 ); +end \ No newline at end of file diff --git a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl/parser/antlr4/soundslike_operator.drl b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl/parser/antlr4/soundslike_operator.drl new file mode 100644 index 00000000000..0b6c21d5bc4 --- /dev/null +++ b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl/parser/antlr4/soundslike_operator.drl @@ -0,0 +1,30 @@ +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you 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 + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations + * under the License. + */ + +package nesting; + + + + +rule "test something" + + when + p: Person( name soundslike "Michael" ) + then + p.name = "goober" + System.out.println(p.name) +end diff --git a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl/parser/antlr4/statement_ordering_1.drl b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl/parser/antlr4/statement_ordering_1.drl new file mode 100644 index 00000000000..4b0b93995d1 --- /dev/null +++ b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl/parser/antlr4/statement_ordering_1.drl @@ -0,0 +1,45 @@ +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you 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 + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations + * under the License. + */ + + +package com.foo; + +import im.one + +import im.two + +rule foo + when + then +end + +function cheeseIt() { + +} + +import im.three; + +rule bar + when + then +end + +function uncheeseIt() { + +} + +import im.four; \ No newline at end of file diff --git a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl/parser/antlr4/ternary_expression.drl b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl/parser/antlr4/ternary_expression.drl new file mode 100644 index 00000000000..23013d6b5d2 --- /dev/null +++ b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl/parser/antlr4/ternary_expression.drl @@ -0,0 +1,26 @@ +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you 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 + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations + * under the License. + */ + +package foo + +rule rule_one + when + Foo() + then + if (speed > speedLimit ? true : false;) + pullEmOver(); +end diff --git a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl/parser/antlr4/test_CommentLineNumbersInConsequence.drl b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl/parser/antlr4/test_CommentLineNumbersInConsequence.drl new file mode 100644 index 00000000000..7c7df07bd51 --- /dev/null +++ b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl/parser/antlr4/test_CommentLineNumbersInConsequence.drl @@ -0,0 +1,34 @@ +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you 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 + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations + * under the License. + */ + +package la + + +rule simple_rule + when + Baz() + then + //woot + first; + + // + + /* lala + + */ + second; +end diff --git a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl/parser/antlr4/test_ComplexChainedCallWithFrom.drl b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl/parser/antlr4/test_ComplexChainedCallWithFrom.drl new file mode 100755 index 00000000000..4c50536c900 --- /dev/null +++ b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl/parser/antlr4/test_ComplexChainedCallWithFrom.drl @@ -0,0 +1,24 @@ +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you 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 + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations + * under the License. + */ + +rule blah + when + Col1() from doIt1( foo,bar,42,"hello",[ a : "b"], [a, "b", 42] ).doIt2(bar, [a, "b", 42]).field["key"] + Col2() + then + partay(); +end diff --git a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl/parser/antlr4/test_EmptyPattern.drl b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl/parser/antlr4/test_EmptyPattern.drl new file mode 100644 index 00000000000..de85f100561 --- /dev/null +++ b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl/parser/antlr4/test_EmptyPattern.drl @@ -0,0 +1,26 @@ +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you 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 + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations + * under the License. + */ + +package org.drools.compiler.test; + +import org.drools.compiler.Cheese; + +rule "simple rule" + when + Cheese( ) + then +end \ No newline at end of file diff --git a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl/parser/antlr4/test_EndPosition.drl b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl/parser/antlr4/test_EndPosition.drl new file mode 100644 index 00000000000..f867e69fe2d --- /dev/null +++ b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl/parser/antlr4/test_EndPosition.drl @@ -0,0 +1,27 @@ +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you 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 + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations + * under the License. + */ + + + + +rule simple_rule + when + Foo( + bar == baz, la==laz + ) + then +end diff --git a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl/parser/antlr4/test_FunctionImport.drl b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl/parser/antlr4/test_FunctionImport.drl new file mode 100644 index 00000000000..1b56f045643 --- /dev/null +++ b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl/parser/antlr4/test_FunctionImport.drl @@ -0,0 +1,29 @@ +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you 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 + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations + * under the License. + */ + +package HR1 + +import function abd.def.x +import function qed.wah.* + +rule simple_rule + when + not ( Cheese(type == "stilton") ) + exists ( Foo() ) + then + funky(); +end diff --git a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl/parser/antlr4/test_SimpleAccessorArgWithFrom.drl b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl/parser/antlr4/test_SimpleAccessorArgWithFrom.drl new file mode 100644 index 00000000000..2bf358046e0 --- /dev/null +++ b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl/parser/antlr4/test_SimpleAccessorArgWithFrom.drl @@ -0,0 +1,27 @@ +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you 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 + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations + * under the License. + */ + + +rule blah + + when + + Col1() from something.doIt["key"] + Col2() + then + partay(); +end diff --git a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl/parser/antlr4/test_SimpleAccessorWithFrom.drl b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl/parser/antlr4/test_SimpleAccessorWithFrom.drl new file mode 100644 index 00000000000..da376e84385 --- /dev/null +++ b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl/parser/antlr4/test_SimpleAccessorWithFrom.drl @@ -0,0 +1,27 @@ +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you 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 + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations + * under the License. + */ + + +rule blah + + when + + Col1() from something.doIt + Col2() + then + partay(); +end diff --git a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl/parser/antlr4/test_SimpleFunctionCallWithFrom.drl b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl/parser/antlr4/test_SimpleFunctionCallWithFrom.drl new file mode 100644 index 00000000000..af156c5ea1c --- /dev/null +++ b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl/parser/antlr4/test_SimpleFunctionCallWithFrom.drl @@ -0,0 +1,27 @@ +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you 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 + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations + * under the License. + */ + + +rule blah + + when + + Col1() from doIt( foo,bar,42,"hello",[ a : "b", "something" : 42, "a" : foo, x : [x:y]],"end", [a, "b", 42] ) + Col2() + then + partay(); +end diff --git a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl/parser/antlr4/test_SimpleMethodCallWithFrom.drl b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl/parser/antlr4/test_SimpleMethodCallWithFrom.drl new file mode 100644 index 00000000000..a8e32df1d53 --- /dev/null +++ b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl/parser/antlr4/test_SimpleMethodCallWithFrom.drl @@ -0,0 +1,27 @@ +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you 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 + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations + * under the License. + */ + + +rule blah + + when + + Col1() from something.doIt( foo,bar,42,"hello",[ a : "b", "something" : 42, "a" : foo, x : [x:y]],"end", [a, "b", 42] ) + Col2() + then + partay(); +end diff --git a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl/parser/antlr4/type_with_meta.drl b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl/parser/antlr4/type_with_meta.drl new file mode 100644 index 00000000000..708bd667b0a --- /dev/null +++ b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl/parser/antlr4/type_with_meta.drl @@ -0,0 +1,48 @@ +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you 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 + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations + * under the License. + */ + +package org.drools.compiler + +declare NetworkNode + locElevation: java.math.BigDecimal + name: String @key + nodeClass: String + locLongitude: java.math.BigDecimal + nodeType: String + locLatitude: java.math.BigDecimal +end + +declare NetworkConnection + id: String @key + node1: NetworkNode + node2: NetworkNode + hops: Integer +end + +declare NetworkEvent + @role( event ) + @timestamp( creationTime ) + + id: String @key + locElevation: java.math.BigDecimal + description: String + sourceComponent: NetworkNode + locLongitude: java.math.BigDecimal + severity: Integer + creationTime: java.util.Date + locLatitude: java.math.BigDecimal +end diff --git a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl/parser/antlr4/with_eval.drl b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl/parser/antlr4/with_eval.drl new file mode 100644 index 00000000000..c2e0145747d --- /dev/null +++ b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl/parser/antlr4/with_eval.drl @@ -0,0 +1,26 @@ +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you 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 + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations + * under the License. + */ + + +rule simple_rule + when + Foo() + Bar() + eval(abc("foo")) + then + Kapow +end diff --git a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl/parser/antlr4/with_predicate.drl b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl/parser/antlr4/with_predicate.drl new file mode 100644 index 00000000000..41ff2715d8a --- /dev/null +++ b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl/parser/antlr4/with_predicate.drl @@ -0,0 +1,23 @@ +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you 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 + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations + * under the License. + */ + + +rule simple_rule + when + Person( $age2:age, $age2 == $age1+2 ) + then +end diff --git a/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl/parser/antlr4/with_retval.drl b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl/parser/antlr4/with_retval.drl new file mode 100644 index 00000000000..8db9671fee7 --- /dev/null +++ b/drools-drl/drools-drl-parser-tests/src/test/resources/org/drools/drl/parser/antlr4/with_retval.drl @@ -0,0 +1,23 @@ +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you 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 + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations + * under the License. + */ + + +rule simple_rule + when + Foo(name== (a + b)) + then +end diff --git a/drools-drl/drools-drl-parser/Developer_Notes.md b/drools-drl/drools-drl-parser/Developer_Notes.md new file mode 100644 index 00000000000..4e09d2afd6a --- /dev/null +++ b/drools-drl/drools-drl-parser/Developer_Notes.md @@ -0,0 +1,123 @@ + + +# drools-drl-parser + +In this `dev-new-parser` branch, `drools-drl-parser` has 2 implementations of the DRL parser. The new parser is under development, and the old parser is used in the current drools code base. + +The old DRL parser is based on Antlr3 and contains lots of hard-coded logic in generated java codes, so it's hard to maintain e.g. [DRL6Parser](https://github.com/apache/incubator-kie-drools/blob/main/drools-drl/drools-drl-parser/src/main/java/org/drools/drl/parser/lang/DRL6Parser.java). It is the reason why the new parser is being developed. The old parser resources are placed under `src/main/java/org/drools/drl/parser/lang` and `src/main/resources/org/drools/drl/parser`. + +The new DRL parser is based on Antlr4, which has Visitor and Listener support, so the parser would have cleaner separation between the parser syntax (`DRLParser.g4`) and Java code which generates Descr objects (`DRLVisitorImpl.java`). It would be easier to maintain and extend the parser. The new parser resources are placed under `src/main/java/org/drools/drl/parser/antlr4` and `src/main/antlr4/org/drools/drl/parser/antlr4`. + +## The current status of the new parser development +The new DRL parser doesn't introduce new syntax at the first stage. In order to keep the compatibility with the old parser, we make use of existing unit tests. + +As of 2024/02/27, we hit lots of test failures in existing drools unit tests. The test failures are filed as child issues of the parent issue [Experiment: New DRL Parser](https://github.com/apache/incubator-kie-drools/issues/5678). We will fix the test failures one by one. + +## How to contribute to the development + +**Contribution would be highly appreciated!** Here is a rough guide to contribute to the development. + +1. Look at the parent issue [Experiment: New DRL Parser](https://github.com/apache/incubator-kie-drools/issues/5678) and choose a child issue which you want to work on. +2. If you have an ASF committer role, assign yourself to the child issue. If you don't have the role, post a comment on the child issue that you are working on it so that we can avoid duplicated work. +3. Create a feature branch based on the `dev-new-parser` branch. +4. Fix the issue and make sure that the test in problem is passed and also all tests under `drools-drl-parser-tests` are passed. +5. Add new tests to `drools-drl-parser-tests` to cover the issue. Hopefully, such a test would be a Descr comparison test. See `MiscDRLParserTest` and `DRLExprParserTest`. +6. File a pull request to the `dev-new-parser` branch. **Be careful not to file a pull request to the `main` branch.** + +## Design notes + +`org.drools.drl.parser.DrlParser` is a common entry point of the new/old parser implementations. Depending on a system property switch `drools.drl.antlr4.parser.enabled`, it chooses the new parser `org.drools.drl.parser.antlr4.DRLParserWrapper` or the old parser `org.drools.drl.parser.lang.DRL6Parser`. + +The responsibilities of a DRL parser are: + +1. Parse DRL text and generate an AST (abstract syntax tree) +2. Using the AST, generate `Descr` objects which encapsulate information to be used in the later build phase. The top level object is `PackageDescr`. +3. If there are any parse errors, populate `List results`. + +Common to Antlr 3 and 4, Lexer/Parser java classes are generated from grammar files. For the new parser, grammar files are `DRLLexer.g4` and `DRLParser.g4`. For the old parser, the lexer grammar is `DRL6Lexer.g`, but the parser grammar `drl.g` had been removed from the repo long time ago (https://github.com/apache/incubator-kie-drools/commit/c2ef448d8ed2f935480b9576f4dc83ba7b007a9b) because we directly customized the generated `DRL6Parser.java`. We no longer generate `DRL6Parser.java` with Antlr3 tooling. + +With the Antlr3 old parser, we had to write the `Descr` object generation java code inside the parser grammar file (= parser actions). Eventually, we had gone to the direct java code customization, probably because some features were not feasible with parser actions. + +With the Antlr4 new parser, we can isolate java codes from `DRLParser.g4` to `DRLVisitorImpl.java` which visits the AST and generate the `Descr` objects. There is no need to customize generated java codes (e.g. `DRLLexer.java`, `DRLParser.java` under `target/generated-sources`). When we fix or expand the parser, we should edit java sources under `src/main/java/org/drools/drl/parser/antlr4` (e.g. `DRLVisitorImpl.java`, `DRLParserWrapper.jva`). + +--- + +For `DRL6Expressions`, we take a little different approach. `DrlExprParserFactory` is a common entry point of the new/old **expression** parser implementations. Similar to `DrlParser`, depending on a system property switch `drools.drl.antlr4.parser.enabled`, it chooses the new parser `org.drools.drl.parser.antlr4.Drl6ExprParserAntlr4` or the old parser `org.drools.drl.parser.Drl6ExprParser`. + +The responsibilities of an expression parser are: + +1. Parse DRL constraint text and generate an AST +2. Using the AST, generate `Descr` objects which encapsulate information to be used in the build phase. The top level object depends on the constraint. +3. If there are any parse errors, store them to be retrieved by `List getErrors()` + +As the old expression parser doesn't have the problem of "hard-coded", the new expression parser grammar file `DRL6Expressions.g4` is basically the same as the old `DRL6Expressions.g`, but just adjusted to work with Antlr4. So not using Visitor pattern at the moment. Applying Visitor pattern to the new expression parser is one of refactoring candidates. + +## Additional notes + +- The new parser are consist of 2 important parsers. + - One is `DRLParser` which is generated from `DRLParser.g4`. This parser is responsible for parsing an entire DRL text and generating an AST. Descr objects are generated by applying `DRLVisitorImpl` to the AST. Drools engine uses the parser with `DRLParserWrapper`. + - The other is `DRL6Expressions` which is generated from `Drl6Expressions.g4`. This parser is specifically used to parse LHS constraints at the later rule compile phase. Drools engine uses the parser with `Drl6ExprParserAntlr4`. + +- As of 2024/02/27, we have 4 test classes under `drools-drl-parser-tests`. + - `DRLParserTest` is a very basic test to check if the parser can parse DRL. + - `MiscDRLParserTest` contains various DRL syntax to check if the parser generates correct Descr objects. `MiscDRLParserTest` was ported from [RuleParserTest](https://github.com/apache/incubator-kie-drools/blob/main/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/mvel/compiler/lang/RuleParserTest.java) so that we can ensure the compatibility of generated Descr objects between the old implementation and the new one. `MiscDRLParserTest` still has several test cases with `@Disabled` which are relatively lower priority or edge cases. They are also the target of the ongoing development. + - `DRLExprParserTest` is to test `DRL6Expressions` parser. + - `DescrDumperTest` is to test the dump result of generated Descr objects. This is originally a test for `DescDumper`, but it's also useful to test `DRL6Expressions` parser. + - It would be fine to add more test classes if necessary. + +- As of 2024/02/27, the `dev-new-parser` branch even fails to build `kie-dmn-validation`. Please ignore the build failure until we fix the test failures of `drools-model-codegen` +- `drools-model-codegen` is a good place to detect various test failures. Once we clean up the test failures of `drools-model-codegen`, we would tackle `kie-dmn-validation` build and `drools-test-coverage` tests. + +- `DRL5Parser` and `DRL6StrictParser` are minor variants, and they will likely be removed in the near feature. + +- About similar areas: + - `drools-compiler` contains `JavaParser` which was generated by `Java.g`. This is used by `drools-mvel` to execute java dialect. As `drools-mvel` is deprecated, it is not the scope of this new parser development. + - `drools-model/drools-mvel-parser` contains javacc based `mvel.jj` to parse constraint and RHS in executable models. It is good enough as it is, so not the scope of this new parser development. + +### (Advanced) How was the new parser developed? + +**DRLParser** + +1. The starting point is [DRL6Parser](https://github.com/apache/incubator-kie-drools/blob/main/drools-drl/drools-drl-parser/src/main/java/org/drools/drl/parser/lang/DRL6Parser.java). While it contains lots of customizations, we can map its javadoc (e.g. `packageStatement := PACKAGE qualifiedIdentifier SEMICOLON?`) to `DRLParser.g4` (e.g. `packagedef : PACKAGE name=drlQualifiedName SEMI? ;`). +2. `DRLLexer.g4` is written to define tokens for DRL. +3. `DRLLexer.g4` imports `JavaLexer.g4` to reuse Java tokens. `DRLParser.g4` imports `JavaParser.g4` to reuse Java grammar. These Java parser files are distributed by ANTLR4 under BSD license. +4. In `DRLLexer.g4`, basically define tokens with a prefix "DRL_" to clarify they are DRL keywords. +5. In `DRLParser.g4`, define parser rules with a prefix "drl" if the rule name conflicts with `JavaParser.g4`. Sometimes we need to do that, because such a rule may contain DRL keywords. +6. (As of 2024/02/27) this parser doesn't deeply parse rule RHS (just multiple `RHS_CHUNK`s), because Drools passes RHS text to drools-compiler as-is. In case of developing DRL editors, we may need to integrate another Java LSP to support RHS code completion, etc. +7. LHS constraint (e.g. `age > 30`) is also handled as text. Further processing will be done by `DRL6Expressions` parser in the later compiler phase. +8. `DRLParser` processes a DRL text and produces an AST. Then apply `DRLVisitorImpl` to generate PackageDescr following the visitor pattern. So the main work would be implementing `DRLParser.g4` and `DRLVisitorImpl`. +9. Errors are handled by `DRLErrorListener` + +**DRL6Expressions** + +1. `DRL6Expressions.g4` was copied from `DRL6Expressions.g` in the old parser. Then, it was modified to work with Antlr4. + +### Refactoring candidates +- New parser related class names are not very consistent. There is a room to improve. +- `DRLParserHelper` and `DRLParserWrapper` have some duplicated code and purpose. We can merge them into one class. +- `MiscDRLParserTest` can be cleaner and fixed to align with SonarLint suggestions. +- There is parser rules overlap between `DRLParser.g4` and `DRL6Expressions.g4` after `conditionalOrExpression`. There is a room to improve. e.g. delegating the constraint parsing to `DRL6Expressions` parser. +- `DRL6Expressions` parser doesn't use Visitor pattern at the moment. Rather, it uses more parser actions. It would be nice to use Visitor pattern to generate Descr objects. + +### Development environment tips +- IntelliJ IDEA has an ANTLR4 plugin, which "ANTLR Preview" window displays a parse tree. It is very useful to debug the parser rules. + +### Resources +[The Definitive ANTLR 4 Reference](https://pragprog.com/titles/tpantlr2/the-definitive-antlr-4-reference/) \ No newline at end of file diff --git a/drools-drl/drools-drl-parser/pom.xml b/drools-drl/drools-drl-parser/pom.xml index 545625e5ad4..d8b66f13e5a 100644 --- a/drools-drl/drools-drl-parser/pom.xml +++ b/drools-drl/drools-drl-parser/pom.xml @@ -66,7 +66,32 @@ org.antlr antlr-runtime + + org.antlr + antlr4-runtime + + + + org.assertj + assertj-core + test + + + org.junit.jupiter + junit-jupiter-api + test + + + org.junit.jupiter + junit-jupiter-engine + test + + + ch.qos.logback + logback-classic + test + @@ -101,6 +126,26 @@ + + + + org.antlr + antlr4-maven-plugin + ${version.org.antlr4} + + + + antlr4 + + + true + false + src/main/antlr4/org/drools/drl/parser/antlr4 + + + + + diff --git a/drools-drl/drools-drl-parser/src/main/antlr4/org/drools/drl/parser/antlr4/DRL6Expressions.g4 b/drools-drl/drools-drl-parser/src/main/antlr4/org/drools/drl/parser/antlr4/DRL6Expressions.g4 new file mode 100644 index 00000000000..063e4ed48cf --- /dev/null +++ b/drools-drl/drools-drl-parser/src/main/antlr4/org/drools/drl/parser/antlr4/DRL6Expressions.g4 @@ -0,0 +1,1011 @@ +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you 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 + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +parser grammar DRL6Expressions; + +options { + language = Java; + tokenVocab = DRLLexer; + superClass=DRLExpressions; +} + +@header { + import java.util.LinkedList; + import org.drools.drl.parser.DroolsParserException; + import org.drools.drl.parser.lang.DroolsEditorType; + import org.drools.drl.parser.lang.DroolsParserExceptionFactory; + import org.drools.drl.parser.lang.DroolsSentence; + import org.drools.drl.parser.lang.DroolsSoftKeywords; + import org.drools.drl.parser.lang.Location; + + import org.drools.drl.ast.dsl.AnnotatedDescrBuilder; + import org.drools.drl.ast.dsl.AnnotationDescrBuilder; + + import org.drools.drl.ast.descr.AnnotatedBaseDescr; + import org.drools.drl.ast.descr.AnnotationDescr; + import org.drools.drl.ast.descr.AtomicExprDescr; + import org.drools.drl.ast.descr.BaseDescr; + import org.drools.drl.ast.descr.BindingDescr; + import org.drools.drl.ast.descr.ConstraintConnectiveDescr; + import org.drools.drl.ast.descr.RelationalExprDescr; +} + +@members { + private ParserHelper helper; + + public void setHelper( ParserHelper helper ) { this.helper = helper; } + public ParserHelper getHelper() { return helper; } + public boolean hasErrors() { return helper.hasErrors(); } + public List getErrors() { return helper.getErrors(); } + public List getErrorMessages() { return helper.getErrorMessages(); } + public void enableEditorInterface() { helper.enableEditorInterface(); } + public void disableEditorInterface() { helper.disableEditorInterface(); } + public LinkedList getEditorInterface() { return helper.getEditorInterface(); } + public void reportError(RecognitionException ex) { helper.reportError( ex ); } + public void emitErrorMessage(String msg) {} + + private boolean buildDescr; + private int inMap = 0; + private int ternOp = 0; + private boolean hasBindings; + public void setBuildDescr( boolean build ) { this.buildDescr = build; } + public boolean isBuildDescr() { return this.buildDescr; } + + public void setLeftMostExpr( String value ) { helper.setLeftMostExpr( value ); } + public String getLeftMostExpr() { return helper.getLeftMostExpr(); } + + public void setHasBindings( boolean value ) { this.hasBindings = value; } + public boolean hasBindings() { return this.hasBindings; } + + public final BaseDescr conditionalOrExpressionDescr() throws RecognitionException { + return conditionalOrExpression().result; + } + + private boolean isNotEOF() { + // TODO verify that we can omit the backtracking check + /*if (state.backtracking != 0){ + return false; + }*/ + if (_input.get( _input.index() - 1 ).getType() == DRLLexer.WS){ + return true; + } + if (_input.LA(-1) == DRLLexer.LPAREN){ + return true; + } + return _input.get( _input.index() ).getType() != DRLLexer.EOF; + } + + private boolean notStartWithNewline() { + int currentTokenIndex = _input.index(); // current position in input stream + Token previousHiddenToken = _input.get(currentTokenIndex - 1); + String previousHiddenTokenText = previousHiddenToken.getText(); + return !previousHiddenTokenText.contains("\n"); + } +} + +// Alter code generation so catch-clauses get replace with +// this action. +@rulecatch { +catch (RecognitionException re) { + throw re; +} +} + +// -------------------------------------------------------- +// GENERAL RULES +// -------------------------------------------------------- +literal + : STRING_LITERAL { helper.emit($STRING_LITERAL, DroolsEditorType.STRING_CONST); } + | DRL_STRING_LITERAL { helper.emit($DRL_STRING_LITERAL, DroolsEditorType.STRING_CONST); } + | DECIMAL_LITERAL { helper.emit($DECIMAL_LITERAL, DroolsEditorType.NUMERIC_CONST); } + | DRL_BIG_INTEGER_LITERAL { helper.emit($DRL_BIG_INTEGER_LITERAL, DroolsEditorType.NUMERIC_CONST); } + | HEX_LITERAL { helper.emit($HEX_LITERAL, DroolsEditorType.NUMERIC_CONST); } + | FLOAT_LITERAL { helper.emit($FLOAT_LITERAL, DroolsEditorType.NUMERIC_CONST); } + | DRL_BIG_DECIMAL_LITERAL { helper.emit($DRL_BIG_DECIMAL_LITERAL, DroolsEditorType.NUMERIC_CONST); } + | BOOL_LITERAL { helper.emit($BOOL_LITERAL, DroolsEditorType.BOOLEAN_CONST); } + | NULL_LITERAL { helper.emit($NULL_LITERAL, DroolsEditorType.NULL_CONST); } + | TIME_INTERVAL { helper.emit($TIME_INTERVAL, DroolsEditorType.NULL_CONST); } + | MUL { helper.emit($MUL, DroolsEditorType.NUMERIC_CONST); } // this means "infinity" in Drools + ; + +operator returns [boolean negated, String opr] +@init{ if ( isNotEOF() ) helper.emit( Location.LOCATION_LHS_INSIDE_CONDITION_OPERATOR ); helper.setHasOperator( true ); } +// TODO verify that we can omit the backtracking check +@after{ if( /*state.backtracking == 0 &&*/ _input.LA( 1 ) != DRLLexer.EOF) { helper.emit( Location.LOCATION_LHS_INSIDE_CONDITION_ARGUMENT ); } } + : x=TILDE? + ( op=EQUAL { $negated = false; $opr=($x != null ? $x.text : "")+$op.text; helper.emit($op, DroolsEditorType.SYMBOL); } + | op=NOTEQUAL { $negated = false; $opr=($x != null ? $x.text : "")+$op.text; helper.emit($op, DroolsEditorType.SYMBOL); } + | rop=relationalOp { $negated = $rop.negated; $opr=($x != null ? $x.text : "")+$rop.opr; } + ) + ; + + + +relationalOp returns [boolean negated, String opr, java.util.List params] +@init{ if ( isNotEOF() ) helper.emit( Location.LOCATION_LHS_INSIDE_CONDITION_OPERATOR ); helper.setHasOperator( true ); } +// TODO verify that we can omit the backtracking check +@after{ if( /*state.backtracking == 0 &&*/ _input.LA( 1 ) != DRLLexer.EOF) { helper.emit( Location.LOCATION_LHS_INSIDE_CONDITION_ARGUMENT ); } } + : ( op=LE { $negated = false; $opr=$op.text; $params = null; helper.emit($op, DroolsEditorType.SYMBOL);} + | op=GE { $negated = false; $opr=$op.text; $params = null; helper.emit($op, DroolsEditorType.SYMBOL);} + | op=LT { $negated = false; $opr=$op.text; $params = null; helper.emit($op, DroolsEditorType.SYMBOL);} + | op=GT { $negated = false; $opr=$op.text; $params = null; helper.emit($op, DroolsEditorType.SYMBOL);} + | xop=complexOp { $negated = false; $opr=$op.text; $params = null; helper.emit($op, DroolsEditorType.SYMBOL);} + | not_key nop=neg_operator_key { $negated = true; $opr=$nop.text;} + | cop=operator_key { $negated = false; $opr=$cop.text;} + ) + ; + +complexOp returns [String opr] + : t=TILDE e=ASSIGN { $opr=$t.text+$e.text; } + ; + +typeList + : type (COMMA type)* + ; + +type + : tm=typeMatch + ; + +typeMatch + : primitiveType (LBRACK RBRACK)* + | drlIdentifier (typeArguments)? (DOT drlIdentifier (typeArguments)? )* (LBRACK RBRACK)* + ; + +typeArguments + : LT typeArgument (COMMA typeArgument)* GT + ; + +typeArgument + : type + | QUESTION ((extends_key | super_key) type)? + ; + +// matches any identifiers including acceptable java keywords (defined in JavaParser.g4) and drl keywords +drlIdentifier returns [Token token] + : drlKeywords + | IDENTIFIER + // java keywords + | ABSTRACT + | ASSERT + | BOOLEAN + | BREAK + | BYTE + | CASE + | CATCH + | CHAR + | CLASS + | CONST + | CONTINUE + | DEFAULT + | DO + | DOUBLE + | ELSE + | ENUM + | EXTENDS + | FINAL + | FINALLY + | FLOAT + | FOR + | IF + | GOTO + | IMPLEMENTS + | IMPORT + | INSTANCEOF + | INT + | INTERFACE + | LONG + | NATIVE +// | NEW // avoid ambiguity with 'new_key creator' and 'drlIdentifier' in 'primary' + | PACKAGE + | PRIVATE + | PROTECTED + | PUBLIC + | RETURN + | SHORT + | STATIC + | STRICTFP + | SUPER + | SWITCH + | SYNCHRONIZED + | THIS + | THROW + | THROWS + | TRANSIENT + | TRY + | VOID + | VOLATILE + | WHILE + // Module related keywords + | MODULE + | OPEN + | REQUIRES + | EXPORTS + | OPENS + | TO + | USES + | PROVIDES + | WITH + | TRANSITIVE + // other java keywords + | VAR + | YIELD + | RECORD + | SEALED + | PERMITS + | NON_SEALED + ; + +// matches any drl keywords +drlKeywords returns [Token token] + : builtInOperator + | DRL_UNIT + | DRL_FUNCTION + | DRL_GLOBAL + | DRL_DECLARE + | DRL_TRAIT + | DRL_TYPE + | DRL_RULE + | DRL_QUERY + | DRL_WHEN + | DRL_THEN + | DRL_END + | DRL_AND + | DRL_OR + | DRL_EXISTS + | DRL_NOT + | DRL_IN + | DRL_FROM + | DRL_COLLECT + | DRL_ACCUMULATE + | DRL_ACC + | DRL_INIT + | DRL_ACTION + | DRL_REVERSE + | DRL_RESULT + | DRL_ENTRY_POINT + | DRL_EVAL + | DRL_FORALL + | DRL_OVER + | DRL_ATTRIBUTES + | DRL_SALIENCE + | DRL_ENABLED + | DRL_NO_LOOP + | DRL_AUTO_FOCUS + | DRL_LOCK_ON_ACTIVE + | DRL_REFRACT + | DRL_DIRECT + | DRL_AGENDA_GROUP + | DRL_ACTIVATION_GROUP + | DRL_RULEFLOW_GROUP + | DRL_DATE_EFFECTIVE + | DRL_DATE_EXPIRES + | DRL_DIALECT + | DRL_CALENDARS + | DRL_TIMER + | DRL_DURATION + | DRL_WINDOW + ; + +builtInOperator returns[Token token] + : DRL_CONTAINS + | DRL_EXCLUDES + | DRL_MATCHES + | DRL_MEMBEROF + | DRL_SOUNDSLIKE + | DRL_AFTER + | DRL_BEFORE + | DRL_COINCIDES + | DRL_DURING + | DRL_FINISHED_BY + | DRL_FINISHES + | DRL_INCLUDES + | DRL_MEETS + | DRL_MET_BY + | DRL_OVERLAPPED_BY + | DRL_OVERLAPS + | DRL_STARTED_BY + | DRL_STARTS + | DRL_STR + ; + +// -------------------------------------------------------- +// EXPRESSIONS +// -------------------------------------------------------- +// the following dymmy rule is to force the AT symbol to be +// included in the follow set of the expression on the DFAs +dummy + : expression ( AT | SEMI | EOF | IDENTIFIER | RPAREN ) ; + +dummy2 + : relationalExpression EOF; + +// top level entry point for arbitrary expression parsing +expression returns [BaseDescr result] + : left=conditionalExpression { if( buildDescr ) { $result = $left.result; } } + (op=assignmentOperator right=expression)? + ; + +conditionalExpression returns [BaseDescr result] + : left=conditionalOrExpression { if( buildDescr ) { $result = $left.result; } } + ternaryExpression? + ; + +ternaryExpression +@init{ ternOp++; } + : QUESTION ts=expression COLON fs=expression + ; +finally { ternOp--; } + + +fullAnnotation [AnnotatedDescrBuilder inDescrBuilder] returns [AnnotationDescr result] +@init{ String n = ""; AnnotationDescrBuilder annoBuilder = null; } + : AT name=drlIdentifier { n = $name.text; } ( DOT x=drlIdentifier { n += "." + $x.text; } )* + { if( buildDescr ) { + if ( inDescrBuilder == null ) { + $result = new AnnotationDescr( n ); + } else { + annoBuilder = inDescrBuilder instanceof AnnotationDescrBuilder ? + ((AnnotationDescrBuilder) inDescrBuilder).newAnnotation( n ) : inDescrBuilder.newAnnotation( n ); + $result = (AnnotationDescr) annoBuilder.getDescr(); + } + } + } + annotationArgs[$result, annoBuilder] + ; + +annotationArgs [AnnotationDescr descr, AnnotatedDescrBuilder inDescrBuilder] + : LPAREN + ( + annotationElementValuePairs[descr, inDescrBuilder] + | value=annotationValue[inDescrBuilder] { if ( buildDescr ) { $descr.setValue( $value.result ); } } + )? + RPAREN + ; + +annotationElementValuePairs [AnnotationDescr descr, AnnotatedDescrBuilder inDescrBuilder] + : annotationElementValuePair[descr, inDescrBuilder] ( COMMA annotationElementValuePair[descr, inDescrBuilder] )* + ; + +annotationElementValuePair [AnnotationDescr descr, AnnotatedDescrBuilder inDescrBuilder] + : key=drlIdentifier ASSIGN val=annotationValue[inDescrBuilder] { if ( buildDescr ) { $descr.setKeyValue( $key.text, $val.result ); } } + ; + +annotationValue[AnnotatedDescrBuilder inDescrBuilder] returns [Object result] + : exp=expression { if ( buildDescr ) $result = $exp.text; } + | annos=annotationArray[inDescrBuilder] { if ( buildDescr ) $result = $annos.result.toArray(); } + | anno=fullAnnotation[inDescrBuilder] { if ( buildDescr ) $result = $anno.result; } + ; + +annotationArray[AnnotatedDescrBuilder inDescrBuilder] returns [java.util.List result] +@init { $result = new java.util.ArrayList();} + : LBRACE ( anno=annotationValue[inDescrBuilder] { $result.add( $anno.result ); } + ( COMMA anno=annotationValue[inDescrBuilder] { $result.add( $anno.result ); } )* )? + RBRACE + ; + + + +conditionalOrExpression returns [BaseDescr result] + : left=conditionalAndExpression { if( buildDescr ) { $result = $left.result; } } + ( OR + { if ( isNotEOF() ) helper.emit( Location.LOCATION_LHS_INSIDE_CONDITION_OPERATOR ); } + args=fullAnnotation[null]? right=conditionalAndExpression + { if( buildDescr ) { + ConstraintConnectiveDescr descr = ConstraintConnectiveDescr.newOr(); + descr.addOrMerge( $result ); + descr.addOrMerge( $right.result ); + if ( $ctx.args != null ) { descr.addAnnotation( $args.result ); } + $result = descr; + } + } + )* + ; + +conditionalAndExpression returns [BaseDescr result] + : left=inclusiveOrExpression { if( buildDescr ) { $result = $left.result; } } + ( AND + { if ( isNotEOF() ) helper.emit( Location.LOCATION_LHS_INSIDE_CONDITION_OPERATOR ); } + args=fullAnnotation[null]? right=inclusiveOrExpression + { if( buildDescr ) { + ConstraintConnectiveDescr descr = ConstraintConnectiveDescr.newAnd(); + descr.addOrMerge( $result ); + descr.addOrMerge( $right.result ); + if ( $ctx.args != null ) { descr.addAnnotation( $args.result ); } + $result = descr; + } + } + )* + ; + +inclusiveOrExpression returns [BaseDescr result] + : left=exclusiveOrExpression { if( buildDescr ) { $result = $left.result; } } + ( BITOR right=exclusiveOrExpression + { if( buildDescr ) { + ConstraintConnectiveDescr descr = ConstraintConnectiveDescr.newIncOr(); + descr.addOrMerge( $result ); + descr.addOrMerge( $right.result ); + $result = descr; + } + } + )* + ; + +exclusiveOrExpression returns [BaseDescr result] + : left=andExpression { if( buildDescr ) { $result = $left.result; } } + ( CARET right=andExpression + { if( buildDescr ) { + ConstraintConnectiveDescr descr = ConstraintConnectiveDescr.newXor(); + descr.addOrMerge( $result ); + descr.addOrMerge( $right.result ); + $result = descr; + } + } + )* + ; + +andExpression returns [BaseDescr result] + : left=equalityExpression { if( buildDescr ) { $result = $left.result; } } + ( BITAND right=equalityExpression + { if( buildDescr ) { + ConstraintConnectiveDescr descr = ConstraintConnectiveDescr.newIncAnd(); + descr.addOrMerge( $result ); + descr.addOrMerge( $right.result ); + $result = descr; + } + } + )* + ; + +equalityExpression returns [BaseDescr result] + : left=instanceOfExpression { if( buildDescr ) { $result = $left.result; } } + ( ( op=EQUAL | op=NOTEQUAL ) + { helper.setHasOperator( true ); + if( _input.LA( 1 ) != DRLLexer.EOF ) helper.emit( Location.LOCATION_LHS_INSIDE_CONDITION_ARGUMENT ); } + right=instanceOfExpression + { if( buildDescr ) { + $result = new RelationalExprDescr( $op.text, false, null, $left.result, $right.result ); + } + } + )* + ; + +instanceOfExpression returns [BaseDescr result] + : left=inExpression { if( buildDescr ) { $result = $left.result; } } + ( op=instanceof_key + { helper.setHasOperator( true ); + if( _input.LA( 1 ) != DRLLexer.EOF ) helper.emit( Location.LOCATION_LHS_INSIDE_CONDITION_ARGUMENT ); } + right=type + { if( buildDescr ) { + $result = new RelationalExprDescr( $op.text, false, null, $left.result, new AtomicExprDescr($right.text) ); + } + } + )? + ; + +inExpression returns [BaseDescr result] +@init { ConstraintConnectiveDescr descr = null; BaseDescr leftDescr = null; BindingDescr binding = null; } +@after { if( binding != null && descr != null ) descr.addOrMerge( binding ); } + : left=relationalExpression + { if( buildDescr ) { $result = $left.result; } + if( $left.result instanceof BindingDescr ) { + binding = (BindingDescr)$left.result; + leftDescr = new AtomicExprDescr( binding.getExpression() ); + } else { + leftDescr = $left.result; + } + } + (not_key in=in_key LPAREN + { helper.emit( Location.LOCATION_LHS_INSIDE_CONDITION_ARGUMENT ); } + e1=expression + { descr = ConstraintConnectiveDescr.newAnd(); + RelationalExprDescr rel1 = new RelationalExprDescr( "!=", false, null, leftDescr, $e1.result ); + descr.addOrMerge( rel1 ); + $result = descr; + } + (COMMA e2=expression + { RelationalExprDescr rel2 = new RelationalExprDescr( "!=", false, null, leftDescr, $e2.result ); + descr.addOrMerge( rel2 ); + } + )* RPAREN + { helper.emit( Location.LOCATION_LHS_INSIDE_CONDITION_END ); } + | in=in_key LPAREN + { helper.emit( Location.LOCATION_LHS_INSIDE_CONDITION_ARGUMENT ); } + e1=expression + { descr = ConstraintConnectiveDescr.newOr(); + RelationalExprDescr rel1 = new RelationalExprDescr( "==", false, null, leftDescr, $e1.result ); + descr.addOrMerge( rel1 ); + $result = descr; + } + (COMMA e2=expression + { RelationalExprDescr rel2 = new RelationalExprDescr( "==", false, null, leftDescr, $e2.result ); + descr.addOrMerge( rel2 ); + } + )* RPAREN + { helper.emit( Location.LOCATION_LHS_INSIDE_CONDITION_END ); } + )? + ; + +relationalExpression returns [BaseDescr result] +locals [ BaseDescr lsd ] +// TODO access lsd directly instead of through dynamic context here +@init { $relationalExpression::lsd = null; } + : left=shiftExpression + { if( buildDescr ) { + if ( $left.result == null ) { + $result = new AtomicExprDescr( $left.text ); + } else if ( $left.result instanceof AtomicExprDescr ) { + if ( $left.text.equals(((AtomicExprDescr)$left.result).getExpression()) ) { + $result = $left.result; + } else { + $result = new AtomicExprDescr( $left.text ) ; + } + } else if ( $left.result instanceof BindingDescr ) { + if ( $left.text.equals(((BindingDescr)$left.result).getExpression()) ) { + $result = $left.result; + } else { + BindingDescr bind = (BindingDescr) $left.result; + int offset = bind.isUnification() ? 2 : 1; + String fullExpression = $left.text.substring( $left.text.indexOf( ":" ) + offset ).trim(); + $result = new BindingDescr( bind.getVariable(), bind.getExpression(), fullExpression, bind.isUnification() ); + } + } else { + $result = $left.result; + } + // TODO access lsd directly instead of through dynamic context here + $relationalExpression::lsd = $result; + } + } + ( right=orRestriction + { if( buildDescr ) { + $result = $right.result; + // TODO access lsd directly instead of through dynamic context here + $relationalExpression::lsd = $result; + } + } + )* + ; + +orRestriction returns [BaseDescr result] + : left=andRestriction { if( buildDescr ) { $result = $left.result; } } + ( lop=OR args=fullAnnotation[null]? right=andRestriction + { if( buildDescr ) { + ConstraintConnectiveDescr descr = ConstraintConnectiveDescr.newOr(); + descr.addOrMerge( $result ); + descr.addOrMerge( $right.result ); + if ( $ctx.args != null ) { descr.addAnnotation( $args.result ); } + $result = descr; + } + } + )*? EOF? + ; + +andRestriction returns [BaseDescr result] + : left=singleRestriction { if( buildDescr ) { $result = $left.result; } } + ( lop=AND + { if ( isNotEOF() ) helper.emit( Location.LOCATION_LHS_INSIDE_CONDITION_OPERATOR ); } + args=fullAnnotation[null]?right=singleRestriction + { if( buildDescr ) { + ConstraintConnectiveDescr descr = ConstraintConnectiveDescr.newAnd(); + descr.addOrMerge( $result ); + descr.addOrMerge( $right.result ); + if ( $ctx.args != null ) { descr.addAnnotation( $args.result ); } + $result = descr; + } + } + )*? + ; + +singleRestriction returns [BaseDescr result] + : op=operator + { helper.emit( Location.LOCATION_LHS_INSIDE_CONDITION_ARGUMENT ); } + ( sa=squareArguments value=shiftExpression + | value=shiftExpression + ) + { if( buildDescr ) { + BaseDescr descr = ( $value.result != null && + ( (!($value.result instanceof AtomicExprDescr)) || + ($value.text.equals(((AtomicExprDescr)$value.result).getExpression())) )) ? + $value.result : + new AtomicExprDescr( $value.text ) ; + $result = new RelationalExprDescr( $op.opr, $op.negated, $ctx.sa != null ? $sa.args : null, $relationalExpression::lsd, descr ); + if( $relationalExpression::lsd instanceof BindingDescr ) { + $relationalExpression::lsd = new AtomicExprDescr( ((BindingDescr)$relationalExpression::lsd).getExpression() ); + } + } + helper.emit( Location.LOCATION_LHS_INSIDE_CONDITION_END ); + } + | LPAREN or=orRestriction RPAREN { $result = $or.result; } + ; + + + +shiftExpression returns [BaseDescr result] + : left=additiveExpression { if( buildDescr ) { $result = $left.result; } } + ( shiftOp additiveExpression )* + ; + +shiftOp + : ( LT LT + | GT GT GT + | GT GT ) + ; + +additiveExpression returns [BaseDescr result] + : left=multiplicativeExpression { if( buildDescr ) { $result = $left.result; } } + ( (ADD | SUB) multiplicativeExpression )* + ; + +multiplicativeExpression returns [BaseDescr result] + : left=unaryExpression { if( buildDescr ) { $result = $left.result; } } + ( ( MUL | DIV | MOD ) unaryExpression )* + ; + +unaryExpression returns [BaseDescr result] + : ADD ue=unaryExpression + { if( buildDescr ) { + $result = $ue.result; + if( $result instanceof AtomicExprDescr ) { + ((AtomicExprDescr)$result).setExpression( "+" + ((AtomicExprDescr)$result).getExpression() ); + } + } } + | SUB ue=unaryExpression + { if( buildDescr ) { + $result = $ue.result; + if( $result instanceof AtomicExprDescr ) { + ((AtomicExprDescr)$result).setExpression( "-" + ((AtomicExprDescr)$result).getExpression() ); + } + } } + | INC primary + | DEC primary + | left=unaryExpressionNotPlusMinus { if( buildDescr ) { $result = $left.result; } } + ; + +unaryExpressionNotPlusMinus returns [BaseDescr result] +@init { boolean isLeft = false; BindingDescr bind = null;} + : TILDE unaryExpression + | BANG ue=unaryExpression + { + if( buildDescr && $ue.result != null ) { + $result = $ue.result.negate(); + } + } + | castExpression + | backReferenceExpression + | { isLeft = helper.getLeftMostExpr() == null;} + ( ({inMap == 0 && ternOp == 0 && _input.LA(2) == DRLLexer.COLON}? (var=drlIdentifier COLON + { hasBindings = true; helper.emit($var.token, DroolsEditorType.IDENTIFIER_VARIABLE); helper.emit($COLON, DroolsEditorType.SYMBOL); if( buildDescr ) { bind = new BindingDescr($var.text, null, false); helper.setStart( bind, $var.token ); } } )) + | ({inMap == 0 && ternOp == 0 && _input.LA(2) == DRLLexer.DRL_UNIFY}? (var=drlIdentifier DRL_UNIFY + { hasBindings = true; helper.emit($var.token, DroolsEditorType.IDENTIFIER_VARIABLE); helper.emit($DRL_UNIFY, DroolsEditorType.SYMBOL); if( buildDescr ) { bind = new BindingDescr($var.text, null, true); helper.setStart( bind, $var.token ); } } )) + )? + + ( left2=xpathPrimary { if( buildDescr ) { $result = $left2.result; } } + | left1=primary { if( buildDescr ) { $result = $left1.result; } } + ) + + (selector)* + { + if( buildDescr ) { + String expr = $text; + if( isLeft ) { + helper.setLeftMostExpr( expr ); + } + if( bind != null ) { + if( bind.isUnification() ) { + expr = expr.substring( expr.indexOf( ":=" ) + 2 ).trim(); + } else { + expr = expr.substring( expr.indexOf( ":" ) + 1 ).trim(); + } + bind.setExpressionAndBindingField( expr ); + helper.setEnd( bind ); + $result = bind; + } + } + } + ((INC|DEC))? + ; + +castExpression + : LPAREN primitiveType RPAREN expr=unaryExpression + | LPAREN type RPAREN unaryExpressionNotPlusMinus + ; + +backReferenceExpression + : (DOT DOT DIV)+ unaryExpressionNotPlusMinus + ; + +primitiveType + : boolean_key + | char_key + | byte_key + | short_key + | int_key + | long_key + | float_key + | double_key + ; + +xpathSeparator + : DIV + | QUESTION_DIV + ; + +xpathPrimary returns [BaseDescr result] + : xpathChunk ({notStartWithNewline()}? xpathChunk)* + ; + +xpathChunk returns [BaseDescr result] + : xpathSeparator drlIdentifier (DOT drlIdentifier)* (HASH drlIdentifier)? (LBRACK xpathExpressionList RBRACK)? + ; + +xpathExpressionList returns [java.util.List exprs] +@init { $exprs = new java.util.ArrayList();} + : f=expression { $exprs.add( $f.text ); } + (COMMA s=expression { $exprs.add( $s.text ); })* + ; + +primary returns [BaseDescr result] + : expr=parExpression { if( buildDescr ) { $result = $expr.result; } } + | nonWildcardTypeArguments (explicitGenericInvocationSuffix | this_key arguments) + | literal { if( buildDescr ) { $result = new AtomicExprDescr( $literal.text, true ); } } + | super_key superSuffix + | new_key creator + | primitiveType (LBRACK RBRACK)* DOT class_key + //| void_key DOT class_key + | inlineMapExpression + | inlineListExpression + | i1=drlIdentifier { helper.emit($i1.token, DroolsEditorType.IDENTIFIER); } + ( + ( d=DOT i2=drlIdentifier { helper.emit($d, DroolsEditorType.SYMBOL); helper.emit($i2.token, DroolsEditorType.IDENTIFIER); } ) + | + ( d=(DOT|NULL_SAFE_DOT) LPAREN { helper.emit($d, DroolsEditorType.SYMBOL); helper.emit($LPAREN, DroolsEditorType.SYMBOL); } + expression (COMMA { helper.emit($COMMA, DroolsEditorType.SYMBOL); } expression)* + RPAREN { helper.emit($RPAREN, DroolsEditorType.SYMBOL); } + ) + | + ( h=HASH i2=drlIdentifier { helper.emit($h, DroolsEditorType.SYMBOL); helper.emit($i2.token, DroolsEditorType.IDENTIFIER); } ) + | + ( n=NULL_SAFE_DOT i2=drlIdentifier { helper.emit($n, DroolsEditorType.SYMBOL); helper.emit($i2.token, DroolsEditorType.IDENTIFIER); } ) + )* (identifierSuffix)? + ; + +inlineListExpression + : LBRACK expressionList? RBRACK + ; + +inlineMapExpression +@init{ inMap++; } + : LBRACK mapExpressionList RBRACK + ; +finally { inMap--; } + +mapExpressionList + : mapEntry (COMMA mapEntry)* + ; + +mapEntry + : expression COLON expression + ; + +parExpression returns [BaseDescr result] + : LPAREN expr=expression RPAREN + { if( buildDescr ) { + $result = $expr.result; + if( $result instanceof AtomicExprDescr ) { + ((AtomicExprDescr)$result).setExpression("(" +((AtomicExprDescr)$result).getExpression() + ")" ); + } + } + } + ; + +identifierSuffix + : (LBRACK { helper.emit($LBRACK, DroolsEditorType.SYMBOL); } + RBRACK { helper.emit($RBRACK, DroolsEditorType.SYMBOL); } )+ + DOT { helper.emit($DOT, DroolsEditorType.SYMBOL); } class_key + | (LBRACK { helper.emit($LBRACK, DroolsEditorType.SYMBOL); } + expression + RBRACK { helper.emit($RBRACK, DroolsEditorType.SYMBOL); } )+ // can also be matched by selector, but do here + | arguments + | DOT class_key +// | DOT explicitGenericInvocation +// | DOT this_key +// | DOT super_key arguments +// | DOT new_key (nonWildcardTypeArguments)? innerCreator + ; + +creator + : nonWildcardTypeArguments? createdName + (arrayCreatorRest | classCreatorRestExpr) + ; + +createdName + : drlIdentifier typeArguments? + ( DOT drlIdentifier typeArguments?)* + | primitiveType + ; + +// Old parser cannot parse innerCreator with selector expression (outer.new InnerClass() != null) TODO: Delete this after investigation +innerCreator + : {!(helper.validateIdentifierKey(DroolsSoftKeywords.INSTANCEOF))}? drlIdentifier classCreatorRestExpr + ; + +arrayCreatorRest + : LBRACK + ( RBRACK (LBRACK RBRACK)* arrayInitializer + | expression RBRACK ({!helper.validateLT(2,"]")}? LBRACK expression RBRACK)* (LBRACK RBRACK)* + ) + ; + +variableInitializer + : arrayInitializer + | expression + ; + +arrayInitializer + : LBRACE (variableInitializer (COMMA variableInitializer)* (COMMA)? )? RBRACE + ; + +classCreatorRestExpr // do not overwrite JavaParser.g4 classCreatorRest + : arguments //classBody? //sotty: restored classBody to allow for inline, anonymous classes + ; + +explicitGenericInvocation + : nonWildcardTypeArguments arguments + ; + +nonWildcardTypeArguments + : LT typeList GT + ; + +explicitGenericInvocationSuffix + : super_key superSuffix + | drlIdentifier arguments + ; + +selector + : DOT { helper.emit($DOT, DroolsEditorType.SYMBOL); } super_key superSuffix + | DOT { helper.emit($DOT, DroolsEditorType.SYMBOL); } new_key (nonWildcardTypeArguments)? innerCreator + | DOT { helper.emit($DOT, DroolsEditorType.SYMBOL); } + id=drlIdentifier { helper.emit($id.token, DroolsEditorType.IDENTIFIER); } + (arguments)? + | NULL_SAFE_DOT { helper.emit($NULL_SAFE_DOT, DroolsEditorType.SYMBOL); } + id=drlIdentifier { helper.emit($id.token, DroolsEditorType.IDENTIFIER); } + (arguments)? + //| DOT this_key + | LBRACK { helper.emit($LBRACK, DroolsEditorType.SYMBOL); } + expression + RBRACK { helper.emit($RBRACK, DroolsEditorType.SYMBOL); } + ; + +superSuffix + : arguments + | DOT drlIdentifier (arguments)? + ; + +squareArguments returns [java.util.List args] + : LBRACK (el=expressionList { $args = $el.exprs; })? RBRACK + ; + +arguments + : LPAREN { helper.emit($LPAREN, DroolsEditorType.SYMBOL); } + expressionList? + RPAREN { helper.emit($RPAREN, DroolsEditorType.SYMBOL); } + ; + +expressionList returns [java.util.List exprs] +@init { $exprs = new java.util.ArrayList();} + : f=expression { $exprs.add( $f.text ); } + (COMMA s=expression { $exprs.add( $s.text ); })* + ; + +assignmentOperator + : ASSIGN + | ADD_ASSIGN + | SUB_ASSIGN + | MUL_ASSIGN + | DIV_ASSIGN + | AND_ASSIGN + | OR_ASSIGN + | XOR_ASSIGN + | MOD_ASSIGN + | LT LT ASSIGN + | GT GT GT ASSIGN + | GT GT ASSIGN + ; + +// -------------------------------------------------------- +// KEYWORDS +// -------------------------------------------------------- +extends_key + : id=EXTENDS { helper.emit($id, DroolsEditorType.KEYWORD); } + ; + +super_key + : id=SUPER { helper.emit($id, DroolsEditorType.KEYWORD); } + ; + +instanceof_key + : id=INSTANCEOF { helper.emit($id, DroolsEditorType.KEYWORD); } + ; + +boolean_key + : id=BOOLEAN { helper.emit($id, DroolsEditorType.KEYWORD); } + ; + +char_key + : id=CHAR { helper.emit($id, DroolsEditorType.KEYWORD); } + ; + +byte_key + : id=BYTE { helper.emit($id, DroolsEditorType.KEYWORD); } + ; + +short_key + : id=SHORT { helper.emit($id, DroolsEditorType.KEYWORD); } + ; + +int_key + : id=INT { helper.emit($id, DroolsEditorType.KEYWORD); } + ; + +float_key + : id=FLOAT { helper.emit($id, DroolsEditorType.KEYWORD); } + ; + +long_key + : id=LONG { helper.emit($id, DroolsEditorType.KEYWORD); } + ; + +double_key + : id=DOUBLE { helper.emit($id, DroolsEditorType.KEYWORD); } + ; + +void_key + : id=VOID { helper.emit($id, DroolsEditorType.KEYWORD); } + ; + +this_key + : id=THIS { helper.emit($id, DroolsEditorType.KEYWORD); } + ; + +class_key + : id=CLASS { helper.emit($id, DroolsEditorType.KEYWORD); } + ; + +new_key + : id=NEW { helper.emit($id, DroolsEditorType.KEYWORD); } + ; + +not_key + : id=DRL_NOT { helper.emit($id, DroolsEditorType.KEYWORD); } + ; + +in_key + : id=DRL_IN { helper.emit($id, DroolsEditorType.KEYWORD); } + ; + +operator_key + // IDENTIFIER is required to accept custom operators. We need to keep this semantic predicate for custom operators + : {(helper.isPluggableEvaluator(false))}? id=IDENTIFIER { helper.emit($id, DroolsEditorType.KEYWORD); } + | op=builtInOperator { helper.emit($op.token, DroolsEditorType.KEYWORD); } + ; + +neg_operator_key + : {(helper.isPluggableEvaluator(true))}? id=IDENTIFIER { helper.emit($id, DroolsEditorType.KEYWORD); } + | op=builtInOperator { helper.emit($op.token, DroolsEditorType.KEYWORD); } + ; diff --git a/drools-drl/drools-drl-parser/src/main/antlr4/org/drools/drl/parser/antlr4/DRLLexer.g4 b/drools-drl/drools-drl-parser/src/main/antlr4/org/drools/drl/parser/antlr4/DRLLexer.g4 new file mode 100644 index 00000000000..2c05b4dc38b --- /dev/null +++ b/drools-drl/drools-drl-parser/src/main/antlr4/org/drools/drl/parser/antlr4/DRLLexer.g4 @@ -0,0 +1,216 @@ +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you 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 + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +lexer grammar DRLLexer; + +import JavaLexer; + +@members { + public String normalizeString( String input ) { + if( input != null && (input.length() == 2 || input.length() >= 4) ) { + input = input.substring( 1, input.length() - 1 ); + input = input.replaceAll( "\'", "'" ); + input = input.replaceAll( "\"", "\\\"" ); + input = "\"" + input + "\""; + } + return input; + } + + public boolean isRhsDrlEnd() { + return new LexerHelper(_input).isRhsDrlEnd(); + } +} + +///////////////// +// KEYWORDS +///////////////// + +// These keywords are already declared in JavaLexer. They should not be overriden with different names, or else Vocabulary's literalName will be null. +// So no need to declare by DRLLexer +// PACKAGE : 'package'; +// IMPORT : 'import'; +// STATIC : 'static'; +// EXTENDS : 'extends'; +// SUPER : 'super'; + +// DRL keywords +DRL_UNIT : 'unit'; +DRL_FUNCTION : 'function'; +DRL_GLOBAL : 'global'; +DRL_DECLARE : 'declare'; +DRL_TRAIT : 'trait'; +DRL_TYPE : 'type'; +DRL_RULE : 'rule'; +DRL_QUERY : 'query'; +DRL_WHEN : 'when'; +DRL_THEN : 'then' -> pushMode(RHS); +DRL_END : 'end'; + +DRL_AND : 'and'; +DRL_OR : 'or'; + +DRL_EXISTS : 'exists'; +DRL_NOT : 'not'; +DRL_IN : 'in'; +DRL_FROM : 'from'; +DRL_COLLECT : 'collect'; +DRL_ACCUMULATE : 'accumulate'; +DRL_ACC : 'acc'; +DRL_INIT : 'init'; +DRL_ACTION : 'action'; +DRL_REVERSE : 'reverse'; +DRL_RESULT : 'result'; +DRL_ENTRY_POINT : 'entry-point'; +DRL_EVAL : 'eval'; +DRL_FORALL : 'forall'; +DRL_OVER : 'over'; +DRL_GROUPBY : 'groupby'; + +// constraint operators +DRL_MATCHES : 'matches'; +DRL_MEMBEROF : 'memberOf'; +DRL_CONTAINS : 'contains'; +DRL_EXCLUDES : 'excludes'; +DRL_SOUNDSLIKE : 'soundslike'; +DRL_STR : 'str'; + +// temporal operators +DRL_AFTER : 'after'; +DRL_BEFORE : 'before'; +DRL_COINCIDES : 'coincides'; +DRL_DURING : 'during'; +DRL_INCLUDES : 'includes'; +DRL_FINISHES : 'finishes'; +DRL_FINISHED_BY : 'finishedby'; +DRL_MEETS : 'meets'; +DRL_MET_BY : 'metby'; +DRL_OVERLAPS : 'overlaps'; +DRL_OVERLAPPED_BY : 'overlappedby'; +DRL_STARTS : 'starts'; +DRL_STARTED_BY : 'startedby'; + +DRL_WINDOW : 'window'; + +// attributes +DRL_ATTRIBUTES : 'attributes'; +DRL_SALIENCE : 'salience'; +DRL_ENABLED : 'enabled'; +DRL_NO_LOOP : 'no-loop'; +DRL_AUTO_FOCUS : 'auto-focus'; +DRL_LOCK_ON_ACTIVE : 'lock-on-active'; +DRL_REFRACT : 'refract'; +DRL_DIRECT : 'direct'; +DRL_AGENDA_GROUP : 'agenda-group'; +DRL_ACTIVATION_GROUP : 'activation-group'; +DRL_RULEFLOW_GROUP : 'ruleflow-group'; +DRL_DATE_EFFECTIVE : 'date-effective'; +DRL_DATE_EXPIRES : 'date-expires'; +DRL_DIALECT : 'dialect'; +DRL_CALENDARS : 'calendars'; +DRL_TIMER : 'timer'; +DRL_DURATION : 'duration'; + +///////////////// +// LEXER +///////////////// + +TIME_INTERVAL + : (('0'..'9')+ 'd') (('0'..'9')+ 'h')?(('0'..'9')+ 'm')?(('0'..'9')+ 's')?(('0'..'9')+ 'ms'?)? + | (('0'..'9')+ 'h') (('0'..'9')+ 'm')?(('0'..'9')+ 's')?(('0'..'9')+ 'ms'?)? + | (('0'..'9')+ 'm') (('0'..'9')+ 's')?(('0'..'9')+ 'ms'?)? + | (('0'..'9')+ 's') (('0'..'9')+ 'ms'?)? + | (('0'..'9')+ 'ms') + ; + +DRL_STRING_LITERAL + : ('"' ( DrlEscapeSequence | ~('\\'|'"') )* '"') + | ('\'' ( DrlEscapeSequence | ~('\\'|'\'') )* '\'') { setText( normalizeString( getText() ) ); } + ; + +DRL_BIG_DECIMAL_LITERAL + : ('0'..'9')+ [B] + | ('0'..'9')+ '.' ('0'..'9')+ [B] + ; + +DRL_BIG_INTEGER_LITERAL + : ('0'..'9')+ [I] + ; + +///////////////// +// SYMBOLS +///////////////// + +HASH : '#'; +DRL_UNIFY : ':=' ; +NULL_SAFE_DOT : '!.' ; +QUESTION_DIV : '?/' ; + +MISC : '\'' | '\\' | '$' ; + +///////////////// +// Fragment +///////////////// +fragment +DrlEscapeSequence + : '\\' ('b'|'B'|'t'|'n'|'f'|'r'|'"'|'\''|'\\'|'.'|'o'| + 'x'|'a'|'e'|'c'|'d'|'D'|'s'|'S'|'w'|'W'|'p'|'A'| + 'G'|'Z'|'z'|'Q'|'E'|'*'|'['|']'|'('|')'|'$'|'^'| + '{'|'}'|'?'|'+'|'-'|'&'|'|') + | DrlUnicodeEscape + | DrlOctalEscape + ; + +fragment +DrlOctalEscape + : '\\' ('0'..'3') ('0'..'7') ('0'..'7') + | '\\' ('0'..'7') ('0'..'7') + | '\\' ('0'..'7') + ; + +fragment +DrlUnicodeEscape + : '\\' 'u' HexDigit HexDigit HexDigit HexDigit + ; + +mode RHS; +RHS_WS : [ \t\r\n\u000C]+ -> channel(HIDDEN); +RHS_COMMENT: '/*' .*? '*/' ; +RHS_LINE_COMMENT: '//' ~[\r\n]* ; + +//DRL_RHS_END : 'end' [ \t]* SEMI? [ \t]* ('\n' | '\r\n' | EOF) { setText("end"); } -> popMode; +DRL_RHS_END : {isRhsDrlEnd()}? DRL_END -> popMode; + +RHS_STRING_LITERAL + // cannot reuse DRL_STRING_LITERAL because Actions are ignored in referenced rules + : ('"' ( DrlEscapeSequence | ~('\\'|'"') )* '"') + | ('\'' ( DrlEscapeSequence | ~('\\'|'\'') )* '\'') { setText( normalizeString( getText() ) ); } + ; + +RHS_NAMED_CONSEQUENCE_THEN : DRL_THEN LBRACK IDENTIFIER RBRACK ; + +RHS_CHUNK + : ~[ "'()[\]{},;\t\r\n\u000C]+ // ;}) could be a delimitter proceding 'end'. ()[]{},; are delimiters to match RHS_STRING_LITERAL + | LPAREN + | RPAREN + | LBRACK + | RBRACK + | LBRACE + | RBRACE + | COMMA + | SEMI + ; diff --git a/drools-drl/drools-drl-parser/src/main/antlr4/org/drools/drl/parser/antlr4/DRLParser.g4 b/drools-drl/drools-drl-parser/src/main/antlr4/org/drools/drl/parser/antlr4/DRLParser.g4 new file mode 100644 index 00000000000..8ccaf9b4cd8 --- /dev/null +++ b/drools-drl/drools-drl-parser/src/main/antlr4/org/drools/drl/parser/antlr4/DRLParser.g4 @@ -0,0 +1,560 @@ +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you 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 + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + parser grammar DRLParser; + +options { tokenVocab=DRLLexer; } + +import DRL6Expressions, JavaParser; + + /* + * statement := importStatement + * | globalStatement + * | declare + * | rule + * | ruleAttribute + * | function + * | query + * ; + */ +compilationUnit : packagedef? unitdef? drlStatementdef* EOF ; + +drlStatementdef + : importdef SEMI? + | globaldef SEMI? + | declaredef SEMI? + | ruledef SEMI? + | attributes SEMI? + | functiondef SEMI? + | querydef SEMI? + ; + +packagedef : PACKAGE name=drlQualifiedName SEMI? ; + +unitdef : DRL_UNIT name=drlQualifiedName SEMI? ; + +importdef : IMPORT (DRL_FUNCTION|STATIC)? drlQualifiedName (DOT MUL)? #importStandardDef + | IMPORT (DRL_ACCUMULATE|DRL_ACC) drlQualifiedName drlIdentifier #importAccumulateDef + ; + +globaldef : DRL_GLOBAL type drlIdentifier ; + +/** + * declare := DECLARE + * | (ENTRY-POINT) => entryPointDeclaration + * | (WINDOW) => windowDeclaration + * | (TRAIT) => typeDeclaration (trait) + * | (ENUM) => enumDeclaration + * | typeDeclaration (class) + * END + */ + +declaredef : DRL_DECLARE ( + | entryPointDeclaration + | windowDeclaration + | typeDeclaration + | enumDeclaration + ) + ; // DRL_END belongs to entryPointDeclaration etc. + +/* + * typeDeclaration := [TYPE] qualifiedIdentifier (EXTENDS qualifiedIdentifier)? + * annotation* + * field* + * END + */ + +typeDeclaration : DRL_TRAIT? DRL_TYPE? name=drlQualifiedName (EXTENDS superTypes+=drlQualifiedName (COMMA superTypes+=drlQualifiedName)* )? drlAnnotation* field* DRL_END ; + +// entryPointDeclaration := ENTRY-POINT stringId annotation* END + +entryPointDeclaration : DRL_ENTRY_POINT name=stringId drlAnnotation* DRL_END ; + +// windowDeclaration := WINDOW ID annotation* lhsPatternBind END + +windowDeclaration : DRL_WINDOW name=drlIdentifier drlAnnotation* lhsPatternBind DRL_END ; + +// (enum)typeDeclaration := [ENUM] qualifiedIdentifier annotation* enumerative+ field* END + +enumDeclaration : ENUM name=drlQualifiedName drlAnnotation* enumeratives SEMI field* DRL_END ; + +enumeratives : enumerative (COMMA enumerative)* ; + +// enumerative := ID ( LEFT_PAREN expression (COMMA expression)* RIGHT_PAREN )? + +enumerative: drlIdentifier ( LPAREN expression ( COMMA expression )* RPAREN )? ; + +// field := label fieldType (EQUALS_ASSIGN conditionalExpression)? annotation* SEMICOLON? + +field : label type (ASSIGN initExpr=conditionalOrExpression)? drlAnnotation* SEMI? ; + +// rule := RULE stringId (EXTENDS stringId)? annotation* attributes? lhs? rhs END + +ruledef : DRL_RULE name=stringId (EXTENDS parentName=stringId)? drlAnnotation* attributes? lhs? rhs DRL_RHS_END ; + +// query := QUERY stringId parameters? annotation* lhsExpression END + +querydef : DRL_QUERY name=stringId parameters? drlAnnotation* queryLhs DRL_END ; + +// parameters := LEFT_PAREN ( parameter ( COMMA parameter )* )? RIGHT_PAREN +parameters : LPAREN ( parameter ( COMMA parameter )* )? RPAREN ; + +// parameter := ({requiresType}?=>type)? ID (LEFT_SQUARE RIGHT_SQUARE)* +parameter : type? drlIdentifier ; // type is optional. Removed (LEFT_SQUARE RIGHT_SQUARE)* as it doesn't make sense in the grammar + +lhs : DRL_WHEN lhsExpression* ; + +queryLhs : lhsExpression* ; + +lhsExpression : LPAREN lhsExpression RPAREN #lhsExpressionEnclosed + | DRL_OR drlAnnotation* lhsExpression+ #lhsOr + | lhsExpression ((DRL_OR|OR) drlAnnotation* lhsExpression)+ #lhsOr + | DRL_AND drlAnnotation* lhsExpression+ #lhsAnd + | lhsExpression ((DRL_AND|AND) drlAnnotation* lhsExpression)+ #lhsAnd + | lhsUnary #lhsUnarySingle + ; + +// lhsAnd is used as a label in lhsExpression rule. But some other rules explicitly use the def, so lhsAndDef is declared. +lhsAndDef : LPAREN lhsAndDef RPAREN + | lhsUnary ((DRL_AND|AND) lhsUnary)* + | LPAREN DRL_AND lhsUnary+ RPAREN + ; + +/* +lhsUnary : ( lhsExists namedConsequence? + | lhsNot namedConsequence? + | lhsEval consequenceInvocation* + | lhsForall + | lhsAccumulate + | LPAREN lhsOr RPAREN namedConsequence? + | lhsPatternBind consequenceInvocation* + ) SEMI? ; +*/ + +lhsUnary : ( + lhsExists namedConsequenceInvocation? + | lhsNot namedConsequenceInvocation? + | lhsEval consequenceInvocation* + | lhsForall + | lhsAccumulate + | lhsGroupBy + | LPAREN lhsExpression RPAREN namedConsequenceInvocation? + | conditionalBranch // not in the above old parser definition, but actually implemented in the old parser + | lhsPatternBind consequenceInvocation* + ) SEMI? ; + +lhsPatternBind : (label|unif)? ( LPAREN lhsPattern (DRL_OR lhsPattern)* RPAREN | lhsPattern ) ; + +/* +lhsPattern : xpathPrimary (OVER patternFilter)? | + ( QUESTION? qualifiedIdentifier LPAREN positionalConstraints? constraints? RPAREN (OVER patternFilter)? (FROM patternSource)? ) ; +*/ + +lhsPattern + : xpathPrimary (DRL_OVER patternFilter)? + | QUESTION? objectType=drlQualifiedName LPAREN positionalConstraints? constraints? RPAREN drlAnnotation* (DRL_OVER patternFilter)? (DRL_FROM patternSource)? + ; +positionalConstraints : constraint (COMMA constraint)* SEMI ; +constraints : constraint (COMMA constraint)* ; +constraint : ( nestedConstraint | conditionalOrExpression ) ; +nestedConstraint : ( drlIdentifier ( DOT | NULL_SAFE_DOT | HASH ) )* drlIdentifier (DOT | NULL_SAFE_DOT ) LPAREN constraints RPAREN ; + +// named consequence + +// consequenceInvocation := conditionalBranch | namedConsequence +consequenceInvocation : conditionalBranch | namedConsequenceInvocation ; + +// conditionalBranch := IF LEFT_PAREN conditionalExpression RIGHT_PAREN +// ( namedConsequence | breakingNamedConsequence ) +// ( ELSE ( namedConsequence | breakingNamedConsequence | conditionalBranch ) )? +conditionalBranch : IF LPAREN conditionalOrExpression RPAREN + ( do1=namedConsequenceInvocation | break1=breakingNamedConsequenceInvocation ) + ( ELSE ( do2=namedConsequenceInvocation | break2=breakingNamedConsequenceInvocation | conditionalBranch ) )? ; + +// namedConsequence := DO LEFT_SQUARE ID RIGHT_SQUARE BREAK? +namedConsequenceInvocation : DO LBRACK drlIdentifier RBRACK ; // BREAK? is not actually implmented in the old parser + +// breakingNamedConsequence := BREAK LEFT_SQUARE ID RIGHT_SQUARE +breakingNamedConsequenceInvocation : BREAK LBRACK drlIdentifier RBRACK ; + + +relationalOperator + : EQUAL + | NOTEQUAL + | LE + | GE + | GT + | LT + | drlRelationalOperator + | temporalOperator + ; + +drlRelationalOperator : DRL_NOT? builtInOperator ; + +/* function := FUNCTION type? ID parameters(typed) chunk_{_} */ +functiondef : DRL_FUNCTION typeTypeOrVoid? drlIdentifier formalParameters drlBlock ; + + +/* extending JavaParser qualifiedName */ +drlQualifiedName + : drlIdentifier (DOT drlIdentifier)* + ; + +/* extending JavaParser expression */ +drlExpression + : drlPrimary + | drlExpression bop=DOT + ( + drlIdentifier + | drlMethodCall + | THIS + | NEW nonWildcardTypeArguments? innerCreator + | SUPER superSuffix + | explicitGenericInvocation + | inlineCast + ) + | drlExpression NULL_SAFE_DOT ( drlIdentifier | drlMethodCall ) + | drlExpression LBRACK drlExpression RBRACK + | DRL_EVAL LPAREN conditionalOrExpression RPAREN + | drlMethodCall + | NEW drlCreator + | LPAREN annotation* typeType (BITAND typeType)* RPAREN drlExpression + | drlExpression postfix=(INC | DEC) + | prefix=(ADD|SUB|INC|DEC) drlExpression + | prefix=(TILDE|BANG) drlExpression + | drlExpression bop=(MUL|DIV|MOD) drlExpression + | drlExpression bop=(ADD|SUB) drlExpression + | drlExpression (LT LT | GT GT GT | GT GT) drlExpression + | drlExpression bop=INSTANCEOF (typeType | pattern) + | drlExpression relationalOperator drlExpression + | drlExpression bop=DRL_UNIFY drlExpression + | drlExpression bop=BITAND drlExpression + | drlExpression bop=CARET drlExpression + | drlExpression bop=BITOR drlExpression + | drlExpression bop=AND drlExpression + | drlExpression bop=OR drlExpression + | drlExpression bop=QUESTION drlExpression COLON drlExpression + | drlExpression + bop=(ASSIGN | ADD_ASSIGN | SUB_ASSIGN | MUL_ASSIGN | DIV_ASSIGN | AND_ASSIGN | OR_ASSIGN | XOR_ASSIGN | RSHIFT_ASSIGN | URSHIFT_ASSIGN | LSHIFT_ASSIGN | MOD_ASSIGN) + drlExpression + | lambdaExpression // Java8 + | switchExpression // Java17 + + // Java 8 methodReference + | drlExpression COLONCOLON typeArguments? drlIdentifier + | typeType COLONCOLON (typeArguments? drlIdentifier | NEW) + | classType COLONCOLON typeArguments? NEW + + // OOPath + | xpathPrimary + | backReferenceExpression + ; + +backReferenceExpression : (DOT DOT DIV)+ drlExpression ; + + +/* extending JavaParser methodCall in order to accept drl keywords as method name */ +drlMethodCall + : drlIdentifier LPAREN expressionList? RPAREN + | THIS LPAREN expressionList? RPAREN + | SUPER LPAREN expressionList? RPAREN + ; + +temporalOperator : DRL_NOT? bop=(DRL_AFTER | DRL_BEFORE | DRL_COINCIDES | DRL_DURING | DRL_INCLUDES | DRL_FINISHES | DRL_FINISHED_BY | DRL_MEETS | DRL_MET_BY | DRL_OVERLAPS | DRL_OVERLAPPED_BY | DRL_STARTS | DRL_STARTED_BY) timeAmount? ; + +timeAmount : LBRACK (TIME_INTERVAL | DECIMAL_LITERAL | MUL | SUB MUL) (COMMA (TIME_INTERVAL | DECIMAL_LITERAL | MUL | SUB MUL))* RBRACK ; + +/* extending JavaParser primary */ +drlPrimary + : LPAREN drlExpression RPAREN + | THIS + | SUPER + | NEW drlCreator + | drlLiteral + | drlIdentifier + | typeTypeOrVoid DOT CLASS + | nonWildcardTypeArguments (explicitGenericInvocationSuffix | THIS arguments) + | inlineListExpression + | inlineMapExpression + | inlineCast + ; + +inlineCast : drlIdentifier HASH drlIdentifier ; + +/* extending JavaParser literal */ +drlLiteral + : integerLiteral + | floatLiteral + | DRL_BIG_DECIMAL_LITERAL + | DRL_BIG_INTEGER_LITERAL + | CHAR_LITERAL + | DRL_STRING_LITERAL + | BOOL_LITERAL + | NULL_LITERAL + | TEXT_BLOCK // Java17 + | TIME_INTERVAL + ; + +inlineListExpression + : LBRACK expressionList? RBRACK + ; + +inlineMapExpression + : LBRACK mapExpressionList RBRACK + ; + +mapExpressionList + : mapEntry (COMMA mapEntry)* + ; + +mapEntry + : drlExpression COLON drlExpression + ; + +/* + patternFilter := OVER filterDef + filterDef := label ID LEFT_PAREN parameters RIGHT_PAREN +*/ +patternFilter : DRL_WINDOW COLON drlIdentifier LPAREN expressionList RPAREN ; + +/* + patternSource := FROM + ( fromAccumulate + | fromCollect + | fromEntryPoint + | fromWindow + | fromExpression ) +*/ +patternSource : fromAccumulate + | fromCollect + | fromEntryPoint + | fromWindow + | fromExpression + ; + +fromExpression : conditionalOrExpression ; + + +/* +fromAccumulate := ACCUMULATE LEFT_PAREN lhsAnd (COMMA|SEMICOLON) + ( INIT chunk_(_) COMMA ACTION chunk_(_) COMMA + ( REVERSE chunk_(_) COMMA)? RESULT chunk_(_) + | accumulateFunction + ) RIGHT_PAREN +*/ +fromAccumulate : (DRL_ACCUMULATE|DRL_ACC) LPAREN lhsAndDef (COMMA|SEMI) + ( DRL_INIT LPAREN initBlockStatements=chunk? RPAREN COMMA? DRL_ACTION LPAREN actionBlockStatements=chunk? RPAREN COMMA? DRL_REVERSE LPAREN reverseBlockStatements=chunk? RPAREN COMMA? DRL_RESULT LPAREN resultBlockStatements=chunk RPAREN + | DRL_INIT LPAREN initBlockStatements=chunk? RPAREN COMMA? DRL_ACTION LPAREN actionBlockStatements=chunk? RPAREN COMMA? DRL_RESULT LPAREN resultBlockStatements=chunk RPAREN + | accumulateFunction + ) + RPAREN (SEMI)? + ; + +blockStatements : drlBlockStatement* ; + +/* +accumulateFunction := label? ID parameters +*/ +accumulateFunction : (label|unif)? drlIdentifier conditionalExpressions ; + +// parameters := LEFT_PAREN (conditionalExpression (COMMA conditionalExpression)* )? RIGHT_PAREN +conditionalExpressions : LPAREN (conditionalExpression (COMMA conditionalExpression)* )? RPAREN ; + +// fromCollect := COLLECT LEFT_PAREN lhsPatternBind RIGHT_PAREN + +fromCollect : DRL_COLLECT LPAREN lhsPatternBind RPAREN ; + +fromEntryPoint : DRL_ENTRY_POINT stringId ; + +// fromWindow := WINDOW ID +fromWindow : DRL_WINDOW drlIdentifier ; + +/* + lhsExists := EXISTS + ( (LEFT_PAREN (or_key|and_key))=> lhsOr // prevents '((' for prefixed and/or + | LEFT_PAREN lhsOr RIGHT_PAREN + | lhsPatternBind + ) +*/ +// Use lhsExpression instead of lhsOr because lhsExpression has good enough structure +lhsExists : DRL_EXISTS ( LPAREN lhsExpression RPAREN | lhsPatternBind ) ; + +/* + lhsNot := NOT + ( (LEFT_PAREN (or_key|and_key))=> lhsOr // prevents '((' for prefixed and/or + | LEFT_PAREN lhsOr RIGHT_PAREN + | lhsPatternBind + ) +*/ +// Use lhsExpression instead of lhsOr because lhsExpression has good enough structure +lhsNot : DRL_NOT ( LPAREN lhsExpression RPAREN | lhsPatternBind ) ; + +/** + * lhsEval := EVAL LEFT_PAREN conditionalExpression RIGHT_PAREN + */ +lhsEval : DRL_EVAL LPAREN conditionalOrExpression RPAREN ; + +/** + * lhsForall := FORALL LEFT_PAREN lhsPatternBind+ RIGHT_PAREN + */ + +lhsForall : DRL_FORALL LPAREN lhsPatternBind+ RPAREN ; + +/** + * lhsAccumulate := (ACCUMULATE|ACC) LEFT_PAREN lhsAnd (COMMA|SEMICOLON) + * accumulateFunctionBinding (COMMA accumulateFunctionBinding)* + * (SEMICOLON constraints)? + * RIGHT_PAREN SEMICOLON? + */ + +lhsAccumulate : (DRL_ACCUMULATE|DRL_ACC) LPAREN lhsAndDef (COMMA|SEMI) + accumulateFunction (COMMA accumulateFunction)* + (SEMI constraints)? + RPAREN (SEMI)? + ; + +lhsGroupBy : DRL_GROUPBY LPAREN lhsAndDef (COMMA|SEMI) + groupByKeyBinding SEMI + accumulateFunction (COMMA accumulateFunction)* + (SEMI constraints)? + RPAREN (SEMI)? + ; + +groupByKeyBinding : label? conditionalExpression ; + +rhs : DRL_THEN consequenceBody namedConsequence* ; + +consequenceBody : ( RHS_COMMENT | RHS_LINE_COMMENT | RHS_STRING_LITERAL | RHS_CHUNK )* ; + +// THEN LEFT_SQUARE ID RIGHT_SQUARE chunk +namedConsequence : RHS_NAMED_CONSEQUENCE_THEN consequenceBody ; + +stringId : ( drlIdentifier | DRL_STRING_LITERAL ) ; + +//type := ID typeArguments? ( DOT ID typeArguments? )* (LEFT_SQUARE RIGHT_SQUARE)* +//typeArguments : LT typeArgument (COMMA typeArgument)* GT ; +//typeArgument : QUESTION (( EXTENDS | SUPER ) type )? | type ; + +drlArguments : LPAREN drlArgument (COMMA drlArgument)* RPAREN ; +drlArgument : ( stringId | floatLiteral | BOOL_LITERAL | NULL_LITERAL ) ; + +drlAnnotation + // TODO actions can be removed once there is a DRL6ExpressionsVisitorImpl. + : {boolean buildState = buildDescr; buildDescr = true;} anno=fullAnnotation[null] {buildDescr = buildState;} // either standard Java annotation + | AT name=drlQualifiedName (LPAREN chunk RPAREN)? ; // or support @watch(!*, age) etc. + +// attributes := (ATTRIBUTES COLON?)? [ attribute ( COMMA? attribute )* ] +attributes : (DRL_ATTRIBUTES COLON?)? attribute ( COMMA? attribute )* ; +attribute : name=( DRL_SALIENCE | DRL_ENABLED ) conditionalAttributeValue #expressionAttribute + | name=( DRL_NO_LOOP | DRL_AUTO_FOCUS | DRL_LOCK_ON_ACTIVE | DRL_REFRACT | DRL_DIRECT ) BOOL_LITERAL? #booleanAttribute + | name=( DRL_AGENDA_GROUP | DRL_ACTIVATION_GROUP | DRL_RULEFLOW_GROUP | DRL_DATE_EFFECTIVE | DRL_DATE_EXPIRES | DRL_DIALECT ) DRL_STRING_LITERAL #stringAttribute + | name=DRL_CALENDARS DRL_STRING_LITERAL ( COMMA DRL_STRING_LITERAL )* #stringListAttribute + | name=DRL_TIMER ( DECIMAL_LITERAL | LPAREN chunk RPAREN ) #intOrChunkAttribute + | name=DRL_DURATION ( DECIMAL_LITERAL | LPAREN chunk RPAREN ) #intOrChunkAttribute + ; + +conditionalAttributeValue : ( LPAREN conditionalExpression RPAREN | conditionalExpression ) ; + +chunk : .+?; + +assignmentOperator : ASSIGN + | ADD_ASSIGN + | SUB_ASSIGN + | MUL_ASSIGN + | DIV_ASSIGN + | AND_ASSIGN + | OR_ASSIGN + | XOR_ASSIGN + | MOD_ASSIGN + | LT LT ASSIGN ; + +label : drlIdentifier COLON ; +unif : drlIdentifier DRL_UNIFY ; + +/* extending JavaParser variableInitializer */ +drlVariableInitializer + : arrayInitializer + | drlExpression + ; + + drlCreator + : nonWildcardTypeArguments createdName classCreatorRest + | createdName (drlArrayCreatorRest | classCreatorRest) + ; + + drlArrayCreatorRest + : LBRACK (RBRACK (LBRACK RBRACK)* drlArrayInitializer | expression RBRACK (LBRACK expression RBRACK)* (LBRACK RBRACK)*) + ; + + drlArrayInitializer + : LBRACE (drlVariableInitializer (COMMA drlVariableInitializer)* (COMMA)? )? RBRACE + ; + +/* extending JavaParser block */ +drlBlock + : LBRACE drlBlockStatement* RBRACE + ; +/* extending JavaParser blockStatement */ +drlBlockStatement + : drlLocalVariableDeclaration SEMI? + | drlStatement + | localTypeDeclaration + ; + +/* extending JavaParser statement */ +drlStatement + : blockLabel=drlBlock + | ASSERT drlExpression (COLON drlExpression)? SEMI + | IF parExpression drlStatement (ELSE drlStatement)? + | FOR LPAREN forControl RPAREN drlStatement + | WHILE parExpression drlStatement + | DO drlStatement WHILE parExpression SEMI + | TRY drlBlock (catchClause+ finallyBlock? | finallyBlock) + | TRY resourceSpecification drlBlock catchClause* finallyBlock? + | SWITCH parExpression LBRACE switchBlockStatementGroup* switchLabel* RBRACE + | SYNCHRONIZED parExpression drlBlock + | RETURN drlExpression? SEMI + | THROW drlExpression SEMI + | BREAK drlIdentifier? SEMI + | CONTINUE drlIdentifier? SEMI + | YIELD drlExpression SEMI // Java17 + | SEMI + | statementExpression=drlExpression SEMI + | switchExpression SEMI? // Java17 + | identifierLabel=drlIdentifier COLON drlStatement + ; + +/* extending JavaParser localVariableDeclaration */ +drlLocalVariableDeclaration + : variableModifier* (typeType drlVariableDeclarators | VAR drlIdentifier ASSIGN expression) + ; + +/* extending JavaParser variableDeclarators */ +drlVariableDeclarators + : drlVariableDeclarator (COMMA drlVariableDeclarator)* + ; + +/* extending JavaParser variableDeclarator */ +drlVariableDeclarator + : drlVariableDeclaratorId (ASSIGN drlVariableInitializer)? + ; + +/* extending JavaParser variableDeclaratorId */ +drlVariableDeclaratorId + : drlIdentifier (LBRACK RBRACK)* + ; diff --git a/drools-drl/drools-drl-parser/src/main/antlr4/org/drools/drl/parser/antlr4/JavaLexer.g4 b/drools-drl/drools-drl-parser/src/main/antlr4/org/drools/drl/parser/antlr4/JavaLexer.g4 new file mode 100644 index 00000000000..1af884db096 --- /dev/null +++ b/drools-drl/drools-drl-parser/src/main/antlr4/org/drools/drl/parser/antlr4/JavaLexer.g4 @@ -0,0 +1,245 @@ +/* + [The "BSD licence"] + Copyright (c) 2013 Terence Parr, Sam Harwell + Copyright (c) 2017 Ivan Kochurkin (upgrade to Java 8) + Copyright (c) 2021 Michał Lorek (upgrade to Java 11) + Copyright (c) 2022 Michał Lorek (upgrade to Java 17) + All rights reserved. + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions + are met: + 1. Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + 2. Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + 3. The name of the author may not be used to endorse or promote products + derived from this software without specific prior written permission. + + THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 AUTHOR 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. +*/ + +// source: https://github.com/antlr/grammars-v4/tree/master/java/java + +lexer grammar JavaLexer; + +// Keywords + +ABSTRACT: 'abstract'; +ASSERT: 'assert'; +BOOLEAN: 'boolean'; +BREAK: 'break'; +BYTE: 'byte'; +CASE: 'case'; +CATCH: 'catch'; +CHAR: 'char'; +CLASS: 'class'; +CONST: 'const'; +CONTINUE: 'continue'; +DEFAULT: 'default'; +DO: 'do'; +DOUBLE: 'double'; +ELSE: 'else'; +ENUM: 'enum'; +EXTENDS: 'extends'; +FINAL: 'final'; +FINALLY: 'finally'; +FLOAT: 'float'; +FOR: 'for'; +IF: 'if'; +GOTO: 'goto'; +IMPLEMENTS: 'implements'; +IMPORT: 'import'; +INSTANCEOF: 'instanceof'; +INT: 'int'; +INTERFACE: 'interface'; +LONG: 'long'; +NATIVE: 'native'; +NEW: 'new'; +PACKAGE: 'package'; +PRIVATE: 'private'; +PROTECTED: 'protected'; +PUBLIC: 'public'; +RETURN: 'return'; +SHORT: 'short'; +STATIC: 'static'; +STRICTFP: 'strictfp'; +SUPER: 'super'; +SWITCH: 'switch'; +SYNCHRONIZED: 'synchronized'; +THIS: 'this'; +THROW: 'throw'; +THROWS: 'throws'; +TRANSIENT: 'transient'; +TRY: 'try'; +VOID: 'void'; +VOLATILE: 'volatile'; +WHILE: 'while'; + +// Module related keywords +MODULE: 'module'; +OPEN: 'open'; +REQUIRES: 'requires'; +EXPORTS: 'exports'; +OPENS: 'opens'; +TO: 'to'; +USES: 'uses'; +PROVIDES: 'provides'; +WITH: 'with'; +TRANSITIVE: 'transitive'; + +// Local Variable Type Inference +VAR: 'var'; // reserved type name + +// Switch Expressions +YIELD: 'yield'; + +// Records +RECORD: 'record'; + +// Sealed Classes +SEALED: 'sealed'; +PERMITS: 'permits'; +NON_SEALED: 'non-sealed'; + +// Literals + +DECIMAL_LITERAL: ('0' | [1-9] (Digits? | '_'+ Digits)) [lL]?; +HEX_LITERAL: '0' [xX] [0-9a-fA-F] ([0-9a-fA-F_]* [0-9a-fA-F])? [lL]?; +OCT_LITERAL: '0' '_'* [0-7] ([0-7_]* [0-7])? [lL]?; +BINARY_LITERAL: '0' [bB] [01] ([01_]* [01])? [lL]?; + +FLOAT_LITERAL: (Digits '.' Digits? | '.' Digits) ExponentPart? [fFdD]? + | Digits (ExponentPart [fFdD]? | [fFdD]) + ; + +HEX_FLOAT_LITERAL: '0' [xX] (HexDigits '.'? | HexDigits? '.' HexDigits) [pP] [+-]? Digits [fFdD]?; + +BOOL_LITERAL: 'true' + | 'false' + ; + +CHAR_LITERAL: '\'' (~['\\\r\n] | EscapeSequence) '\''; + +STRING_LITERAL: '"' (~["\\\r\n] | EscapeSequence)* '"'; + +TEXT_BLOCK: '"""' [ \t]* [\r\n] (. | EscapeSequence)*? '"""'; + +NULL_LITERAL: 'null'; + +// Separators + +LPAREN: '('; +RPAREN: ')'; +LBRACE: '{'; +RBRACE: '}'; +LBRACK: '['; +RBRACK: ']'; +SEMI: ';'; +COMMA: ','; +DOT: '.'; + +// Operators + +ASSIGN: '='; +GT: '>'; +LT: '<'; +BANG: '!'; +TILDE: '~'; +QUESTION: '?'; +COLON: ':'; +EQUAL: '=='; +LE: '<='; +GE: '>='; +NOTEQUAL: '!='; +AND: '&&'; +OR: '||'; +INC: '++'; +DEC: '--'; +ADD: '+'; +SUB: '-'; +MUL: '*'; +DIV: '/'; +BITAND: '&'; +BITOR: '|'; +CARET: '^'; +MOD: '%'; + +ADD_ASSIGN: '+='; +SUB_ASSIGN: '-='; +MUL_ASSIGN: '*='; +DIV_ASSIGN: '/='; +AND_ASSIGN: '&='; +OR_ASSIGN: '|='; +XOR_ASSIGN: '^='; +MOD_ASSIGN: '%='; +LSHIFT_ASSIGN: '<<='; +RSHIFT_ASSIGN: '>>='; +URSHIFT_ASSIGN: '>>>='; + +// Java 8 tokens + +ARROW: '->'; +COLONCOLON: '::'; + +// Additional symbols not defined in the lexical specification + +AT: '@'; +ELLIPSIS: '...'; + +// Whitespace and comments + +WS: [ \t\r\n\u000C]+ -> channel(HIDDEN); +COMMENT: '/*' .*? '*/' -> channel(HIDDEN); +LINE_COMMENT: '//' ~[\r\n]* -> channel(HIDDEN); + +// Identifiers + +IDENTIFIER: Letter LetterOrDigit*; + +// Fragment rules + +fragment ExponentPart + : [eE] [+-]? Digits + ; + +fragment EscapeSequence + : '\\' [btnfr"'\\] + | '\\' ([0-3]? [0-7])? [0-7] + | '\\' 'u'+ HexDigit HexDigit HexDigit HexDigit + ; + +fragment HexDigits + : HexDigit ((HexDigit | '_')* HexDigit)? + ; + +fragment HexDigit + : [0-9a-fA-F] + ; + +fragment Digits + : [0-9] ([0-9_]* [0-9])? + ; + +fragment LetterOrDigit + : Letter + | [0-9] + ; + +fragment Letter + : [a-zA-Z$_] // these are the "java letters" below 0x7F + | ~[\u0000-\u007F\uD800-\uDBFF] // covers all characters above 0x7F which are not a surrogate + | [\uD800-\uDBFF] [\uDC00-\uDFFF] // covers UTF-16 surrogate pairs encodings for U+10000 to U+10FFFF + ; + +TEXT : .+? ; diff --git a/drools-drl/drools-drl-parser/src/main/antlr4/org/drools/drl/parser/antlr4/JavaParser.g4 b/drools-drl/drools-drl-parser/src/main/antlr4/org/drools/drl/parser/antlr4/JavaParser.g4 new file mode 100644 index 00000000000..9e9f0a68513 --- /dev/null +++ b/drools-drl/drools-drl-parser/src/main/antlr4/org/drools/drl/parser/antlr4/JavaParser.g4 @@ -0,0 +1,752 @@ +/* + [The "BSD licence"] + Copyright (c) 2013 Terence Parr, Sam Harwell + Copyright (c) 2017 Ivan Kochurkin (upgrade to Java 8) + Copyright (c) 2021 Michał Lorek (upgrade to Java 11) + Copyright (c) 2022 Michał Lorek (upgrade to Java 17) + All rights reserved. + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions + are met: + 1. Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + 2. Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + 3. The name of the author may not be used to endorse or promote products + derived from this software without specific prior written permission. + + THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 AUTHOR 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. +*/ + +// source: https://github.com/antlr/grammars-v4/tree/master/java/java + +parser grammar JavaParser; + +options { tokenVocab=JavaLexer; } + +compilationUnit + : packageDeclaration? importDeclaration* typeDeclaration* + | moduleDeclaration EOF + ; + +packageDeclaration + : annotation* PACKAGE qualifiedName SEMI + ; + +importDeclaration + : IMPORT STATIC? qualifiedName (DOT MUL)? SEMI + ; + +typeDeclaration + : classOrInterfaceModifier* + (classDeclaration | enumDeclaration | interfaceDeclaration | annotationTypeDeclaration | recordDeclaration) + | SEMI + ; + +modifier + : classOrInterfaceModifier + | NATIVE + | SYNCHRONIZED + | TRANSIENT + | VOLATILE + ; + +classOrInterfaceModifier + : annotation + | PUBLIC + | PROTECTED + | PRIVATE + | STATIC + | ABSTRACT + | FINAL // FINAL for class only -- does not apply to interfaces + | STRICTFP + | SEALED // Java17 + | NON_SEALED // Java17 + ; + +variableModifier + : FINAL + | annotation + ; + +classDeclaration + : CLASS identifier typeParameters? + (EXTENDS typeType)? + (IMPLEMENTS typeList)? + (PERMITS typeList)? // Java17 + classBody + ; + +typeParameters + : LT typeParameter (COMMA typeParameter)* GT + ; + +typeParameter + : annotation* identifier (EXTENDS annotation* typeBound)? + ; + +typeBound + : typeType (BITAND typeType)* + ; + +enumDeclaration + : ENUM identifier (IMPLEMENTS typeList)? LBRACE enumConstants? COMMA? enumBodyDeclarations? RBRACE + ; + +enumConstants + : enumConstant (COMMA enumConstant)* + ; + +enumConstant + : annotation* identifier arguments? classBody? + ; + +enumBodyDeclarations + : SEMI classBodyDeclaration* + ; + +interfaceDeclaration + : INTERFACE identifier typeParameters? (EXTENDS typeList)? (PERMITS typeList)? interfaceBody + ; + +classBody + : LBRACE classBodyDeclaration* RBRACE + ; + +interfaceBody + : LBRACE interfaceBodyDeclaration* RBRACE + ; + +classBodyDeclaration + : SEMI + | STATIC? block + | modifier* memberDeclaration + ; + +memberDeclaration + : methodDeclaration + | genericMethodDeclaration + | fieldDeclaration + | constructorDeclaration + | genericConstructorDeclaration + | interfaceDeclaration + | annotationTypeDeclaration + | classDeclaration + | enumDeclaration + | recordDeclaration //Java17 + ; + +/* We use rule this even for void methods which cannot have [] after parameters. + This simplifies grammar and we can consider void to be a type, which + renders the [] matching as a context-sensitive issue or a semantic check + for invalid return type after parsing. + */ +methodDeclaration + : typeTypeOrVoid identifier formalParameters (LBRACK RBRACK)* + (THROWS qualifiedNameList)? + methodBody + ; + +methodBody + : block + | SEMI + ; + +typeTypeOrVoid + : typeType + | VOID + ; + +genericMethodDeclaration + : typeParameters methodDeclaration + ; + +genericConstructorDeclaration + : typeParameters constructorDeclaration + ; + +constructorDeclaration + : identifier formalParameters (THROWS qualifiedNameList)? constructorBody=block + ; + +fieldDeclaration + : typeType variableDeclarators SEMI + ; + +interfaceBodyDeclaration + : modifier* interfaceMemberDeclaration + | SEMI + ; + +interfaceMemberDeclaration + : constDeclaration + | interfaceMethodDeclaration + | genericInterfaceMethodDeclaration + | interfaceDeclaration + | annotationTypeDeclaration + | classDeclaration + | enumDeclaration + | recordDeclaration // Java17 + ; + +constDeclaration + : typeType constantDeclarator (COMMA constantDeclarator)* SEMI + ; + +constantDeclarator + : identifier (LBRACK RBRACK)* ASSIGN variableInitializer + ; + +// Early versions of Java allows brackets after the method name, eg. +// public int[] return2DArray() [] { ... } +// is the same as +// public int[][] return2DArray() { ... } +interfaceMethodDeclaration + : interfaceMethodModifier* interfaceCommonBodyDeclaration + ; + +// Java8 +interfaceMethodModifier + : annotation + | PUBLIC + | ABSTRACT + | DEFAULT + | STATIC + | STRICTFP + ; + +genericInterfaceMethodDeclaration + : interfaceMethodModifier* typeParameters interfaceCommonBodyDeclaration + ; + +interfaceCommonBodyDeclaration + : annotation* typeTypeOrVoid identifier formalParameters (LBRACK RBRACK)* (THROWS qualifiedNameList)? methodBody + ; + +variableDeclarators + : variableDeclarator (COMMA variableDeclarator)* + ; + +variableDeclarator + : variableDeclaratorId (ASSIGN variableInitializer)? + ; + +variableDeclaratorId + : identifier (LBRACK RBRACK)* + ; + +variableInitializer + : arrayInitializer + | expression + ; + +arrayInitializer + : LBRACE (variableInitializer (COMMA variableInitializer)* (COMMA)? )? RBRACE + ; + +classOrInterfaceType + : identifier typeArguments? (DOT identifier typeArguments?)* + ; + +typeArgument + : typeType + | annotation* QUESTION ((EXTENDS | SUPER) typeType)? + ; + +qualifiedNameList + : qualifiedName (COMMA qualifiedName)* + ; + +formalParameters + : LPAREN ( receiverParameter? + | receiverParameter (COMMA formalParameterList)? + | formalParameterList? + ) RPAREN + ; + +receiverParameter + : typeType (identifier DOT)* THIS + ; + +formalParameterList + : formalParameter (COMMA formalParameter)* (COMMA lastFormalParameter)? + | lastFormalParameter + ; + +formalParameter + : variableModifier* typeType variableDeclaratorId + ; + +lastFormalParameter + : variableModifier* typeType annotation* ELLIPSIS variableDeclaratorId + ; + +// local variable type inference +lambdaLVTIList + : lambdaLVTIParameter (COMMA lambdaLVTIParameter)* + ; + +lambdaLVTIParameter + : variableModifier* VAR identifier + ; + +qualifiedName + : identifier (DOT identifier)* + ; + +literal + : integerLiteral + | floatLiteral + | CHAR_LITERAL + | STRING_LITERAL + | BOOL_LITERAL + | NULL_LITERAL + | TEXT_BLOCK // Java17 + ; + +integerLiteral + : DECIMAL_LITERAL + | HEX_LITERAL + | OCT_LITERAL + | BINARY_LITERAL + ; + +floatLiteral + : FLOAT_LITERAL + | HEX_FLOAT_LITERAL + ; + +// ANNOTATIONS +altAnnotationQualifiedName + : (identifier DOT)* AT identifier + ; + +annotation + : (AT qualifiedName | altAnnotationQualifiedName) (LPAREN ( elementValuePairs | elementValue )? RPAREN)? + ; + +elementValuePairs + : elementValuePair (COMMA elementValuePair)* + ; + +elementValuePair + : identifier ASSIGN elementValue + ; + +elementValue + : expression + | annotation + | elementValueArrayInitializer + ; + +elementValueArrayInitializer + : LBRACE (elementValue (COMMA elementValue)*)? (COMMA)? RBRACE + ; + +annotationTypeDeclaration + : AT INTERFACE identifier annotationTypeBody + ; + +annotationTypeBody + : LBRACE (annotationTypeElementDeclaration)* RBRACE + ; + +annotationTypeElementDeclaration + : modifier* annotationTypeElementRest + | SEMI // this is not allowed by the grammar, but apparently allowed by the actual compiler + ; + +annotationTypeElementRest + : typeType annotationMethodOrConstantRest SEMI + | classDeclaration SEMI? + | interfaceDeclaration SEMI? + | enumDeclaration SEMI? + | annotationTypeDeclaration SEMI? + | recordDeclaration SEMI? // Java17 + ; + +annotationMethodOrConstantRest + : annotationMethodRest + | annotationConstantRest + ; + +annotationMethodRest + : identifier LPAREN RPAREN defaultValue? + ; + +annotationConstantRest + : variableDeclarators + ; + +defaultValue + : DEFAULT elementValue + ; + +// MODULES - Java9 + +moduleDeclaration + : OPEN? MODULE qualifiedName moduleBody + ; + +moduleBody + : LBRACE moduleDirective* RBRACE + ; + +moduleDirective + : REQUIRES requiresModifier* qualifiedName SEMI + | EXPORTS qualifiedName (TO qualifiedName)? SEMI + | OPENS qualifiedName (TO qualifiedName)? SEMI + | USES qualifiedName SEMI + | PROVIDES qualifiedName WITH qualifiedName SEMI + ; + +requiresModifier + : TRANSITIVE + | STATIC + ; + +// RECORDS - Java 17 + +recordDeclaration + : RECORD identifier typeParameters? recordHeader + (IMPLEMENTS typeList)? + recordBody + ; + +recordHeader + : LPAREN recordComponentList? RPAREN + ; + +recordComponentList + : recordComponent (COMMA recordComponent)* + ; + +recordComponent + : typeType identifier + ; + +recordBody + : LBRACE classBodyDeclaration* RBRACE + ; + +// STATEMENTS / BLOCKS + +block + : LBRACE blockStatement* RBRACE + ; + +blockStatement + : localVariableDeclaration SEMI + | statement + | localTypeDeclaration + ; + +localVariableDeclaration + : variableModifier* (typeType variableDeclarators | VAR identifier ASSIGN expression) + ; + +identifier + : IDENTIFIER + | MODULE + | OPEN + | REQUIRES + | EXPORTS + | OPENS + | TO + | USES + | PROVIDES + | WITH + | TRANSITIVE + | YIELD + | SEALED + | PERMITS + | RECORD + | VAR + ; + +localTypeDeclaration + : classOrInterfaceModifier* + (classDeclaration | interfaceDeclaration | recordDeclaration) + | SEMI + ; + +statement + : blockLabel=block + | ASSERT expression (COLON expression)? SEMI + | IF parExpression statement (ELSE statement)? + | FOR LPAREN forControl RPAREN statement + | WHILE parExpression statement + | DO statement WHILE parExpression SEMI + | TRY block (catchClause+ finallyBlock? | finallyBlock) + | TRY resourceSpecification block catchClause* finallyBlock? + | SWITCH parExpression LBRACE switchBlockStatementGroup* switchLabel* RBRACE + | SYNCHRONIZED parExpression block + | RETURN expression? SEMI + | THROW expression SEMI + | BREAK identifier? SEMI + | CONTINUE identifier? SEMI + | YIELD expression SEMI // Java17 + | SEMI + | statementExpression=expression SEMI + | switchExpression SEMI? // Java17 + | identifierLabel=identifier COLON statement + ; + +catchClause + : CATCH LPAREN variableModifier* catchType identifier RPAREN block + ; + +catchType + : qualifiedName (BITOR qualifiedName)* + ; + +finallyBlock + : FINALLY block + ; + +resourceSpecification + : LPAREN resources SEMI? RPAREN + ; + +resources + : resource (SEMI resource)* + ; + +resource + : variableModifier* ( classOrInterfaceType variableDeclaratorId | VAR identifier ) ASSIGN expression + | identifier + ; + +/** Matches cases then statements, both of which are mandatory. + * To handle empty cases at the end, we add switchLabel* to statement. + */ +switchBlockStatementGroup + : switchLabel+ blockStatement+ + ; + +switchLabel + : CASE (constantExpression=expression | enumConstantName=IDENTIFIER | typeType varName=identifier) COLON + | DEFAULT COLON + ; + +forControl + : enhancedForControl + | forInit? SEMI expression? SEMI forUpdate=expressionList? + ; + +forInit + : localVariableDeclaration + | expressionList + ; + +enhancedForControl + : variableModifier* (typeType | VAR) variableDeclaratorId COLON expression + ; + +// EXPRESSIONS + +parExpression + : LPAREN expression RPAREN + ; + +expressionList + : expression (COMMA expression)* + ; + +methodCall + : identifier LPAREN expressionList? RPAREN + | THIS LPAREN expressionList? RPAREN + | SUPER LPAREN expressionList? RPAREN + ; + +expression + : primary + | expression bop=DOT + ( + identifier + | methodCall + | THIS + | NEW nonWildcardTypeArguments? innerCreator + | SUPER superSuffix + | explicitGenericInvocation + ) + | expression LBRACK expression RBRACK + | methodCall + | NEW creator + | LPAREN annotation* typeType (BITAND typeType)* RPAREN expression + | expression postfix=(INC | DEC) + | prefix=(ADD|SUB|INC|DEC) expression + | prefix=(TILDE|BANG) expression + | expression bop=(MUL|DIV|MOD) expression + | expression bop=(ADD|SUB) expression + | expression (LT LT | GT GT GT | GT GT) expression + | expression bop=(LE | GE | GT | LT) expression + | expression bop=INSTANCEOF (typeType | pattern) + | expression bop=(EQUAL | NOTEQUAL) expression + | expression bop=BITAND expression + | expression bop=CARET expression + | expression bop=BITOR expression + | expression bop=AND expression + | expression bop=OR expression + | expression bop=QUESTION expression COLON expression + | expression + bop=(ASSIGN | ADD_ASSIGN | SUB_ASSIGN | MUL_ASSIGN | DIV_ASSIGN | AND_ASSIGN | OR_ASSIGN | XOR_ASSIGN | RSHIFT_ASSIGN | URSHIFT_ASSIGN | LSHIFT_ASSIGN | MOD_ASSIGN) + expression + | lambdaExpression // Java8 + | switchExpression // Java17 + + // Java 8 methodReference + | expression COLONCOLON typeArguments? identifier + | typeType COLONCOLON (typeArguments? identifier | NEW) + | classType COLONCOLON typeArguments? NEW + ; + +// Java17 +pattern + : variableModifier* typeType annotation* identifier + ; + +// Java8 +lambdaExpression + : lambdaParameters ARROW lambdaBody + ; + +// Java8 +lambdaParameters + : identifier + | LPAREN formalParameterList? RPAREN + | LPAREN identifier (COMMA identifier)* RPAREN + | LPAREN lambdaLVTIList? RPAREN + ; + +// Java8 +lambdaBody + : expression + | block + ; + +primary + : LPAREN expression RPAREN + | THIS + | SUPER + | literal + | identifier + | typeTypeOrVoid DOT CLASS + | nonWildcardTypeArguments (explicitGenericInvocationSuffix | THIS arguments) + ; + +// Java17 +switchExpression + : SWITCH parExpression LBRACE switchLabeledRule* RBRACE + ; + +// Java17 +switchLabeledRule + : CASE (expressionList | NULL_LITERAL | guardedPattern) (ARROW | COLON) switchRuleOutcome + | DEFAULT (ARROW | COLON) switchRuleOutcome + ; + +// Java17 +guardedPattern + : LPAREN guardedPattern RPAREN + | variableModifier* typeType annotation* identifier (AND expression)* + | guardedPattern AND expression + ; + +// Java17 +switchRuleOutcome + : block + | blockStatement* + ; + +classType + : (classOrInterfaceType DOT)? annotation* identifier typeArguments? + ; + +creator + : nonWildcardTypeArguments createdName classCreatorRest + | createdName (arrayCreatorRest | classCreatorRest) + ; + +createdName + : identifier typeArgumentsOrDiamond? (DOT identifier typeArgumentsOrDiamond?)* + | primitiveType + ; + +innerCreator + : identifier nonWildcardTypeArgumentsOrDiamond? classCreatorRest + ; + +arrayCreatorRest + : LBRACK (RBRACK (LBRACK RBRACK)* arrayInitializer | expression RBRACK (LBRACK expression RBRACK)* (LBRACK RBRACK)*) + ; + +classCreatorRest + : arguments classBody? + ; + +explicitGenericInvocation + : nonWildcardTypeArguments explicitGenericInvocationSuffix + ; + +typeArgumentsOrDiamond + : LT GT + | typeArguments + ; + +nonWildcardTypeArgumentsOrDiamond + : LT GT + | nonWildcardTypeArguments + ; + +nonWildcardTypeArguments + : LT typeList GT + ; + +typeList + : typeType (COMMA typeType)* + ; + +typeType + : annotation* (classOrInterfaceType | primitiveType) (annotation* LBRACK RBRACK)* + ; + +primitiveType + : BOOLEAN + | CHAR + | BYTE + | SHORT + | INT + | LONG + | FLOAT + | DOUBLE + ; + +typeArguments + : LT typeArgument (COMMA typeArgument)* GT + ; + +superSuffix + : arguments + | DOT typeArguments? identifier arguments? + ; + +explicitGenericInvocationSuffix + : SUPER superSuffix + | identifier arguments + ; + +arguments + : LPAREN expressionList? RPAREN + ; \ No newline at end of file diff --git a/drools-drl/drools-drl-parser/src/main/java/org/drools/drl/parser/Drl6ExprParser.java b/drools-drl/drools-drl-parser/src/main/java/org/drools/drl/parser/Drl6ExprParser.java new file mode 100644 index 00000000000..9fb0186afb7 --- /dev/null +++ b/drools-drl/drools-drl-parser/src/main/java/org/drools/drl/parser/Drl6ExprParser.java @@ -0,0 +1,90 @@ +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you 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 + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.drools.drl.parser; + +import java.util.Collections; +import java.util.List; + +import org.antlr.runtime.ANTLRStringStream; +import org.antlr.runtime.CommonTokenStream; +import org.antlr.runtime.RecognitionException; +import org.antlr.runtime.RecognizerSharedState; +import org.drools.drl.ast.descr.BaseDescr; +import org.drools.drl.ast.descr.ConstraintConnectiveDescr; +import org.drools.drl.parser.lang.DRLExpressions; +import org.drools.drl.parser.lang.DRLLexer; +import org.drools.drl.parser.lang.ParserHelper; +import org.kie.internal.builder.conf.LanguageLevelOption; + +/** + * This is a helper class that provides helper methods to parse expressions + * using both the DRLExpressions parser and the DRLExprTree parser. + */ +public class Drl6ExprParser implements DrlExprParser { + + private ParserHelper helper = null; + + private final LanguageLevelOption languageLevel; + + public Drl6ExprParser(LanguageLevelOption languageLevel) { + this.languageLevel = languageLevel; + } + + /** Parse an expression from text */ + public ConstraintConnectiveDescr parse( final String text ) { + ConstraintConnectiveDescr constraint = null; + try { + DRLLexer lexer = DRLFactory.getDRLLexer(new ANTLRStringStream(text), languageLevel); + CommonTokenStream input = new CommonTokenStream( lexer ); + RecognizerSharedState state = new RecognizerSharedState(); + helper = new ParserHelper( input, state, languageLevel ); + DRLExpressions parser = DRLFactory.getDRLExpressions(input, state, helper, languageLevel); + parser.setBuildDescr( true ); + parser.setLeftMostExpr( null ); // setting initial value just in case + BaseDescr expr = parser.conditionalOrExpression(); + if ( expr != null && !parser.hasErrors() ) { + constraint = ConstraintConnectiveDescr.newAnd(); + constraint.addOrMerge( expr ); + } + } catch ( RecognitionException e ) { + helper.reportError( e ); + } + return constraint; + } + + public String getLeftMostExpr() { + return helper != null ? helper.getLeftMostExpr() : null; + } + + /** + * @return true if there were parser errors. + */ + public boolean hasErrors() { + return helper != null && helper.hasErrors(); + } + + /** + * @return a list of errors found while parsing. + */ + @SuppressWarnings("unchecked") + public List getErrors() { + return helper != null ? helper.getErrors() : Collections.EMPTY_LIST; + } + +} diff --git a/drools-drl/drools-drl-parser/src/main/java/org/drools/drl/parser/DrlExprParser.java b/drools-drl/drools-drl-parser/src/main/java/org/drools/drl/parser/DrlExprParser.java index 60c61ac248d..0702a1d1461 100644 --- a/drools-drl/drools-drl-parser/src/main/java/org/drools/drl/parser/DrlExprParser.java +++ b/drools-drl/drools-drl-parser/src/main/java/org/drools/drl/parser/DrlExprParser.java @@ -18,73 +18,29 @@ */ package org.drools.drl.parser; -import java.util.Collections; import java.util.List; -import org.antlr.runtime.ANTLRStringStream; -import org.antlr.runtime.CommonTokenStream; -import org.antlr.runtime.RecognitionException; -import org.antlr.runtime.RecognizerSharedState; -import org.drools.drl.parser.lang.DRLExpressions; -import org.drools.drl.parser.lang.DRLLexer; -import org.drools.drl.parser.lang.ParserHelper; -import org.drools.drl.ast.descr.BaseDescr; import org.drools.drl.ast.descr.ConstraintConnectiveDescr; -import org.kie.internal.builder.conf.LanguageLevelOption; /** * This is a helper class that provides helper methods to parse expressions * using both the DRLExpressions parser and the DRLExprTree parser. */ -public class DrlExprParser { - - private ParserHelper helper = null; - - private final LanguageLevelOption languageLevel; - - public DrlExprParser(LanguageLevelOption languageLevel) { - this.languageLevel = languageLevel; - } +public interface DrlExprParser { /** Parse an expression from text */ - public ConstraintConnectiveDescr parse( final String text ) { - ConstraintConnectiveDescr constraint = null; - try { - DRLLexer lexer = DRLFactory.getDRLLexer(new ANTLRStringStream(text), languageLevel); - CommonTokenStream input = new CommonTokenStream( lexer ); - RecognizerSharedState state = new RecognizerSharedState(); - helper = new ParserHelper( input, state, languageLevel ); - DRLExpressions parser = DRLFactory.getDRLExpressions(input, state, helper, languageLevel); - parser.setBuildDescr( true ); - parser.setLeftMostExpr( null ); // setting initial value just in case - BaseDescr expr = parser.conditionalOrExpression(); - if ( expr != null && !parser.hasErrors() ) { - constraint = ConstraintConnectiveDescr.newAnd(); - constraint.addOrMerge( expr ); - } - } catch ( RecognitionException e ) { - helper.reportError( e ); - } - return constraint; - } - - public String getLeftMostExpr() { - return helper != null ? helper.getLeftMostExpr() : null; - } + ConstraintConnectiveDescr parse( final String text ); + + String getLeftMostExpr(); /** * @return true if there were parser errors. */ - public boolean hasErrors() { - return helper != null && helper.hasErrors(); - } + boolean hasErrors(); /** * @return a list of errors found while parsing. */ @SuppressWarnings("unchecked") - public List getErrors() { - return helper != null ? helper.getErrors() : Collections.EMPTY_LIST; - } - + List getErrors(); } diff --git a/drools-drl/drools-drl-parser/src/main/java/org/drools/drl/parser/DrlExprParserFactory.java b/drools-drl/drools-drl-parser/src/main/java/org/drools/drl/parser/DrlExprParserFactory.java new file mode 100644 index 00000000000..4ddbf289705 --- /dev/null +++ b/drools-drl/drools-drl-parser/src/main/java/org/drools/drl/parser/DrlExprParserFactory.java @@ -0,0 +1,36 @@ +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you 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 + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.drools.drl.parser; + +import org.drools.drl.parser.antlr4.Drl6ExprParserAntlr4; +import org.kie.internal.builder.conf.LanguageLevelOption; + +public class DrlExprParserFactory { + + public static DrlExprParser getDrlExprParser(LanguageLevelOption languageLevel) { + switch (languageLevel) { + case DRL5: + case DRL6: + case DRL6_STRICT: + return DrlParser.ANTLR4_PARSER_ENABLED ? new Drl6ExprParserAntlr4(languageLevel) : new Drl6ExprParser(languageLevel); + default: + throw new RuntimeException("Unsupported language level: " + languageLevel); + } + } +} diff --git a/drools-drl/drools-drl-parser/src/main/java/org/drools/drl/parser/DrlParser.java b/drools-drl/drools-drl-parser/src/main/java/org/drools/drl/parser/DrlParser.java index 7b852c8dce3..714fd8a21c6 100644 --- a/drools-drl/drools-drl-parser/src/main/java/org/drools/drl/parser/DrlParser.java +++ b/drools-drl/drools-drl-parser/src/main/java/org/drools/drl/parser/DrlParser.java @@ -18,6 +18,8 @@ */ package org.drools.drl.parser; +import org.drools.drl.parser.antlr4.DRLParserError; +import org.drools.drl.parser.antlr4.DRLParserWrapper; import org.drools.io.InternalResource; import org.drools.drl.ast.descr.PackageDescr; import org.drools.drl.parser.lang.DRLLexer; @@ -35,9 +37,11 @@ import java.io.IOException; import java.io.InputStream; import java.io.Reader; +import java.io.StringReader; import java.util.ArrayList; import java.util.Arrays; import java.util.List; +import java.util.function.Function; /** * This is a low level parser API. This will return textual AST representations @@ -49,12 +53,18 @@ public class DrlParser { // TODO: REMOVE THIS GENERIC MESSAGE ASAP private static final String GENERIC_ERROR_MESSAGE = "Unexpected exception raised while parsing. This is a bug. Please contact the Development team :\n"; + private static final String DEBUG_PARSER_LOG = "parse : ANTLR4_PARSER_ENABLED = {}"; private final List results = new ArrayList<>(); private List editorSentences = null; private Location location = new Location( Location.LOCATION_UNKNOWN ); private DRLLexer lexer = null; private Resource resource = null; + public static final String ANTLR4_PARSER_ENABLED_PROPERTY = "drools.drl.antlr4.parser.enabled"; + + // temporarily removed 'final' for testing purposes. This should be final when the feature gets stable + public static boolean ANTLR4_PARSER_ENABLED = Boolean.parseBoolean(System.getProperty(ANTLR4_PARSER_ENABLED_PROPERTY, "false")); // default is false + public static final LanguageLevelOption DEFAULT_LANGUAGE_LEVEL = LanguageLevelOption.DRL6; private final LanguageLevelOption languageLevel; @@ -74,16 +84,28 @@ public PackageDescr parse(final Resource resource, final String text) throws Dro public PackageDescr parse(final boolean isEditor, final String text) throws DroolsParserException { - lexer = DRLFactory.buildLexer(text, languageLevel); - DRLParser parser = DRLFactory.buildParser(lexer, languageLevel); - return compile(isEditor, parser); + LOG.debug(DEBUG_PARSER_LOG, ANTLR4_PARSER_ENABLED); + if (ANTLR4_PARSER_ENABLED) { + // new parser based on antlr4 + return compileWithAntlr4Parser(parser -> parser.parse(new StringReader(text))); + } else { + lexer = DRLFactory.buildLexer(text, languageLevel); + DRLParser parser = DRLFactory.buildParser(lexer, languageLevel); + return compile(isEditor, parser); + } } public PackageDescr parse(final boolean isEditor, final Reader reader) throws DroolsParserException { - lexer = DRLFactory.buildLexer(reader, languageLevel); - DRLParser parser = DRLFactory.buildParser( lexer, languageLevel ); - return compile(isEditor, parser); + LOG.debug(DEBUG_PARSER_LOG, ANTLR4_PARSER_ENABLED); + if (ANTLR4_PARSER_ENABLED) { + // new parser based on antlr4 + return compileWithAntlr4Parser(parser -> parser.parse(reader)); + } else { + lexer = DRLFactory.buildLexer(reader, languageLevel); + DRLParser parser = DRLFactory.buildParser(lexer, languageLevel); + return compile(isEditor, parser); + } } public PackageDescr parse(final Resource resource, final Reader reader) throws DroolsParserException { @@ -164,10 +186,40 @@ public PackageDescr parse(final boolean isEditor, final InputStream is) throws DroolsParserException, IOException { this.resource = resource; String encoding = resource instanceof InternalResource ? ((InternalResource) resource).getEncoding() : null; + LOG.debug(DEBUG_PARSER_LOG, ANTLR4_PARSER_ENABLED); + if (ANTLR4_PARSER_ENABLED) { + // new parser based on antlr4 + return compileWithAntlr4Parser(parser -> parser.parse(is, encoding)); + } else { + // old parsers based on antlr3 + lexer = DRLFactory.buildLexer(is, encoding, languageLevel); + DRLParser parser = DRLFactory.buildParser(lexer, languageLevel); + return compile(isEditor, parser); + } + } - lexer = DRLFactory.buildLexer(is, encoding, languageLevel); - DRLParser parser = DRLFactory.buildParser(lexer, languageLevel); - return compile(isEditor, parser); + private PackageDescr compileWithAntlr4Parser(Function packageDescrFunction) throws DroolsParserException { + try { + // we don't use languageLevel here, assuming DRL6 compatible + DRLParserWrapper parser = new DRLParserWrapper(resource); + PackageDescr packageDescr = packageDescrFunction.apply(parser); + for (final DRLParserError drlParserError : parser.getErrors()) { + final ParserError err = new ParserError(resource, + drlParserError.getMessage(), + drlParserError.getLineNumber(), + drlParserError.getColumn()); + this.results.add(err); + } + return !this.hasErrors() ? packageDescr : null; + } catch (Exception e) { + LOG.error("Exception", e); + final ParserError err = new ParserError(resource, + GENERIC_ERROR_MESSAGE + e.toString() + "\n" + Arrays.toString(e.getStackTrace()), + -1, + 0); + this.results.add(err); + throw new DroolsParserException(GENERIC_ERROR_MESSAGE + e.getMessage(), e); + } } /** diff --git a/drools-drl/drools-drl-parser/src/main/java/org/drools/drl/parser/antlr4/Antlr4ParserStringUtils.java b/drools-drl/drools-drl-parser/src/main/java/org/drools/drl/parser/antlr4/Antlr4ParserStringUtils.java new file mode 100644 index 00000000000..74fb54c2c4c --- /dev/null +++ b/drools-drl/drools-drl-parser/src/main/java/org/drools/drl/parser/antlr4/Antlr4ParserStringUtils.java @@ -0,0 +1,88 @@ +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you 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 + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.drools.drl.parser.antlr4; + +import java.util.List; +import java.util.stream.Collectors; + +import org.antlr.v4.runtime.ParserRuleContext; +import org.antlr.v4.runtime.TokenStream; +import org.antlr.v4.runtime.misc.Interval; + +/** + * Collection of String utilities used by antlr4 DRLParser. + */ +public class Antlr4ParserStringUtils { + + private Antlr4ParserStringUtils() { + // Private constructor to prevent instantiation. + } + + /** + * Get text from ParserRuleContext's CharStream without trimming whitespace + */ + public static String getTextPreservingWhitespace(ParserRuleContext ctx) { + if (ctx == null) { + return ""; + } + // Using raw CharStream + int startIndex = ctx.start.getStartIndex(); + int stopIndex = ctx.stop.getStopIndex(); + if (startIndex > stopIndex) { + // no text + return ""; + } + Interval interval = new Interval(startIndex, stopIndex); + return ctx.start.getTokenSource().getInputStream().getText(interval); + } + + /** + * Get text from List of ParserRuleContext's CharStream without trimming whitespace + */ + public static String getTextPreservingWhitespace(List ctx) { + if (ctx == null) { + return ""; + } + return ctx.stream().map(Antlr4ParserStringUtils::getTextPreservingWhitespace).collect(Collectors.joining()); + } + + /** + * Get text from ParserRuleContext's CharStream without trimming whitespace + * tokenStream is required to get hidden channel token (e.g. whitespace). + * Unlike getTextPreservingWhitespace, this method reflects Lexer normalizeString + */ + public static String getTokenTextPreservingWhitespace(ParserRuleContext ctx, TokenStream tokenStream) { + if (ctx == null) { + return ""; + } + return tokenStream.getText(ctx.start, ctx.stop); + } + + /** + * Extract name from "then[name]" of RHS_NAMED_CONSEQUENCE_THEN + */ + public static String extractNamedConsequenceName(String namedConsequenceThen) { + if (namedConsequenceThen.toLowerCase().startsWith("then[") && namedConsequenceThen.endsWith("]")) { + return namedConsequenceThen.substring("then[".length(), namedConsequenceThen.length() - 1); + } else { + throw new DRLParserException("namedConsequenceThen has to be surrounded by 'then[', ']' : " + namedConsequenceThen); + } + } + +} diff --git a/drools-drl/drools-drl-parser/src/main/java/org/drools/drl/parser/antlr4/BaseDescrFactory.java b/drools-drl/drools-drl-parser/src/main/java/org/drools/drl/parser/antlr4/BaseDescrFactory.java new file mode 100644 index 00000000000..f48db5926b8 --- /dev/null +++ b/drools-drl/drools-drl-parser/src/main/java/org/drools/drl/parser/antlr4/BaseDescrFactory.java @@ -0,0 +1,66 @@ +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you 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 + *

+ * http://www.apache.org/licenses/LICENSE-2.0 + *

+ * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.drools.drl.parser.antlr4; + +import org.antlr.v4.runtime.ParserRuleContext; +import org.drools.drl.ast.descr.BaseDescr; +import org.kie.api.io.Resource; + +import static org.drools.drl.parser.antlr4.DescrHelper.populateCommonProperties; + +/** + * Factory class for Descr instantiation. + */ +public class BaseDescrFactory { + + private BaseDescrFactory() { + // Private constructor to prevent instantiation. + } + + public static Builder builder(T toBuild) { + return new Builder<>(toBuild); + } + + public static class Builder { + + T toReturn; + + private Builder(T toBuild) { + this.toReturn = toBuild; + } + + /** + * Initializes a BaseDescr instance with common properties from the given context. + * DRLVisitor implementations should always use this method to initialize BaseDescr instances. + */ + public Builder withParserRuleContext(ParserRuleContext ctx) { + populateCommonProperties(toReturn, ctx); + return this; + } + + public Builder withResource(Resource resource) { + toReturn.setResource(resource); + return this; + } + + public T build() { + return toReturn; + } + } +} diff --git a/drools-drl/drools-drl-parser/src/main/java/org/drools/drl/parser/antlr4/DRLErrorListener.java b/drools-drl/drools-drl-parser/src/main/java/org/drools/drl/parser/antlr4/DRLErrorListener.java new file mode 100644 index 00000000000..00f9c4bc48f --- /dev/null +++ b/drools-drl/drools-drl-parser/src/main/java/org/drools/drl/parser/antlr4/DRLErrorListener.java @@ -0,0 +1,49 @@ +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you 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 + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.drools.drl.parser.antlr4; + +import java.util.ArrayList; +import java.util.List; + +import org.antlr.v4.runtime.BaseErrorListener; +import org.antlr.v4.runtime.RecognitionException; +import org.antlr.v4.runtime.Recognizer; + +/** + * Collect errors while parsing DRL + */ +public class DRLErrorListener extends BaseErrorListener { + + private final List errors = new ArrayList<>(); + + public List getErrors() { + return errors; + } + + @Override + public void syntaxError(Recognizer recognizer, + Object offendingSymbol, + int line, + int charPositionInLine, + String msg, + RecognitionException e) { + + errors.add(new DRLParserError(line, charPositionInLine, msg)); + } +} diff --git a/drools-drl/drools-drl-parser/src/main/java/org/drools/drl/parser/antlr4/DRLExpressions.java b/drools-drl/drools-drl-parser/src/main/java/org/drools/drl/parser/antlr4/DRLExpressions.java new file mode 100644 index 00000000000..4c057189a15 --- /dev/null +++ b/drools-drl/drools-drl-parser/src/main/java/org/drools/drl/parser/antlr4/DRLExpressions.java @@ -0,0 +1,61 @@ +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you 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 + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.drools.drl.parser.antlr4; + +import java.util.LinkedList; +import java.util.List; + +import org.antlr.v4.runtime.Parser; +import org.antlr.v4.runtime.RecognitionException; +import org.antlr.v4.runtime.TokenStream; +import org.drools.drl.ast.descr.BaseDescr; +import org.drools.drl.parser.DroolsParserException; +import org.drools.drl.parser.lang.DroolsSentence; + +public abstract class DRLExpressions extends Parser { + public DRLExpressions(TokenStream input) { + super(input); + } + + public abstract void setBuildDescr( boolean build ); + public abstract boolean isBuildDescr(); + + public abstract void setLeftMostExpr( String value ); + public abstract String getLeftMostExpr(); + + public abstract void setHasBindings( boolean value ); + public abstract boolean hasBindings(); + + /* + * This is the original method signature in drools/drools-drl/drools-drl-parser: + * public abstract BaseDescr conditionalOrExpression() throws RecognitionException; + * I changed it here because the conditionalOrExpression() method generated by ANTLR 4 from the conditionalOrExpression rule + * returns ConditionalOrExpressionContext, so it has a return type that's different from what was originally expected here. + * The Descr object is of course inside that context (go to this method's impl to see). + */ + public abstract BaseDescr conditionalOrExpressionDescr() throws RecognitionException; + + public abstract ParserHelper getHelper(); + public abstract boolean hasErrors(); + public abstract List getErrors(); + public abstract List getErrorMessages(); + public abstract void enableEditorInterface(); + public abstract void disableEditorInterface(); + public abstract LinkedList getEditorInterface(); +} diff --git a/drools-drl/drools-drl-parser/src/main/java/org/drools/drl/parser/antlr4/DRLParserError.java b/drools-drl/drools-drl-parser/src/main/java/org/drools/drl/parser/antlr4/DRLParserError.java new file mode 100644 index 00000000000..e07eef4a491 --- /dev/null +++ b/drools-drl/drools-drl-parser/src/main/java/org/drools/drl/parser/antlr4/DRLParserError.java @@ -0,0 +1,76 @@ +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you 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 + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.drools.drl.parser.antlr4; + +/** + * Error information while parsing DRL + */ +public class DRLParserError { + + private int lineNumber; + private int column; + private String message; + + private Exception exception; + + public DRLParserError(int lineNumber, int column, String message) { + this.lineNumber = lineNumber; + this.column = column; + this.message = message; + } + + public DRLParserError(Exception exception) { + this.message = exception.getMessage(); + this.exception = exception; + } + + public int getLineNumber() { + return lineNumber; + } + + public void setLineNumber(int lineNumber) { + this.lineNumber = lineNumber; + } + + public int getColumn() { + return column; + } + + public void setColumn(int column) { + this.column = column; + } + + public String getMessage() { + return message; + } + + public void setMessage(String message) { + this.message = message; + } + + @Override + public String toString() { + return "DRLParserError{" + + "lineNumber=" + lineNumber + + ", column=" + column + + ", message='" + message + '\'' + + ", exception=" + exception + + '}'; + } +} diff --git a/drools-drl/drools-drl-parser/src/main/java/org/drools/drl/parser/antlr4/DRLParserException.java b/drools-drl/drools-drl-parser/src/main/java/org/drools/drl/parser/antlr4/DRLParserException.java new file mode 100644 index 00000000000..79bd114d997 --- /dev/null +++ b/drools-drl/drools-drl-parser/src/main/java/org/drools/drl/parser/antlr4/DRLParserException.java @@ -0,0 +1,30 @@ +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you 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 + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.drools.drl.parser.antlr4; + +public class DRLParserException extends RuntimeException { + + public DRLParserException() { + super(); + } + + public DRLParserException(String message) { + super(message); + } +} diff --git a/drools-drl/drools-drl-parser/src/main/java/org/drools/drl/parser/antlr4/DRLParserHelper.java b/drools-drl/drools-drl-parser/src/main/java/org/drools/drl/parser/antlr4/DRLParserHelper.java new file mode 100644 index 00000000000..131145b2d75 --- /dev/null +++ b/drools-drl/drools-drl-parser/src/main/java/org/drools/drl/parser/antlr4/DRLParserHelper.java @@ -0,0 +1,144 @@ +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you 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 + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.drools.drl.parser.antlr4; + +import java.io.IOException; +import java.io.InputStream; +import java.io.Reader; +import java.io.UncheckedIOException; +import java.nio.charset.Charset; + +import org.antlr.v4.runtime.CharStream; +import org.antlr.v4.runtime.CharStreams; +import org.antlr.v4.runtime.CommonTokenStream; +import org.antlr.v4.runtime.Token; +import org.antlr.v4.runtime.TokenStream; +import org.antlr.v4.runtime.tree.ErrorNode; +import org.antlr.v4.runtime.tree.ParseTree; +import org.antlr.v4.runtime.tree.TerminalNode; +import org.drools.drl.ast.descr.PackageDescr; +import org.kie.api.io.Resource; +import org.kie.internal.builder.conf.LanguageLevelOption; + +/** + * Collection of static helper methods for DRLParser + */ +public class DRLParserHelper { + + private DRLParserHelper() { + } + + /** + * Entry point for parsing DRL. + * Unlike DRLParserWrapper.parse(), this method does not collect errors. + */ + public static PackageDescr parse(String drl) { + DRLParser drlParser = createDrlParser(drl); + return compilationUnitContext2PackageDescr(drlParser.compilationUnit(), drlParser.getTokenStream(), null); + } + + public static DRLParser createDrlParser(String drl) { + CharStream charStream = CharStreams.fromString(drl); + return createDrlParser(charStream); + } + + public static DRLParser createDrlParser(InputStream is, String encoding) { + try { + CharStream charStream = encoding != null + ? CharStreams.fromStream(is, Charset.forName(encoding)) + : CharStreams.fromStream(is); + return createDrlParser(charStream); + } catch (IOException e) { + throw new UncheckedIOException(e); + } + } + + public static DRLParser createDrlParser(Reader reader) { + try { + CharStream charStream = CharStreams.fromReader(reader); + return createDrlParser(charStream); + } catch (IOException e) { + throw new UncheckedIOException(e); + } + } + + private static DRLParser createDrlParser(CharStream charStream) { + DRLLexer drlLexer = new DRLLexer(charStream); + CommonTokenStream commonTokenStream = new CommonTokenStream(drlLexer); + DRLParser parser = new DRLParser(commonTokenStream); + ParserHelper helper = new ParserHelper(commonTokenStream, LanguageLevelOption.DRL6); + parser.setHelper(helper); + return parser; + } + + /** + * DRLVisitorImpl visits a parse tree and creates a PackageDescr + */ + public static PackageDescr compilationUnitContext2PackageDescr(DRLParser.CompilationUnitContext ctx, TokenStream tokenStream, Resource resource) { + DRLVisitorImpl visitor = new DRLVisitorImpl(tokenStream, resource); + Object descr = visitor.visit(ctx); + if (descr instanceof PackageDescr) { + return (PackageDescr) descr; + } else { + throw new DRLParserException("CompilationUnitContext should produce PackageDescr. descr = " + descr.getClass()); + } + } + + /** + * Given a row and column of the input DRL, return the index of the matched token + */ + public static Integer computeTokenIndex(DRLParser parser, int row, int col) { + for (int i = 0; i < parser.getInputStream().size(); i++) { + Token token = parser.getInputStream().get(i); + int start = token.getCharPositionInLine(); + int stop = token.getCharPositionInLine() + token.getText().length(); + if (token.getLine() > row) { + return token.getTokenIndex() - 1; + } else if (token.getLine() == row && start >= col) { + return token.getTokenIndex() == 0 ? 0 : token.getTokenIndex() - 1; + } else if (token.getLine() == row && start < col && stop >= col) { + return token.getTokenIndex(); + } + } + return null; + } + + /** + * RuleContext.getText() connects all nodes including ErrorNode. This method appends texts only from valid nodes + */ + public static String getTextWithoutErrorNode(ParseTree tree) { + if (tree.getChildCount() == 0) { + return ""; + } + + StringBuilder builder = new StringBuilder(); + for (int i = 0; i < tree.getChildCount(); i++) { + ParseTree child = tree.getChild(i); + if (!(child instanceof ErrorNode)) { + if (child instanceof TerminalNode) { + builder.append(child.getText()); + } else { + builder.append(getTextWithoutErrorNode(child)); + } + } + } + + return builder.toString(); + } +} diff --git a/drools-drl/drools-drl-parser/src/main/java/org/drools/drl/parser/antlr4/DRLParserWrapper.java b/drools-drl/drools-drl-parser/src/main/java/org/drools/drl/parser/antlr4/DRLParserWrapper.java new file mode 100644 index 00000000000..e89ad669197 --- /dev/null +++ b/drools-drl/drools-drl-parser/src/main/java/org/drools/drl/parser/antlr4/DRLParserWrapper.java @@ -0,0 +1,101 @@ +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you 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 + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.drools.drl.parser.antlr4; + +import java.io.InputStream; +import java.io.Reader; +import java.util.ArrayList; +import java.util.List; +import java.util.stream.Collectors; + +import org.drools.drl.ast.descr.PackageDescr; +import org.kie.api.io.Resource; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import static org.drools.drl.parser.antlr4.DRLParserHelper.compilationUnitContext2PackageDescr; + +/** + * Wrapper for DRLParser. Somewhat duplicated from DRLParserHelper, but this class is instantiated and holds errors. + */ +public class DRLParserWrapper { + + private static final Logger LOGGER = LoggerFactory.getLogger(DRLParserWrapper.class); + + private final List errors = new ArrayList<>(); + + private final Resource resource; + + public DRLParserWrapper(Resource resource) { + this.resource = resource; + } + + /** + * Main entry point for parsing DRL + */ + public PackageDescr parse(String drl) { + DRLParser drlParser = DRLParserHelper.createDrlParser(drl); + return parse(drlParser); + } + + /** + * Main entry point for parsing DRL + */ + public PackageDescr parse(InputStream is, String encoding) { + DRLParser drlParser = DRLParserHelper.createDrlParser(is, encoding); + return parse(drlParser); + } + + /** + * Main entry point for parsing DRL + */ + public PackageDescr parse(Reader reader) { + DRLParser drlParser = DRLParserHelper.createDrlParser(reader); + return parse(drlParser); + } + + private PackageDescr parse(DRLParser drlParser) { + DRLErrorListener errorListener = new DRLErrorListener(); + drlParser.addErrorListener(errorListener); + + DRLParser.CompilationUnitContext cxt = drlParser.compilationUnit(); + + errors.addAll(errorListener.getErrors()); + + try { + return compilationUnitContext2PackageDescr(cxt, drlParser.getTokenStream(), resource); + } catch (Exception e) { + LOGGER.error("Exception while creating PackageDescr", e); + errors.add(new DRLParserError(e)); + return null; + } + } + + public List getErrors() { + return errors; + } + + public List getErrorMessages() { + return errors.stream().map(DRLParserError::getMessage).collect(Collectors.toList()); + } + + public boolean hasErrors() { + return !errors.isEmpty(); + } +} diff --git a/drools-drl/drools-drl-parser/src/main/java/org/drools/drl/parser/antlr4/DRLVisitorImpl.java b/drools-drl/drools-drl-parser/src/main/java/org/drools/drl/parser/antlr4/DRLVisitorImpl.java new file mode 100644 index 00000000000..47d1b40bf9b --- /dev/null +++ b/drools-drl/drools-drl-parser/src/main/java/org/drools/drl/parser/antlr4/DRLVisitorImpl.java @@ -0,0 +1,1218 @@ +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you 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 + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.drools.drl.parser.antlr4; + +import java.util.ArrayList; +import java.util.List; +import java.util.stream.Collectors; + +import org.antlr.v4.runtime.ParserRuleContext; +import org.antlr.v4.runtime.RuleContext; +import org.antlr.v4.runtime.Token; +import org.antlr.v4.runtime.TokenStream; +import org.antlr.v4.runtime.tree.ParseTree; +import org.antlr.v4.runtime.tree.RuleNode; +import org.drools.drl.ast.descr.AccumulateDescr; +import org.drools.drl.ast.descr.AccumulateImportDescr; +import org.drools.drl.ast.descr.AndDescr; +import org.drools.drl.ast.descr.AnnotationDescr; +import org.drools.drl.ast.descr.AttributeDescr; +import org.drools.drl.ast.descr.BaseDescr; +import org.drools.drl.ast.descr.BehaviorDescr; +import org.drools.drl.ast.descr.CollectDescr; +import org.drools.drl.ast.descr.ConditionalBranchDescr; +import org.drools.drl.ast.descr.EntryPointDeclarationDescr; +import org.drools.drl.ast.descr.EntryPointDescr; +import org.drools.drl.ast.descr.EnumDeclarationDescr; +import org.drools.drl.ast.descr.EnumLiteralDescr; +import org.drools.drl.ast.descr.EvalDescr; +import org.drools.drl.ast.descr.ExistsDescr; +import org.drools.drl.ast.descr.ExprConstraintDescr; +import org.drools.drl.ast.descr.ForallDescr; +import org.drools.drl.ast.descr.FromDescr; +import org.drools.drl.ast.descr.FunctionDescr; +import org.drools.drl.ast.descr.FunctionImportDescr; +import org.drools.drl.ast.descr.GlobalDescr; +import org.drools.drl.ast.descr.GroupByDescr; +import org.drools.drl.ast.descr.ImportDescr; +import org.drools.drl.ast.descr.MVELExprDescr; +import org.drools.drl.ast.descr.NamedConsequenceDescr; +import org.drools.drl.ast.descr.NotDescr; +import org.drools.drl.ast.descr.OrDescr; +import org.drools.drl.ast.descr.PackageDescr; +import org.drools.drl.ast.descr.PatternDescr; +import org.drools.drl.ast.descr.PatternSourceDescr; +import org.drools.drl.ast.descr.QueryDescr; +import org.drools.drl.ast.descr.RuleDescr; +import org.drools.drl.ast.descr.TypeDeclarationDescr; +import org.drools.drl.ast.descr.TypeFieldDescr; +import org.drools.drl.ast.descr.UnitDescr; +import org.drools.drl.ast.descr.WindowDeclarationDescr; +import org.drools.drl.ast.descr.WindowReferenceDescr; +import org.kie.api.io.Resource; + +import static org.drools.drl.parser.antlr4.Antlr4ParserStringUtils.extractNamedConsequenceName; +import static org.drools.drl.parser.antlr4.Antlr4ParserStringUtils.getTextPreservingWhitespace; +import static org.drools.drl.parser.antlr4.Antlr4ParserStringUtils.getTokenTextPreservingWhitespace; +import static org.drools.drl.parser.antlr4.DRLParserHelper.getTextWithoutErrorNode; +import static org.drools.drl.parser.util.ParserStringUtils.appendPrefix; +import static org.drools.drl.parser.util.ParserStringUtils.safeStripStringDelimiters; +import static org.drools.util.StringUtils.unescapeJava; + +/** + * Visitor implementation for DRLParser. + * Basically, each visit method creates and returns a Descr object traversing the parse tree. + * Finally, visitCompilationUnit() returns a PackageDescr object. + * Try not to depend on DRLVisitorImpl's internal state for clean maintainability + */ +public class DRLVisitorImpl extends DRLParserBaseVisitor { + + private final TokenStream tokenStream; + private final Resource resource; + + public DRLVisitorImpl(TokenStream tokenStream, Resource resource) { + this.tokenStream = tokenStream; + this.resource = resource; + } + + /** + * Main entry point for creating PackageDescr from a parser tree. + */ + @Override + public PackageDescr visitCompilationUnit(DRLParser.CompilationUnitContext ctx) { + PackageDescr packageDescr = BaseDescrFactory.builder(new PackageDescr()) + .withParserRuleContext(ctx) + .withResource(resource) + .build(); + if (ctx.packagedef() != null) { + packageDescr.setName(getTextWithoutErrorNode(ctx.packagedef().name)); + } + List descrList = visitDescrChildren(ctx); + applyChildrenDescrs(packageDescr, descrList); + return packageDescr; + } + + /** + * Add all children Descr to PackageDescr + */ + private void applyChildrenDescrs(PackageDescr packageDescr, List descrList) { + // This bunch of if-blocks will be refactored by DROOLS-7564 + descrList.forEach(descr -> { + if (descr instanceof UnitDescr) { + descr.setNamespace(packageDescr.getNamespace()); + packageDescr.setUnit((UnitDescr) descr); + } else if (descr instanceof GlobalDescr) { + descr.setNamespace(packageDescr.getNamespace()); + packageDescr.addGlobal((GlobalDescr) descr); + } else if (descr instanceof FunctionImportDescr) { + descr.setNamespace(packageDescr.getNamespace()); + packageDescr.addFunctionImport((FunctionImportDescr) descr); + } else if (descr instanceof AccumulateImportDescr) { + descr.setNamespace(packageDescr.getNamespace()); + packageDescr.addAccumulateImport((AccumulateImportDescr) descr); + } else if (descr instanceof ImportDescr) { + descr.setNamespace(packageDescr.getNamespace()); + packageDescr.addImport((ImportDescr) descr); + } else if (descr instanceof FunctionDescr) { + FunctionDescr functionDescr = (FunctionDescr) descr; + functionDescr.setNamespace(packageDescr.getNamespace()); + AttributeDescr dialect = packageDescr.getAttribute("dialect"); + if (dialect != null) { + functionDescr.setDialect(dialect.getValue()); + } + packageDescr.addFunction(functionDescr); + } else if (descr instanceof TypeDeclarationDescr) { + packageDescr.addTypeDeclaration((TypeDeclarationDescr) descr); + } else if (descr instanceof EntryPointDeclarationDescr) { + packageDescr.addEntryPointDeclaration((EntryPointDeclarationDescr) descr); + } else if (descr instanceof WindowDeclarationDescr) { + packageDescr.addWindowDeclaration((WindowDeclarationDescr) descr); + } else if (descr instanceof EnumDeclarationDescr) { + packageDescr.addEnumDeclaration((EnumDeclarationDescr) descr); + } else if (descr instanceof AttributeDescr) { + descr.setNamespace(packageDescr.getNamespace()); + packageDescr.addAttribute((AttributeDescr) descr); + } else if (descr instanceof RuleDescr) { // QueryDescr extends RuleDescr + RuleDescr ruleDescr = (RuleDescr) descr; + packageDescr.addRule(ruleDescr); + packageDescr.afterRuleAdded(ruleDescr); + ruleDescr.setNamespace(packageDescr.getNamespace()); + ruleDescr.setUnit(packageDescr.getUnit()); + } + }); + } + + @Override + public UnitDescr visitUnitdef(DRLParser.UnitdefContext ctx) { + return BaseDescrFactory.builder(new UnitDescr(ctx.name.getText())) + .withParserRuleContext(ctx) + .withResource(resource) + .build(); + } + + @Override + public BaseDescr visitDrlStatementdef(DRLParser.DrlStatementdefContext ctx) { + return visitDescrChildren(ctx).get(0); // only one child. Ignore SEMICOLON + } + + @Override + public GlobalDescr visitGlobaldef(DRLParser.GlobaldefContext ctx) { + return BaseDescrFactory.builder(new GlobalDescr(ctx.drlIdentifier().getText(), ctx.type().getText())) + .withParserRuleContext(ctx) + .withResource(resource) + .build(); + } + + @Override + public ImportDescr visitImportStandardDef(DRLParser.ImportStandardDefContext ctx) { + String target = ctx.drlQualifiedName().getText() + (ctx.MUL() != null ? ".*" : ""); + if (ctx.DRL_FUNCTION() != null || ctx.STATIC() != null) { + FunctionImportDescr functionImportDescr = BaseDescrFactory.builder(new FunctionImportDescr()) + .withParserRuleContext(ctx) + .withResource(resource) + .build(); + functionImportDescr.setTarget(target); + return functionImportDescr; + } else { + ImportDescr importDescr = BaseDescrFactory.builder(new ImportDescr()) + .withParserRuleContext(ctx) + .withResource(resource) + .build(); + importDescr.setTarget(target); + return importDescr; + } + } + + @Override + public AccumulateImportDescr visitImportAccumulateDef(DRLParser.ImportAccumulateDefContext ctx) { + AccumulateImportDescr accumulateImportDescr = BaseDescrFactory.builder(new AccumulateImportDescr()) + .withParserRuleContext(ctx) + .withResource(resource) + .build(); + accumulateImportDescr.setTarget(ctx.drlQualifiedName().getText()); + accumulateImportDescr.setFunctionName(ctx.drlIdentifier().getText()); + return accumulateImportDescr; + } + + @Override + public FunctionDescr visitFunctiondef(DRLParser.FunctiondefContext ctx) { + FunctionDescr functionDescr = BaseDescrFactory.builder(new FunctionDescr()) + .withParserRuleContext(ctx) + .withResource(resource) + .build(); + if (ctx.typeTypeOrVoid() != null) { + functionDescr.setReturnType(getTextPreservingWhitespace(ctx.typeTypeOrVoid())); + } else { + functionDescr.setReturnType("void"); + } + functionDescr.setName(ctx.drlIdentifier().getText()); + + // add function parameters + DRLParser.FormalParametersContext formalParametersContext = ctx.formalParameters(); + DRLParser.FormalParameterListContext formalParameterListContext = formalParametersContext.formalParameterList(); + if (formalParameterListContext != null) { + List formalParameterContexts = formalParameterListContext.formalParameter(); + formalParameterContexts.forEach(formalParameterContext -> { + DRLParser.TypeTypeContext typeTypeContext = formalParameterContext.typeType(); + DRLParser.VariableDeclaratorIdContext variableDeclaratorIdContext = formalParameterContext.variableDeclaratorId(); + functionDescr.addParameter(typeTypeContext.getText(), variableDeclaratorIdContext.getText()); + }); + } + functionDescr.setBody(getTextPreservingWhitespace(ctx.drlBlock().drlBlockStatement())); + return functionDescr; + } + + @Override + public BaseDescr visitDeclaredef(DRLParser.DeclaredefContext ctx) { + return visitDescrChildren(ctx).get(0); // only one child + } + + @Override + public TypeDeclarationDescr visitTypeDeclaration(DRLParser.TypeDeclarationContext ctx) { + TypeDeclarationDescr typeDeclarationDescr = BaseDescrFactory.builder(new TypeDeclarationDescr()) + .withParserRuleContext(ctx) + .withResource(resource) + .build(); + + typeDeclarationDescr.setTypeName(ctx.name.getText()); + + if (ctx.DRL_TRAIT() != null) { + typeDeclarationDescr.setTrait(true); + } + if (ctx.EXTENDS() != null) { + for (DRLParser.DrlQualifiedNameContext superType : ctx.superTypes) { + typeDeclarationDescr.addSuperType(superType.getText()); + } + } + ctx.drlAnnotation().stream() + .map(this::visitDrlAnnotation) + .forEach(typeDeclarationDescr::addAnnotation); + ctx.field().stream() + .map(this::visitField) + .forEach(typeDeclarationDescr::addField); + return typeDeclarationDescr; + } + + @Override + public EnumDeclarationDescr visitEnumDeclaration(DRLParser.EnumDeclarationContext ctx) { + EnumDeclarationDescr enumDeclarationDescr = BaseDescrFactory.builder(new EnumDeclarationDescr()) + .withParserRuleContext(ctx) + .withResource(resource) + .build(); + + enumDeclarationDescr.setTypeName(ctx.name.getText()); + + ctx.drlAnnotation().stream() + .map(this::visitDrlAnnotation) + .forEach(enumDeclarationDescr::addAnnotation); + + List descrList = visitDescrChildren(ctx.enumeratives()); + descrList.stream() + .filter(EnumLiteralDescr.class::isInstance) + .map(EnumLiteralDescr.class::cast) + .forEach(enumDeclarationDescr::addLiteral); + + ctx.field().stream() + .map(this::visitField) + .forEach(enumDeclarationDescr::addField); + return enumDeclarationDescr; + } + + @Override + public EnumLiteralDescr visitEnumerative(DRLParser.EnumerativeContext ctx) { + EnumLiteralDescr enumLiteralDescr = BaseDescrFactory.builder(new EnumLiteralDescr(ctx.drlIdentifier().getText())) + .withParserRuleContext(ctx) + .withResource(resource) + .build(); + ctx.expression().stream() + .map(Antlr4ParserStringUtils::getTextPreservingWhitespace) + .forEach(enumLiteralDescr::addConstructorArg); + return enumLiteralDescr; + } + + @Override + public EntryPointDeclarationDescr visitEntryPointDeclaration(DRLParser.EntryPointDeclarationContext ctx) { + EntryPointDeclarationDescr entryPointDeclarationDescr = BaseDescrFactory.builder(new EntryPointDeclarationDescr()) + .withParserRuleContext(ctx) + .withResource(resource) + .build(); + entryPointDeclarationDescr.setEntryPointId(safeStripStringDelimiters(ctx.name.getText())); + ctx.drlAnnotation().stream() + .map(this::visitDrlAnnotation) + .forEach(entryPointDeclarationDescr::addAnnotation); + return entryPointDeclarationDescr; + } + + @Override + public WindowDeclarationDescr visitWindowDeclaration(DRLParser.WindowDeclarationContext ctx) { + WindowDeclarationDescr windowDeclarationDescr = BaseDescrFactory.builder(new WindowDeclarationDescr()) + .withParserRuleContext(ctx) + .withResource(resource) + .build(); + windowDeclarationDescr.setName(ctx.name.getText()); + ctx.drlAnnotation().stream() + .map(this::visitDrlAnnotation) + .forEach(windowDeclarationDescr::addAnnotation); + windowDeclarationDescr.setPattern((PatternDescr) visitLhsPatternBind(ctx.lhsPatternBind())); + return windowDeclarationDescr; + } + + /** + * entry point for one rule + */ + @Override + public RuleDescr visitRuledef(DRLParser.RuledefContext ctx) { + RuleDescr ruleDescr = BaseDescrFactory.builder(new RuleDescr(safeStripStringDelimiters(ctx.name.getText()))) + .withParserRuleContext(ctx) + .withResource(resource) + .build(); + + if (ctx.EXTENDS() != null) { + ruleDescr.setParentName(safeStripStringDelimiters(ctx.parentName.getText())); + } + + ctx.drlAnnotation().stream().map(this::visitDrlAnnotation).forEach(ruleDescr::addAnnotation); + + if (ctx.attributes() != null) { + List descrList = visitDescrChildren(ctx.attributes()); + descrList.stream() + .filter(AttributeDescr.class::isInstance) + .map(AttributeDescr.class::cast) + .forEach(ruleDescr::addAttribute); + } + + if (ctx.lhs() != null) { + final AndDescr rootDescr = ruleDescr.getLhs(); + List lhsDescrList = visitLhs(ctx.lhs()); + // Root Descr is always AndDescr. + // For example, if there are nested AndDescr like + // AndDescr + // /\ + // P AndDescr + // /\ + // P P + // is slimmed down to + // AndDescr + // / | \ + // P P P + // by addOrMerge() method. + lhsDescrList.forEach(rootDescr::addOrMerge); + DescrHelper.populateCommonProperties(rootDescr, ctx.lhs().lhsExpression()); + } else { + ruleDescr.setLhs(BaseDescrFactory.builder(new AndDescr()) + .withResource(resource) + .build()); + } + + if (ctx.rhs() != null) { + // default consequence + ruleDescr.setConsequenceLocation(ctx.rhs().getStart().getLine(), ctx.rhs().getStart().getCharPositionInLine()); // location of "then" + ruleDescr.setConsequence(getTokenTextPreservingWhitespace(ctx.rhs().consequenceBody(), tokenStream)); // RHS is just a text + + // named consequences + ctx.rhs().namedConsequence() + .forEach(namedConsequenceCtx -> { + String name = extractNamedConsequenceName(namedConsequenceCtx.RHS_NAMED_CONSEQUENCE_THEN().getText()); + String body = getTokenTextPreservingWhitespace(namedConsequenceCtx.consequenceBody(), tokenStream); + ruleDescr.addNamedConsequences(name, body); + } ); + } + + return ruleDescr; + } + + @Override + public QueryDescr visitQuerydef(DRLParser.QuerydefContext ctx) { + QueryDescr queryDescr = BaseDescrFactory.builder(new QueryDescr(safeStripStringDelimiters(ctx.name.getText()))) + .withParserRuleContext(ctx) + .withResource(resource) + .build(); + + DRLParser.ParametersContext parametersContext = ctx.parameters(); + if (parametersContext != null) { + List parameterContexts = parametersContext.parameter(); + parameterContexts.forEach(parameterContext -> { + String type = parameterContext.type() != null ? parameterContext.type().getText() : "Object"; // default type is Object + String name = parameterContext.drlIdentifier().getText(); + queryDescr.addParameter(type, name); + }); + } + + ctx.drlAnnotation().stream().map(this::visitDrlAnnotation).forEach(queryDescr::addAnnotation); + + final AndDescr rootDescr = queryDescr.getLhs(); + List lhsDescrList = visitDescrChildren(ctx.queryLhs()); // queryLhs never be null + lhsDescrList.forEach(rootDescr::addOrMerge); + DescrHelper.populateCommonProperties(rootDescr, ctx.queryLhs()); + + return queryDescr; + } + + @Override + public AnnotationDescr visitDrlAnnotation(DRLParser.DrlAnnotationContext ctx) { + // Full Java-style annotation. + if (ctx.anno != null) { + if (ctx.anno.result == null) { + throw new IllegalStateException("anno.result must not be null!"); + } + return BaseDescrFactory.builder(ctx.anno.result) + .withParserRuleContext(ctx) + .withResource(resource) + .build(); + } + + // A chunk that is neither a single value nor a list of key-value pairs. For example `!*, age` in `@watch(!*, age)`. + AnnotationDescr annotationDescr = BaseDescrFactory.builder(new AnnotationDescr(ctx.name.getText())) + .withParserRuleContext(ctx) + .withResource(resource) + .build(); + if (ctx.chunk() != null) { + annotationDescr.setValue(getTextPreservingWhitespace(ctx.chunk())); + } + return annotationDescr; + } + + @Override + public TypeFieldDescr visitField(DRLParser.FieldContext ctx) { + TypeFieldDescr typeFieldDescr = BaseDescrFactory.builder(new TypeFieldDescr()) + .withParserRuleContext(ctx) + .withResource(resource) + .build(); + typeFieldDescr.setFieldName(ctx.label().drlIdentifier().getText()); + typeFieldDescr.setPattern(new PatternDescr(ctx.type().getText())); + if (ctx.ASSIGN() != null) { + typeFieldDescr.setInitExpr(getTextPreservingWhitespace(ctx.initExpr)); + } + ctx.drlAnnotation().stream() + .map(this::visitDrlAnnotation) + .forEach(typeFieldDescr::addAnnotation); + return typeFieldDescr; + } + + @Override + public AttributeDescr visitExpressionAttribute(DRLParser.ExpressionAttributeContext ctx) { + AttributeDescr attributeDescr = BaseDescrFactory.builder(new AttributeDescr(ctx.name.getText())) + .withParserRuleContext(ctx) + .withResource(resource) + .build(); + attributeDescr.setValue(getTextPreservingWhitespace(ctx.conditionalAttributeValue())); + attributeDescr.setType(AttributeDescr.Type.EXPRESSION); + return attributeDescr; + } + + @Override + public AttributeDescr visitBooleanAttribute(DRLParser.BooleanAttributeContext ctx) { + AttributeDescr attributeDescr = BaseDescrFactory.builder(new AttributeDescr(ctx.name.getText())) + .withParserRuleContext(ctx) + .withResource(resource) + .build(); + attributeDescr.setValue(ctx.BOOL_LITERAL() != null ? ctx.BOOL_LITERAL().getText() : "true"); + attributeDescr.setType(AttributeDescr.Type.BOOLEAN); + return attributeDescr; + } + + @Override + public AttributeDescr visitStringAttribute(DRLParser.StringAttributeContext ctx) { + AttributeDescr attributeDescr = BaseDescrFactory.builder(new AttributeDescr(ctx.name.getText())) + .withParserRuleContext(ctx) + .withResource(resource) + .build(); + attributeDescr.setValue(unescapeJava(safeStripStringDelimiters(ctx.DRL_STRING_LITERAL().getText()))); + attributeDescr.setType(AttributeDescr.Type.STRING); + return attributeDescr; + } + + @Override + public AttributeDescr visitStringListAttribute(DRLParser.StringListAttributeContext ctx) { + AttributeDescr attributeDescr = BaseDescrFactory.builder(new AttributeDescr(ctx.name.getText())) + .withParserRuleContext(ctx) + .withResource(resource) + .build(); + List valueList = ctx.DRL_STRING_LITERAL().stream() + .map(ParseTree::getText) + .collect(Collectors.toList()); + attributeDescr.setValue(createStringList(valueList)); + attributeDescr.setType(AttributeDescr.Type.LIST); + return attributeDescr; + } + + private static String createStringList(List valueList) { + StringBuilder sb = new StringBuilder(); + sb.append("[ "); + for (int i = 0; i < valueList.size(); i++) { + sb.append(valueList.get(i)); + if (i < valueList.size() - 1) { + sb.append(", "); + } + } + sb.append(" ]"); + return sb.toString(); + } + + @Override + public AttributeDescr visitIntOrChunkAttribute(DRLParser.IntOrChunkAttributeContext ctx) { + AttributeDescr attributeDescr = BaseDescrFactory.builder(new AttributeDescr(ctx.name.getText())) + .withParserRuleContext(ctx) + .withResource(resource) + .build(); + if (ctx.DECIMAL_LITERAL() != null) { + attributeDescr.setValue(ctx.DECIMAL_LITERAL().getText()); + attributeDescr.setType(AttributeDescr.Type.NUMBER); + } else { + attributeDescr.setValue(getTextPreservingWhitespace(ctx.chunk())); + attributeDescr.setType(AttributeDescr.Type.EXPRESSION); + } + return attributeDescr; + } + + /** + * entry point for LHS + */ + @Override + public List visitLhs(DRLParser.LhsContext ctx) { + if (ctx.lhsExpression() != null) { + return visitDescrChildren(ctx); + } else { + return new ArrayList<>(); + } + } + + @Override + public BaseDescr visitLhsPatternBind(DRLParser.LhsPatternBindContext ctx) { + if (ctx.lhsPattern().size() == 1) { + return getSinglePatternDescr(ctx); + } else if (ctx.lhsPattern().size() > 1) { + return getOrDescrWithMultiplePatternDescr(ctx); + } else { + return null; // only caused by a parser error + } + } + + private PatternDescr getSinglePatternDescr(DRLParser.LhsPatternBindContext ctx) { + List patternDescrList = visitDescrChildren(ctx); + if (patternDescrList.isEmpty() || !(patternDescrList.get(0) instanceof PatternDescr)) { + throw new IllegalStateException("lhsPatternBind must have at least one lhsPattern : " + ctx.getText()); + } + PatternDescr patternDescr = (PatternDescr)patternDescrList.get(0); + + if (ctx.label() != null) { + patternDescr.setIdentifier(ctx.label().drlIdentifier().getText()); + } else if (ctx.unif() != null) { + patternDescr.setIdentifier(ctx.unif().drlIdentifier().getText()); + patternDescr.setUnification(true); + } + DescrHelper.refreshPatternDescrProperties(patternDescr, ctx); + return patternDescr; + } + + private OrDescr getOrDescrWithMultiplePatternDescr(DRLParser.LhsPatternBindContext ctx) { + OrDescr orDescr = BaseDescrFactory.builder(new OrDescr()) + .withParserRuleContext(ctx) + .withResource(resource) + .build(); + List descrList = visitDescrChildren(ctx); + descrList.stream() + .filter(PatternDescr.class::isInstance) + .map(PatternDescr.class::cast) + .forEach(patternDescr -> { + if (ctx.label() != null) { + patternDescr.setIdentifier(ctx.label().drlIdentifier().getText()); + } + orDescr.addDescr(patternDescr); + }); + + return orDescr; + } + + /** + * entry point for a Pattern + */ + @Override + public PatternDescr visitLhsPattern(DRLParser.LhsPatternContext ctx) { + if (ctx.xpathPrimary() != null) { + String constraint = visitConstraintChildren(ctx); + ExprConstraintDescr constraintDescr = BaseDescrFactory.builder(new ExprConstraintDescr(constraint)) + .withParserRuleContext(ctx) + .withResource(resource) + .build(); + constraintDescr.setType(ExprConstraintDescr.Type.NAMED); + constraintDescr.setPosition(0); + PatternDescr patternDescr = BaseDescrFactory.builder(new PatternDescr()) + .withParserRuleContext(ctx) + .withResource(resource) + .build(); + patternDescr.addConstraint(constraintDescr); + return patternDescr; + } + + PatternDescr patternDescr = BaseDescrFactory.builder(new PatternDescr(ctx.objectType.getText())) + .withParserRuleContext(ctx) + .withResource(resource) + .build(); + if (ctx.QUESTION() != null) { + patternDescr.setQuery(true); + } + if (ctx.patternFilter() != null) { + patternDescr.addBehavior(visitPatternFilter(ctx.patternFilter())); + } + if (ctx.patternSource() != null) { + PatternSourceDescr patternSourceDescr = (PatternSourceDescr) visitPatternSource(ctx.patternSource()); + patternSourceDescr.setResource(patternDescr.getResource()); + patternDescr.setSource(patternSourceDescr); + } + + ctx.drlAnnotation().stream().map(this::visitDrlAnnotation).forEach(patternDescr::addAnnotation); + List constraintDescrList = visitConstraints(ctx.positionalConstraints(), ctx.constraints()); + constraintDescrList.forEach(descr -> addToPatternDescr(patternDescr, descr)); + return patternDescr; + } + + private void addToPatternDescr(PatternDescr patternDescr, ExprConstraintDescr exprConstraintDescr) { + exprConstraintDescr.setResource(patternDescr.getResource()); + patternDescr.addConstraint(exprConstraintDescr); + } + + @Override + public NamedConsequenceDescr visitNamedConsequenceInvocation(DRLParser.NamedConsequenceInvocationContext ctx) { + NamedConsequenceDescr namedConsequenceDescr = BaseDescrFactory.builder(new NamedConsequenceDescr(ctx.drlIdentifier().getText())) + .withParserRuleContext(ctx) + .withResource(resource) + .build(); + return namedConsequenceDescr; + } + + @Override + public NamedConsequenceDescr visitBreakingNamedConsequenceInvocation(DRLParser.BreakingNamedConsequenceInvocationContext ctx) { + NamedConsequenceDescr namedConsequenceDescr = BaseDescrFactory.builder(new NamedConsequenceDescr(ctx.drlIdentifier().getText())) + .withParserRuleContext(ctx) + .withResource(resource) + .build(); + namedConsequenceDescr.setBreaking(true); + return namedConsequenceDescr; + } + + /** + * process + * + * if (condition) do[namedConsequence1] else do[namedConsequence2] + * + * into a ConditionalBranchDescr + */ + @Override + public ConditionalBranchDescr visitConditionalBranch(DRLParser.ConditionalBranchContext ctx) { + ConditionalBranchDescr conditionalBranchDescr = BaseDescrFactory.builder(new ConditionalBranchDescr()) + .withParserRuleContext(ctx) + .withResource(resource) + .build(); + EvalDescr evalDescr = BaseDescrFactory.builder(new EvalDescr()) + .withParserRuleContext(ctx.conditionalOrExpression()) + .withResource(resource) + .build(); + evalDescr.setContent(getTextPreservingWhitespace(ctx.conditionalOrExpression())); + conditionalBranchDescr.setCondition(evalDescr); + + // main branch + if (ctx.do1 != null) { + NamedConsequenceDescr namedConsequenceDescr = visitNamedConsequenceInvocation(ctx.do1); + conditionalBranchDescr.setConsequence(namedConsequenceDescr); + } else if (ctx.break1 != null) { + NamedConsequenceDescr namedConsequenceDescr = visitBreakingNamedConsequenceInvocation(ctx.break1); + conditionalBranchDescr.setConsequence(namedConsequenceDescr); + } + + // else branch + if (ctx.do2 != null) { + ConditionalBranchDescr elseBranchDescr = BaseDescrFactory.builder(new ConditionalBranchDescr()) + .withParserRuleContext(ctx.do2) + .withResource(resource) + .build(); + conditionalBranchDescr.setElseBranch(elseBranchDescr); + NamedConsequenceDescr namedConsequenceDescr = visitNamedConsequenceInvocation(ctx.do2); + elseBranchDescr.setConsequence(namedConsequenceDescr); + } else if (ctx.break2 != null) { + ConditionalBranchDescr elseBranchDescr = BaseDescrFactory.builder(new ConditionalBranchDescr()) + .withParserRuleContext(ctx.break2) + .withResource(resource) + .build(); + conditionalBranchDescr.setElseBranch(elseBranchDescr); + NamedConsequenceDescr namedConsequenceDescr = visitBreakingNamedConsequenceInvocation(ctx.break2); + elseBranchDescr.setConsequence(namedConsequenceDescr); + } else if (ctx.conditionalBranch() != null) { + // nested if + ConditionalBranchDescr nestedConditionalBranchDescr = visitConditionalBranch(ctx.conditionalBranch()); + conditionalBranchDescr.setElseBranch(nestedConditionalBranchDescr); + } + + return conditionalBranchDescr; + } + + @Override + public ForallDescr visitLhsForall(DRLParser.LhsForallContext ctx) { + ForallDescr forallDescr = BaseDescrFactory.builder(new ForallDescr()) + .withParserRuleContext(ctx) + .withResource(resource) + .build(); + visitDescrChildren(ctx).forEach(forallDescr::addDescr); + return forallDescr; + } + + @Override + public PatternDescr visitLhsAccumulate(DRLParser.LhsAccumulateContext ctx) { + AccumulateDescr accumulateDescr = BaseDescrFactory.builder(new AccumulateDescr()) + .withParserRuleContext(ctx) + .withResource(resource) + .build(); + // accumulateDescr.input is always AndDescr + accumulateDescr.setInput(wrapWithAndDescr(visitLhsAndDef(ctx.lhsAndDef()), ctx.lhsAndDef())); + + // accumulate function + for (DRLParser.AccumulateFunctionContext accumulateFunctionContext : ctx.accumulateFunction()) { + accumulateDescr.addFunction(visitAccumulateFunction(accumulateFunctionContext)); + } + + PatternDescr patternDescr = BaseDescrFactory.builder(new PatternDescr("Object")) + .withResource(resource) + .build(); + patternDescr.setSource(accumulateDescr); + List constraintDescrList = visitConstraints(ctx.constraints()); + constraintDescrList.forEach(patternDescr::addConstraint); + + return patternDescr; + } + + private AndDescr wrapWithAndDescr(BaseDescr baseDescr, ParserRuleContext ctx) { + if (baseDescr instanceof AndDescr andDescr) { + return andDescr; + } else { + AndDescr andDescr = BaseDescrFactory.builder(new AndDescr()) + .withParserRuleContext(ctx) + .build(); + andDescr.addDescr(baseDescr); + return andDescr; + } + } + + @Override + public Object visitLhsGroupBy(DRLParser.LhsGroupByContext ctx) { + GroupByDescr groupByDescr = BaseDescrFactory.builder(new GroupByDescr()) + .withParserRuleContext(ctx) + .withResource(resource) + .build(); + groupByDescr.setInput(visitLhsAndDef(ctx.lhsAndDef())); + + if (ctx.groupByKeyBinding().label() != null) { + groupByDescr.setGroupingKey(ctx.groupByKeyBinding().label().drlIdentifier().getText()); + } + groupByDescr.setGroupingFunction(getTextPreservingWhitespace(ctx.groupByKeyBinding().conditionalExpression())); + + // accumulate function + for (DRLParser.AccumulateFunctionContext accumulateFunctionContext : ctx.accumulateFunction()) { + groupByDescr.addFunction(visitAccumulateFunction(accumulateFunctionContext)); + } + + PatternDescr patternDescr = BaseDescrFactory.builder(new PatternDescr("Object")) + .withResource(resource) + .build(); + patternDescr.setSource(groupByDescr); + List constraintDescrList = visitConstraints(ctx.constraints()); + constraintDescrList.forEach(patternDescr::addConstraint); + + return patternDescr; + } + + @Override + public BehaviorDescr visitPatternFilter(DRLParser.PatternFilterContext ctx) { + BehaviorDescr behaviorDescr = BaseDescrFactory.builder(new BehaviorDescr()) + .withParserRuleContext(ctx) + .withResource(resource) + .build(); + behaviorDescr.setType(ctx.DRL_WINDOW().getText()); + behaviorDescr.setSubType(ctx.drlIdentifier().getText()); + List expressionContexts = ctx.expressionList().expression(); + List parameters = expressionContexts.stream().map(Antlr4ParserStringUtils::getTextPreservingWhitespace).collect(Collectors.toList()); + behaviorDescr.setParameters(parameters); + return behaviorDescr; + } + + @Override + public FromDescr visitFromExpression(DRLParser.FromExpressionContext ctx) { + FromDescr fromDescr = BaseDescrFactory.builder(new FromDescr()) + .withParserRuleContext(ctx) + .withResource(resource) + .build(); + fromDescr.setDataSource(new MVELExprDescr(getTextPreservingWhitespace(ctx))); + return fromDescr; + } + + @Override + public CollectDescr visitFromCollect(DRLParser.FromCollectContext ctx) { + CollectDescr collectDescr = BaseDescrFactory.builder(new CollectDescr()) + .withParserRuleContext(ctx) + .withResource(resource) + .build(); + collectDescr.setInputPattern((PatternDescr) visitLhsPatternBind(ctx.lhsPatternBind())); + return collectDescr; + } + + @Override + public AccumulateDescr visitFromAccumulate(DRLParser.FromAccumulateContext ctx) { + AccumulateDescr accumulateDescr = BaseDescrFactory.builder(new AccumulateDescr()) + .withParserRuleContext(ctx) + .withResource(resource) + .build(); + // accumulateDescr.input is always AndDescr + accumulateDescr.setInput(wrapWithAndDescr(visitLhsAndDef(ctx.lhsAndDef()), ctx.lhsAndDef())); + if (ctx.DRL_INIT() != null) { + // inline custom accumulate + accumulateDescr.setInitCode(getTextPreservingWhitespace(ctx.initBlockStatements)); + accumulateDescr.setActionCode(getTextPreservingWhitespace(ctx.actionBlockStatements)); + if (ctx.DRL_REVERSE() != null) { + accumulateDescr.setReverseCode(getTextPreservingWhitespace(ctx.reverseBlockStatements)); + } + accumulateDescr.setResultCode(getTextPreservingWhitespace(ctx.resultBlockStatements)); + } else { + // accumulate function + accumulateDescr.addFunction(visitAccumulateFunction(ctx.accumulateFunction())); + } + return accumulateDescr; + } + + @Override + public AccumulateDescr.AccumulateFunctionCallDescr visitAccumulateFunction(DRLParser.AccumulateFunctionContext ctx) { + String function = ctx.drlIdentifier().getText(); + String bind = null; + boolean unify = false; + if (ctx.label() != null) { + bind = ctx.label().drlIdentifier().getText(); + } else if (ctx.unif() != null) { + bind = ctx.unif().drlIdentifier().getText(); + unify = true; + } + + String[] params = ctx.conditionalExpressions().conditionalExpression().stream() + .map(Antlr4ParserStringUtils::getTextPreservingWhitespace) + .toArray(String[]::new); + return new AccumulateDescr.AccumulateFunctionCallDescr(function, bind, unify, params); + } + + @Override + public EntryPointDescr visitFromEntryPoint(DRLParser.FromEntryPointContext ctx) { + return BaseDescrFactory.builder(new EntryPointDescr(safeStripStringDelimiters(ctx.stringId().getText()))) + .withParserRuleContext(ctx) + .withResource(resource) + .build(); + } + + @Override + public WindowReferenceDescr visitFromWindow(DRLParser.FromWindowContext ctx) { + return BaseDescrFactory.builder(new WindowReferenceDescr(ctx.drlIdentifier().getText())) + .withParserRuleContext(ctx) + .withResource(resource) + .build(); + } + + /** + * Collect constraints in a Pattern + */ + @Override + public List visitConstraints(DRLParser.ConstraintsContext ctx) { + List exprConstraintDescrList = new ArrayList<>(); + populateExprConstraintDescrList(ctx, exprConstraintDescrList); + return exprConstraintDescrList; + } + + /** + * Collect constraints in a Pattern. Positional constraints comes first with semicolon. + */ + private List visitConstraints(DRLParser.PositionalConstraintsContext positionalCtx, DRLParser.ConstraintsContext ctx) { + List exprConstraintDescrList = new ArrayList<>(); + populateExprConstraintDescrList(positionalCtx, exprConstraintDescrList); + populateExprConstraintDescrList(ctx, exprConstraintDescrList); + return exprConstraintDescrList; + } + + private void populateExprConstraintDescrList(ParserRuleContext ctx, List exprConstraintDescrList) { + if (ctx == null) { + return; + } + List descrList = visitDescrChildren(ctx); + for (BaseDescr descr : descrList) { + if (descr instanceof ExprConstraintDescr) { + ExprConstraintDescr exprConstraintDescr = (ExprConstraintDescr) descr; + exprConstraintDescr.setType(ctx instanceof DRLParser.PositionalConstraintsContext ? ExprConstraintDescr.Type.POSITIONAL : ExprConstraintDescr.Type.NAMED); + exprConstraintDescr.setPosition(exprConstraintDescrList.size()); + exprConstraintDescrList.add(exprConstraintDescr); + } + } + } + + /** + * Takes one constraint as String and create ExprConstraintDescr. + * In case of nested constraint, it could be multiple ExprConstraintDescr objects. + */ + @Override + public List visitConstraint(DRLParser.ConstraintContext ctx) { + List descrList = new ArrayList<>(); + if (ctx.nestedConstraint() != null) { + // nested constraint requires special string manipulation + return visitNestedConstraint(ctx.nestedConstraint()); + } + // get a simple constraint as String + String constraint = visitConstraintChildren(ctx); + if (!constraint.isEmpty()) { + ExprConstraintDescr constraintDescr = BaseDescrFactory.builder(new ExprConstraintDescr(constraint)) + .withParserRuleContext(ctx) + .withResource(resource) + .build(); + constraintDescr.setType(ExprConstraintDescr.Type.NAMED); + descrList.add(constraintDescr); + return descrList; + } + return descrList; + } + + /** + * Append a prefix to nested constraints. + * For example, + * address.(city.startsWith("I"), city.length() == 5) + * becomes + * address.city.startsWith("I"), address.city.length() == 5 + */ + @Override + public List visitNestedConstraint(DRLParser.NestedConstraintContext ctx) { + Token prefixStartToken = ctx.start; + Token prefixEndToken = tokenStream.get(ctx.LPAREN().getSymbol().getTokenIndex() - 1); + String prefix = tokenStream.getText(prefixStartToken, prefixEndToken); + List exprConstraintDescr = visitConstraints(ctx.constraints()); + exprConstraintDescr.forEach(d -> d.setText(appendPrefix(prefix, d.getText()))); + return exprConstraintDescr; + } + + @Override + public String visitDrlIdentifier(DRLParser.DrlIdentifierContext ctx) { + return ctx.getText(); + } + + @Override + public ExistsDescr visitLhsExists(DRLParser.LhsExistsContext ctx) { + ExistsDescr existsDescr = BaseDescrFactory.builder(new ExistsDescr()) + .withParserRuleContext(ctx) + .withResource(resource) + .build(); + if (ctx.lhsExpression() != null) { + // exists( A() or B() ) + List baseDescrs = visitDescrChildren(ctx); + if (baseDescrs.size() == 1) { + existsDescr.addDescr(baseDescrs.get(0)); + } else { + throw new IllegalStateException("'exists()' children descr size must be 1 : " + ctx.getText()); + } + } else { + // exists A() + BaseDescr descr = visitLhsPatternBind(ctx.lhsPatternBind()); + existsDescr.addDescr(descr); + } + return existsDescr; + } + + @Override + public NotDescr visitLhsNot(DRLParser.LhsNotContext ctx) { + NotDescr notDescr = BaseDescrFactory.builder(new NotDescr()) + .withParserRuleContext(ctx) + .withResource(resource) + .build(); + if (ctx.lhsExpression() != null) { + // not ( A() or B() ) + List baseDescrs = visitDescrChildren(ctx); + if (baseDescrs.size() == 1) { + notDescr.addDescr(baseDescrs.get(0)); + } else { + throw new IllegalStateException("'not()' children descr size must be 1 : " + ctx.getText()); + } + } else { + // not A() + BaseDescr descr = visitLhsPatternBind(ctx.lhsPatternBind()); + notDescr.addDescr(descr); + } + return notDescr; + } + + @Override + public EvalDescr visitLhsEval(DRLParser.LhsEvalContext ctx) { + return BaseDescrFactory.builder(new EvalDescr(getTextPreservingWhitespace(ctx.conditionalOrExpression()))) + .withParserRuleContext(ctx) + .withResource(resource) + .build(); + } + + @Override + public List visitLhsExpressionEnclosed(DRLParser.LhsExpressionEnclosedContext ctx) { + // enclosed expression is simply stripped because Descr itself is encapsulated + return visitDescrChildren(ctx); + } + + @Override + public BaseDescr visitLhsOr(DRLParser.LhsOrContext ctx) { + // For flatten nested OrDescr logic, we call visitDescrChildrenForDescrNodePair instead of usual visitDescrChildren + List descrList = visitDescrChildrenForDescrNodePair(ctx); + if (descrList.size() == 1) { + // Avoid nested OrDescr + return descrList.get(0).getDescr(); + } else { + OrDescr orDescr = BaseDescrFactory.builder(new OrDescr()) + .withParserRuleContext(ctx) + .withResource(resource) + .build(); + // For example, in case of A() or B() or C(), + // Parser creates AST like this: + // lhsOr + // / \ + // A() lhsOr + // / \ + // B() C() + // So, we need to flatten it so that OrDescr has A(), B() and C() as children. + List flattenedDescrs = flattenOrDescr(descrList); + flattenedDescrs.forEach(descr -> { + if (descr instanceof AnnotationDescr annotationDescr) { + orDescr.addAnnotation(annotationDescr); + } else { + orDescr.addDescr(descr); + } + }); + return orDescr; + } + } + + private List flattenOrDescr(List descrList) { + List flattenedDescrs = new ArrayList<>(); + for (DescrNodePair descrNodePair : descrList) { + BaseDescr descr = descrNodePair.getDescr(); + ParseTree node = descrNodePair.getNode(); // parser node corresponding to the descr + if (descr instanceof OrDescr orDescr && !(node instanceof DRLParser.LhsExpressionEnclosedContext)) { + // sibling OrDescr should be flattened unless it's explicitly enclosed by parenthesis + flattenedDescrs.addAll(orDescr.getDescrs()); + flattenedDescrs.addAll(orDescr.getAnnotations()); + } else { + flattenedDescrs.add(descr); + } + } + return flattenedDescrs; + } + + @Override + public BaseDescr visitLhsAnd(DRLParser.LhsAndContext ctx) { + return createAndDescr(ctx); + } + + private BaseDescr createAndDescr(ParserRuleContext ctx) { + // For flatten nested AndDescr logic, we call visitDescrChildrenForDescrNodePair instead of usual visitDescrChildren + List descrList = visitDescrChildrenForDescrNodePair(ctx); + if (descrList.size() == 1) { + // Avoid nested AndDescr + return descrList.get(0).getDescr(); + } else { + AndDescr andDescr = BaseDescrFactory.builder(new AndDescr()) + .withParserRuleContext(ctx) + .withResource(resource) + .build(); + // For example, in case of A() and B() and C(), + // Parser creates AST like this: + // lhsAnd + // / \ + // A() lhsAnd + // / \ + // B() C() + // So, we need to flatten it so that AndDescr has A(), B() and C() as children. + List flattenedDescrs = flattenAndDescr(descrList); + flattenedDescrs.forEach(descr -> { + if (descr instanceof AnnotationDescr annotationDescr) { + andDescr.addAnnotation(annotationDescr); + } else { + andDescr.addDescr(descr); + } + }); + return andDescr; + } + } + + private List flattenAndDescr(List descrList) { + List flattenedDescrs = new ArrayList<>(); + for (DescrNodePair descrNodePair : descrList) { + BaseDescr descr = descrNodePair.getDescr(); + ParseTree node = descrNodePair.getNode(); // parser node corresponding to the descr + if (descr instanceof AndDescr andDescr && !(node instanceof DRLParser.LhsExpressionEnclosedContext)) { + // sibling AndDescr should be flattened unless it's explicitly enclosed by parenthesis + flattenedDescrs.addAll(andDescr.getDescrs()); + flattenedDescrs.addAll(andDescr.getAnnotations()); + } else { + flattenedDescrs.add(descr); + } + } + return flattenedDescrs; + } + + @Override + public BaseDescr visitLhsAndDef(DRLParser.LhsAndDefContext ctx) { + return createAndDescr(ctx); + } + + @Override + public BaseDescr visitLhsUnary(DRLParser.LhsUnaryContext ctx) { + List children = visitDescrChildren(ctx); + if (children.size() > 1) { + // lhsUnary may have multiple children e.g. consequenceInvocation, connect with AND + AndDescr andDescr = BaseDescrFactory.builder(new AndDescr()) + .withParserRuleContext(ctx) + .withResource(resource) + .build(); + children.forEach(andDescr::addDescr); + return andDescr; + } else if (children.size() == 1) { + return children.get(0); + } else { + return null; // only caused by a parser error + } + } + + /** + * This is a special version of visitChildren(). + * This collects children BaseDescr objects and returns them as a list. + */ + private List visitDescrChildren(RuleNode node) { + List aggregator = new ArrayList<>(); + int n = node.getChildCount(); + + for (int i = 0; i < n && this.shouldVisitNextChild(node, aggregator); ++i) { + ParseTree c = node.getChild(i); + Object childResult = c.accept(this); + if (childResult instanceof BaseDescr) { + aggregator.add((BaseDescr) childResult); + } else if (childResult instanceof List) { + aggregator.addAll((List) childResult); + } + } + return aggregator; + } + + // This method is used when the parent descr requires children parser node information for composing the descr. + // Ideally, we should use visitDescrChildren as possible and use the returned Descr object to compose the parent descr. + // However, for example, in flatten OrDescr/AndDescr logic, + // enhancing the returned Descr object of visitLhsExpressionEnclosed() (e.g. adding 'enclosed' flag to OrDescr/AndDescr) could be intrusive just for composing the parent descr. + private List visitDescrChildrenForDescrNodePair(RuleNode node) { + List aggregator = new ArrayList<>(); + int n = node.getChildCount(); + + for (int i = 0; i < n && this.shouldVisitNextChild(node, aggregator); ++i) { + ParseTree c = node.getChild(i); + Object childResult = c.accept(this); + if (childResult instanceof BaseDescr) { + aggregator.add(new DescrNodePair((BaseDescr) childResult, c)); // pairing the returned Descr and the parser node + } else if (childResult instanceof List) { + List descrList = (List) childResult; + descrList.forEach(descr -> aggregator.add(new DescrNodePair(descr, c))); // pairing the returned Descr and the parser node + } + } + return aggregator; + } + + private static class DescrNodePair { + private final BaseDescr descr; // returned Descr object + private final ParseTree node; // parser node corresponding to the descr. This is used for composing the parent descr. + + private DescrNodePair(BaseDescr descr, ParseTree node) { + this.descr = descr; + this.node = node; + } + + public BaseDescr getDescr() { + return descr; + } + + public ParseTree getNode() { + return node; + } + } + + /** + * Return the text of constraint as-is + */ + private String visitConstraintChildren(ParserRuleContext ctx) { + return getTokenTextPreservingWhitespace(ctx, tokenStream); + } +} diff --git a/drools-drl/drools-drl-parser/src/main/java/org/drools/drl/parser/antlr4/DescrHelper.java b/drools-drl/drools-drl-parser/src/main/java/org/drools/drl/parser/antlr4/DescrHelper.java new file mode 100644 index 00000000000..02a4f38d276 --- /dev/null +++ b/drools-drl/drools-drl-parser/src/main/java/org/drools/drl/parser/antlr4/DescrHelper.java @@ -0,0 +1,87 @@ +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you 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 + *

+ * http://www.apache.org/licenses/LICENSE-2.0 + *

+ * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.drools.drl.parser.antlr4; + +import java.util.List; + +import org.antlr.v4.runtime.ParserRuleContext; +import org.antlr.v4.runtime.Token; +import org.drools.drl.ast.descr.BaseDescr; +import org.drools.drl.ast.descr.ExprConstraintDescr; +import org.drools.drl.ast.descr.PatternDescr; + +/** + * Helper class for Descr manipulation. + */ +public class DescrHelper { + + private DescrHelper() { + // Private constructor to prevent instantiation. + } + + public static T populateCommonProperties(T descr, ParserRuleContext ctx) { + Token startToken = ctx.getStart(); // Start token is never null. + // If the stop token is null, use the start token as both the start end the end. + Token stopToken = ctx.getStop() != null ? ctx.getStop() : startToken; + + if (descr instanceof ExprConstraintDescr) { + // Backward Compatibility Notes: + // Old DRL6Parser.constraint() has slightly different behavior for ExprConstraintDescr. Keep it for backward compatibility + // When we will update LanguageLevel, we can align this with other Descr. + descr.setStartCharacter(startToken.getStartIndex()); + descr.setEndCharacter(stopToken.getStopIndex()); + descr.setLocation(startToken.getLine(), startToken.getCharPositionInLine()); + descr.setEndLocation(stopToken.getLine(), stopToken.getCharPositionInLine()); + } else { + descr.setStartCharacter(startToken.getStartIndex()); + // Backward Compatibility Notes: + // Old DRL6Parser adds +1 for EndCharacter (except ExprConstraintDescr). This new parser follows the same to keep the backward compatibility. + // However, it doesn't look reasonable. When we will update LanguageLevel, we can remove this +1. + descr.setEndCharacter(stopToken.getStopIndex() + 1); + descr.setLocation(startToken.getLine(), startToken.getCharPositionInLine()); + descr.setEndLocation(stopToken.getLine(), stopToken.getCharPositionInLine() + stopTokenLength(stopToken) - 1); // last column of the end token + } + return descr; + } + + private static int stopTokenLength(Token token) { + return token.getType() == Token.EOF ? 0 : token.getText().length(); + } + + public static T populateCommonProperties(T descr, List ctxList) { + if (ctxList.isEmpty()) { + return descr; + } + ParserRuleContext firstCtx = ctxList.get(0); + ParserRuleContext lastCtx = ctxList.get(ctxList.size() - 1); + + descr.setStartCharacter(firstCtx.getStart().getStartIndex()); + descr.setEndCharacter(lastCtx.getStop().getStopIndex() + 1); + descr.setLocation(firstCtx.getStart().getLine(), firstCtx.getStart().getCharPositionInLine()); + descr.setEndLocation(lastCtx.getStop().getLine(), lastCtx.getStop().getCharPositionInLine() + lastCtx.getStop().getText().length() - 1); // last column of the end token + return descr; + } + + /** + * PatternDescr requires special handling for properties, because it should be updated with PatternBindContext. e.g. label + */ + public static PatternDescr refreshPatternDescrProperties(PatternDescr descr, DRLParser.LhsPatternBindContext ctx) { + return populateCommonProperties(descr, ctx); + } +} diff --git a/drools-drl/drools-drl-parser/src/main/java/org/drools/drl/parser/antlr4/Drl6ExprParserAntlr4.java b/drools-drl/drools-drl-parser/src/main/java/org/drools/drl/parser/antlr4/Drl6ExprParserAntlr4.java new file mode 100644 index 00000000000..29102a0f7d0 --- /dev/null +++ b/drools-drl/drools-drl-parser/src/main/java/org/drools/drl/parser/antlr4/Drl6ExprParserAntlr4.java @@ -0,0 +1,92 @@ +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you 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 + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.drools.drl.parser.antlr4; + +import java.util.Collections; +import java.util.List; + +import org.antlr.v4.runtime.BaseErrorListener; +import org.antlr.v4.runtime.CharStreams; +import org.antlr.v4.runtime.CommonTokenStream; +import org.antlr.v4.runtime.RecognitionException; +import org.antlr.v4.runtime.Recognizer; +import org.drools.drl.ast.descr.BaseDescr; +import org.drools.drl.ast.descr.ConstraintConnectiveDescr; +import org.drools.drl.parser.DrlExprParser; +import org.drools.drl.parser.DroolsParserException; +import org.kie.internal.builder.conf.LanguageLevelOption; + +/** + * This is a helper class that provides helper methods to parse expressions + * using both the DRLExpressions parser and the DRLExprTree parser. + */ +public class Drl6ExprParserAntlr4 implements DrlExprParser { + + private ParserHelper helper = null; + + private final LanguageLevelOption languageLevel; + + public Drl6ExprParserAntlr4(LanguageLevelOption languageLevel) { + this.languageLevel = languageLevel; + } + + /** Parse an expression from text */ + public ConstraintConnectiveDescr parse(final String text) { + ConstraintConnectiveDescr constraint = null; + DRLLexer lexer = new DRLLexer(CharStreams.fromString(text)); + CommonTokenStream input = new CommonTokenStream(lexer); + helper = new ParserHelper(input, languageLevel); + DRL6Expressions parser = new DRL6Expressions(input); + parser.setHelper(helper); + parser.addErrorListener(new BaseErrorListener() { + @Override + public void syntaxError(Recognizer recognizer, Object offendingSymbol, int line, int charPositionInLine, String msg, RecognitionException e) { + helper.reportError(offendingSymbol, line, charPositionInLine, msg, e); + } + }); + parser.setBuildDescr(true); + parser.setLeftMostExpr(null); // setting initial value just in case + BaseDescr expr = parser.conditionalOrExpressionDescr(); + if (expr != null && !parser.hasErrors()) { + constraint = ConstraintConnectiveDescr.newAnd(); + constraint.addOrMerge(expr); + } + return constraint; + } + + public String getLeftMostExpr() { + return helper != null ? helper.getLeftMostExpr() : null; + } + + /** + * @return true if there were parser errors. + */ + public boolean hasErrors() { + return helper != null && helper.hasErrors(); + } + + /** + * @return a list of errors found while parsing. + */ + @SuppressWarnings("unchecked") + public List getErrors() { + return helper != null ? helper.getErrors() : Collections.EMPTY_LIST; + } + +} diff --git a/drools-drl/drools-drl-parser/src/main/java/org/drools/drl/parser/antlr4/DroolsParserExceptionFactory.java b/drools-drl/drools-drl-parser/src/main/java/org/drools/drl/parser/antlr4/DroolsParserExceptionFactory.java new file mode 100644 index 00000000000..c40636256f8 --- /dev/null +++ b/drools-drl/drools-drl-parser/src/main/java/org/drools/drl/parser/antlr4/DroolsParserExceptionFactory.java @@ -0,0 +1,234 @@ +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you 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 + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.drools.drl.parser.antlr4; + +import java.io.PrintWriter; +import java.io.StringWriter; +import java.util.Collection; +import java.util.Map; +import java.util.Map.Entry; + +import org.antlr.v4.runtime.FailedPredicateException; +import org.antlr.v4.runtime.InputMismatchException; +import org.antlr.v4.runtime.NoViableAltException; +import org.antlr.v4.runtime.RecognitionException; +import org.antlr.v4.runtime.Token; +import org.drools.drl.parser.DRLFactory; +import org.drools.drl.parser.DroolsParserException; +import org.drools.drl.parser.lang.DroolsParaphraseTypes; +import org.kie.internal.builder.conf.LanguageLevelOption; + +/** + * Helper class that generates DroolsParserException with user friendly error + * messages. + * + * @see DroolsParserException + */ +public class DroolsParserExceptionFactory { + public final static String TRAILING_SEMI_COLON_NOT_ALLOWED_MESSAGE = "Line %1$d:%2$d trailing semi-colon not allowed%3$s"; + public final static String PARSER_LOCATION_MESSAGE_COMPLETE = " in %1$s %2$s"; + public final static String PARSER_LOCATION_MESSAGE_PART = " in %1$s"; + public final static String UNEXPECTED_EXCEPTION = "Line %1$d:%2$d unexpected exception at input '%3$s'. Exception: %4$s. Stack trace:\n %5$s"; + + private final Collection> paraphrases; + + // TODO: need to deal with this array + private String[] tokenNames = null; + + private final LanguageLevelOption languageLevel; + + /** + * DroolsParserErrorMessages constructor. + * + * @param tokenNames + * tokenNames generated by ANTLR + * @param paraphrases + * paraphrases parser structure + */ + public DroolsParserExceptionFactory(Collection> paraphrases, + LanguageLevelOption languageLevel) { + this.paraphrases = paraphrases; + this.languageLevel = languageLevel; + } + + /** + * This method creates a DroolsParserException for trailing semicolon + * exception, full of information. + * + * @param line + * line number + * @param column + * column position + * @param offset + * char offset + * @return DroolsParserException filled. + */ + public DroolsParserException createTrailingSemicolonException( int line, + int column, + int offset ) { + String message = String + .format( + TRAILING_SEMI_COLON_NOT_ALLOWED_MESSAGE, + line, + column, + formatParserLocation() ); + + return new DroolsParserException( "ERR 104", + message, + line, + column, + offset, + null ); + } + + /** + * This method creates a DroolsParserException full of information. + * + * @param offendingSymbol + * @param line + * @param charPositionInLine + * @param e original exception + * @return DroolsParserException filled. + */ + public DroolsParserException createDroolsException(Object offendingSymbol, int line, int charPositionInLine, String message, RecognitionException e ) { + return new DroolsParserException( determineErrorCode( e ), + String.format("Line %d:%d %s", line, charPositionInLine, message), + line, + charPositionInLine, + determineStartingIndex(offendingSymbol), + e ); + } + + private int determineStartingIndex(Object offendingSymbol) { + if (offendingSymbol instanceof Token) { + return ((Token) offendingSymbol).getStartIndex(); + } + return -1; + } + + /** + * Determines the error code based on a specific subtype of RecognitionException. + */ + private String determineErrorCode( RecognitionException e ) { + if (e == null) { + return "ERR 109"; + } + if ( e instanceof InputMismatchException) { + return "ERR 102"; + } + if ( e instanceof NoViableAltException ) { + return "ERR 101"; + } + if ( e instanceof FailedPredicateException ) { + return "ERR 103"; + } + throw new IllegalArgumentException("Unexpected exception type: " + e); + } + + public DroolsParserException createDroolsException( Exception e, + Token token ) { + StringWriter sw = new StringWriter(); + e.printStackTrace( new PrintWriter(sw) ); + return new DroolsParserException( String.format( + DroolsParserExceptionFactory.UNEXPECTED_EXCEPTION, + token.getLine(), + token.getCharPositionInLine(), + getBetterToken( token ), + e.toString(), + sw.toString() ), + e ); + + } + + /** + * This will take Paraphrases stack, and create a sensible location + */ + private String formatParserLocation() { + StringBuilder sb = new StringBuilder(); + if ( paraphrases != null ) { + for ( Map map : paraphrases ) { + for ( Entry activeEntry : map.entrySet() ) { + if ( activeEntry.getValue().length() == 0 ) { + String kStr = getLocationName( activeEntry.getKey() ); + if( kStr.length() > 0 ){ + sb.append( String.format( PARSER_LOCATION_MESSAGE_PART, kStr ) ); + } + } else { + sb.append( String.format( PARSER_LOCATION_MESSAGE_COMPLETE, + getLocationName( activeEntry.getKey() ), + activeEntry.getValue() ) ); + } + } + } + } + return sb.toString(); + } + + /** + * Returns a string based on Paraphrase Type + * + * @param type + * Paraphrase Type + * @return a string representing the + */ + private String getLocationName( DroolsParaphraseTypes type ) { + switch ( type ) { + case PACKAGE : + return "package"; + case IMPORT : + return "import"; + case FUNCTION_IMPORT : + return "function import"; + case ACCUMULATE_IMPORT : + return "accumulate import"; + case GLOBAL : + return "global"; + case FUNCTION : + return "function"; + case QUERY : + return "query"; + case TEMPLATE : + return "template"; + case RULE : + return "rule"; + case RULE_ATTRIBUTE : + return "rule attribute"; + case PATTERN : + return "pattern"; + case EVAL : + return "eval"; + default : + return ""; + } + } + + /** + * Helper method that creates a user friendly token definition + * + * @param token + * token + * @return user friendly token definition + */ + private String getBetterToken( Token token ) { + if ( token == null ) { + return ""; + } + return DRLFactory.getBetterToken(token.getType(), token.getText(), languageLevel); + } +} diff --git a/drools-drl/drools-drl-parser/src/main/java/org/drools/drl/parser/antlr4/LexerHelper.java b/drools-drl/drools-drl-parser/src/main/java/org/drools/drl/parser/antlr4/LexerHelper.java new file mode 100644 index 00000000000..4960baaf315 --- /dev/null +++ b/drools-drl/drools-drl-parser/src/main/java/org/drools/drl/parser/antlr4/LexerHelper.java @@ -0,0 +1,162 @@ +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you 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 + *

+ * http://www.apache.org/licenses/LICENSE-2.0 + *

+ * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.drools.drl.parser.antlr4; + +import java.util.Set; + +import org.antlr.v4.runtime.CharStream; +import org.antlr.v4.runtime.IntStream; +import org.drools.drl.parser.lang.DroolsSoftKeywords; + +/** + * Helper class for lexer. It requires instance creation to keep track of the lookahead counter. + */ +public class LexerHelper { + + private static final Set semiAndWS = Set.of(';', ' ', '\t', '\n', '\r'); + private static final Set delimiters = Set.of(';', ' ', '\t', '\n', '\r', '"', '\''); + private static final Set statementKeywordsList = Set.of(ParserHelper.statementKeywords); + private static final Set attributeKeywordsList = Set.of(DroolsSoftKeywords.SALIENCE, + DroolsSoftKeywords.ENABLED, + DroolsSoftKeywords.NO + "-" + DroolsSoftKeywords.LOOP, + DroolsSoftKeywords.AUTO + "-" + DroolsSoftKeywords.FOCUS, + DroolsSoftKeywords.LOCK + "-" + DroolsSoftKeywords.ON + "-" + DroolsSoftKeywords.ACTIVE, + DroolsSoftKeywords.AGENDA + "-" + DroolsSoftKeywords.GROUP, + DroolsSoftKeywords.ACTIVATION + "-" + DroolsSoftKeywords.GROUP, + DroolsSoftKeywords.RULEFLOW + "-" + DroolsSoftKeywords.GROUP, + DroolsSoftKeywords.DATE + "-" + DroolsSoftKeywords.EFFECTIVE, + DroolsSoftKeywords.DATE + "-" + DroolsSoftKeywords.EXPIRES, + DroolsSoftKeywords.DIALECT, + DroolsSoftKeywords.CALENDARS, + DroolsSoftKeywords.TIMER, + DroolsSoftKeywords.DURATION, + DroolsSoftKeywords.REFRACT, + DroolsSoftKeywords.DIRECT); + + private final CharStream input; + private int lookAheadCounter; + + public LexerHelper(CharStream input) { + this.input = input; + this.lookAheadCounter = 1; + } + + /** + * Determine if the current token is the end of a RHS DRL by lookahead. + * 1. 'end' + * 2. skip semi, WS, and comment + * 3. next token should be EOF or statement or attribute keyword + * + * TODO: This method is low-level and may be too complex in order to keep backward compatibility. + * This could be refactored by going back to a parser rather than the lexer island mode. + */ + boolean isRhsDrlEnd() { + if (!validateDrlEnd()) { + return false; + } + skipSemiAndWSAndComment(); + + return validateEOForNextStatement(); + } + + private boolean validateDrlEnd() { + return captureNextToken().equals(DroolsSoftKeywords.END); + } + + private String captureNextToken() { + StringBuilder sb = new StringBuilder(); + while (true) { + int la = input.LA(lookAheadCounter); + if (delimiters.contains((char) la) || la == IntStream.EOF) { + break; + } + sb.append((char) la); + lookAheadCounter++; + } + return sb.toString(); // never null + } + + private void skipSemiAndWSAndComment() { + do { + // skip semi and WS, and repeat that so long as it's followed by a valid and skipped comment + skipSemiAndWS(); + } while (skipComment()); + } + + private void skipSemiAndWS() { + while (true) { + int la = input.LA(lookAheadCounter); + if (!semiAndWS.contains((char) la)) { + break; + } + lookAheadCounter++; + } + } + + // if comment is found, skip it and return true + private boolean skipComment() { + boolean skipped = false; + // skip single line comment + int la1 = input.LA(lookAheadCounter); + int la2 = input.LA(lookAheadCounter + 1); + if (la1 == '/' && la2 == '/') { + // skip single line comment + skipSingleLineComment(); + skipped = true; + } else if (la1 == '/' && la2 == '*') { + // skip multi line comment + skipMultiLineComment(); + skipped = true; + } + + return skipped; + } + + private void skipSingleLineComment() { + while (true) { + int la = input.LA(lookAheadCounter); + if (la == '\n' || la == IntStream.EOF) { // this can handle `\r\n` as well + break; + } + lookAheadCounter++; + } + } + + private void skipMultiLineComment() { + while (true) { + int la = input.LA(lookAheadCounter); + if (la == IntStream.EOF) { + break; + } + if (la == '*' && input.LA(lookAheadCounter + 1) == '/') { + lookAheadCounter += 2; + break; + } + lookAheadCounter++; + } + } + + private boolean validateEOForNextStatement() { + if (input.LA(lookAheadCounter) == IntStream.EOF) { + return true; + } + String nextToken = captureNextToken(); + return statementKeywordsList.contains(nextToken) || attributeKeywordsList.contains(nextToken); + } +} diff --git a/drools-drl/drools-drl-parser/src/main/java/org/drools/drl/parser/antlr4/ParserHelper.java b/drools-drl/drools-drl-parser/src/main/java/org/drools/drl/parser/antlr4/ParserHelper.java new file mode 100644 index 00000000000..fed7024c20c --- /dev/null +++ b/drools-drl/drools-drl-parser/src/main/java/org/drools/drl/parser/antlr4/ParserHelper.java @@ -0,0 +1,677 @@ +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you 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 + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +/* + * 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 + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.drools.drl.parser.antlr4; + +import java.util.ArrayDeque; +import java.util.ArrayList; +import java.util.Deque; +import java.util.HashMap; +import java.util.LinkedList; +import java.util.List; +import java.util.Map; + +import org.antlr.runtime.RecognizerSharedState; +import org.antlr.v4.runtime.CommonToken; +import org.antlr.v4.runtime.RecognitionException; +import org.antlr.v4.runtime.Token; +import org.antlr.v4.runtime.TokenStream; +import org.drools.drl.ast.descr.AttributeDescr; +import org.drools.drl.ast.descr.BaseDescr; +import org.drools.drl.ast.dsl.AbstractClassTypeDeclarationBuilder; +import org.drools.drl.ast.dsl.AccumulateDescrBuilder; +import org.drools.drl.ast.dsl.AccumulateImportDescrBuilder; +import org.drools.drl.ast.dsl.AttributeDescrBuilder; +import org.drools.drl.ast.dsl.AttributeSupportBuilder; +import org.drools.drl.ast.dsl.BehaviorDescrBuilder; +import org.drools.drl.ast.dsl.CEDescrBuilder; +import org.drools.drl.ast.dsl.CollectDescrBuilder; +import org.drools.drl.ast.dsl.ConditionalBranchDescrBuilder; +import org.drools.drl.ast.dsl.DeclareDescrBuilder; +import org.drools.drl.ast.dsl.DescrBuilder; +import org.drools.drl.ast.dsl.DescrFactory; +import org.drools.drl.ast.dsl.EntryPointDeclarationDescrBuilder; +import org.drools.drl.ast.dsl.EnumDeclarationDescrBuilder; +import org.drools.drl.ast.dsl.EnumLiteralDescrBuilder; +import org.drools.drl.ast.dsl.EvalDescrBuilder; +import org.drools.drl.ast.dsl.FieldDescrBuilder; +import org.drools.drl.ast.dsl.ForallDescrBuilder; +import org.drools.drl.ast.dsl.FunctionDescrBuilder; +import org.drools.drl.ast.dsl.GlobalDescrBuilder; +import org.drools.drl.ast.dsl.GroupByDescrBuilder; +import org.drools.drl.ast.dsl.ImportDescrBuilder; +import org.drools.drl.ast.dsl.NamedConsequenceDescrBuilder; +import org.drools.drl.ast.dsl.PackageDescrBuilder; +import org.drools.drl.ast.dsl.PatternContainerDescrBuilder; +import org.drools.drl.ast.dsl.PatternDescrBuilder; +import org.drools.drl.ast.dsl.QueryDescrBuilder; +import org.drools.drl.ast.dsl.RuleDescrBuilder; +import org.drools.drl.ast.dsl.TypeDeclarationDescrBuilder; +import org.drools.drl.ast.dsl.UnitDescrBuilder; +import org.drools.drl.ast.dsl.WindowDeclarationDescrBuilder; +import org.drools.drl.parser.DroolsParserException; +import org.drools.drl.parser.lang.DroolsEditorType; +import org.drools.drl.parser.lang.DroolsParaphraseTypes; +import org.drools.drl.parser.lang.DroolsSentence; +import org.drools.drl.parser.lang.DroolsSentenceType; +import org.drools.drl.parser.lang.DroolsSoftKeywords; +import org.drools.drl.parser.lang.DroolsToken; +import org.kie.internal.builder.conf.LanguageLevelOption; + +/** + * This is a class to hold all the helper functions/methods used + * by the DRL parser + */ +public class ParserHelper { + public static final String[] statementKeywords = new String[]{ + DroolsSoftKeywords.PACKAGE, + DroolsSoftKeywords.UNIT, + DroolsSoftKeywords.IMPORT, + DroolsSoftKeywords.GLOBAL, + DroolsSoftKeywords.DECLARE, + DroolsSoftKeywords.FUNCTION, + DroolsSoftKeywords.RULE, + DroolsSoftKeywords.QUERY + }; + + public List errors = new ArrayList<>(); + public LinkedList editorInterface = null; + public boolean isEditorInterfaceEnabled = false; + private Deque> paraphrases = new ArrayDeque<>(); + + // parameters from parser + private DroolsParserExceptionFactory errorMessageFactory = null; + private TokenStream input = null; + private RecognizerSharedState state = null; + + private String leftMostExpr = null; + + // helper attribute + private boolean hasOperator = false; + + private final LanguageLevelOption languageLevel; + + public ParserHelper(TokenStream input, + LanguageLevelOption languageLevel) { + this.errorMessageFactory = new DroolsParserExceptionFactory( paraphrases, languageLevel ); + this.input = input; + this.languageLevel = languageLevel; + } + + public LinkedList getEditorInterface() { + return editorInterface; + } + + public void setLeftMostExpr( String value ) { + this.leftMostExpr = value; + } + + public String getLeftMostExpr() { + return this.leftMostExpr; + } + + public void enableEditorInterface() { + isEditorInterfaceEnabled = true; + } + + public void disableEditorInterface() { + isEditorInterfaceEnabled = false; + } + + public void setHasOperator( boolean hasOperator ) { + this.hasOperator = hasOperator; + } + + public boolean getHasOperator() { + return hasOperator; + } + + public void beginSentence( DroolsSentenceType sentenceType ) { + if ( isEditorInterfaceEnabled ) { + if ( null == editorInterface ) { + editorInterface = new LinkedList<>(); + } + if (editorInterface.isEmpty()){ + DroolsSentence sentence = new DroolsSentence(); + sentence.setType( sentenceType ); + editorInterface.add( sentence ); + } + } + } + + public DroolsSentence getActiveSentence() { + return editorInterface.getLast(); + } + + public void emit( List< ? > tokens, + DroolsEditorType editorType ) { + if ( isEditorInterfaceEnabled && tokens != null ) { + for ( Object activeObject : tokens ) { + emit( (Token) activeObject, + editorType ); + } + } + } + + public void emit( Token token, + DroolsEditorType editorType ) { + if ( isEditorInterfaceEnabled && token != null && editorType != null ) { + ((DroolsToken) token).setEditorType( editorType ); + getActiveSentence().addContent( (DroolsToken) token ); + } + } + + public void emit( int activeContext ) { + if ( isEditorInterfaceEnabled ) { + getActiveSentence().addContent( activeContext ); + } + } + + public DroolsToken getLastTokenOnList( LinkedList< ? > list ) { + DroolsToken lastToken = null; + for ( Object object : list ) { + if ( object instanceof DroolsToken ) { + lastToken = (DroolsToken) object; + } + } + return lastToken; + } + + public String retrieveLT( int LTNumber ) { + if ( null == input ) return null; + if ( null == input.LT( LTNumber ) ) return null; + if ( null == input.LT( LTNumber ).getText() ) return null; + + return input.LT( LTNumber ).getText(); + } + + public boolean validateLT( int LTNumber, + String text ) { + String text2Validate = retrieveLT( LTNumber ); + return validateText( text, text2Validate ); + } + + private boolean validateText( String text, String text2Validate ) { + return text2Validate != null && text2Validate.equals( text ); + } + + public boolean isPluggableEvaluator( int offset, + boolean negated ) { + String text2Validate = retrieveLT( offset ); + return text2Validate != null && DroolsSoftKeywords.isOperator(text2Validate, negated); + } + + /** + * Check if the next token is a registered operator. + * The registry is dynamic, so we can add custom operators dynamically. + * @see org.drools.drl.parser.impl.Operator#addOperatorToRegistry(String, boolean) + * + * @param negated true if the operator needs to support negation + * @return true if the next token is a registered operator + */ + public boolean isPluggableEvaluator( boolean negated ) { + return isPluggableEvaluator( 1, + negated ); + } + + public boolean validateIdentifierKey( String text ) { + return validateLT( 1, + text ); + } + + public boolean validateCEKeyword( int index ) { + String text2Validate = retrieveLT( index ); + return validateText( text2Validate, + DroolsSoftKeywords.NOT ) || + validateText( text2Validate, + DroolsSoftKeywords.EXISTS ) || + validateText( text2Validate, + DroolsSoftKeywords.FORALL ) || + validateText( text2Validate, + DroolsSoftKeywords.AND ) || + validateText( text2Validate, + DroolsSoftKeywords.OR ) || + validateText( text2Validate, + DroolsSoftKeywords.COLLECT ) || + validateText( text2Validate, + DroolsSoftKeywords.FROM ) || + validateText( text2Validate, + DroolsSoftKeywords.END ) || + validateText( text2Validate, + DroolsSoftKeywords.EVAL ) || + validateText( text2Validate, + DroolsSoftKeywords.OVER ) || + validateText( text2Validate, + DroolsSoftKeywords.THEN ); + } + + public boolean validateStatement( int index ) { + boolean ret = false; + String text2Validate = retrieveLT( index ); + for ( String st : statementKeywords ) { + if ( validateText( text2Validate, + st ) ) { + ret = true; + break; + } + } + return ret || validateAttribute( index ); + } + + public boolean validateAttribute( int index ) { + String text2Validate = retrieveLT( index ); + return validateText( text2Validate, + DroolsSoftKeywords.SALIENCE ) || + validateText( text2Validate, + DroolsSoftKeywords.ENABLED ) || + (validateText( text2Validate, + DroolsSoftKeywords.NO ) && + validateLT( index + 1, + "-" ) && + validateLT( index + 2, + DroolsSoftKeywords.LOOP )) || + (validateText( text2Validate, + DroolsSoftKeywords.AUTO ) && + validateLT( index + 1, + "-" ) && + validateLT( index + 2, + DroolsSoftKeywords.FOCUS )) || + (validateText( text2Validate, + DroolsSoftKeywords.LOCK ) && + validateLT( index + 1, + "-" ) && + validateLT( index + 2, + DroolsSoftKeywords.ON ) && + validateLT( index + 3, + "-" ) && + validateLT( index + 4, + DroolsSoftKeywords.ACTIVE )) || + (validateText( text2Validate, + DroolsSoftKeywords.AGENDA ) && + validateLT( index + 1, + "-" ) && + validateLT( index + 2, + DroolsSoftKeywords.GROUP )) || + (validateText( text2Validate, + DroolsSoftKeywords.ACTIVATION ) && + validateLT( index + 1, + "-" ) && + validateLT( index + 2, + DroolsSoftKeywords.GROUP )) || + (validateText( text2Validate, + DroolsSoftKeywords.RULEFLOW ) && + validateLT( index + 1, + "-" ) && + validateLT( index + 2, + DroolsSoftKeywords.GROUP )) || + (validateText( text2Validate, + DroolsSoftKeywords.DATE ) && + validateLT( index + 1, + "-" ) && + validateLT( index + 2, + DroolsSoftKeywords.EFFECTIVE )) || + (validateText( text2Validate, + DroolsSoftKeywords.DATE ) && + validateLT( index + 1, + "-" ) && + validateLT( index + 2, + DroolsSoftKeywords.EXPIRES )) || + validateText( text2Validate, + DroolsSoftKeywords.DIALECT ) || + validateText( text2Validate, + DroolsSoftKeywords.CALENDARS ) || + validateText( text2Validate, + DroolsSoftKeywords.TIMER ) || + validateText( text2Validate, + DroolsSoftKeywords.DURATION ) || + validateText( text2Validate, + DroolsSoftKeywords.REFRACT ) || + validateText( text2Validate, + DroolsSoftKeywords.DIRECT ); + } + + public void reportError(Object offendingSymbol, int line, int charPositionInLine, String message, RecognitionException ex ) { + errors.add( errorMessageFactory.createDroolsException( offendingSymbol, line, charPositionInLine, message, ex ) ); + } + + public void reportError( Exception e ) { + try { + errors.add( errorMessageFactory.createDroolsException( e, + input.LT( 1 ) ) ); + } catch (Exception ignored) { + errors.add(new DroolsParserException( "Unexpected error: " + e.getMessage(), e )); + } + } + + /** return the raw DroolsParserException errors */ + public List getErrors() { + return errors; + } + + /** Return a list of pretty strings summarising the errors */ + public List getErrorMessages() { + List messages = new ArrayList<>( errors.size() ); + + for ( DroolsParserException activeException : errors ) { + messages.add( activeException.getMessage() ); + } + + return messages; + } + + /** return true if any parser errors were accumulated */ + public boolean hasErrors() { + return !errors.isEmpty(); + } + + /** + * Method that adds a paraphrase type into paraphrases stack. + * + * @param type + * paraphrase type + */ + public void pushParaphrases( DroolsParaphraseTypes type ) { + Map activeMap = new HashMap<>(); + activeMap.put( type, + "" ); + paraphrases.push( activeMap ); + } + + public Map popParaphrases() { + return paraphrases.pop(); + } + + /** + * Method that sets paraphrase value for a type into paraphrases stack. + * + * @param type + * paraphrase type + * @param value + * paraphrase value + */ + public void setParaphrasesValue( DroolsParaphraseTypes type, + String value ) { + paraphrases.peek().put( type, + value ); + } + + void setStart( DescrBuilder< ? , ? > db ) { + setStart( db, + input.LT( 1 ) ); + } + + void setStart( DescrBuilder< ? , ? > db, + Token first ) { + if ( db != null && first != null ) { + db.startCharacter( ((CommonToken) first).getStartIndex() ).startLocation( first.getLine(), + first.getCharPositionInLine() ); + } + } + + void setStart( BaseDescr descr, + Token first ) { + if ( descr != null && first != null ) { + descr.setLocation( first.getLine(), + first.getCharPositionInLine() ); + descr.setStartCharacter( ((CommonToken) first).getStartIndex() ); + } + } + + void setEnd( BaseDescr descr ) { + Token last = input.LT( -1 ); + if ( descr != null && last != null ) { + int endLocation = last.getText() != null ? last.getCharPositionInLine() + last.getText().length() - 1 : last.getCharPositionInLine(); + descr.setEndCharacter( ((CommonToken) last).getStopIndex() + 1 ); + descr.setEndLocation( last.getLine(), + endLocation ); + } + } + + void setEnd( DescrBuilder< ? , ? > db ) { + Token last = input.LT( -1 ); + if ( db != null && last != null ) { + int endLocation = last.getText() != null ? last.getCharPositionInLine() + last.getText().length() - 1 : last.getCharPositionInLine(); + db.endCharacter( ((CommonToken) last).getStopIndex() + 1 ).endLocation( last.getLine(), + endLocation ); + } + } + + @SuppressWarnings("unchecked") + public > T start( DescrBuilder< ? , ? > ctxBuilder, + Class clazz, + String param ) { + if ( state.backtracking == 0 ) { + if ( PackageDescrBuilder.class.isAssignableFrom( clazz ) ) { + pushParaphrases( DroolsParaphraseTypes.PACKAGE ); + beginSentence( DroolsSentenceType.PACKAGE ); + setStart( ctxBuilder ); + } else if ( ImportDescrBuilder.class.isAssignableFrom( clazz ) ) { + ImportDescrBuilder imp; + if ( validateLT( 2, + DroolsSoftKeywords.FUNCTION ) || + validateLT( 2, + DroolsSoftKeywords.STATIC ) ) { + imp = ctxBuilder == null ? + DescrFactory.newPackage().newFunctionImport() : + ((PackageDescrBuilder) ctxBuilder).newFunctionImport(); + } else { + imp = ctxBuilder == null ? + DescrFactory.newPackage().newImport() : + ((PackageDescrBuilder) ctxBuilder).newImport(); + } + pushParaphrases( DroolsParaphraseTypes.IMPORT ); + beginSentence( DroolsSentenceType.IMPORT_STATEMENT ); + setStart( imp ); + return (T) imp; + } else if ( UnitDescrBuilder.class.isAssignableFrom( clazz ) ) { + UnitDescrBuilder imp = ctxBuilder == null ? + DescrFactory.newPackage().newUnit() : + ((PackageDescrBuilder) ctxBuilder).newUnit(); + pushParaphrases( DroolsParaphraseTypes.UNIT ); + beginSentence( DroolsSentenceType.UNIT ); + setStart( imp ); + return (T) imp; + } else if ( AccumulateImportDescrBuilder.class.isAssignableFrom( clazz ) ) { + AccumulateImportDescrBuilder imp = ctxBuilder == null ? + DescrFactory.newPackage().newAccumulateImport() : + ((PackageDescrBuilder) ctxBuilder).newAccumulateImport(); + pushParaphrases( DroolsParaphraseTypes.ACCUMULATE_IMPORT ); + beginSentence( DroolsSentenceType.ACCUMULATE_IMPORT_STATEMENT ); + setStart( imp ); + return (T) imp; + } else if ( GlobalDescrBuilder.class.isAssignableFrom( clazz ) ) { + GlobalDescrBuilder global = ctxBuilder == null ? + DescrFactory.newPackage().newGlobal() : + ((PackageDescrBuilder) ctxBuilder).newGlobal(); + pushParaphrases( DroolsParaphraseTypes.GLOBAL ); + beginSentence( DroolsSentenceType.GLOBAL ); + setStart( global ); + return (T) global; + } else if ( DeclareDescrBuilder.class.isAssignableFrom( clazz ) ) { + DeclareDescrBuilder declare = ctxBuilder == null ? + DescrFactory.newPackage().newDeclare() : + ((PackageDescrBuilder) ctxBuilder).newDeclare(); + return (T) declare; + } else if ( TypeDeclarationDescrBuilder.class.isAssignableFrom( clazz ) ) { + TypeDeclarationDescrBuilder declare = ctxBuilder == null ? + DescrFactory.newPackage().newDeclare().type() : + ((DeclareDescrBuilder) ctxBuilder).type(); + pushParaphrases( DroolsParaphraseTypes.TYPE_DECLARE ); + beginSentence( DroolsSentenceType.TYPE_DECLARATION ); + setStart( declare ); + return (T) declare; + } else if ( EnumDeclarationDescrBuilder.class.isAssignableFrom( clazz ) ) { + EnumDeclarationDescrBuilder declare = ctxBuilder == null ? + DescrFactory.newPackage().newDeclare().enumerative() : + ((DeclareDescrBuilder) ctxBuilder).enumerative(); + pushParaphrases( DroolsParaphraseTypes.ENUM_DECLARE ); + beginSentence( DroolsSentenceType.ENUM_DECLARATION ); + setStart( declare ); + return (T) declare; + }else if ( EntryPointDeclarationDescrBuilder.class.isAssignableFrom( clazz ) ) { + EntryPointDeclarationDescrBuilder declare = ctxBuilder == null ? + DescrFactory.newPackage().newDeclare().entryPoint() : + ((DeclareDescrBuilder) ctxBuilder).entryPoint(); + pushParaphrases( DroolsParaphraseTypes.ENTRYPOINT_DECLARE ); + beginSentence( DroolsSentenceType.ENTRYPOINT_DECLARATION ); + setStart( declare ); + return (T) declare; + } else if ( WindowDeclarationDescrBuilder.class.isAssignableFrom( clazz ) ) { + WindowDeclarationDescrBuilder declare = ctxBuilder == null ? + DescrFactory.newPackage().newDeclare().window() : + ((DeclareDescrBuilder) ctxBuilder).window(); + pushParaphrases( DroolsParaphraseTypes.WINDOW_DECLARE ); + beginSentence( DroolsSentenceType.WINDOW_DECLARATION ); + setStart( declare ); + return (T) declare; + } else if ( FieldDescrBuilder.class.isAssignableFrom( clazz ) ) { + FieldDescrBuilder field = ((AbstractClassTypeDeclarationBuilder) ctxBuilder).newField( param ); + setStart( field ); + return (T) field; + } else if ( EnumLiteralDescrBuilder.class.isAssignableFrom( clazz ) ) { + EnumLiteralDescrBuilder literal = ((EnumDeclarationDescrBuilder) ctxBuilder).newEnumLiteral( param ); + setStart( literal ); + return (T) literal; + } else if ( FunctionDescrBuilder.class.isAssignableFrom( clazz ) ) { + FunctionDescrBuilder function; + if ( ctxBuilder == null ) { + function = DescrFactory.newPackage().newFunction(); + } else { + PackageDescrBuilder pkg = (PackageDescrBuilder) ctxBuilder; + function = pkg.newFunction().namespace( pkg.getDescr().getName() ); + AttributeDescr attribute = pkg.getDescr().getAttribute( "dialect" ); + if ( attribute != null ) { + function.dialect( attribute.getValue() ); + } + } + pushParaphrases( DroolsParaphraseTypes.FUNCTION ); + beginSentence( DroolsSentenceType.FUNCTION ); + setStart( function ); + return (T) function; + } else if ( RuleDescrBuilder.class.isAssignableFrom( clazz ) ) { + RuleDescrBuilder rule = ctxBuilder == null ? + DescrFactory.newPackage().newRule() : + ((PackageDescrBuilder) ctxBuilder).newRule(); + pushParaphrases( DroolsParaphraseTypes.RULE ); + beginSentence( DroolsSentenceType.RULE ); + setStart( rule ); + return (T) rule; + } else if ( QueryDescrBuilder.class.isAssignableFrom( clazz ) ) { + QueryDescrBuilder query = ctxBuilder == null ? + DescrFactory.newPackage().newQuery() : + ((PackageDescrBuilder) ctxBuilder).newQuery(); + pushParaphrases( DroolsParaphraseTypes.QUERY ); + beginSentence( DroolsSentenceType.QUERY ); + setStart( query ); + return (T) query; + } else if ( AttributeDescrBuilder.class.isAssignableFrom( clazz ) ) { + AttributeDescrBuilder< ? > attribute = ((AttributeSupportBuilder< ? >) ctxBuilder).attribute(param); + setStart( attribute ); + return (T) attribute; + } else if ( EvalDescrBuilder.class.isAssignableFrom( clazz ) ) { + EvalDescrBuilder< ? > eval = ((CEDescrBuilder< ? , ? >) ctxBuilder).eval(); + pushParaphrases( DroolsParaphraseTypes.EVAL ); + beginSentence( DroolsSentenceType.EVAL ); + setStart( eval ); + return (T) eval; + } else if ( ForallDescrBuilder.class.isAssignableFrom( clazz ) ) { + ForallDescrBuilder< ? > forall = ((CEDescrBuilder< ? , ? >) ctxBuilder).forall(); + setStart( forall ); + return (T) forall; + } else if ( CEDescrBuilder.class.isAssignableFrom( clazz ) ) { + setStart( ctxBuilder ); + return (T) ctxBuilder; + } else if ( PatternDescrBuilder.class.isAssignableFrom( clazz ) ) { + PatternDescrBuilder< ? > pattern = ((PatternContainerDescrBuilder< ? , ? >) ctxBuilder).pattern(); + pushParaphrases( DroolsParaphraseTypes.PATTERN ); + setStart( pattern ); + return (T) pattern; + } else if ( CollectDescrBuilder.class.isAssignableFrom( clazz ) ) { + CollectDescrBuilder< ? > collect = ((PatternDescrBuilder< ? >) ctxBuilder).from().collect(); + setStart( collect ); + return (T) collect; + } else if ( GroupByDescrBuilder.class.isAssignableFrom(clazz) ) { + // GroupBy extends Accumulate and thus need to be before it + GroupByDescrBuilder< ? > groupBy = ((PatternDescrBuilder< ? >) ctxBuilder).from().groupBy(); + setStart( groupBy ); + return (T) groupBy; + } else if ( AccumulateDescrBuilder.class.isAssignableFrom( clazz ) ) { + AccumulateDescrBuilder< ? > accumulate = ((PatternDescrBuilder< ? >) ctxBuilder).from().accumulate(); + setStart( accumulate ); + return (T) accumulate; + } else if ( BehaviorDescrBuilder.class.isAssignableFrom( clazz ) ) { + BehaviorDescrBuilder< ? > behavior = ((PatternDescrBuilder< ? >) ctxBuilder).behavior(); + setStart( behavior ); + return (T) behavior; + } else if ( NamedConsequenceDescrBuilder.class.isAssignableFrom( clazz ) ) { + NamedConsequenceDescrBuilder< ? > namedConsequence = ((CEDescrBuilder< ? , ? >) ctxBuilder).namedConsequence(); + setStart( namedConsequence ); + return (T) namedConsequence; + } else if ( ConditionalBranchDescrBuilder.class.isAssignableFrom( clazz ) ) { + ConditionalBranchDescrBuilder< ? > conditionalBranch = ((CEDescrBuilder< ? , ? >) ctxBuilder).conditionalBranch(); + setStart( conditionalBranch ); + return (T) conditionalBranch; + } + } + return null; + } + + @SuppressWarnings("unchecked") + public > T end( Class clazz, + DescrBuilder< ? , ? > builder ) { + if ( state.backtracking == 0 ) { + if ( !(FieldDescrBuilder.class.isAssignableFrom( clazz ) || + AttributeDescrBuilder.class.isAssignableFrom( clazz ) || + CEDescrBuilder.class.isAssignableFrom( clazz ) || + CollectDescrBuilder.class.isAssignableFrom( clazz ) || + AccumulateDescrBuilder.class.isAssignableFrom( clazz ) || + ForallDescrBuilder.class.isAssignableFrom( clazz ) || + BehaviorDescrBuilder.class.isAssignableFrom( clazz ) || + ConditionalBranchDescrBuilder.class.isAssignableFrom( clazz ) || + NamedConsequenceDescrBuilder.class.isAssignableFrom( clazz )) ) { + popParaphrases(); + } + + if (RuleDescrBuilder.class.isAssignableFrom(clazz)) { + RuleDescrBuilder ruleDescrBuilder = (RuleDescrBuilder)builder; + ruleDescrBuilder.end().getDescr().afterRuleAdded(ruleDescrBuilder.getDescr()); + } + + setEnd( builder ); + return (T) builder; + } + return null; + } + + public String[] getStatementKeywords() { + return statementKeywords; + } +} diff --git a/drools-drl/drools-drl-parser/src/main/java/org/drools/drl/parser/lang/DRL6Parser.java b/drools-drl/drools-drl-parser/src/main/java/org/drools/drl/parser/lang/DRL6Parser.java index ebfec99223d..f2181a37b86 100644 --- a/drools-drl/drools-drl-parser/src/main/java/org/drools/drl/parser/lang/DRL6Parser.java +++ b/drools-drl/drools-drl-parser/src/main/java/org/drools/drl/parser/lang/DRL6Parser.java @@ -85,6 +85,10 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import static org.drools.drl.parser.util.ParserStringUtils.appendPrefix; +import static org.drools.drl.parser.util.ParserStringUtils.safeStripDelimiters; +import static org.drools.drl.parser.util.ParserStringUtils.safeStripStringDelimiters; + public class DRL6Parser extends AbstractDRLParser implements DRLParser { private static final Logger LOG = LoggerFactory.getLogger(DRL6Parser.class); @@ -3778,44 +3782,7 @@ private void constraint(PatternDescrBuilder pattern, private String toExpression(String prefix, int first, int last) { String expr = input.toString(first, last); - if (prefix.length() == 0) { - return expr; - } - StringBuilder sb = new StringBuilder(); - toOrExpression(sb, prefix, expr); - return sb.toString(); - } - - private void toOrExpression(StringBuilder sb, String prefix, String expr) { - int start = 0; - int end = expr.indexOf("||"); - do { - if (start > 0) { - sb.append(" || "); - } - toAndExpression(sb, prefix, end > 0 ? expr.substring(start, end) : expr.substring(start)); - start = end + 2; - end = expr.indexOf("||", start); - } while (start > 1); - } - - private void toAndExpression(StringBuilder sb, String prefix, String expr) { - int start = 0; - int end = expr.indexOf("&&"); - do { - if (start > 0) { - sb.append(" && "); - } - sb.append(toExpression(prefix, end > 0 ? expr.substring(start, end) : expr.substring(start))); - start = end + 2; - end = expr.indexOf("&&", start); - } while (start > 1); - } - - private String toExpression(String prefix, String expr) { - expr = expr.trim(); - int colonPos = expr.indexOf(":"); - return colonPos < 0 ? prefix + expr : expr.substring(0, colonPos + 1) + " " + prefix + expr.substring(colonPos + 1).trim(); + return appendPrefix(prefix, expr); } private boolean speculateNestedConstraint() throws RecognitionException { @@ -5227,29 +5194,4 @@ public boolean mismatchIsMissingToken(TokenStream input, return false; } - private String safeStripDelimiters(String value, - String left, - String right) { - if (value != null) { - value = value.trim(); - if (value.length() >= left.length() + right.length() && - value.startsWith(left) && value.endsWith(right)) { - value = value.substring(left.length(), - value.length() - right.length()); - } - } - return value; - } - - private String safeStripStringDelimiters(String value) { - if (value != null) { - value = value.trim(); - if (value.length() >= 2 && value.startsWith("\"") && value.endsWith("\"")) { - value = value.substring(1, - value.length() - 1); - } - } - return value; - } - } diff --git a/drools-drl/drools-drl-parser/src/main/java/org/drools/drl/parser/util/ParserStringUtils.java b/drools-drl/drools-drl-parser/src/main/java/org/drools/drl/parser/util/ParserStringUtils.java new file mode 100644 index 00000000000..6226cc070e0 --- /dev/null +++ b/drools-drl/drools-drl-parser/src/main/java/org/drools/drl/parser/util/ParserStringUtils.java @@ -0,0 +1,102 @@ +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you 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 + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.drools.drl.parser.util; + +/** + * String utilities used by DRL Parser. Not dependent on ANTLR version. + */ +public class ParserStringUtils { + + private ParserStringUtils() { + // Private constructor to prevent instantiation. + } + + /** + * Strip string delimiters (e.g. "foo" -> foo) + */ + public static String safeStripStringDelimiters(String value) { + if (value != null) { + value = value.trim(); + if (value.length() >= 2 && ( + value.startsWith("\"") && value.endsWith("\"") + || value.startsWith("'") && value.endsWith("'") + )) { + value = value.substring(1, value.length() - 1); + } + } + return value; + } + + public static String safeStripDelimiters(String value, String left, String right) { + if (value != null) { + value = value.trim(); + if (value.length() >= left.length() + right.length() && + value.startsWith(left) && value.endsWith(right)) { + value = value.substring(left.length(), + value.length() - right.length()); + } + } + return value; + } + + /** + * Append a prefix to a grouped constraint. + * Even if the constraint contains || and/or &&, append the prefix to each element. + */ + public static String appendPrefix(String prefix, String expr) { + if (prefix.length() == 0) { + return expr; + } + StringBuilder sb = new StringBuilder(); + appendPrefixToOrExpression(sb, prefix, expr); + return sb.toString(); + } + + private static void appendPrefixToOrExpression(StringBuilder sb, String prefix, String expr) { + int start = 0; + int end = expr.indexOf("||"); + do { + if (start > 0) { + sb.append(" || "); + } + appendPrefixToAndExpression(sb, prefix, end > 0 ? expr.substring(start, end) : expr.substring(start)); + start = end + 2; + end = expr.indexOf("||", start); + } while (start > 1); + } + + private static void appendPrefixToAndExpression(StringBuilder sb, String prefix, String expr) { + int start = 0; + int end = expr.indexOf("&&"); + do { + if (start > 0) { + sb.append(" && "); + } + sb.append(appendPrefixToExpression(prefix, end > 0 ? expr.substring(start, end) : expr.substring(start))); + start = end + 2; + end = expr.indexOf("&&", start); + } while (start > 1); + } + + private static String appendPrefixToExpression(String prefix, String expr) { + expr = expr.trim(); + int colonPos = expr.indexOf(":"); + return colonPos < 0 ? prefix + expr : expr.substring(0, colonPos + 1) + " " + prefix + expr.substring(colonPos + 1).trim(); + } +} diff --git a/drools-drl/drools-drl-parser/src/test/java/org/drools/drl/parser/util/ParserStringUtilsTest.java b/drools-drl/drools-drl-parser/src/test/java/org/drools/drl/parser/util/ParserStringUtilsTest.java new file mode 100644 index 00000000000..9ef0e6edd5a --- /dev/null +++ b/drools-drl/drools-drl-parser/src/test/java/org/drools/drl/parser/util/ParserStringUtilsTest.java @@ -0,0 +1,66 @@ +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you 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 + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.drools.drl.parser.util; + +import org.junit.jupiter.api.Test; + +import static org.assertj.core.api.Assertions.assertThat; + +public class ParserStringUtilsTest { + + @Test + public void appendPrefix() { + String prefix = "prefix."; + String expr = "a == 1"; + String result = ParserStringUtils.appendPrefix(prefix, expr); + assertThat(result).isEqualToIgnoringWhitespace("prefix.a == 1"); + } + + @Test + public void appendPrefixWithAnd() { + String prefix = "prefix."; + String expr = "a == 1 && b.equals(\"foo\")"; + String result = ParserStringUtils.appendPrefix(prefix, expr); + assertThat(result).isEqualToIgnoringWhitespace("prefix.a == 1 && prefix.b.equals(\"foo\")"); + } + + @Test + public void appendPrefixWithOr() { + String prefix = "prefix."; + String expr = "a == 1 || b.equals(\"foo\")"; + String result = ParserStringUtils.appendPrefix(prefix, expr); + assertThat(result).isEqualToIgnoringWhitespace("prefix.a == 1 || prefix.b.equals(\"foo\")"); + } + + @Test + public void appendPrefixWithANDOr() { + String prefix = "prefix."; + String expr = "a == 1 && b.equals(\"foo\") || c == 2 && d.equals(\"bar\")"; + String result = ParserStringUtils.appendPrefix(prefix, expr); + assertThat(result).isEqualToIgnoringWhitespace("prefix.a == 1 && prefix.b.equals(\"foo\") || prefix.c == 2 && prefix.d.equals(\"bar\")"); + } + + @Test + public void appendPrefixWithBindingVariable() { + String prefix = "prefix."; + String expr = "$a : a == 1 && $b : b.equals(\"foo\")"; + String result = ParserStringUtils.appendPrefix(prefix, expr); + assertThat(result).isEqualToIgnoringWhitespace("$a : prefix.a == 1 && $b : prefix.b.equals(\"foo\")"); + } +} diff --git a/drools-drl/pom.xml b/drools-drl/pom.xml index 91f12f3d758..2fb61bb3006 100644 --- a/drools-drl/pom.xml +++ b/drools-drl/pom.xml @@ -39,6 +39,7 @@ drools-drl-ast drools-drl-extensions drools-drl-parser + drools-drl-parser-tests diff --git a/drools-drlonyaml-parent/pom.xml b/drools-drlonyaml-parent/pom.xml index 9976e1ecbfe..a1f8cb50797 100644 --- a/drools-drlonyaml-parent/pom.xml +++ b/drools-drlonyaml-parent/pom.xml @@ -31,6 +31,15 @@ Drools :: DRL on YAML pom + + + drools-drlonyaml-schemagen + drools-drlonyaml-model + drools-drlonyaml-todrl + drools-drlonyaml-cli + drools-drlonyaml-cli-tests + + allSubmodules @@ -40,30 +49,9 @@ - drools-drlonyaml-schemagen - drools-drlonyaml-model - drools-drlonyaml-todrl - drools-drlonyaml-cli - drools-drlonyaml-cli-tests drools-drlonyaml-integration-tests - - - onlyReproducible - - - only.reproducible - - - - drools-drlonyaml-schemagen - drools-drlonyaml-model - drools-drlonyaml-todrl - drools-drlonyaml-cli - drools-drlonyaml-cli-tests - - diff --git a/drools-model/drools-canonical-model/pom.xml b/drools-model/drools-canonical-model/pom.xml index 58d14809398..0b11dd11640 100644 --- a/drools-model/drools-canonical-model/pom.xml +++ b/drools-model/drools-canonical-model/pom.xml @@ -43,11 +43,10 @@ logback-classic test - - junit - junit - test + org.junit.jupiter + junit-jupiter + test org.assertj diff --git a/drools-model/drools-canonical-model/src/test/java/org/drools/model/operators/MatchesOperatorTest.java b/drools-model/drools-canonical-model/src/test/java/org/drools/model/operators/MatchesOperatorTest.java index 4520828c4ea..85904614f4d 100644 --- a/drools-model/drools-canonical-model/src/test/java/org/drools/model/operators/MatchesOperatorTest.java +++ b/drools-model/drools-canonical-model/src/test/java/org/drools/model/operators/MatchesOperatorTest.java @@ -18,11 +18,11 @@ */ package org.drools.model.operators; -import org.junit.After; -import org.junit.Test; import static org.assertj.core.api.Assertions.assertThat; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; public class MatchesOperatorTest { @@ -60,7 +60,7 @@ public void testMatchesOperatorNoCache() { assertThat(instance.mapSize()).isEqualTo(0); } - @After + @AfterEach public void resetCache() { MatchesOperator instance = MatchesOperator.INSTANCE; instance.reInitialize(); diff --git a/drools-model/drools-canonical-model/src/test/java/org/drools/model/util/OperatorUtilsTest.java b/drools-model/drools-canonical-model/src/test/java/org/drools/model/util/OperatorUtilsTest.java index 9a42b767312..0b2b2797720 100644 --- a/drools-model/drools-canonical-model/src/test/java/org/drools/model/util/OperatorUtilsTest.java +++ b/drools-model/drools-canonical-model/src/test/java/org/drools/model/util/OperatorUtilsTest.java @@ -20,7 +20,7 @@ import java.math.BigDecimal; -import org.junit.Test; +import org.junit.jupiter.api.Test; import static org.assertj.core.api.Assertions.assertThat; diff --git a/drools-model/drools-model-codegen/pom.xml b/drools-model/drools-model-codegen/pom.xml index b8df4eda918..174224e2c04 100644 --- a/drools-model/drools-model-codegen/pom.xml +++ b/drools-model/drools-model-codegen/pom.xml @@ -127,36 +127,16 @@ test - - junit - junit - test - - + + org.junit.jupiter + junit-jupiter + test + + org.assertj assertj-core test - - org.junit.vintage - junit-vintage-engine - test - - - org.junit.jupiter - junit-jupiter-api - test - - - org.junit.jupiter - junit-jupiter-engine - test - - - org.junit.jupiter - junit-jupiter-params - test - org.drools drools-decisiontables diff --git a/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/AccumulateTest.java b/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/AccumulateTest.java index f46c7f77084..95d368192c9 100644 --- a/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/AccumulateTest.java +++ b/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/AccumulateTest.java @@ -50,6 +50,8 @@ import org.drools.core.base.accumulators.IntegerMaxAccumulateFunction; import org.drools.core.rule.consequence.InternalMatch; import org.drools.model.functions.accumulate.GroupKey; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; import org.drools.model.codegen.execmodel.domain.Adult; import org.drools.model.codegen.execmodel.domain.Child; import org.drools.model.codegen.execmodel.domain.Customer; @@ -59,7 +61,6 @@ import org.drools.model.codegen.execmodel.domain.StockTick; import org.drools.model.codegen.execmodel.domain.TargetPolicy; import org.drools.model.codegen.execmodel.oopathdtables.InternationalAddress; -import org.junit.Test; import org.kie.api.builder.Message; import org.kie.api.builder.Results; import org.kie.api.definition.type.FactType; @@ -68,16 +69,14 @@ import org.kie.api.runtime.rule.FactHandle; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.assertj.core.api.Assertions.fail; public class AccumulateTest extends BaseModelTest { - public AccumulateTest( RUN_TYPE testRunType ) { - super( testRunType ); - } - - @Test - public void testAccumulate1() { + @ParameterizedTest + @MethodSource("parameters") + public void testAccumulate1(RUN_TYPE runType) { String str = "import " + Person.class.getCanonicalName() + ";" + "import " + Result.class.getCanonicalName() + ";" + @@ -89,7 +88,7 @@ public void testAccumulate1() { " insert(new Result($sum));\n" + "end"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); ksession.insert(new Person("Mark", 37)); ksession.insert(new Person("Edson", 35)); @@ -102,8 +101,9 @@ public void testAccumulate1() { assertThat(results.iterator().next().getValue()).isEqualTo(77); } - @Test - public void testFromOnAccumulatedValue() { + @ParameterizedTest + @MethodSource("parameters") + public void testFromOnAccumulatedValue(RUN_TYPE runType) { // DROOLS-5635 String str = "import " + Person.class.getCanonicalName() + ";" + @@ -117,7 +117,7 @@ public void testFromOnAccumulatedValue() { " insert(new Result($s));\n" + "end"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); ksession.insert("test"); ksession.insert(new Person("Mark", 37)); @@ -131,8 +131,9 @@ public void testFromOnAccumulatedValue() { assertThat(results.iterator().next().getValue()).isEqualTo("77"); } - @Test - public void testFromOnAccumulatedValueUsingExists() { + @ParameterizedTest + @MethodSource("parameters") + public void testFromOnAccumulatedValueUsingExists(RUN_TYPE runType) { // DROOLS-5635 String str = "import " + Person.class.getCanonicalName() + ";" + @@ -146,7 +147,7 @@ public void testFromOnAccumulatedValueUsingExists() { " insert(new Result($s));\n" + "end"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); ksession.insert("test"); ksession.insert(new Person("Mark", 37)); @@ -160,8 +161,9 @@ public void testFromOnAccumulatedValueUsingExists() { assertThat(results.iterator().next().getValue()).isEqualTo("77"); } - @Test - public void testAccumulateWithoutParameters() { + @ParameterizedTest + @MethodSource("parameters") + public void testAccumulateWithoutParameters(RUN_TYPE runType) { String str = "import " + Person.class.getCanonicalName() + ";" + "import " + Result.class.getCanonicalName() + ";" + @@ -173,7 +175,7 @@ public void testAccumulateWithoutParameters() { " insert(new Result($count));\n" + "end"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); ksession.insert(new Person("Mark", 37)); ksession.insert(new Person("Edson", 35)); @@ -186,8 +188,9 @@ public void testAccumulateWithoutParameters() { assertThat(results.iterator().next().getValue()).isEqualTo(2l); } - @Test - public void testAccumulateWithLessParameter() { + @ParameterizedTest + @MethodSource("parameters") + public void testAccumulateWithLessParameter(RUN_TYPE runType) { String str = "import " + Person.class.getCanonicalName() + ";" + "import " + Result.class.getCanonicalName() + ";" + @@ -199,7 +202,7 @@ public void testAccumulateWithLessParameter() { " insert(new Result(\"fired\"));\n" + "end"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); ksession.insert(new Person("Mark", 37)); ksession.insert(new Person("Edson", 35)); @@ -214,8 +217,9 @@ public void testAccumulateWithLessParameter() { assertThat(results.iterator().next().getValue()).isEqualTo("fired"); } - @Test - public void testAccumulateOverConstant() { + @ParameterizedTest + @MethodSource("parameters") + public void testAccumulateOverConstant(RUN_TYPE runType) { String str = "import " + Person.class.getCanonicalName() + ";" + "import " + Result.class.getCanonicalName() + ";" + @@ -227,7 +231,7 @@ public void testAccumulateOverConstant() { " insert(new Result($sum));\n" + "end"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); ksession.insert(new Person("Mark", 37)); ksession.insert(new Person("Edson", 35)); @@ -240,8 +244,9 @@ public void testAccumulateOverConstant() { assertThat(results.iterator().next().getValue()).isEqualTo(2); } - @Test - public void testAccumulateConstrainingValue() { + @ParameterizedTest + @MethodSource("parameters") + public void testAccumulateConstrainingValue(RUN_TYPE runType) { String str = "import " + Person.class.getCanonicalName() + ";" + "import " + Result.class.getCanonicalName() + ";" + @@ -253,7 +258,7 @@ public void testAccumulateConstrainingValue() { " insert(new Result($sum));\n" + "end"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); ksession.insert(new Person("Mark", 37)); ksession.insert(new Person("Edson", 35)); @@ -266,8 +271,9 @@ public void testAccumulateConstrainingValue() { assertThat(results.iterator().next().getValue()).isEqualTo(77); } - @Test - public void testAccumulateConstrainingValue2() { + @ParameterizedTest + @MethodSource("parameters") + public void testAccumulateConstrainingValue2(RUN_TYPE runType) { String str = "import " + Person.class.getCanonicalName() + ";" + "import " + Result.class.getCanonicalName() + ";" + @@ -279,7 +285,7 @@ public void testAccumulateConstrainingValue2() { " insert(new Result($sum));\n" + "end"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); ksession.insert(new Person("Mark", 37)); ksession.insert(new Person("Edson", 35)); @@ -291,8 +297,9 @@ public void testAccumulateConstrainingValue2() { assertThat(results.size()).isEqualTo(0); } - @Test - public void testAccumulateConstrainingValueInPattern() { + @ParameterizedTest + @MethodSource("parameters") + public void testAccumulateConstrainingValueInPattern(RUN_TYPE runType) { String str = "import " + Person.class.getCanonicalName() + ";" + "import " + Result.class.getCanonicalName() + ";" + @@ -304,7 +311,7 @@ public void testAccumulateConstrainingValueInPattern() { " insert(new Result($sum));\n" + "end"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); ksession.insert(new Person("Mark", 37)); ksession.insert(new Person("Edson", 35)); @@ -317,8 +324,9 @@ public void testAccumulateConstrainingValueInPattern() { assertThat(results.iterator().next().getValue()).isEqualTo(77); } - @Test - public void testAccumulateWithProperty() { + @ParameterizedTest + @MethodSource("parameters") + public void testAccumulateWithProperty(RUN_TYPE runType) { String str = "import " + Person.class.getCanonicalName() + ";" + "import " + Result.class.getCanonicalName() + ";" + @@ -330,7 +338,7 @@ public void testAccumulateWithProperty() { " insert(new Result($sum));\n" + "end"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); ksession.insert(new Person("Mark", 37)); ksession.insert(new Person("Edson", 35)); @@ -343,8 +351,9 @@ public void testAccumulateWithProperty() { assertThat(results.iterator().next().getValue()).isEqualTo(77); } - @Test - public void testAccumulate2() { + @ParameterizedTest + @MethodSource("parameters") + public void testAccumulate2(RUN_TYPE runType) { String str = "import " + Person.class.getCanonicalName() + ";" + "import " + Result.class.getCanonicalName() + ";" + @@ -358,7 +367,7 @@ public void testAccumulate2() { " insert(new Result($average));\n" + "end"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); ksession.insert(new Person("Mark", 37)); ksession.insert(new Person("Edson", 35)); @@ -371,8 +380,9 @@ public void testAccumulate2() { assertThat(results).contains(new Result(77)); } - @Test - public void testAccumulateMultipleFunctions() { + @ParameterizedTest + @MethodSource("parameters") + public void testAccumulateMultipleFunctions(RUN_TYPE runType) { String str = "import " + Person.class.getCanonicalName() + ";" + "import " + Result.class.getCanonicalName() + ";" + @@ -386,7 +396,7 @@ public void testAccumulateMultipleFunctions() { " insert(new Result($average));\n" + "end"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); ksession.insert(new Person("Mark", 37)); ksession.insert(new Person("Edson", 35)); @@ -399,8 +409,9 @@ public void testAccumulateMultipleFunctions() { assertThat(results).contains(new Result(77)); } - @Test - public void testAccumulateMultipleFunctionsConstrainingValues() { + @ParameterizedTest + @MethodSource("parameters") + public void testAccumulateMultipleFunctionsConstrainingValues(RUN_TYPE runType) { String str = "import " + Person.class.getCanonicalName() + ";" + "import " + Result.class.getCanonicalName() + ";" + @@ -415,7 +426,7 @@ public void testAccumulateMultipleFunctionsConstrainingValues() { " insert(new Result($min));\n" + "end"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); ksession.insert(new Person("Mark", 37)); ksession.insert(new Person("Edson", 35)); @@ -428,8 +439,9 @@ public void testAccumulateMultipleFunctionsConstrainingValues() { assertThat(results).contains(new Result(77)); } - @Test - public void testAccumulateWithAnd() { + @ParameterizedTest + @MethodSource("parameters") + public void testAccumulateWithAnd(RUN_TYPE runType) { String str = "import " + Adult.class.getCanonicalName() + ";\n" + "import " + Child.class.getCanonicalName() + ";\n" + @@ -440,7 +452,7 @@ public void testAccumulateWithAnd() { " insert(new Result($parentAge));\n" + "end"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); Adult a = new Adult( "Mario", 43 ); Child c = new Child( "Sofia", 6, "Mario" ); @@ -453,8 +465,9 @@ public void testAccumulateWithAnd() { assertThat(results).contains(new Result(43)); } - @Test - public void testAccumulateWithAnd2() { + @ParameterizedTest + @MethodSource("parameters") + public void testAccumulateWithAnd2(RUN_TYPE runType) { String str = "import " + Adult.class.getCanonicalName() + ";\n" + "import " + Child.class.getCanonicalName() + ";\n" + @@ -465,7 +478,7 @@ public void testAccumulateWithAnd2() { " insert(new Result($parentAge));\n" + "end"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); Adult a = new Adult( "Mario", 43 ); Child c = new Child( "Sofia", 6, "Mario" ); @@ -479,8 +492,9 @@ public void testAccumulateWithAnd2() { assertThat(((Number) results.iterator().next().getValue()).intValue()).isEqualTo(49); } - @Test - public void testAccumulateWithAnd3() { + @ParameterizedTest + @MethodSource("parameters") + public void testAccumulateWithAnd3(RUN_TYPE runType) { String str = "import " + Adult.class.getCanonicalName() + ";\n" + "import " + Child.class.getCanonicalName() + ";\n" + @@ -491,7 +505,7 @@ public void testAccumulateWithAnd3() { " insert(new Result($parentAge));\n" + "end"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); Adult a = new Adult( "Mario", 43 ); Child c = new Child( "Sofia", 6, "Mario" ); @@ -505,8 +519,9 @@ public void testAccumulateWithAnd3() { assertThat(((Number) results.iterator().next().getValue()).intValue()).isEqualTo(49); } - @Test - public void testAccumulateWithAnd3Binds() { + @ParameterizedTest + @MethodSource("parameters") + public void testAccumulateWithAnd3Binds(RUN_TYPE runType) { String str = "import " + Adult.class.getCanonicalName() + ";\n" + "import " + Child.class.getCanonicalName() + ";\n" + @@ -518,7 +533,7 @@ public void testAccumulateWithAnd3Binds() { " insert(new Result($parentAge));\n" + "end"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); Adult a = new Adult( "Mario", 43 ); Child c = new Child( "Sofia", 6, "Mario" ); @@ -533,8 +548,9 @@ public void testAccumulateWithAnd3Binds() { assertThat(((Number) results.iterator().next().getValue()).intValue()).isEqualTo(54); } - @Test - public void testAccumulateWithAnd4Binds() { + @ParameterizedTest + @MethodSource("parameters") + public void testAccumulateWithAnd4Binds(RUN_TYPE runType) { String str = "import " + Adult.class.getCanonicalName() + ";\n" + "import " + Child.class.getCanonicalName() + ";\n" + @@ -546,7 +562,7 @@ public void testAccumulateWithAnd4Binds() { " insert(new Result($parentAge));\n" + "end"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); Adult a = new Adult( "Mario", 43 ); Child c = new Child( "Sofia", 6, "Mario" ); @@ -562,8 +578,9 @@ public void testAccumulateWithAnd4Binds() { assertThat(((Number) results.iterator().next().getValue()).intValue()).isEqualTo(59); } - @Test - public void testAccumulateWithCustomImport() { + @ParameterizedTest + @MethodSource("parameters") + public void testAccumulateWithCustomImport(RUN_TYPE runType) { String str = "import accumulate " + TestFunction.class.getCanonicalName() + " f;\n" + "import " + Adult.class.getCanonicalName() + ";\n" + @@ -575,7 +592,7 @@ public void testAccumulateWithCustomImport() { " insert(new Result($parentAge));\n" + "end"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); Adult a = new Adult( "Mario", 43 ); Child c = new Child( "Sofia", 6, "Mario" ); @@ -630,8 +647,9 @@ public Class getResultType() { } } - @Test - public void testFromAccumulate() { + @ParameterizedTest + @MethodSource("parameters") + public void testFromAccumulate(RUN_TYPE runType) { String str = "import " + Person.class.getCanonicalName() + ";" + "import " + Result.class.getCanonicalName() + ";" + @@ -643,7 +661,7 @@ public void testFromAccumulate() { " insert(new Result($sum));\n" + "end"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); ksession.insert(new Person("Mark", 37)); ksession.insert(new Person("Edson", 35)); @@ -656,8 +674,9 @@ public void testFromAccumulate() { assertThat(results.iterator().next().getValue()).isEqualTo(77); } - @Test - public void testFromCollect() { + @ParameterizedTest + @MethodSource("parameters") + public void testFromCollect(RUN_TYPE runType) { String str = "import " + Customer.class.getCanonicalName() + ";\n" + "import " + TargetPolicy.class.getCanonicalName() + ";\n" + @@ -671,11 +690,12 @@ public void testFromCollect() { " update($target);\n" + "end"; - checkCollect( str ); + checkCollect(runType, str); } - @Test - public void testFromCollectWithAccumulate() { + @ParameterizedTest + @MethodSource("parameters") + public void testFromCollectWithAccumulate(RUN_TYPE runType) { String str = "import " + Customer.class.getCanonicalName() + ";\n" + "import " + TargetPolicy.class.getCanonicalName() + ";\n" + @@ -689,11 +709,12 @@ public void testFromCollectWithAccumulate() { " update($target);\n" + "end"; - checkCollect( str ); + checkCollect(runType, str); } - @Test - public void testFromCollectWithExpandedAccumulate() { + @ParameterizedTest + @MethodSource("parameters") + public void testFromCollectWithExpandedAccumulate(RUN_TYPE runType) { String str = "import " + Customer.class.getCanonicalName() + ";\n" + "import " + TargetPolicy.class.getCanonicalName() + ";\n" + @@ -712,11 +733,11 @@ public void testFromCollectWithExpandedAccumulate() { " update($target);\n" + "end"; - checkCollect( str ); + checkCollect(runType, str); } - private void checkCollect( String str ) { - KieSession ksession = getKieSession(str); + private void checkCollect(RUN_TYPE runType, String str ) { + KieSession ksession = getKieSession(runType, str); Customer customer = new Customer(); customer.setCode("code1"); @@ -744,17 +765,19 @@ private void checkCollect( String str ) { assertThat(filtered).isEqualTo(1); } - @Test - public void testFromCollectWithExpandedAccumulate2() { - testFromCollectWithExpandedAccumulate2(false); + @ParameterizedTest + @MethodSource("parameters") + public void testFromCollectWithExpandedAccumulate2(RUN_TYPE runType) { + testFromCollectWithExpandedAccumulate2(runType, false); } - @Test - public void testFromCollectWithExpandedAccumulate2WithReverse() { - testFromCollectWithExpandedAccumulate2(true); + @ParameterizedTest + @MethodSource("parameters") + public void testFromCollectWithExpandedAccumulate2WithReverse(RUN_TYPE runType) { + testFromCollectWithExpandedAccumulate2(runType, true); } - public void testFromCollectWithExpandedAccumulate2(boolean performReverse) { + public void testFromCollectWithExpandedAccumulate2(RUN_TYPE runType, boolean performReverse) { String str = "import " + Person.class.getCanonicalName() + ";\n" + "rule R when\n" + " $sum : Integer() from accumulate (\n" + @@ -764,7 +787,7 @@ public void testFromCollectWithExpandedAccumulate2(boolean performReverse) { " insert($sum);\n" + "end"; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); FactHandle fh_Mark = ksession.insert(new Person("Mark", 37)); FactHandle fh_Edson = ksession.insert(new Person("Edson", 35)); @@ -785,8 +808,9 @@ public void testFromCollectWithExpandedAccumulate2(boolean performReverse) { } } - @Test - public void testExpandedAccumulateWith2Args() { + @ParameterizedTest + @MethodSource("parameters") + public void testExpandedAccumulateWith2Args(RUN_TYPE runType) { String str = "import " + Person.class.getCanonicalName() + ";\n" + "rule R when\n" + " $avg : Integer() from accumulate (\n" + @@ -799,7 +823,7 @@ public void testExpandedAccumulateWith2Args() { " insert($avg);\n" + "end"; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); FactHandle fh_Mark = ksession.insert(new Person("Mark", 37)); FactHandle fh_Edson = ksession.insert(new Person("Edson", 35)); @@ -818,8 +842,9 @@ public void testExpandedAccumulateWith2Args() { assertThat(results).contains(36); } - @Test - public void testExpandedAccumulateWith2Args2Bindings() { + @ParameterizedTest + @MethodSource("parameters") + public void testExpandedAccumulateWith2Args2Bindings(RUN_TYPE runType) { String str = "import " + Person.class.getCanonicalName() + ";\n" + "rule R when\n" + " $avg : Integer() from accumulate (\n" + @@ -833,7 +858,7 @@ public void testExpandedAccumulateWith2Args2Bindings() { " insert($avg);\n" + "end"; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); FactHandle fh_Mark = ksession.insert(new Person("Mark", 37)); FactHandle fh_Edson = ksession.insert(new Person("Edson", 35)); @@ -853,8 +878,9 @@ public void testExpandedAccumulateWith2Args2Bindings() { } - @Test - public void testExpandedAccumulateWith3Args() { + @ParameterizedTest + @MethodSource("parameters") + public void testExpandedAccumulateWith3Args(RUN_TYPE runType) { String str = "rule \"TestAccumulate2\" when\n" + " $dx : Number () from accumulate ( $d : Double (),\n" + @@ -866,7 +892,7 @@ public void testExpandedAccumulateWith3Args() { " insert($dx.intValue());\n" + "end"; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); ksession.insert(1.0); ksession.insert(2.0); @@ -878,8 +904,9 @@ public void testExpandedAccumulateWith3Args() { assertThat(results).contains(8); } - @Test - public void testAccumulateFromWithConstraint() { + @ParameterizedTest + @MethodSource("parameters") + public void testAccumulateFromWithConstraint(RUN_TYPE runType) { String str = "import " + java.util.List.class.getCanonicalName() + ";" + "import " + org.drools.model.codegen.execmodel.oopathdtables.Person.class.getCanonicalName() + ";" + @@ -892,7 +919,7 @@ public void testAccumulateFromWithConstraint() { " insert($cities.get(0));\n" + "end"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); ksession.insert(new InternationalAddress("", 1, "Milan", "Safecountry")); ksession.fireAllRules(); @@ -902,8 +929,9 @@ public void testAccumulateFromWithConstraint() { assertThat(results).contains("Milan"); } - @Test - public void testAccumulateWithThis() { + @ParameterizedTest + @MethodSource("parameters") + public void testAccumulateWithThis(RUN_TYPE runType) { final String drl1 = "import java.util.*;\n" + "rule B\n" + @@ -916,7 +944,7 @@ public void testAccumulateWithThis() { "then\n" + " insert($eventCodeDistinctMois);\n" + "end"; - KieSession ksession = getKieSession( drl1 ); + KieSession ksession = getKieSession(runType, drl1); ksession.insert("1"); ksession.insert("3"); @@ -930,8 +958,9 @@ public void testAccumulateWithThis() { assertThat(results).contains(4); } - @Test - public void testAccumulateWithExternalBind() { + @ParameterizedTest + @MethodSource("parameters") + public void testAccumulateWithExternalBind(RUN_TYPE runType) { String str = "import " + Person.class.getCanonicalName() + ";" + "import " + Result.class.getCanonicalName() + ";" + @@ -944,7 +973,7 @@ public void testAccumulateWithExternalBind() { " insert(new Result($sum));\n" + "end"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); ksession.insert("x"); ksession.insert(new Person("Mark", 37)); @@ -958,8 +987,9 @@ public void testAccumulateWithExternalBind() { assertThat(((Number) results.iterator().next().getValue()).intValue()).isEqualTo(77); } - @Test - public void testFromCollectWithExpandedAccumulateExternalBindInInit() { + @ParameterizedTest + @MethodSource("parameters") + public void testFromCollectWithExpandedAccumulateExternalBindInInit(RUN_TYPE runType) { String str = "import " + Person.class.getCanonicalName() + ";\n" + "rule R when\n" + " String( $l : length )\n" + @@ -970,7 +1000,7 @@ public void testFromCollectWithExpandedAccumulateExternalBindInInit() { " insert($sum);\n" + "end"; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); ksession.insert("x"); FactHandle fh_Mark = ksession.insert(new Person("Mark", 37)); @@ -984,8 +1014,9 @@ public void testFromCollectWithExpandedAccumulateExternalBindInInit() { } - @Test - public void testFromCollectWithExpandedAccumulateExternalBindInAction() { + @ParameterizedTest + @MethodSource("parameters") + public void testFromCollectWithExpandedAccumulateExternalBindInAction(RUN_TYPE runType) { String str = "import " + Person.class.getCanonicalName() + ";\n" + "rule R when\n" + " String( $l : length )" + @@ -996,7 +1027,7 @@ public void testFromCollectWithExpandedAccumulateExternalBindInAction() { " insert($sum);\n" + "end"; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); ksession.insert("x"); FactHandle fh_Mark = ksession.insert(new Person("Mark", 37)); @@ -1010,8 +1041,9 @@ public void testFromCollectWithExpandedAccumulateExternalBindInAction() { } - @Test - public void testUseAccumulateFunctionWithOperationInBinding() { + @ParameterizedTest + @MethodSource("parameters") + public void testUseAccumulateFunctionWithOperationInBinding(RUN_TYPE runType) { String str = "import " + Person.class.getCanonicalName() + ";\n" + "rule R when\n" + @@ -1022,7 +1054,7 @@ public void testUseAccumulateFunctionWithOperationInBinding() { " insert($result);\n" + "end"; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); ksession.insert("x"); FactHandle fh_Mark = ksession.insert(new Person("Mark", 37)); @@ -1036,8 +1068,9 @@ public void testUseAccumulateFunctionWithOperationInBinding() { } - @Test - public void testUseAccumulateFunctionWithArrayAccessOperation() { + @ParameterizedTest + @MethodSource("parameters") + public void testUseAccumulateFunctionWithArrayAccessOperation(RUN_TYPE runType) { String str = "import " + Adult.class.getCanonicalName() + ";\n" + "rule R when\n" + @@ -1048,7 +1081,7 @@ public void testUseAccumulateFunctionWithArrayAccessOperation() { " insert($result);\n" + "end"; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); ksession.insert("x"); Adult luca = new Adult("Luca", 33); @@ -1065,8 +1098,9 @@ public void testUseAccumulateFunctionWithArrayAccessOperation() { assertThat(results.get(0).intValue()).isEqualTo(11); } - @Test - public void testUseAccumulateFunctionWithListMvelDialectWithoutBias() throws Exception { + @ParameterizedTest + @MethodSource("parameters") + public void testUseAccumulateFunctionWithListMvelDialectWithoutBias(RUN_TYPE runType) throws Exception { String str = "package org.test;" + "import java.util.*; " + "declare Data " + @@ -1081,7 +1115,7 @@ public void testUseAccumulateFunctionWithListMvelDialectWithoutBias() throws Exc " insert($tot);\n" + "end"; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); FactType dataType = ksession.getKieBase().getFactType("org.test", "Data"); Object data1 = dataType.newInstance(); @@ -1095,8 +1129,9 @@ public void testUseAccumulateFunctionWithListMvelDialectWithoutBias() throws Exc assertThat(results.get(0).intValue()).isEqualTo(2); } - @Test - public void testUseAccumulateFunctionWithListMvelDialect() throws Exception { + @ParameterizedTest + @MethodSource("parameters") + public void testUseAccumulateFunctionWithListMvelDialect(RUN_TYPE runType) throws Exception { String str = "package org.test;" + "import java.util.*; " + "declare Data " + @@ -1112,7 +1147,7 @@ public void testUseAccumulateFunctionWithListMvelDialect() throws Exception { " insert($tot);\n" + "end"; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); FactType dataType = ksession.getKieBase().getFactType("org.test", "Data"); Object data1 = dataType.newInstance(); @@ -1132,8 +1167,9 @@ public void testUseAccumulateFunctionWithListMvelDialect() throws Exception { assertThat(results.get(0).intValue()).isEqualTo(212); } - @Test - public void testTypedResultOnAccumulate() { + @ParameterizedTest + @MethodSource("parameters") + public void testTypedResultOnAccumulate(RUN_TYPE runType) { String str = "import " + Person.class.getCanonicalName() + ";" + "import " + Result.class.getCanonicalName() + ";" + @@ -1145,7 +1181,7 @@ public void testTypedResultOnAccumulate() { " insert(new Person(\"test\", $max));\n" + "end"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); ksession.insert("xyz"); @@ -1156,8 +1192,9 @@ public void testTypedResultOnAccumulate() { assertThat(results.iterator().next().getAge()).isEqualTo(3); } - @Test - public void testExtractorInPattern() { + @ParameterizedTest + @MethodSource("parameters") + public void testExtractorInPattern(RUN_TYPE runType) { String str = "import " + Person.class.getCanonicalName() + ";" + "import " + Result.class.getCanonicalName() + ";" + @@ -1169,7 +1206,7 @@ public void testExtractorInPattern() { " insert(new Result($max));\n" + "end"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); ksession.insert(new Person("a", 23)); @@ -1181,8 +1218,9 @@ public void testExtractorInPattern() { } - @Test - public void testThisInPattern() { + @ParameterizedTest + @MethodSource("parameters") + public void testThisInPattern(RUN_TYPE runType) { String str = "import " + Person.class.getCanonicalName() + ";" + "import " + Result.class.getCanonicalName() + ";" + @@ -1194,7 +1232,7 @@ public void testThisInPattern() { " insert(new Result($max));\n" + "end"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); ksession.insert(2); ksession.insert(10); @@ -1208,8 +1246,9 @@ public void testThisInPattern() { - @Test - public void testExtractorInFunction() { + @ParameterizedTest + @MethodSource("parameters") + public void testExtractorInFunction(RUN_TYPE runType) { String str = "import " + Person.class.getCanonicalName() + ";" + "import " + Result.class.getCanonicalName() + ";" + @@ -1221,7 +1260,7 @@ public void testExtractorInFunction() { " insert(new Result($max));\n" + "end"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); ksession.insert(new Person("a", 23)); @@ -1232,8 +1271,9 @@ public void testExtractorInFunction() { assertThat(results.iterator().next().getValue()).isEqualTo(23); } - @Test - public void testBigDecimalOperationsInAccumulateConstraint() { + @ParameterizedTest + @MethodSource("parameters") + public void testBigDecimalOperationsInAccumulateConstraint(RUN_TYPE runType) { String str = "import " + Person.class.getCanonicalName() + ";\n" + "import " + BigDecimal.class.getCanonicalName() + ";\n" + "global java.util.List results;\n" + @@ -1246,7 +1286,7 @@ public void testBigDecimalOperationsInAccumulateConstraint() { " results.add($moneySummed);\n" + "end\n"; - KieSession ksession1 = getKieSession(str); + KieSession ksession1 = getKieSession(runType, str); ArrayList results = new ArrayList<>(); ksession1.setGlobal("results", results); @@ -1266,8 +1306,9 @@ public void testBigDecimalOperationsInAccumulateConstraint() { // do also the test with two functions - @Test - public void testAccumulateWithMax() { + @ParameterizedTest + @MethodSource("parameters") + public void testAccumulateWithMax(RUN_TYPE runType) { String str = "import " + StockTick.class.getCanonicalName() + ";" + "import " + StockTick.class.getCanonicalName() + ";" + @@ -1279,7 +1320,7 @@ public void testAccumulateWithMax() { "then\n" + "end\n"; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); StockTick st = new StockTick("RHT"); st.setTimeField(new Date().getTime()); @@ -1287,8 +1328,9 @@ public void testAccumulateWithMax() { assertThat(ksession.fireAllRules()).isEqualTo(1); } - @Test - public void testAccumulateWithMaxCalendar() { + @ParameterizedTest + @MethodSource("parameters") + public void testAccumulateWithMaxCalendar(RUN_TYPE runType) { String str = "import " + StockTick.class.getCanonicalName() + ";\n" + "rule AccumulateMaxDate\n" + @@ -1300,7 +1342,7 @@ public void testAccumulateWithMaxCalendar() { "then\n" + "end\n"; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); StockTick st = new StockTick("RHT"); st.setDueDate(Calendar.getInstance()); @@ -1308,8 +1350,9 @@ public void testAccumulateWithMaxCalendar() { assertThat(ksession.fireAllRules()).isEqualTo(1); } - @Test - public void testAccumulateWithMaxCalendarAndConstraint() { + @ParameterizedTest + @MethodSource("parameters") + public void testAccumulateWithMaxCalendarAndConstraint(RUN_TYPE runType) { String str = "import " + Customer.class.getCanonicalName() + ";\n" + "import " + StockTick.class.getCanonicalName() + ";\n" + @@ -1324,7 +1367,7 @@ public void testAccumulateWithMaxCalendarAndConstraint() { "then\n" + "end\n"; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); StockTick st = new StockTick("RHT"); st.setDueDate(Calendar.getInstance()); @@ -1335,8 +1378,9 @@ public void testAccumulateWithMaxCalendarAndConstraint() { assertThat(ksession.fireAllRules()).isEqualTo(1); } - @Test - public void testNoBinding() { + @ParameterizedTest + @MethodSource("parameters") + public void testNoBinding(RUN_TYPE runType) { final String str = "rule foo\n" + "when\n" + @@ -1347,7 +1391,7 @@ public void testNoBinding() { "then\n" + "end"; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); ksession.insert("xyz"); ksession.fireAllRules(); } @@ -1358,8 +1402,9 @@ public Short getValue() { } } - @Test - public void testImplicitCastInAccumulateFunction() { + @ParameterizedTest + @MethodSource("parameters") + public void testImplicitCastInAccumulateFunction(RUN_TYPE runType) { String str = "import " + ShortValue.class.getCanonicalName() + ";" + "rule X when\n" + @@ -1367,15 +1412,16 @@ public void testImplicitCastInAccumulateFunction() { "then\n" + "end"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); ksession.insert(new ShortValue()); assertThat(ksession.fireAllRules()).isEqualTo(1); } - @Test - public void testAccumulateWithFunctionWithExternalBinding() { + @ParameterizedTest + @MethodSource("parameters") + public void testAccumulateWithFunctionWithExternalBinding(RUN_TYPE runType) { final String drl = "import " + Converter.class.getCanonicalName() + ";\n" + "global java.util.List list;\n" + @@ -1387,7 +1433,7 @@ public void testAccumulateWithFunctionWithExternalBinding() { " list.add($result);\n" + "end"; - KieSession ksession = getKieSession(drl); + KieSession ksession = getKieSession(runType, drl); final List list = new ArrayList<>(); ksession.setGlobal("list", list); @@ -1408,8 +1454,9 @@ public static int convert(final int i) { } } - @Test - public void testAccumulateWithFunctionWithExternalBindingAndOR() { + @ParameterizedTest + @MethodSource("parameters") + public void testAccumulateWithFunctionWithExternalBindingAndOR(RUN_TYPE runType) { final String drl = "import " + Converter.class.getCanonicalName() + ";\n" + "global java.util.List list;\n" + @@ -1424,7 +1471,7 @@ public void testAccumulateWithFunctionWithExternalBindingAndOR() { " list.add($result);\n" + "end"; - KieSession ksession = getKieSession(drl); + KieSession ksession = getKieSession(runType, drl); final List list = new ArrayList<>(); ksession.setGlobal("list", list); @@ -1438,8 +1485,9 @@ public void testAccumulateWithFunctionWithExternalBindingAndOR() { assertThat(list.get(0).intValue()).isEqualTo(5); } - @Test - public void testAccumulateWithOR() { + @ParameterizedTest + @MethodSource("parameters") + public void testAccumulateWithOR(RUN_TYPE runType) { final String drl = "import " + Converter.class.getCanonicalName() + ";\n" + "global java.util.List list;\n" + @@ -1453,7 +1501,7 @@ public void testAccumulateWithOR() { " list.add($result);\n" + "end"; - KieSession ksession = getKieSession(drl); + KieSession ksession = getKieSession(runType, drl); final List list = new ArrayList<>(); ksession.setGlobal("list", list); @@ -1466,8 +1514,9 @@ public void testAccumulateWithOR() { assertThat(list.get(0).intValue()).isEqualTo(5); } - @Test - public void testPatternMatchingOverNumberWhileAccumulatingShort() { + @ParameterizedTest + @MethodSource("parameters") + public void testPatternMatchingOverNumberWhileAccumulatingShort(RUN_TYPE runType) { String drl= "import " + AccumulateResult.class.getCanonicalName() + "\n" + "import " + Person.class.getCanonicalName() + "\n" + @@ -1486,7 +1535,7 @@ public void testPatternMatchingOverNumberWhileAccumulatingShort() { " update($accumulateResult);\n" + "end"; - KieSession ksession = getKieSession(drl); + KieSession ksession = getKieSession(runType, drl); AccumulateResult result = new AccumulateResult(false); @@ -1538,8 +1587,9 @@ public void setBigDecimalValue(BigDecimal bigDecimalValue) { } - @Test - public void testAccumulateOverField() { + @ParameterizedTest + @MethodSource("parameters") + public void testAccumulateOverField(RUN_TYPE runType) { String str = "import java.lang.Number;\n" + "import java.math.BigDecimal;\n" + @@ -1558,7 +1608,7 @@ public void testAccumulateOverField() { " }\n" + "end\n"; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); ksession.insert(new Person("Mario", BigDecimal.valueOf(1000))); ksession.insert(new Person("Luca", BigDecimal.valueOf(2000))); @@ -1572,8 +1622,9 @@ public void testAccumulateOverField() { assertThat(result.getBigDecimalValue()).isEqualTo(BigDecimal.valueOf(3000)); } - @Test - public void testFromAccumulateBigDecimalMvel() { + @ParameterizedTest + @MethodSource("parameters") + public void testFromAccumulateBigDecimalMvel(RUN_TYPE runType) { String str = "import " + Person.class.getCanonicalName() + ";\n" + "import " + BigDecimal.class.getCanonicalName() + ";\n" + "global java.util.List list;\n" + @@ -1590,7 +1641,7 @@ public void testFromAccumulateBigDecimalMvel() { " list.add($b);\n" + "end"; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); final List list = new ArrayList<>(); ksession.setGlobal("list", list); @@ -1607,8 +1658,9 @@ public void testFromAccumulateBigDecimalMvel() { } - @Test - public void testSemicolonMissingInInit() { + @ParameterizedTest + @MethodSource("parameters") + public void testSemicolonMissingInInit(RUN_TYPE runType) { String str = "import " + Person.class.getCanonicalName() + ";\n" + "import " + BigDecimal.class.getCanonicalName() + ";\n" + "global java.util.List list;\n" + @@ -1624,7 +1676,7 @@ public void testSemicolonMissingInInit() { " list.add($sum);\n" + "end"; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); final List list = new ArrayList<>(); ksession.setGlobal("list", list); @@ -1643,8 +1695,9 @@ public void testSemicolonMissingInInit() { } - @Test(expected = AssertionError.class) - public void testSemicolonMissingInAction() { + @ParameterizedTest + @MethodSource("parameters") + public void testSemicolonMissingInAction(RUN_TYPE runType) { String str = "import " + Person.class.getCanonicalName() + ";\n" + "import " + BigDecimal.class.getCanonicalName() + ";\n" + "global java.util.List list;\n" + @@ -1660,11 +1713,13 @@ public void testSemicolonMissingInAction() { " list.add($sum);\n" + "end"; - getKieSession(str); + + assertThatExceptionOfType(AssertionError.class).isThrownBy(() -> getKieSession(runType, str)); } - @Test(expected = AssertionError.class) - public void testSemicolonMissingInReverse() { + @ParameterizedTest + @MethodSource("parameters") + public void testSemicolonMissingInReverse(RUN_TYPE runType) { String str = "import " + Person.class.getCanonicalName() + ";\n" + "import " + BigDecimal.class.getCanonicalName() + ";\n" + "global java.util.List list;\n" + @@ -1680,11 +1735,12 @@ public void testSemicolonMissingInReverse() { " list.add($sum);\n" + "end"; - getKieSession(str); + assertThatExceptionOfType(AssertionError.class).isThrownBy(() -> getKieSession(runType, str)); } - @Test - public void testGroupBy() { + @ParameterizedTest + @MethodSource("parameters") + public void testGroupBy(RUN_TYPE runType) { // DROOLS-4737 String str = "import java.util.*;\n" + @@ -1704,7 +1760,7 @@ public void testGroupBy() { " System.out.println(\"Sum of ages of person with initial '\" + $initial + \"' is \" + $sumOfAges);\n" + "end"; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); ksession.insert(new Person("Mark", 42)); ksession.insert(new Person("Edson", 38)); @@ -1765,8 +1821,9 @@ public V getValue() { } } - @Test - public void testGroupBy2() { + @ParameterizedTest + @MethodSource("parameters") + public void testGroupBy2(RUN_TYPE runType) { // DROOLS-4737 String str = "import java.util.*;\n" + @@ -1787,7 +1844,7 @@ public void testGroupBy2() { " results.put($initial, $sumOfAges);\n" + "end"; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); Map results = new HashMap(); ksession.setGlobal( "results", results ); @@ -1822,8 +1879,9 @@ public void testGroupBy2() { assertThat(results.get("M")).isEqualTo(119); } - @Test - public void testGroupBy3() { + @ParameterizedTest + @MethodSource("parameters") + public void testGroupBy3(RUN_TYPE runType) { // DROOLS-4737 String str = "import java.util.*;\n" + @@ -1854,7 +1912,7 @@ public void testGroupBy3() { " results.put($initial, $sumOfAges);\n" + "end"; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); Map results = new HashMap(); ksession.setGlobal( "results", results ); @@ -1889,8 +1947,9 @@ public void testGroupBy3() { assertThat(results.get("M")).isEqualTo(119); } - @Test - public void testGroupBy3WithExists() { + @ParameterizedTest + @MethodSource("parameters") + public void testGroupBy3WithExists(RUN_TYPE runType) { String str = "import java.util.*;\n" + "import " + GroupKey.class.getCanonicalName() + ";\n" + @@ -1921,7 +1980,7 @@ public void testGroupBy3WithExists() { " results.put($initial, $sumOfAges);\n" + "end"; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); Map results = new HashMap(); ksession.setGlobal( "results", results ); @@ -1961,8 +2020,9 @@ public void testGroupBy3WithExists() { assertThat(results.get("M")).isEqualTo(119); } - @Test - public void testGroupBy3WithExists2() { + @ParameterizedTest + @MethodSource("parameters") + public void testGroupBy3WithExists2(RUN_TYPE runType) { String str = "import java.util.*;\n" + "import " + GroupKey.class.getCanonicalName() + ";\n" + @@ -1994,7 +2054,7 @@ public void testGroupBy3WithExists2() { " results.add(java.util.Arrays.asList($k, $count));\n" + "end"; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); List results = new ArrayList(); ksession.setGlobal( "results", results ); @@ -2022,8 +2082,9 @@ public void testGroupBy3WithExists2() { .containsOnly(Arrays.asList(child2, 1L)); } - @Test - public void testGroupBy3With2VarsKey() { + @ParameterizedTest + @MethodSource("parameters") + public void testGroupBy3With2VarsKey(RUN_TYPE runType) { String str = "import java.util.*;\n" + "import " + GroupKey.class.getCanonicalName() + ";\n" + @@ -2057,7 +2118,7 @@ public void testGroupBy3With2VarsKey() { " results.put($k, $sumOfAges);\n" + "end"; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); Map results = new HashMap(); ksession.setGlobal( "results", results ); @@ -2100,8 +2161,9 @@ public void testGroupBy3With2VarsKey() { assertThat(results.get("M5")).isEqualTo(119); } - @Test - public void testFromAfterAccumulate() { + @ParameterizedTest + @MethodSource("parameters") + public void testFromAfterAccumulate(RUN_TYPE runType) { // DROOLS-4737 String str = "import " + List.class.getCanonicalName() + ";\n" + @@ -2113,7 +2175,7 @@ public void testFromAfterAccumulate() { " System.out.println($name + \"' is \" + $age);\n" + "end"; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); ksession.insert(new Person("Mark", 42)); ksession.insert(new Person("Edson", 38)); @@ -2121,8 +2183,9 @@ public void testFromAfterAccumulate() { ksession.fireAllRules(); } - @Test - public void testCoercionInAccumulate() { + @ParameterizedTest + @MethodSource("parameters") + public void testCoercionInAccumulate(RUN_TYPE runType) { String str = "global java.util.List result;\n" + "rule \"Row 1 moveToBiggerCities\"\n" + @@ -2136,7 +2199,7 @@ public void testCoercionInAccumulate() { List result = new ArrayList<>(); - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); ksession.setGlobal("result", result); IntStream.range(1, 7).forEach(ksession::insert); @@ -2147,8 +2210,9 @@ public void testCoercionInAccumulate() { } - @Test - public void testCoercionInAccumulate2() { + @ParameterizedTest +@MethodSource("parameters") + public void testCoercionInAccumulate2(RUN_TYPE runType) { final String drl = "import " + Person.class.getCanonicalName() + "\n" + "global java.util.List result; \n" + @@ -2165,7 +2229,7 @@ public void testCoercionInAccumulate2() { List result = new ArrayList<>(); - KieSession ksession = getKieSession(drl); + KieSession ksession = getKieSession(runType, drl); ksession.setGlobal("result", result); ksession.insert(new Person("Luca", 35)); @@ -2210,8 +2274,9 @@ public long between(LocalDateTime start, LocalDateTime end) { } } - @Test - public void testAccumulateOnStaticMethod() { + @ParameterizedTest +@MethodSource("parameters") + public void testAccumulateOnStaticMethod(RUN_TYPE runType) { // DROOLS-4979 final String drl = "import java.time.Duration\n" + @@ -2230,7 +2295,7 @@ public void testAccumulateOnStaticMethod() { List result = new ArrayList<>(); - KieSession ksession = getKieSession(drl); + KieSession ksession = getKieSession(runType, drl); ksession.setGlobal("result", result); ksession.insert(new Interval( @@ -2244,8 +2309,9 @@ public void testAccumulateOnStaticMethod() { } - @Test - public void testAccumulateOfDurationBetweenDateTime() { + @ParameterizedTest +@MethodSource("parameters") + public void testAccumulateOfDurationBetweenDateTime(RUN_TYPE runType) { // DROOLS-4979 final String drl = "import java.time.Duration\n" + @@ -2264,7 +2330,7 @@ public void testAccumulateOfDurationBetweenDateTime() { List result = new ArrayList<>(); - KieSession ksession = getKieSession(drl); + KieSession ksession = getKieSession(runType, drl); ksession.setGlobal("result", result); ksession.insert(new Interval( @@ -2278,8 +2344,9 @@ public void testAccumulateOfDurationBetweenDateTime() { } - @Test - public void testGroupByRegrouped() { + @ParameterizedTest + @MethodSource("parameters") + public void testGroupByRegrouped(RUN_TYPE runType) { // DROOLS-5283 String str = "import java.util.*;\n" + @@ -2305,7 +2372,7 @@ public void testGroupByRegrouped() { "then\n" + " System.out.println($p.toString());\n" + "end"; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); ksession.insert(new Person("Mark", 42)); ksession.insert(new Person("Edson", 38)); @@ -2327,8 +2394,9 @@ public void testGroupByRegrouped() { ksession.fireAllRules(); } - @Test - public void testAccumulateStaticMethodWithPatternBindVar() { + @ParameterizedTest + @MethodSource("parameters") + public void testAccumulateStaticMethodWithPatternBindVar(RUN_TYPE runType) { String str = "import " + Person.class.getCanonicalName() + ";\n" + "import " + MyUtil.class.getCanonicalName() + ";\n" + "rule R when\n" + @@ -2339,7 +2407,7 @@ public void testAccumulateStaticMethodWithPatternBindVar() { " insert($result);\n" + "end"; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); ksession.insert("x"); ksession.insert(new Person("Mark", 37)); @@ -2358,8 +2426,9 @@ public static int add(int a, int b) { } } - @Test - public void testModifyAccumulatedFactWithNonIndexableConstraint() { + @ParameterizedTest + @MethodSource("parameters") + public void testModifyAccumulatedFactWithNonIndexableConstraint(RUN_TYPE runType) { String str = "import " + Person.class.getCanonicalName() + ";\n" + "rule R when\n" + @@ -2370,7 +2439,7 @@ public void testModifyAccumulatedFactWithNonIndexableConstraint() { "then\n" + "end"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); ksession.insert( "a" ); ksession.insert( "b" ); @@ -2411,8 +2480,9 @@ public void testModifyAccumulatedFactWithNonIndexableConstraint() { assertThat(ksession.fireAllRules()).isEqualTo(2); } - @Test - public void testAccumulateWithManyBindings() { + @ParameterizedTest + @MethodSource("parameters") + public void testAccumulateWithManyBindings(RUN_TYPE runType) { // DROOLS-5546 String str = "import " + Person.class.getCanonicalName() + ";\n" + @@ -2424,7 +2494,7 @@ public void testAccumulateWithManyBindings() { " insert($max);\n" + "end"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); ksession.insert( new Person( "Mario", 40 ) ); ksession.insert( new Person( "Mark", 40 ) ); @@ -2437,8 +2507,9 @@ public void testAccumulateWithManyBindings() { assertThat(results.get(0).intValue()).isEqualTo(5); } - @Test - public void testFalseNodeSharing() { + @ParameterizedTest + @MethodSource("parameters") + public void testFalseNodeSharing(RUN_TYPE runType) { // DROOLS-5686 String str = "import " + Person.class.getCanonicalName() + ";\n" + @@ -2457,7 +2528,7 @@ public void testFalseNodeSharing() { " insert(\"\" + $sum);\n" + "end"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); ksession.insert( new Person( "Mario", 46 ) ); ksession.insert( new Person( "Mark", 44 ) ); @@ -2474,8 +2545,9 @@ public void testFalseNodeSharing() { assertThat(resultsString.get(0)).isEqualTo("13"); } - @Test - public void testAccumulateWithTwoFunctions1() { + @ParameterizedTest + @MethodSource("parameters") + public void testAccumulateWithTwoFunctions1(RUN_TYPE runType) { // DROOLS-5752 String str = "import java.time.Duration;\n" + "import " + Shift.class.getCanonicalName() + ";\n" + @@ -2492,15 +2564,16 @@ public void testAccumulateWithTwoFunctions1() { " System.out.println($shiftCount + \" \" + $totalMinutes);\n" + "end"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); ksession.insert( new Shift( OffsetDateTime.now()) ); assertThat(ksession.fireAllRules()).isEqualTo(1); } - @Test - public void testAccumulateWithTwoFunctions2() { + @ParameterizedTest + @MethodSource("parameters") + public void testAccumulateWithTwoFunctions2(RUN_TYPE runType) { // DROOLS-5752 String str = "import java.time.Duration;\n" + "import " + Shift.class.getCanonicalName() + ";\n" + @@ -2517,7 +2590,7 @@ public void testAccumulateWithTwoFunctions2() { " System.out.println($shiftCount + \" \" + $totalMinutes);\n" + "end"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); ksession.insert( new Shift( OffsetDateTime.now()) ); @@ -2577,8 +2650,9 @@ public static Duration between(OffsetDateTime start, OffsetDateTime end) { return Duration.between(start, end); } - @Test - public void testAccumulateNumberFromSum() { + @ParameterizedTest + @MethodSource("parameters") + public void testAccumulateNumberFromSum(RUN_TYPE runType) { String str = "import " + Shift.class.getCanonicalName() + ";" + "import " + AccumulateTest.class.getCanonicalName() + ";" @@ -2600,7 +2674,7 @@ public void testAccumulateNumberFromSum() { - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); Shift shift = new Shift(OffsetDateTime.now()); @@ -2625,8 +2699,9 @@ private static int switchMachinesInAssignments(KieSession session, MrProcessAssi return session.fireAllRules(); } - @Test - public void testDoubleAccumulateNPE() { + @ParameterizedTest + @MethodSource("parameters") + public void testDoubleAccumulateNPE(RUN_TYPE runType) { // Prepare reproducing data. MrMachine machine2 = new MrMachine(); MrMachine machine3 = new MrMachine(); @@ -2651,7 +2726,7 @@ public void testDoubleAccumulateNPE() { "then\n" + " result.add($count);\n" + "end;"; - KieSession kieSession = getKieSession(rule); + KieSession kieSession = getKieSession(runType, rule); List result = new ArrayList<>(); kieSession.setGlobal("result", result); @@ -2731,8 +2806,9 @@ public static class MrMachine { } - @Test - public void testInlineAccumulateWithAnd() { + @ParameterizedTest + @MethodSource("parameters") + public void testInlineAccumulateWithAnd(RUN_TYPE runType) { // RHDM-1549 String str = "import " + Car.class.getCanonicalName() + ";" + @@ -2749,7 +2825,7 @@ public void testInlineAccumulateWithAnd() { " result.add($total);\n" + "end"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); List result = new ArrayList<>(); ksession.setGlobal("result", result); @@ -2780,8 +2856,9 @@ public void testInlineAccumulateWithAnd() { ksession.dispose(); } - @Test - public void testInlineMvelAccumulateWithAnd() { + @ParameterizedTest + @MethodSource("parameters") + public void testInlineMvelAccumulateWithAnd(RUN_TYPE runType) { // RHDM-1549 String str = "import " + Car.class.getCanonicalName() + ";" + @@ -2799,7 +2876,7 @@ public void testInlineMvelAccumulateWithAnd() { " result.add($total);\n" + "end"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); List result = new ArrayList<>(); ksession.setGlobal("result", result); @@ -2912,8 +2989,9 @@ public void setPrice(BigDecimal price) { } } - @Test - public void testAccumulateOnPartiallyReversibleFunction() { + @ParameterizedTest + @MethodSource("parameters") + public void testAccumulateOnPartiallyReversibleFunction(RUN_TYPE runType) { // DROOLS-5930 String str = "import accumulate " + CountingIntegerMaxAccumulateFunction.class.getCanonicalName() + " countingMax;\n" + @@ -2925,7 +3003,7 @@ public void testAccumulateOnPartiallyReversibleFunction() { " result.add($max);\n" + "end"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); CountingIntegerMaxAccumulateFunction accFunction = CountingIntegerMaxAccumulateFunction.INSTANCE; @@ -2990,8 +3068,9 @@ public void resetAccumulateCount() { } } - @Test - public void testOneAccumulateOnPattern() { + @ParameterizedTest + @MethodSource("parameters") + public void testOneAccumulateOnPattern(RUN_TYPE runType) { // DROOLS-5938 String str = "import " + Person.class.getCanonicalName() + ";\n" + @@ -3004,7 +3083,7 @@ public void testOneAccumulateOnPattern() { " result.add($acc1.iterator().next());" + "end"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); List result = new ArrayList<>(); ksession.setGlobal("result", result); @@ -3019,8 +3098,9 @@ public void testOneAccumulateOnPattern() { assertThat(result.get(0)).isEqualTo(lukas); } - @Test - public void testOneAccumulateOnPatternWithVarBinding() { + @ParameterizedTest + @MethodSource("parameters") + public void testOneAccumulateOnPatternWithVarBinding(RUN_TYPE runType) { // DROOLS-5938 String str = "import " + Person.class.getCanonicalName() + ";\n" + @@ -3033,7 +3113,7 @@ public void testOneAccumulateOnPatternWithVarBinding() { " result.add($acc1.iterator().next());" + "end"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); List result = new ArrayList<>(); ksession.setGlobal("result", result); @@ -3047,8 +3127,9 @@ public void testOneAccumulateOnPatternWithVarBinding() { assertThat(result.get(0)).isEqualTo(lukas); } - @Test - public void testTwoAccumulatesOnPattern() { + @ParameterizedTest + @MethodSource("parameters") + public void testTwoAccumulatesOnPattern(RUN_TYPE runType) { // DROOLS-5938 String str = "import " + Person.class.getCanonicalName() + ";\n" + @@ -3064,7 +3145,7 @@ public void testTwoAccumulatesOnPattern() { " result.add($acc2.iterator().next());" + "end"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); List result = new ArrayList<>(); ksession.setGlobal("result", result); @@ -3076,8 +3157,9 @@ public void testTwoAccumulatesOnPattern() { assertThat(result.get(0)).isEqualTo(Pair.create("Lukas", 35)); } - @Test - public void testTwoAccumulatesOnPatternWithVarBinding() { + @ParameterizedTest + @MethodSource("parameters") + public void testTwoAccumulatesOnPatternWithVarBinding(RUN_TYPE runType) { // DROOLS-5938 String str = "import " + Person.class.getCanonicalName() + ";\n" + @@ -3093,7 +3175,7 @@ public void testTwoAccumulatesOnPatternWithVarBinding() { " result.add($acc2.iterator().next());" + "end"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); List result = new ArrayList<>(); ksession.setGlobal("result", result); @@ -3105,8 +3187,9 @@ public void testTwoAccumulatesOnPatternWithVarBinding() { assertThat(result.get(0)).isEqualTo(Pair.create("Lukas", 35)); } - @Test - public void testBindingOrderWithInlineAccumulate() { + @ParameterizedTest + @MethodSource("parameters") + public void testBindingOrderWithInlineAccumulate(RUN_TYPE runType) { // RHDM-1551 String str = "import " + Aclass.class.getCanonicalName() + ";\n" + @@ -3134,7 +3217,7 @@ public void testBindingOrderWithInlineAccumulate() { " result.add($eSet.iterator().next());" + "end"; - KieSession kSession = getKieSession( str ); + KieSession kSession = getKieSession(runType, str); List result = new ArrayList<>(); kSession.setGlobal("result", result); @@ -3151,8 +3234,9 @@ public void testBindingOrderWithInlineAccumulate() { kSession.dispose(); } - @Test - public void testBindingOrderWithInlineAccumulateAndLists() { + @ParameterizedTest + @MethodSource("parameters") + public void testBindingOrderWithInlineAccumulateAndLists(RUN_TYPE runType) { // RHDM-1551 String str = "import " + Aclass.class.getCanonicalName() + ";\n" + @@ -3180,7 +3264,7 @@ public void testBindingOrderWithInlineAccumulateAndLists() { " result.add($eSet.iterator().next());" + "end"; - KieSession kSession = getKieSession( str ); + KieSession kSession = getKieSession(runType, str); List result = new ArrayList<>(); kSession.setGlobal("result", result); @@ -3197,8 +3281,9 @@ public void testBindingOrderWithInlineAccumulateAndLists() { kSession.dispose(); } - @Test - public void testBindingOrderWithInlineAccumulateAndListsAndFrom() { + @ParameterizedTest + @MethodSource("parameters") + public void testBindingOrderWithInlineAccumulateAndListsAndFrom(RUN_TYPE runType) { // RHDM-1551 String str = "import " + Aclass.class.getCanonicalName() + ";\n" + @@ -3227,7 +3312,7 @@ public void testBindingOrderWithInlineAccumulateAndListsAndFrom() { " result.add($eSet.iterator().next());" + "end"; - KieSession kSession = getKieSession( str ); + KieSession kSession = getKieSession(runType, str); List result = new ArrayList<>(); kSession.setGlobal("result", result); @@ -3324,8 +3409,9 @@ public void setName(String name) { } } - @Test - public void testMultiAccumulate() { + @ParameterizedTest + @MethodSource("parameters") + public void testMultiAccumulate(RUN_TYPE runType) { // RHDM-1572 String str = "global java.util.List result;\n" + @@ -3340,7 +3426,7 @@ public void testMultiAccumulate() { " result.addAll($list);\n" + "end"; - KieSession kSession = getKieSession( str ); + KieSession kSession = getKieSession(runType, str); List result = new ArrayList<>(); kSession.setGlobal( "result", result ); @@ -3360,8 +3446,9 @@ public void testMultiAccumulate() { kSession.dispose(); } - @Test - public void testAccumulateWithExists() { + @ParameterizedTest + @MethodSource("parameters") + public void testAccumulateWithExists(RUN_TYPE runType) { // RHDM-1571 String str = "import " + Car.class.getCanonicalName() + ";" + @@ -3375,7 +3462,7 @@ public void testAccumulateWithExists() { " result.addAll($list);\n" + "end"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); List result = new ArrayList<>(); ksession.setGlobal( "result", result ); @@ -3392,8 +3479,9 @@ public void testAccumulateWithExists() { ksession.dispose(); } - @Test - public void testAccumulateWithForAll() { + @ParameterizedTest + @MethodSource("parameters") + public void testAccumulateWithForAll(RUN_TYPE runType) { // DROOLS-6025 String str = "import " + GrandChild.class.getCanonicalName() + ";\n" + @@ -3408,7 +3496,7 @@ public void testAccumulateWithForAll() { " System.out.println(\"exec \" + $count);\n" + "end\n"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); GrandParent grandParent = new GrandParent(); GrandChild grandChild = new GrandChild(); @@ -3444,8 +3532,9 @@ public void setGrandChild(List grandChild) { } } - @Test - public void testAccumulateSubnetworkEval() { + @ParameterizedTest + @MethodSource("parameters") + public void testAccumulateSubnetworkEval(RUN_TYPE runType) { // DROOLS-6228 String str = "import java.time.Duration;\n" + @@ -3462,7 +3551,7 @@ public void testAccumulateSubnetworkEval() { " holder.set((int)holder.get() + $sum);\n" + "end"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); AtomicReference holder = new AtomicReference<>(0); ksession.setGlobal("holder", holder); @@ -3475,8 +3564,9 @@ public void testAccumulateSubnetworkEval() { assertThat((int) holder.get()).isEqualTo(0); } - @Test - public void testInnerClassInAccumulatingFunction() { + @ParameterizedTest + @MethodSource("parameters") + public void testInnerClassInAccumulatingFunction(RUN_TYPE runType) { // DROOLS-6238 String str = "import java.util.*;\n" + @@ -3501,7 +3591,7 @@ public void testInnerClassInAccumulatingFunction() { "then\n" + "end"; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); ksession.insert(new Person("Mark", 42)); ksession.insert(new Person("Edson", 38)); @@ -3553,8 +3643,9 @@ public List result() { } } - @Test - public void testAccumulateWithSameBindingVariable() { + @ParameterizedTest + @MethodSource("parameters") + public void testAccumulateWithSameBindingVariable(RUN_TYPE runType) { // DROOLS-6102 String str = "import java.util.*;\n" + @@ -3568,7 +3659,7 @@ public void testAccumulateWithSameBindingVariable() { " list.add( $tot2.intValue() ); \n" + "end\n"; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); List list = new ArrayList<>(); ksession.setGlobal("list", list); @@ -3583,8 +3674,9 @@ public void testAccumulateWithSameBindingVariable() { assertThat((int) list.get(1)).isEqualTo(2); } - @Test - public void testAccumulateWithMaxCalendarNullDate() { + @ParameterizedTest + @MethodSource("parameters") + public void testAccumulateWithMaxCalendarNullDate(RUN_TYPE runType) { //DROOLS-4990 String str = "import " + StockTick.class.getCanonicalName() + ";\n" + @@ -3597,7 +3689,7 @@ public void testAccumulateWithMaxCalendarNullDate() { "then\n" + "end\n"; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); StockTick st = new StockTick("RHT"); ksession.insert(st); @@ -3607,8 +3699,9 @@ public void testAccumulateWithMaxCalendarNullDate() { assertThat(ksession.fireAllRules()).isEqualTo(1); } - @Test - public void testSubnetworkTuple() { + @ParameterizedTest + @MethodSource("parameters") + public void testSubnetworkTuple(RUN_TYPE runType) { final String drl = "import java.math.*; " + "import " + InputDataTypes.class.getCanonicalName() + "; " + @@ -3624,7 +3717,7 @@ public void testSubnetworkTuple() { " result.add($min); " + "end"; - final KieSession ksession = getKieSession(drl); + final KieSession ksession = getKieSession(runType, drl); List result = new ArrayList<>(); ksession.setGlobal("result", result); @@ -3685,8 +3778,9 @@ private GregorianCalendar calendarFromString(String inputString) { return GregorianCalendar.from( ZonedDateTime.from( DateTimeFormatter.ISO_DATE_TIME.parse(inputString))); } - @Test - public void testAccumulateCountWithExists() { + @ParameterizedTest + @MethodSource("parameters") + public void testAccumulateCountWithExists(RUN_TYPE runType) { // The following rule uses an accumulate to count all the name Strings for which at least one Person // of that name exists. Expected behavior: // - A name should be counted exactly once no matter how many Persons with that name exists. @@ -3704,7 +3798,7 @@ public void testAccumulateCountWithExists() { + " insert( new Result($count));\n" + " System.out.println(kcontext.getMatch().getObjects());\n" + "end\n"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); ReteDumper.dumpRete(ksession); @@ -3725,8 +3819,9 @@ public void testAccumulateCountWithExists() { assertThat(results.iterator().next().getValue()).isEqualTo(2L); } - @Test - public void testAccumulateWithIndirectArgument() { + @ParameterizedTest + @MethodSource("parameters") + public void testAccumulateWithIndirectArgument(RUN_TYPE runType) { String str = "global java.util.List resultTotal; \n" + "global java.util.List resultPair; \n" + @@ -3745,7 +3840,7 @@ public void testAccumulateWithIndirectArgument() { " resultPair.add($pair);\n" + "end"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); final List resultTotal = new ArrayList<>(); ksession.setGlobal("resultTotal", resultTotal); @@ -3766,8 +3861,9 @@ public void testAccumulateWithIndirectArgument() { assertThat(firstPair.getSecond()).isEqualTo("Mario"); } - @Test - public void testVariableWithMethodCallInAccFunc() { + @ParameterizedTest + @MethodSource("parameters") + public void testVariableWithMethodCallInAccFunc(RUN_TYPE runType) { final String str = "package org.drools.mvel.compiler\n" + "import " + ControlFact.class.getCanonicalName() + ";" + "import " + Payment.class.getCanonicalName() + ";" + @@ -3785,7 +3881,7 @@ public void testVariableWithMethodCallInAccFunc() { System.out.println(str); - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); final Payment payment = new Payment(); payment.setDueDate(Calendar.getInstance()); @@ -3799,8 +3895,9 @@ public void testVariableWithMethodCallInAccFunc() { assertThat(rules).isEqualTo(1); } - @Test - public void testVariableWithMethodCallInAccFuncSimple() { + @ParameterizedTest + @MethodSource("parameters") + public void testVariableWithMethodCallInAccFuncSimple(RUN_TYPE runType) { final String str = "package org.drools.mvel.compiler\n" + "import " + FactA.class.getCanonicalName() + ";" + "rule r1\n" + @@ -3814,7 +3911,7 @@ public void testVariableWithMethodCallInAccFuncSimple() { System.out.println(str); - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); final FactA factA = new FactA(); factA.setValue(1); @@ -3863,8 +3960,9 @@ public void setValue(Integer value) { } } - @Test - public void testAccumulateOnTwoPatterns() { + @ParameterizedTest + @MethodSource("parameters") + public void testAccumulateOnTwoPatterns(RUN_TYPE runType) { // DROOLS-5738 String str = "import " + Person.class.getCanonicalName() + ";\n" + @@ -3876,7 +3974,7 @@ public void testAccumulateOnTwoPatterns() { " insert($sum);\n" + "end\n"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); ksession.insert( new Person( "Mario", 46 ) ); ksession.insert( new Person( "Mark", 44 ) ); @@ -3888,8 +3986,9 @@ public void testAccumulateOnTwoPatterns() { assertThat(results.get(0)).isEqualTo(90); } - @Test - public void testPositionalAccumulate() { + @ParameterizedTest + @MethodSource("parameters") + public void testPositionalAccumulate(RUN_TYPE runType) { // DROOLS-6128 String str = "import " + Result.class.getCanonicalName() + ";" + @@ -3912,7 +4011,7 @@ public void testPositionalAccumulate() { " insert(new Result($sum));\n" + "end"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); ksession.fireAllRules(); @@ -3921,8 +4020,9 @@ public void testPositionalAccumulate() { assertThat(results.iterator().next().getValue()).isEqualTo(112); } - @Test - public void testAccumulateOnSet() { + @ParameterizedTest + @MethodSource("parameters") + public void testAccumulateOnSet(RUN_TYPE runType) { String str = "import java.util.*;\n" + "import " + Person.class.getCanonicalName() + ";\n" + @@ -3933,7 +4033,7 @@ public void testAccumulateOnSet() { " holder.set($size); \n" + "end"; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); AtomicReference holder = new AtomicReference<>(0); ksession.setGlobal("holder", holder); @@ -3954,8 +4054,9 @@ public void testAccumulateOnSet() { assertThat((int) holder.get()).isEqualTo(4); } - @Test - public void testNestedAccumulates() { + @ParameterizedTest + @MethodSource("parameters") + public void testNestedAccumulates(RUN_TYPE runType) { // DROOLS-6202 String str = "import java.util.*;\n" + @@ -3970,7 +4071,7 @@ public void testNestedAccumulates() { " holder.set($max); \n" + "end"; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); AtomicReference holder = new AtomicReference<>(0); ksession.setGlobal("holder", holder); @@ -3991,8 +4092,9 @@ public void testNestedAccumulates() { assertThat((int) holder.get()).isEqualTo(4); } - @Test - public void testIfInInlineAccumulate() { + @ParameterizedTest + @MethodSource("parameters") + public void testIfInInlineAccumulate(RUN_TYPE runType) { // DROOLS-6429 String str = "import " + Person.class.getCanonicalName() + ";\n" + "rule R when\n" + @@ -4006,7 +4108,7 @@ public void testIfInInlineAccumulate() { " insert($avg);\n" + "end"; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); ksession.insert(new Person("Sofia", 10)); FactHandle fh_Mark = ksession.insert(new Person("Mark", 37)); @@ -4026,8 +4128,9 @@ public void testIfInInlineAccumulate() { assertThat(results).contains(36); } - @Test - public void testBindVariableUsedInSubsequentAccumulateString() { + @ParameterizedTest + @MethodSource("parameters") + public void testBindVariableUsedInSubsequentAccumulateString(RUN_TYPE runType) { String str = "import " + Person.class.getCanonicalName() + ";" + "global java.util.List result;\n" + @@ -4044,7 +4147,7 @@ public void testBindVariableUsedInSubsequentAccumulateString() { " result.add($maxAge);\n" + "end"; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); List result = new ArrayList<>(); ksession.setGlobal("result", result); @@ -4058,8 +4161,9 @@ public void testBindVariableUsedInSubsequentAccumulateString() { assertThat(result).containsExactly(50); } - @Test - public void testBindVariableUsedInSubsequentAccumulateBigDecimal() { + @ParameterizedTest + @MethodSource("parameters") + public void testBindVariableUsedInSubsequentAccumulateBigDecimal(RUN_TYPE runType) { String str = "import " + Person.class.getCanonicalName() + ";" + "global java.util.List result;\n" + @@ -4076,7 +4180,7 @@ public void testBindVariableUsedInSubsequentAccumulateBigDecimal() { " result.add($maxAge);\n" + "end"; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); List result = new ArrayList<>(); ksession.setGlobal("result", result); @@ -4090,8 +4194,9 @@ public void testBindVariableUsedInSubsequentAccumulateBigDecimal() { assertThat(result).containsExactly(50); } - @Test - public void testCollectAfterAccumulate() { + @ParameterizedTest + @MethodSource("parameters") + public void testCollectAfterAccumulate(RUN_TYPE runType) { String str = "import " + Person.class.getCanonicalName() + ";\n" + "import " + BigDecimal.class.getCanonicalName() + ";\n" + "import " + ArrayList.class.getCanonicalName() + ";\n" + @@ -4109,7 +4214,7 @@ public void testCollectAfterAccumulate() { " result.addAll($list)\n" + "end"; try { - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); List result = new ArrayList<>(); ksession.setGlobal("result", result); @@ -4130,8 +4235,9 @@ public void testCollectAfterAccumulate() { } } - @Test - public void testExistsFromAccumulate() { + @ParameterizedTest + @MethodSource("parameters") + public void testExistsFromAccumulate(RUN_TYPE runType) { // DROOLS-6959 String str = "import " + Set.class.getCanonicalName() + ";\n" + @@ -4140,15 +4246,16 @@ public void testExistsFromAccumulate() { "then\n" + "end"; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); ksession.insert("String1"); ksession.insert("String2"); assertThat(ksession.fireAllRules()).isEqualTo(1); } - @Test - public void testAccumulateWithBetaConstraint() { + @ParameterizedTest + @MethodSource("parameters") + public void testAccumulateWithBetaConstraint(RUN_TYPE runType) { String str = "import " + Person.class.getCanonicalName() + ";" + "import " + Result.class.getCanonicalName() + ";" + @@ -4161,7 +4268,7 @@ public void testAccumulateWithBetaConstraint() { " insert(new Result($sum + \":\" + $i));\n" + "end"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); ksession.insert(5); ksession.insert(new Person("Mark", 37)); @@ -4175,8 +4282,9 @@ public void testAccumulateWithBetaConstraint() { assertThat(results).containsExactly(new Result("75:5")); } - @Test - public void testJoinInAccumulate() { + @ParameterizedTest + @MethodSource("parameters") + public void testJoinInAccumulate(RUN_TYPE runType) { String str = "import " + Person.class.getCanonicalName() + ";" + "import " + Result.class.getCanonicalName() + ";" + @@ -4188,7 +4296,7 @@ public void testJoinInAccumulate() { " insert(new Result($sum));\n" + "end"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); ksession.insert(new Person("Mark", 37)); ksession.insert(new Person("Edson", 35)); @@ -4207,8 +4315,9 @@ public void testJoinInAccumulate() { assertThat(results).containsExactlyInAnyOrder(new Result(0), new Result(75)); } - @Test - public void testAccumulateSumMultipleParametersExpression() { + @ParameterizedTest + @MethodSource("parameters") + public void testAccumulateSumMultipleParametersExpression(RUN_TYPE runType) { String str = "import " + Person.class.getCanonicalName() + ";" + "import " + Result.class.getCanonicalName() + ";" + @@ -4220,8 +4329,8 @@ public void testAccumulateSumMultipleParametersExpression() { " insert(new Result($sum));\n" + "end"; - Results results = createKieBuilder(str).getResults(); - if (testRunType.isExecutableModel()) { + Results results = createKieBuilder(runType, str).getResults(); + if (runType.isExecutableModel()) { assertThat(results.getMessages(Message.Level.ERROR).get(0).getText().contains( "Function \"sum\" cannot have more than 1 parameter")).isTrue(); } else { @@ -4230,8 +4339,9 @@ public void testAccumulateSumMultipleParametersExpression() { } } - @Test - public void testAccumulateSumUnaryExpression() { + @ParameterizedTest + @MethodSource("parameters") + public void testAccumulateSumUnaryExpression(RUN_TYPE runType) { String str = "import " + Person.class.getCanonicalName() + ";" + "import " + Result.class.getCanonicalName() + ";" + @@ -4243,7 +4353,7 @@ public void testAccumulateSumUnaryExpression() { " insert(new Result($sum));\n" + "end"; - KieSession kieSession = getKieSession( str ); + KieSession kieSession = getKieSession(runType, str); kieSession.insert(new Person("Mark", 37)); kieSession.insert(new Person("Edson", 35)); @@ -4256,8 +4366,9 @@ public void testAccumulateSumUnaryExpression() { assertThat(results.iterator().next().getValue()).isEqualTo(-77); } - @Test - public void testAccumulateSumBinaryExpWithNestedUnaryExpression() { + @ParameterizedTest + @MethodSource("parameters") + public void testAccumulateSumBinaryExpWithNestedUnaryExpression(RUN_TYPE runType) { String str = "import " + Person.class.getCanonicalName() + ";" + "import " + Result.class.getCanonicalName() + ";" + @@ -4269,7 +4380,7 @@ public void testAccumulateSumBinaryExpWithNestedUnaryExpression() { " insert(new Result($sum));\n" + "end"; - KieSession kieSession = getKieSession( str ); + KieSession kieSession = getKieSession(runType, str); kieSession.insert(new Person("Mark", 37)); kieSession.insert(new Person("Edson", 35)); diff --git a/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/BaseModelTest.java b/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/BaseModelTest.java index 5d99cc628fe..20e3bfe6141 100644 --- a/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/BaseModelTest.java +++ b/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/BaseModelTest.java @@ -21,6 +21,7 @@ import java.util.List; import java.util.UUID; import java.util.stream.Collectors; +import java.util.stream.Stream; import org.drools.compiler.kie.builder.impl.DrlProject; import org.drools.compiler.kie.builder.impl.InternalKieModule; @@ -28,9 +29,6 @@ import org.drools.core.reteoo.ObjectTypeNode; import org.drools.kiesession.rulebase.InternalKnowledgeBase; import org.drools.model.codegen.ExecutableModelProject; -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; -import org.junit.runners.Parameterized.Parameters; import org.kie.api.KieServices; import org.kie.api.builder.KieBuilder; import org.kie.api.builder.KieFileSystem; @@ -47,7 +45,6 @@ import static org.drools.model.codegen.execmodel.BaseModelTest.RUN_TYPE.PATTERN_WITH_ALPHA_NETWORK; import static org.drools.model.codegen.execmodel.BaseModelTest.RUN_TYPE.STANDARD_WITH_ALPHA_NETWORK; -@RunWith(Parameterized.class) public abstract class BaseModelTest { public enum RUN_TYPE { PATTERN_DSL( true, false ), @@ -72,66 +69,55 @@ public boolean isExecutableModel() { } } - final static Object[] PLAIN = { - RUN_TYPE.STANDARD_FROM_DRL, - PATTERN_DSL, - }; - - final static Object[] WITH_ALPHA_NETWORK = { - RUN_TYPE.STANDARD_FROM_DRL, - PATTERN_DSL, - STANDARD_WITH_ALPHA_NETWORK, - PATTERN_WITH_ALPHA_NETWORK, - }; - - - @Parameters(name = "{0}") - public static Object[] params() { + + public static Stream parameters() { if(Boolean.valueOf(System.getProperty("alphanetworkCompilerEnabled"))) { - return WITH_ALPHA_NETWORK; + return Stream.of(RUN_TYPE.STANDARD_FROM_DRL, + PATTERN_DSL, + STANDARD_WITH_ALPHA_NETWORK, + PATTERN_WITH_ALPHA_NETWORK); } else { - return PLAIN; + return Stream.of(RUN_TYPE.STANDARD_FROM_DRL, + PATTERN_DSL); } } - protected final CompilerTest.RUN_TYPE testRunType; - - public BaseModelTest( CompilerTest.RUN_TYPE testRunType ) { - this.testRunType = testRunType; + public BaseModelTest() { } - protected KieSession getKieSession(String... rules) { + protected KieSession getKieSession(BaseModelTest.RUN_TYPE testRunType, String... rules) { KieModuleModel model = testRunType.isAlphaNetworkCompiler() ? getKieModuleModelWithAlphaNetworkCompiler() : null; - return getKieSession(model, rules); + return getKieSession(testRunType, model, rules); } + - protected KieSession getKieSession(KieModuleModel model, String... stringRules) { - return getKieContainer( model, stringRules ).newKieSession(); + protected KieSession getKieSession(BaseModelTest.RUN_TYPE testRunType, KieModuleModel model, String... stringRules) { + return getKieContainer(testRunType, model, stringRules ).newKieSession(); } - protected KieContainer getKieContainer( KieModuleModel model, String... stringRules ) { - return getKieContainer( model, toKieFiles( stringRules ) ); + protected KieContainer getKieContainer(BaseModelTest.RUN_TYPE testRunType, KieModuleModel model, String... stringRules ) { + return getKieContainer(testRunType, model, toKieFiles( stringRules ) ); } - protected KieContainer getKieContainer( KieModuleModel model, KieFile... stringRules ) { + protected KieContainer getKieContainer(BaseModelTest.RUN_TYPE testRunType, KieModuleModel model, KieFile... stringRules ) { KieServices ks = KieServices.get(); ReleaseId releaseId = ks.newReleaseId( "org.kie", "kjar-test-" + UUID.randomUUID(), "1.0" ); - KieBuilder kieBuilder = createKieBuilder( ks, model, releaseId, stringRules ); + KieBuilder kieBuilder = createKieBuilder(testRunType, ks, model, releaseId, stringRules ); return ks.newKieContainer( releaseId ); } - protected KieBuilder createKieBuilder( String... stringRules ) { + protected KieBuilder createKieBuilder(BaseModelTest.RUN_TYPE testRunType, String... stringRules ) { KieServices ks = KieServices.get(); ReleaseId releaseId = ks.newReleaseId( "org.kie", "kjar-test-" + UUID.randomUUID(), "1.0" ); - return createKieBuilder( ks, null, releaseId, false, toKieFiles( stringRules ) ); + return createKieBuilder(testRunType, ks, null, releaseId, false, toKieFiles( stringRules ) ); } - protected KieBuilder createKieBuilder( KieServices ks, KieModuleModel model, ReleaseId releaseId, KieFile... stringRules ) { - return createKieBuilder( ks, model, releaseId, true, stringRules ); + protected KieBuilder createKieBuilder(BaseModelTest.RUN_TYPE testRunType, KieServices ks, KieModuleModel model, ReleaseId releaseId, KieFile... stringRules ) { + return createKieBuilder(testRunType, ks, model, releaseId, true, stringRules ); } - protected KieBuilder createKieBuilder( KieServices ks, KieModuleModel model, ReleaseId releaseId, boolean failIfBuildError, KieFile... stringRules ) { + protected KieBuilder createKieBuilder(BaseModelTest.RUN_TYPE testRunType, KieServices ks, KieModuleModel model, ReleaseId releaseId, boolean failIfBuildError, KieFile... stringRules ) { ks.getRepository().removeKieModule( releaseId ); KieFileSystem kfs = ks.newKieFileSystem(); @@ -170,20 +156,20 @@ public static List getObjectsIntoList(KieSession ksession, Class clazz return ksession.getInstancesOf(clazz).stream().collect(Collectors.toList()); } - protected void createAndDeployJar( KieServices ks, ReleaseId releaseId, String... drls ) { - createAndDeployJar( ks, null, releaseId, drls ); + protected void createAndDeployJar(BaseModelTest.RUN_TYPE testRunType, KieServices ks, ReleaseId releaseId, String... drls ) { + createAndDeployJar(testRunType, ks, null, releaseId, drls ); } - protected void createAndDeployJar( KieServices ks, ReleaseId releaseId, KieFile... ruleFiles ) { - createAndDeployJar( ks, null, releaseId, ruleFiles ); + protected void createAndDeployJar(BaseModelTest.RUN_TYPE testRunType, KieServices ks, ReleaseId releaseId, KieFile... ruleFiles ) { + createAndDeployJar(testRunType, ks, null, releaseId, ruleFiles ); } - protected void createAndDeployJar( KieServices ks, KieModuleModel model, ReleaseId releaseId, String... drls ) { - createAndDeployJar( ks, model, releaseId, toKieFiles( drls ) ); + protected void createAndDeployJar(BaseModelTest.RUN_TYPE testRunType, KieServices ks, KieModuleModel model, ReleaseId releaseId, String... drls ) { + createAndDeployJar(testRunType, ks, model, releaseId, toKieFiles( drls ) ); } - protected void createAndDeployJar( KieServices ks, KieModuleModel model, ReleaseId releaseId, KieFile... ruleFiles ) { - KieBuilder kieBuilder = createKieBuilder( ks, model, releaseId, ruleFiles ); + protected void createAndDeployJar(BaseModelTest.RUN_TYPE testRunType, KieServices ks, KieModuleModel model, ReleaseId releaseId, KieFile... ruleFiles ) { + KieBuilder kieBuilder = createKieBuilder(testRunType, ks, model, releaseId, ruleFiles ); InternalKieModule kieModule = (InternalKieModule) kieBuilder.getKieModule(); ks.getRepository().addKieModule( kieModule ); } diff --git a/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/BetaConditionTest.java b/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/BetaConditionTest.java index 03ba9de14c8..2c0eb97cdf5 100644 --- a/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/BetaConditionTest.java +++ b/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/BetaConditionTest.java @@ -22,7 +22,8 @@ import java.util.List; import org.drools.model.codegen.execmodel.domain.Person; -import org.junit.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; import org.kie.api.runtime.KieSession; import static org.assertj.core.api.Assertions.assertThat; @@ -30,12 +31,10 @@ // DROOLS-5852 public class BetaConditionTest extends BaseModelTest { - public BetaConditionTest(RUN_TYPE testRunType ) { - super( testRunType ); - } - @Test - public void betaCheckTwoConditionsExplicit() { + @ParameterizedTest + @MethodSource("parameters") + public void betaCheckTwoConditionsExplicit(RUN_TYPE runType) { final String drl = "global java.util.List list\n" + "import " + Person.class.getCanonicalName() + ";" + @@ -46,11 +45,12 @@ public void betaCheckTwoConditionsExplicit() { " list.add($p2);" + "end\n"; - verify(drl, 2); + verify(runType, drl, 2); } - @Test - public void betaCheckTwoConditionsImplicit() { + @ParameterizedTest + @MethodSource("parameters") + public void betaCheckTwoConditionsImplicit(RUN_TYPE runType) { final String drl = "global java.util.List list\n" + "import " + Person.class.getCanonicalName() + ";" + @@ -61,11 +61,12 @@ public void betaCheckTwoConditionsImplicit() { " list.add($p2);" + "end\n"; - verify(drl, 2); + verify(runType, drl, 2); } - @Test - public void betaCheckORExplicit() { + @ParameterizedTest + @MethodSource("parameters") + public void betaCheckORExplicit(RUN_TYPE runType) { final String drl = "global java.util.List list\n" + "import " + Person.class.getCanonicalName() + ";" + @@ -76,11 +77,12 @@ public void betaCheckORExplicit() { " list.add($p2);" + "end\n"; - verify(drl, 3); + verify(runType, drl, 3); } - @Test - public void betaCheckORImplicit() { + @ParameterizedTest + @MethodSource("parameters") + public void betaCheckORImplicit(RUN_TYPE runType) { final String str = "global java.util.List list\n" + "import " + Person.class.getCanonicalName() + ";" + @@ -91,11 +93,12 @@ public void betaCheckORImplicit() { " list.add($p2);" + "end\n"; - verify(str, 3); + verify(runType, str, 3); } - @Test - public void betaCheckExplicit() { + @ParameterizedTest + @MethodSource("parameters") + public void betaCheckExplicit(RUN_TYPE runType) { final String drl = "global java.util.List list\n" + "import " + Person.class.getCanonicalName() + ";" + @@ -106,12 +109,13 @@ public void betaCheckExplicit() { " list.add($p2);" + "end\n"; - verify(drl, 2); + verify(runType, drl, 2); } - @Test - public void betaCheckImplicit() { + @ParameterizedTest + @MethodSource("parameters") + public void betaCheckImplicit(RUN_TYPE runType) { final String drl = "global java.util.List list\n" + "import " + Person.class.getCanonicalName() + ";" + @@ -122,11 +126,12 @@ public void betaCheckImplicit() { " list.add($p2);" + "end\n"; - verify(drl, 2); + verify(runType, drl, 2); } - @Test - public void checkBooleanExplicit() { + @ParameterizedTest + @MethodSource("parameters") + public void checkBooleanExplicit(RUN_TYPE runType) { final String str = "global java.util.List list\n" + "import " + Person.class.getCanonicalName() + ";" + @@ -136,12 +141,13 @@ public void checkBooleanExplicit() { " list.add($p2);" + "end\n"; - verify(str, 1); + verify(runType, str, 1); } - @Test - public void checkBooleanImplicit() { + @ParameterizedTest + @MethodSource("parameters") + public void checkBooleanImplicit(RUN_TYPE runType) { final String drl = "global java.util.List list\n" + "import " + Person.class.getCanonicalName() + ";" + @@ -151,11 +157,11 @@ public void checkBooleanImplicit() { " list.add($p2);" + "end\n"; - verify(drl, 1); + verify(runType, drl, 1); } - private void verify(String str, int numberOfResults) { - KieSession ksession = getKieSession(str); + private void verify(RUN_TYPE runType, String str, int numberOfResults) { + KieSession ksession = getKieSession(runType, str); List results = new ArrayList<>(); ksession.setGlobal("list", results); diff --git a/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/BigPojoExecModelGenerationTest.java b/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/BigPojoExecModelGenerationTest.java index 2611f306c22..776e0e7b23b 100644 --- a/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/BigPojoExecModelGenerationTest.java +++ b/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/BigPojoExecModelGenerationTest.java @@ -21,7 +21,7 @@ import java.util.UUID; import org.drools.model.codegen.ExecutableModelProject; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.kie.api.KieServices; import org.kie.api.builder.KieBuilder; import org.kie.api.builder.KieFileSystem; diff --git a/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/BindingTest.java b/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/BindingTest.java index 9512691161f..93546bc13a9 100644 --- a/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/BindingTest.java +++ b/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/BindingTest.java @@ -22,19 +22,17 @@ import java.util.List; import org.drools.model.codegen.execmodel.domain.Person; -import org.junit.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; import org.kie.api.runtime.KieSession; import static org.assertj.core.api.Assertions.assertThat; public class BindingTest extends BaseModelTest { - public BindingTest( RUN_TYPE testRunType ) { - super( testRunType ); - } - - @Test - public void testBindUnaryBooleanExpression() { + @ParameterizedTest + @MethodSource("parameters") + public void testBindUnaryBooleanExpression(RUN_TYPE runType) { // RHDM-1612 final String str = "global java.util.List result;\n" + @@ -80,7 +78,7 @@ public void testBindUnaryBooleanExpression() { " result.add(\"R8\");\n" + "end\n"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); List result = new ArrayList<>(); ksession.setGlobal( "result", result ); @@ -105,8 +103,9 @@ public void testBindUnaryBooleanExpression() { assertThat(result.contains("R8")).isFalse(); } - @Test - public void testBindMethodCall() { + @ParameterizedTest + @MethodSource("parameters") + public void testBindMethodCall(RUN_TYPE runType) { // DROOLS-6521 final String str = "import " + Person.class.getCanonicalName() + ";\n" + @@ -118,7 +117,7 @@ public void testBindMethodCall() { " result.add($value);\n" + "end\n"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); List result = new ArrayList<>(); ksession.setGlobal( "result", result ); @@ -130,8 +129,9 @@ public void testBindMethodCall() { assertThat((char) result.get(0)).isEqualTo('r'); } - @Test - public void testEnclosedBinding() { + @ParameterizedTest + @MethodSource("parameters") + public void testEnclosedBinding(RUN_TYPE runType) { String str = "import " + Person.class.getCanonicalName() + ";" + "global java.util.List result;\n" + @@ -141,7 +141,7 @@ public void testEnclosedBinding() { " result.add($n);\n" + "end"; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); List result = new ArrayList<>(); ksession.setGlobal("result", result); @@ -152,8 +152,9 @@ public void testEnclosedBinding() { assertThat(result).containsExactly("Mario"); } - @Test - public void testComplexEnclosedBinding() { + @ParameterizedTest + @MethodSource("parameters") + public void testComplexEnclosedBinding(RUN_TYPE runType) { String str = "import " + Person.class.getCanonicalName() + ";" + "global java.util.List result;\n" + @@ -163,7 +164,7 @@ public void testComplexEnclosedBinding() { " result.add($n);\n" + "end"; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); List result = new ArrayList<>(); ksession.setGlobal("result", result); @@ -174,8 +175,9 @@ public void testComplexEnclosedBinding() { assertThat(result).containsExactly("Mario"); } - @Test - public void testComplexEnclosedDoubleBinding() { + @ParameterizedTest + @MethodSource("parameters") + public void testComplexEnclosedDoubleBinding(RUN_TYPE runType) { String str = "import " + Person.class.getCanonicalName() + ";" + "global java.util.List result;\n" + @@ -185,7 +187,7 @@ public void testComplexEnclosedDoubleBinding() { " result.add($n);\n" + "end"; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); List result = new ArrayList<>(); ksession.setGlobal("result", result); @@ -196,8 +198,9 @@ public void testComplexEnclosedDoubleBinding() { assertThat(result).containsExactly("Mario"); } - @Test - public void testBindingOnRight() { + @ParameterizedTest + @MethodSource("parameters") + public void testBindingOnRight(RUN_TYPE runType) { // DROOLS-6611 String str = "import " + Person.class.getCanonicalName() + ";" + @@ -208,7 +211,7 @@ public void testBindingOnRight() { " result.add($a);\n" + "end"; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); List result = new ArrayList<>(); ksession.setGlobal("result", result); @@ -219,8 +222,9 @@ public void testBindingOnRight() { assertThat(result).containsExactly(40); } - @Test - public void testBindingOnBoth() { + @ParameterizedTest + @MethodSource("parameters") + public void testBindingOnBoth(RUN_TYPE runType) { // DROOLS-6611 String str = "import " + Person.class.getCanonicalName() + ";" + @@ -232,7 +236,7 @@ public void testBindingOnBoth() { " result.add($a);\n" + "end"; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); List result = new ArrayList<>(); ksession.setGlobal("result", result); @@ -243,8 +247,9 @@ public void testBindingOnBoth() { assertThat(result).containsExactlyInAnyOrder("Mario", 40); } - @Test - public void test3BindingOn3Conditions() { + @ParameterizedTest + @MethodSource("parameters") + public void test3BindingOn3Conditions(RUN_TYPE runType) { // DROOLS-6611 String str = "import " + Person.class.getCanonicalName() + ";" + @@ -257,7 +262,7 @@ public void test3BindingOn3Conditions() { " result.add($l);\n" + "end"; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); List result = new ArrayList<>(); ksession.setGlobal("result", result); @@ -269,8 +274,9 @@ public void test3BindingOn3Conditions() { assertThat(result).containsExactlyInAnyOrder("Mario", 40, "Cheddar"); } - @Test - public void test2BindingOn3Conditions() { + @ParameterizedTest + @MethodSource("parameters") + public void test2BindingOn3Conditions(RUN_TYPE runType) { // DROOLS-6611 String str = "import " + Person.class.getCanonicalName() + ";" + @@ -282,7 +288,7 @@ public void test2BindingOn3Conditions() { " result.add($l);\n" + "end"; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); List result = new ArrayList<>(); ksession.setGlobal("result", result); @@ -294,8 +300,9 @@ public void test2BindingOn3Conditions() { assertThat(result).containsExactlyInAnyOrder(40, "Cheddar"); } - @Test - public void testBindingOnRightWithOr() { + @ParameterizedTest + @MethodSource("parameters") + public void testBindingOnRightWithOr(RUN_TYPE runType) { // DROOLS-6920 String str = "import " + Person.class.getCanonicalName() + ";" + @@ -306,7 +313,7 @@ public void testBindingOnRightWithOr() { " result.add($a);\n" + "end"; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); List result = new ArrayList<>(); ksession.setGlobal("result", result); @@ -317,8 +324,9 @@ public void testBindingOnRightWithOr() { assertThat(result).containsExactly(40); } - @Test - public void testBindingOnBothWithOr() { + @ParameterizedTest + @MethodSource("parameters") + public void testBindingOnBothWithOr(RUN_TYPE runType) { // DROOLS-6920 String str = "import " + Person.class.getCanonicalName() + ";" + @@ -330,7 +338,7 @@ public void testBindingOnBothWithOr() { " result.add($a);\n" + "end"; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); List result = new ArrayList<>(); ksession.setGlobal("result", result); @@ -341,8 +349,9 @@ public void testBindingOnBothWithOr() { assertThat(result).containsExactlyInAnyOrder("Toshiya", 40); } - @Test - public void test3BindingOn3ConditionsWithOr() { + @ParameterizedTest + @MethodSource("parameters") + public void test3BindingOn3ConditionsWithOr(RUN_TYPE runType) { // DROOLS-6920 String str = "import " + Person.class.getCanonicalName() + ";" + @@ -355,7 +364,7 @@ public void test3BindingOn3ConditionsWithOr() { " result.add($l);\n" + "end"; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); List result = new ArrayList<>(); ksession.setGlobal("result", result); @@ -367,8 +376,9 @@ public void test3BindingOn3ConditionsWithOr() { assertThat(result).containsExactlyInAnyOrder("Toshiya", 10, "Cheddar"); } - @Test - public void test2BindingOn3ConditionsWithOr() { + @ParameterizedTest + @MethodSource("parameters") + public void test2BindingOn3ConditionsWithOr(RUN_TYPE runType) { // DROOLS-6920 String str = "import " + Person.class.getCanonicalName() + ";" + @@ -380,7 +390,7 @@ public void test2BindingOn3ConditionsWithOr() { " result.add($l);\n" + "end"; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); List result = new ArrayList<>(); ksession.setGlobal("result", result); @@ -392,8 +402,9 @@ public void test2BindingOn3ConditionsWithOr() { assertThat(result).containsExactlyInAnyOrder(10, "Cheddar"); } - @Test - public void test3BindingOn3ConditionsWithAndOr() { + @ParameterizedTest + @MethodSource("parameters") + public void test3BindingOn3ConditionsWithAndOr(RUN_TYPE runType) { // DROOLS-6920 String str = "import " + Person.class.getCanonicalName() + ";" + @@ -406,7 +417,7 @@ public void test3BindingOn3ConditionsWithAndOr() { " result.add($l);\n" + "end"; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); List result = new ArrayList<>(); ksession.setGlobal("result", result); @@ -434,8 +445,9 @@ public void test3BindingOn3ConditionsWithAndOr() { assertThat(result).isEmpty(); } - @Test - public void test3BindingOn3ConditionsWithOrAnd() { + @ParameterizedTest + @MethodSource("parameters") + public void test3BindingOn3ConditionsWithOrAnd(RUN_TYPE runType) { // DROOLS-6920 String str = "import " + Person.class.getCanonicalName() + ";" + @@ -448,7 +460,7 @@ public void test3BindingOn3ConditionsWithOrAnd() { " result.add($l);\n" + "end"; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); List result = new ArrayList<>(); ksession.setGlobal("result", result); @@ -476,8 +488,9 @@ public void test3BindingOn3ConditionsWithOrAnd() { assertThat(result).isEmpty(); } - @Test - public void testConstraintExpression() { + @ParameterizedTest + @MethodSource("parameters") + public void testConstraintExpression(RUN_TYPE runType) { String str = "package constraintexpression\n" + "\n" + "import " + Person.class.getCanonicalName() + "\n" + @@ -492,7 +505,7 @@ public void testConstraintExpression() { " booleanListGlobal.add($booleanVariable); \n " + "end \n"; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); try { final List booleanListGlobal = new ArrayList<>(); ksession.setGlobal("booleanListGlobal", booleanListGlobal); @@ -511,8 +524,9 @@ public void testConstraintExpression() { * enclosed in parentheses. This is intentional behaviour, agreed in discussions, * which may be revised in the future. */ - @Test - public void testIgnoreConstraintInParentheses() { + @ParameterizedTest + @MethodSource("parameters") + public void testIgnoreConstraintInParentheses(RUN_TYPE runType) { String str = "package constraintexpression\n" + "\n" + "import " + Person.class.getCanonicalName() + "\n" + @@ -527,7 +541,7 @@ public void testIgnoreConstraintInParentheses() { " booleanListGlobal.add($booleanVariable); \n " + "end \n"; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); try { final List booleanListGlobal = new ArrayList<>(); ksession.setGlobal("booleanListGlobal", booleanListGlobal); diff --git a/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/BuildFromDescrTest.java b/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/BuildFromDescrTest.java index 2a1f216cf96..44f176c2251 100644 --- a/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/BuildFromDescrTest.java +++ b/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/BuildFromDescrTest.java @@ -25,7 +25,7 @@ import org.drools.model.codegen.ExecutableModelProject; import org.drools.model.codegen.execmodel.domain.Person; import org.drools.model.codegen.execmodel.domain.Result; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.kie.api.runtime.KieSession; import org.kie.internal.utils.KieHelper; diff --git a/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/BuildFromKJarTest.java b/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/BuildFromKJarTest.java index 865a9384474..f0fe20d1cb0 100644 --- a/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/BuildFromKJarTest.java +++ b/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/BuildFromKJarTest.java @@ -21,10 +21,9 @@ import java.util.List; import org.drools.compiler.kie.builder.impl.InternalKieModule; -import org.drools.compiler.kie.builder.impl.KieBuilderImpl; import org.drools.model.codegen.ExecutableModelProject; import org.drools.model.codegen.execmodel.domain.Person; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.kie.api.KieServices; import org.kie.api.builder.KieBuilder; import org.kie.api.builder.KieFileSystem; diff --git a/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/CepTest.java b/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/CepTest.java index f1a4080f8b5..c44597ea046 100644 --- a/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/CepTest.java +++ b/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/CepTest.java @@ -37,7 +37,8 @@ import org.drools.model.codegen.execmodel.domain.StockFact; import org.drools.model.codegen.execmodel.domain.StockTick; import org.drools.model.codegen.execmodel.domain.StockTickEx; -import org.junit.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; import org.kie.api.KieServices; import org.kie.api.builder.model.KieModuleModel; import org.kie.api.conf.EventProcessingOption; @@ -53,9 +54,6 @@ public class CepTest extends BaseModelTest { - public CepTest( RUN_TYPE testRunType ) { - super( testRunType ); - } public static KieModuleModel getCepKieModuleModel() { KieModuleModel kproj = KieServices.get().newKieModuleModel(); @@ -67,8 +65,9 @@ public static KieModuleModel getCepKieModuleModel() { return kproj; } - @Test - public void testAfter() throws Exception { + @ParameterizedTest + @MethodSource("parameters") + public void testAfter(RUN_TYPE runType) throws Exception { String str = "import " + StockTick.class.getCanonicalName() + ";" + "rule R when\n" + @@ -78,7 +77,7 @@ public void testAfter() throws Exception { " System.out.println(\"fired\");\n" + "end\n"; - KieSession ksession = getKieSession(getCepKieModuleModel(), str); + KieSession ksession = getKieSession(runType, getCepKieModuleModel(), str); SessionPseudoClock clock = ksession.getSessionClock(); ksession.insert( new StockTick( "DROO" ) ); @@ -93,8 +92,9 @@ public void testAfter() throws Exception { assertThat(ksession.fireAllRules()).isEqualTo(0); } - @Test - public void testNegatedAfter() throws Exception { + @ParameterizedTest + @MethodSource("parameters") + public void testNegatedAfter(RUN_TYPE runType) throws Exception { String str = "import " + StockTick.class.getCanonicalName() + ";" + "rule R when\n" + @@ -104,7 +104,7 @@ public void testNegatedAfter() throws Exception { " System.out.println(\"fired\");\n" + "end\n"; - KieSession ksession = getKieSession(getCepKieModuleModel(), str); + KieSession ksession = getKieSession(runType, getCepKieModuleModel(), str); SessionPseudoClock clock = ksession.getSessionClock(); ksession.insert( new StockTick( "DROO" ) ); @@ -119,8 +119,9 @@ public void testNegatedAfter() throws Exception { assertThat(ksession.fireAllRules()).isEqualTo(1); } - @Test - public void testAfterWithEntryPoints() throws Exception { + @ParameterizedTest + @MethodSource("parameters") + public void testAfterWithEntryPoints(RUN_TYPE runType) throws Exception { String str = "import " + StockTick.class.getCanonicalName() + ";" + "rule R when\n" + @@ -130,7 +131,7 @@ public void testAfterWithEntryPoints() throws Exception { " System.out.println(\"fired\");\n" + "end\n"; - KieSession ksession = getKieSession(getCepKieModuleModel(), str); + KieSession ksession = getKieSession(runType, getCepKieModuleModel(), str); SessionPseudoClock clock = ksession.getSessionClock(); ksession.getEntryPoint( "ep1" ).insert( new StockTick( "DROO" ) ); @@ -148,8 +149,9 @@ public void testAfterWithEntryPoints() throws Exception { assertThat(ksession.fireAllRules()).isEqualTo(0); } - @Test - public void testSlidingWindow() throws Exception { + @ParameterizedTest + @MethodSource("parameters") + public void testSlidingWindow(RUN_TYPE runType) throws Exception { String str = "import " + StockTick.class.getCanonicalName() + ";\n" + "rule R when\n" + @@ -158,7 +160,7 @@ public void testSlidingWindow() throws Exception { " System.out.println(\"fired\");\n" + "end\n"; - KieSession ksession = getKieSession(getCepKieModuleModel(), str); + KieSession ksession = getKieSession(runType, getCepKieModuleModel(), str); SessionPseudoClock clock = ksession.getSessionClock(); clock.advanceTime( 1, TimeUnit.SECONDS ); @@ -173,8 +175,9 @@ public void testSlidingWindow() throws Exception { assertThat(ksession.fireAllRules()).isEqualTo(2); } - @Test - public void testNotAfter() throws Exception { + @ParameterizedTest + @MethodSource("parameters") + public void testNotAfter(RUN_TYPE runType) throws Exception { String str = "import " + StockTick.class.getCanonicalName() + ";" + "rule R when\n" + @@ -184,7 +187,7 @@ public void testNotAfter() throws Exception { " System.out.println(\"fired\");\n" + "end\n"; - KieSession ksession = getKieSession(getCepKieModuleModel(), str); + KieSession ksession = getKieSession(runType, getCepKieModuleModel(), str); SessionPseudoClock clock = ksession.getSessionClock(); ksession.insert( new StockTick("DROO") ); @@ -202,8 +205,9 @@ public void testNotAfter() throws Exception { assertThat(ksession.fireAllRules()).isEqualTo(1); } - @Test - public void testDeclaredSlidingWindow() throws Exception { + @ParameterizedTest + @MethodSource("parameters") + public void testDeclaredSlidingWindow(RUN_TYPE runType) throws Exception { String str = "import " + StockTick.class.getCanonicalName() + ";\n" + "declare window DeclaredWindow\n" + @@ -215,7 +219,7 @@ public void testDeclaredSlidingWindow() throws Exception { " System.out.println($a.getCompany());\n" + "end\n"; - KieSession ksession = getKieSession(getCepKieModuleModel(), str); + KieSession ksession = getKieSession(runType, getCepKieModuleModel(), str); SessionPseudoClock clock = ksession.getSessionClock(); clock.advanceTime( 2, TimeUnit.SECONDS ); @@ -230,8 +234,9 @@ public void testDeclaredSlidingWindow() throws Exception { assertThat(ksession.fireAllRules()).isEqualTo(2); } - @Test - public void testDeclaredSlidingWindowWithEntryPoint() throws Exception { + @ParameterizedTest + @MethodSource("parameters") + public void testDeclaredSlidingWindowWithEntryPoint(RUN_TYPE runType) throws Exception { String str = "import " + StockTick.class.getCanonicalName() + ";\n" + "declare window DeclaredWindow\n" + @@ -243,7 +248,7 @@ public void testDeclaredSlidingWindowWithEntryPoint() throws Exception { " System.out.println($a.getCompany());\n" + "end\n"; - KieSession ksession = getKieSession(getCepKieModuleModel(), str); + KieSession ksession = getKieSession(runType, getCepKieModuleModel(), str); SessionPseudoClock clock = ksession.getSessionClock(); EntryPoint ep = ksession.getEntryPoint("ticks"); @@ -260,8 +265,9 @@ public void testDeclaredSlidingWindowWithEntryPoint() throws Exception { assertThat(ksession.fireAllRules()).isEqualTo(2); } - @Test - public void testDeclaredSlidingWindowOnEventInTypeDeclaration() throws Exception { + @ParameterizedTest + @MethodSource("parameters") + public void testDeclaredSlidingWindowOnEventInTypeDeclaration(RUN_TYPE runType) throws Exception { String str = "declare String\n" + " @role( event )\n" + @@ -275,7 +281,7 @@ public void testDeclaredSlidingWindowOnEventInTypeDeclaration() throws Exception " System.out.println($a);\n" + "end\n"; - KieSession ksession = getKieSession(getCepKieModuleModel(), str); + KieSession ksession = getKieSession(runType, getCepKieModuleModel(), str); SessionPseudoClock clock = ksession.getSessionClock(); ksession.insert( "ACME" ); @@ -284,8 +290,9 @@ public void testDeclaredSlidingWindowOnEventInTypeDeclaration() throws Exception assertThat(ksession.fireAllRules()).isEqualTo(1); } - @Test - public void testDeclaredSlidingWindowOnDeclaredType() throws Exception { + @ParameterizedTest + @MethodSource("parameters") + public void testDeclaredSlidingWindowOnDeclaredType(RUN_TYPE runType) throws Exception { String str = "declare MyEvent\n" + " @role( event )\n" + @@ -303,13 +310,14 @@ public void testDeclaredSlidingWindowOnDeclaredType() throws Exception { " System.out.println($a);\n" + "end\n"; - KieSession ksession = getKieSession(getCepKieModuleModel(), str); + KieSession ksession = getKieSession(runType, getCepKieModuleModel(), str); SessionPseudoClock clock = ksession.getSessionClock(); assertThat(ksession.fireAllRules()).isEqualTo(2); } - @Test - public void testDeclaredSlidingWindowWith2Arguments() throws Exception { + @ParameterizedTest + @MethodSource("parameters") + public void testDeclaredSlidingWindowWith2Arguments(RUN_TYPE runType) throws Exception { String str = "declare String\n" + " @role( event )\n" + @@ -323,7 +331,7 @@ public void testDeclaredSlidingWindowWith2Arguments() throws Exception { " System.out.println($a);\n" + "end\n"; - KieSession ksession = getKieSession(getCepKieModuleModel(), str); + KieSession ksession = getKieSession(runType, getCepKieModuleModel(), str); SessionPseudoClock clock = ksession.getSessionClock(); ksession.insert( "ACME" ); @@ -332,8 +340,9 @@ public void testDeclaredSlidingWindowWith2Arguments() throws Exception { assertThat(ksession.fireAllRules()).isEqualTo(1); } - @Test - public void testWithDeclaredEvent() throws Exception { + @ParameterizedTest + @MethodSource("parameters") + public void testWithDeclaredEvent(RUN_TYPE runType) throws Exception { String str = "import " + StockFact.class.getCanonicalName() + ";\n" + "declare StockFact @role( event ) end;\n" + @@ -344,7 +353,7 @@ public void testWithDeclaredEvent() throws Exception { " System.out.println(\"fired\");\n" + "end\n"; - KieSession ksession = getKieSession(getCepKieModuleModel(), str); + KieSession ksession = getKieSession(runType, getCepKieModuleModel(), str); SessionPseudoClock clock = ksession.getSessionClock(); ksession.insert( new StockFact( "DROO" ) ); @@ -359,8 +368,9 @@ public void testWithDeclaredEvent() throws Exception { assertThat(ksession.fireAllRules()).isEqualTo(0); } - @Test - public void testExpireEventOnEndTimestamp() throws Exception { + @ParameterizedTest + @MethodSource("parameters") + public void testExpireEventOnEndTimestamp(RUN_TYPE runType) throws Exception { String str = "package org.drools.compiler;\n" + "import " + StockTick.class.getCanonicalName() + ";\n" + @@ -374,7 +384,7 @@ public void testExpireEventOnEndTimestamp() throws Exception { " resultsAfter.add( $b );\n" + "end"; - KieSession ksession = getKieSession(getCepKieModuleModel(), str); + KieSession ksession = getKieSession(runType, getCepKieModuleModel(), str); SessionPseudoClock clock = ksession.getSessionClock(); List resultsAfter = new ArrayList(); @@ -393,8 +403,9 @@ public void testExpireEventOnEndTimestamp() throws Exception { assertThat(resultsAfter.size()).isEqualTo(1); } - @Test - public void testExpireEventOnEndTimestampWithDeclaredEvent() throws Exception { + @ParameterizedTest + @MethodSource("parameters") + public void testExpireEventOnEndTimestampWithDeclaredEvent(RUN_TYPE runType) throws Exception { String str = "package org.drools.compiler;\n" + "import " + StockFact.class.getCanonicalName() + ";\n" + @@ -413,7 +424,7 @@ public void testExpireEventOnEndTimestampWithDeclaredEvent() throws Exception { " resultsAfter.add( $b );\n" + "end"; - KieSession ksession = getKieSession(getCepKieModuleModel(), str); + KieSession ksession = getKieSession(runType, getCepKieModuleModel(), str); SessionPseudoClock clock = ksession.getSessionClock(); List resultsAfter = new ArrayList(); @@ -432,8 +443,9 @@ public void testExpireEventOnEndTimestampWithDeclaredEvent() throws Exception { assertThat(resultsAfter.size()).isEqualTo(1); } - @Test - public void testExpires() throws Exception { + @ParameterizedTest + @MethodSource("parameters") + public void testExpires(RUN_TYPE runType) throws Exception { String str = "package org.drools.compiler;\n" + "import " + StockFact.class.getCanonicalName() + ";\n" + @@ -449,7 +461,7 @@ public void testExpires() throws Exception { "then\n" + "end"; - KieSession ksession = getKieSession(getCepKieModuleModel(), str); + KieSession ksession = getKieSession(runType, getCepKieModuleModel(), str); SessionPseudoClock clock = ksession.getSessionClock(); ksession.insert(new StockFact("DROO")); @@ -463,8 +475,9 @@ public void testExpires() throws Exception { assertThat(ksession.getObjects().size()).isEqualTo(0); } - @Test - public void testDeclareAndExpires() throws Exception { + @ParameterizedTest + @MethodSource("parameters") + public void testDeclareAndExpires(RUN_TYPE runType) throws Exception { String str = "package org.drools.compiler;\n" + "declare StockFact\n" + @@ -480,7 +493,7 @@ public void testDeclareAndExpires() throws Exception { "then\n" + "end"; - KieSession ksession = getKieSession(getCepKieModuleModel(), str); + KieSession ksession = getKieSession(runType, getCepKieModuleModel(), str); SessionPseudoClock clock = ksession.getSessionClock(); FactType stockFactType = ksession.getKieBase().getFactType("org.drools.compiler", "StockFact"); @@ -498,8 +511,9 @@ public void testDeclareAndExpires() throws Exception { assertThat(ksession.getObjects().size()).isEqualTo(0); } - @Test - public void testNoEvent() { + @ParameterizedTest + @MethodSource("parameters") + public void testNoEvent(RUN_TYPE runType) { String str = "declare BaseEvent\n" + " @role(event)\n" + @@ -526,12 +540,13 @@ public void testNoEvent() { "\n" + "end"; - KieSession ksession = getKieSession(getCepKieModuleModel(), str); + KieSession ksession = getKieSession(runType, getCepKieModuleModel(), str); assertThat(ksession.fireAllRules()).isEqualTo(1); } - @Test - public void testIntervalTimer() throws Exception { + @ParameterizedTest + @MethodSource("parameters") + public void testIntervalTimer(RUN_TYPE runType) throws Exception { String str = ""; str += "package org.simple \n"; str += "global java.util.List list \n"; @@ -542,7 +557,7 @@ public void testIntervalTimer() throws Exception { str += " list.add(\"fired\"); \n"; str += "end \n"; - KieSession ksession = getKieSession(getCepKieModuleModel(), str); + KieSession ksession = getKieSession(runType, getCepKieModuleModel(), str); SessionPseudoClock clock = ksession.getSessionClock(); List list = new ArrayList(); @@ -576,8 +591,9 @@ public void testIntervalTimer() throws Exception { assertThat(list.size()).isEqualTo(3); } - @Test - public void testAfterWithAnd() throws Exception { + @ParameterizedTest + @MethodSource("parameters") + public void testAfterWithAnd(RUN_TYPE runType) throws Exception { String str = "import " + StockTick.class.getCanonicalName() + ";" + "rule R when\n" + @@ -587,7 +603,7 @@ public void testAfterWithAnd() throws Exception { " System.out.println(\"fired\");\n" + "end\n"; - KieSession ksession = getKieSession(getCepKieModuleModel(), str); + KieSession ksession = getKieSession(runType, getCepKieModuleModel(), str); SessionPseudoClock clock = ksession.getSessionClock(); ksession.insert( new StockTick( "DROO" ) ); @@ -602,8 +618,9 @@ public void testAfterWithAnd() throws Exception { assertThat(ksession.fireAllRules()).isEqualTo(0); } - @Test - public void testAfterOnLongFields() throws Exception { + @ParameterizedTest + @MethodSource("parameters") + public void testAfterOnLongFields(RUN_TYPE runType) throws Exception { String str = "import " + StockTick.class.getCanonicalName() + ";" + "rule R when\n" + @@ -613,7 +630,7 @@ public void testAfterOnLongFields() throws Exception { " System.out.println(\"fired\");\n" + "end\n"; - KieSession ksession = getKieSession(getCepKieModuleModel(), str); + KieSession ksession = getKieSession(runType, getCepKieModuleModel(), str); SessionPseudoClock clock = ksession.getSessionClock(); ksession.insert( new StockTick( "DROO" ).setTimeField( 0 ) ); @@ -626,8 +643,9 @@ public void testAfterOnLongFields() throws Exception { assertThat(ksession.fireAllRules()).isEqualTo(0); } - @Test - public void testAfterOnDateFields() throws Exception { + @ParameterizedTest + @MethodSource("parameters") + public void testAfterOnDateFields(RUN_TYPE runType) throws Exception { String str = "import " + StockTick.class.getCanonicalName() + ";" + "rule R when\n" + @@ -637,7 +655,7 @@ public void testAfterOnDateFields() throws Exception { " System.out.println(\"fired\");\n" + "end\n"; - KieSession ksession = getKieSession(getCepKieModuleModel(), str); + KieSession ksession = getKieSession(runType, getCepKieModuleModel(), str); SessionPseudoClock clock = ksession.getSessionClock(); ksession.insert( new StockTick( "DROO" ).setTimeField( 0 ) ); @@ -650,8 +668,9 @@ public void testAfterOnDateFields() throws Exception { assertThat(ksession.fireAllRules()).isEqualTo(0); } - @Test - public void testAfterOnDateFieldsWithBinding() throws Exception { + @ParameterizedTest + @MethodSource("parameters") + public void testAfterOnDateFieldsWithBinding(RUN_TYPE runType) throws Exception { String str = "import " + StockTick.class.getCanonicalName() + ";" + "rule R when\n" + @@ -661,7 +680,7 @@ public void testAfterOnDateFieldsWithBinding() throws Exception { " System.out.println(\"fired\");\n" + "end\n"; - KieSession ksession = getKieSession(getCepKieModuleModel(), str); + KieSession ksession = getKieSession(runType, getCepKieModuleModel(), str); SessionPseudoClock clock = ksession.getSessionClock(); clock.advanceTime( 100, TimeUnit.MILLISECONDS ); @@ -675,8 +694,9 @@ public void testAfterOnDateFieldsWithBinding() throws Exception { assertThat(ksession.fireAllRules()).isEqualTo(0); } - @Test - public void testAfterOnFactAndField() throws Exception { + @ParameterizedTest + @MethodSource("parameters") + public void testAfterOnFactAndField(RUN_TYPE runType) throws Exception { String str = "import " + StockTick.class.getCanonicalName() + ";" + "rule R when\n" + @@ -686,7 +706,7 @@ public void testAfterOnFactAndField() throws Exception { " System.out.println(\"fired\");\n" + "end\n"; - KieSession ksession = getKieSession(getCepKieModuleModel(), str); + KieSession ksession = getKieSession(runType, getCepKieModuleModel(), str); SessionPseudoClock clock = ksession.getSessionClock(); ksession.insert( new StockTick( "DROO" ).setTimeField( 0 ) ); @@ -701,8 +721,9 @@ public void testAfterOnFactAndField() throws Exception { assertThat(ksession.fireAllRules()).isEqualTo(0); } - @Test - public void testComplexTimestamp() { + @ParameterizedTest + @MethodSource("parameters") + public void testComplexTimestamp(RUN_TYPE runType) { final String str = "import " + Message.class.getCanonicalName() + "\n" + "declare " + Message.class.getCanonicalName() + "\n" + @@ -711,7 +732,7 @@ public void testComplexTimestamp() { " @duration( getProperties().get( 'duration' ) + 1 ) \n" + "end\n"; - KieSession ksession = getKieSession(getCepKieModuleModel(), str); + KieSession ksession = getKieSession(runType, getCepKieModuleModel(), str); try { final Message msg = new Message(); @@ -759,8 +780,9 @@ public void setDuration(final Long duration) { } } - @Test - public void testTimerWithMillisPrecision() { + @ParameterizedTest + @MethodSource("parameters") + public void testTimerWithMillisPrecision(RUN_TYPE runType) { final String drl = "import " + MyEvent.class.getCanonicalName() + "\n" + "import " + AtomicInteger.class.getCanonicalName() + "\n" + "declare MyEvent\n" + @@ -781,7 +803,7 @@ public void testTimerWithMillisPrecision() { " }\n" + "end"; - KieSession ksession = getKieSession(getCepKieModuleModel(), drl); + KieSession ksession = getKieSession(runType, getCepKieModuleModel(), drl); try { final long now = 1000; @@ -911,8 +933,9 @@ public void setPrice( Double price ) { } } - @Test - public void testCollectWithDeclaredWindow() { + @ParameterizedTest + @MethodSource("parameters") + public void testCollectWithDeclaredWindow(RUN_TYPE runType) { // DROOLS-4492 final String drl = "import " + Quote.class.getCanonicalName() + "\n" + @@ -942,7 +965,7 @@ public void testCollectWithDeclaredWindow() { " }\n" + "end"; - KieSession ksession = getKieSession( getCepKieModuleModel(), drl ); + KieSession ksession = getKieSession(runType, getCepKieModuleModel(), drl ); try { ksession.insert( new Quote("RHT", 10.0) ); @@ -957,8 +980,9 @@ public void testCollectWithDeclaredWindow() { } } - @Test - public void testAfterBindingFirst() throws Exception { + @ParameterizedTest + @MethodSource("parameters") + public void testAfterBindingFirst(RUN_TYPE runType) throws Exception { String str = "import " + StockTick.class.getCanonicalName() + ";" + "rule R when\n" + @@ -968,7 +992,7 @@ public void testAfterBindingFirst() throws Exception { " System.out.println(\"fired\");\n" + "end\n"; - KieSession ksession = getKieSession(getCepKieModuleModel(), str); + KieSession ksession = getKieSession(runType, getCepKieModuleModel(), str); SessionPseudoClock clock = ksession.getSessionClock(); ksession.insert( new StockTick( "ACME" ) ); @@ -983,8 +1007,9 @@ public void testAfterBindingFirst() throws Exception { assertThat(ksession.fireAllRules()).isEqualTo(0); } - @Test - public void testAfterOnLongFieldsBindingFirst() throws Exception { + @ParameterizedTest + @MethodSource("parameters") + public void testAfterOnLongFieldsBindingFirst(RUN_TYPE runType) throws Exception { String str = "import " + StockTick.class.getCanonicalName() + ";\n" + "declare StockTick @timestamp(timeFieldAsLong) end\n" + @@ -995,7 +1020,7 @@ public void testAfterOnLongFieldsBindingFirst() throws Exception { " System.out.println(\"fired\");\n" + "end\n"; - KieSession ksession = getKieSession(getCepKieModuleModel(), str); + KieSession ksession = getKieSession(runType, getCepKieModuleModel(), str); SessionPseudoClock clock = ksession.getSessionClock(); ksession.insert(new StockTick("ACME").setTimeField(0)); @@ -1008,8 +1033,9 @@ public void testAfterOnLongFieldsBindingFirst() throws Exception { assertThat(ksession.fireAllRules()).isEqualTo(0); } - @Test - public void testBefore() throws Exception { + @ParameterizedTest + @MethodSource("parameters") + public void testBefore(RUN_TYPE runType) throws Exception { String str = "import " + StockTick.class.getCanonicalName() + ";" + "rule R when\n" + @@ -1019,7 +1045,7 @@ public void testBefore() throws Exception { " System.out.println(\"fired\");\n" + "end\n"; - KieSession ksession = getKieSession(getCepKieModuleModel(), str); + KieSession ksession = getKieSession(runType, getCepKieModuleModel(), str); SessionPseudoClock clock = ksession.getSessionClock(); ksession.insert( new StockTick( "ACME" ) ); @@ -1034,8 +1060,9 @@ public void testBefore() throws Exception { assertThat(ksession.fireAllRules()).isEqualTo(0); } - @Test - public void testBeforeBindingFirst() throws Exception { + @ParameterizedTest + @MethodSource("parameters") + public void testBeforeBindingFirst(RUN_TYPE runType) throws Exception { String str = "import " + StockTick.class.getCanonicalName() + ";" + "rule R when\n" + @@ -1045,7 +1072,7 @@ public void testBeforeBindingFirst() throws Exception { " System.out.println(\"fired\");\n" + "end\n"; - KieSession ksession = getKieSession(getCepKieModuleModel(), str); + KieSession ksession = getKieSession(runType, getCepKieModuleModel(), str); SessionPseudoClock clock = ksession.getSessionClock(); ksession.insert( new StockTick( "DROO" ) ); @@ -1060,8 +1087,9 @@ public void testBeforeBindingFirst() throws Exception { assertThat(ksession.fireAllRules()).isEqualTo(0); } - @Test - public void testBeforeOnLongFields() throws Exception { + @ParameterizedTest + @MethodSource("parameters") + public void testBeforeOnLongFields(RUN_TYPE runType) throws Exception { String str = "import " + StockTick.class.getCanonicalName() + ";\n" + "declare StockTick @timestamp(timeFieldAsLong) end\n" + @@ -1072,7 +1100,7 @@ public void testBeforeOnLongFields() throws Exception { " System.out.println(\"fired\");\n" + "end\n"; - KieSession ksession = getKieSession(getCepKieModuleModel(), str); + KieSession ksession = getKieSession(runType, getCepKieModuleModel(), str); SessionPseudoClock clock = ksession.getSessionClock(); ksession.insert(new StockTick("ACME").setTimeField(0)); @@ -1085,8 +1113,9 @@ public void testBeforeOnLongFields() throws Exception { assertThat(ksession.fireAllRules()).isEqualTo(0); } - @Test - public void testBeforeOnLongFieldsBindingFirst() throws Exception { + @ParameterizedTest + @MethodSource("parameters") + public void testBeforeOnLongFieldsBindingFirst(RUN_TYPE runType) throws Exception { String str = "import " + StockTick.class.getCanonicalName() + ";\n" + "declare StockTick @timestamp(timeFieldAsLong) end\n" + @@ -1097,7 +1126,7 @@ public void testBeforeOnLongFieldsBindingFirst() throws Exception { " System.out.println(\"fired\");\n" + "end\n"; - KieSession ksession = getKieSession(getCepKieModuleModel(), str); + KieSession ksession = getKieSession(runType, getCepKieModuleModel(), str); SessionPseudoClock clock = ksession.getSessionClock(); ksession.insert(new StockTick("DROO").setTimeField(0)); @@ -1110,8 +1139,9 @@ public void testBeforeOnLongFieldsBindingFirst() throws Exception { assertThat(ksession.fireAllRules()).isEqualTo(0); } - @Test - public void testBeforeOnLongFieldsWithDifferentMethod() throws Exception { + @ParameterizedTest + @MethodSource("parameters") + public void testBeforeOnLongFieldsWithDifferentMethod(RUN_TYPE runType) throws Exception { String str = "import " + StockTick.class.getCanonicalName() + ";\n" + "import " + StockTickEx.class.getCanonicalName() + ";\n" + @@ -1124,7 +1154,7 @@ public void testBeforeOnLongFieldsWithDifferentMethod() throws Exception { " System.out.println(\"fired\");\n" + "end\n"; - KieSession ksession = getKieSession(getCepKieModuleModel(), str); + KieSession ksession = getKieSession(runType, getCepKieModuleModel(), str); SessionPseudoClock clock = ksession.getSessionClock(); ksession.insert(new StockTick("ACME").setTimeField(0)); @@ -1137,8 +1167,9 @@ public void testBeforeOnLongFieldsWithDifferentMethod() throws Exception { assertThat(ksession.fireAllRules()).isEqualTo(0); } - @Test - public void testAfterOnLongFieldsBindingFirstWithDifferentMethod() throws Exception { + @ParameterizedTest + @MethodSource("parameters") + public void testAfterOnLongFieldsBindingFirstWithDifferentMethod(RUN_TYPE runType) throws Exception { String str = "import " + StockTick.class.getCanonicalName() + ";\n" + "import " + StockTickEx.class.getCanonicalName() + ";\n" + @@ -1151,7 +1182,7 @@ public void testAfterOnLongFieldsBindingFirstWithDifferentMethod() throws Except " System.out.println(\"fired\");\n" + "end\n"; - KieSession ksession = getKieSession(getCepKieModuleModel(), str); + KieSession ksession = getKieSession(runType, getCepKieModuleModel(), str); SessionPseudoClock clock = ksession.getSessionClock(); ksession.insert(new StockTick("ACME").setTimeField(0)); @@ -1164,8 +1195,9 @@ public void testAfterOnLongFieldsBindingFirstWithDifferentMethod() throws Except assertThat(ksession.fireAllRules()).isEqualTo(0); } - @Test - public void testLiteral() throws Exception { + @ParameterizedTest + @MethodSource("parameters") + public void testLiteral(RUN_TYPE runType) throws Exception { String str = "import " + StockTick.class.getCanonicalName() + ";" + "declare StockTick @timestamp(timeFieldAsLong) end\n" + @@ -1175,7 +1207,7 @@ public void testLiteral() throws Exception { " System.out.println(\"fired\");\n" + "end\n"; - KieSession ksession = getKieSession(getCepKieModuleModel(), str); + KieSession ksession = getKieSession(runType, getCepKieModuleModel(), str); long time = LocalDateTime.of(2020, 1, 1, 0, 0, 0).atZone(ZoneId.of("UTC")).toInstant().getEpochSecond() * 1000; ksession.insert(new StockTick("DROO").setTimeField(time)); @@ -1183,8 +1215,9 @@ public void testLiteral() throws Exception { assertThat(ksession.fireAllRules()).isEqualTo(1); } - @Test - public void testZonedDateTime() throws Exception { + @ParameterizedTest + @MethodSource("parameters") + public void testZonedDateTime(RUN_TYPE runType) throws Exception { String str = "import " + DateTimeHolder.class.getCanonicalName() + ";" + "rule R when\n" + @@ -1193,7 +1226,7 @@ public void testZonedDateTime() throws Exception { "then\n" + "end\n"; - KieSession ksession = getKieSession(getCepKieModuleModel(), str); + KieSession ksession = getKieSession(runType, getCepKieModuleModel(), str); SessionPseudoClock clock = ksession.getSessionClock(); ksession.insert( new DateTimeHolder( ZonedDateTime.now() ) ); @@ -1202,8 +1235,9 @@ public void testZonedDateTime() throws Exception { assertThat(ksession.fireAllRules()).isEqualTo(1); } - @Test - public void testCalendarsWithCronAndStartAndEnd() throws Exception { + @ParameterizedTest + @MethodSource("parameters") + public void testCalendarsWithCronAndStartAndEnd(RUN_TYPE runType) throws Exception { final Locale defaultLoc = Locale.getDefault(); try { Locale.setDefault(Locale.UK); // Because of the date strings in the DRL, fixable with JBRULES-3444 @@ -1220,7 +1254,7 @@ public void testCalendarsWithCronAndStartAndEnd() throws Exception { " list.add(\"fired\"); \n" + "end \n"; - KieSession ksession = getKieSession(getCepKieModuleModel(), str); + KieSession ksession = getKieSession(runType, getCepKieModuleModel(), str); try { final List list = new ArrayList(); final PseudoClockScheduler timeService = ksession.getSessionClock(); @@ -1263,8 +1297,9 @@ public void testCalendarsWithCronAndStartAndEnd() throws Exception { } } - @Test - public void testNegate() throws Exception { + @ParameterizedTest + @MethodSource("parameters") + public void testNegate(RUN_TYPE runType) throws Exception { String str = "import " + StockTick.class.getCanonicalName() + ";" + "rule R when\n" + @@ -1274,7 +1309,7 @@ public void testNegate() throws Exception { " System.out.println(\"fired\");\n" + "end\n"; - KieSession ksession = getKieSession(getCepKieModuleModel(), str); + KieSession ksession = getKieSession(runType, getCepKieModuleModel(), str); SessionPseudoClock clock = ksession.getSessionClock(); ksession.insert( new StockTick( "DROO" ) ); @@ -1289,8 +1324,9 @@ public void testNegate() throws Exception { assertThat(ksession.fireAllRules()).isEqualTo(1); } - @Test - public void testNegateFromCollect() throws Exception { + @ParameterizedTest + @MethodSource("parameters") + public void testNegateFromCollect(RUN_TYPE runType) throws Exception { String str = "import " + StockTick.class.getCanonicalName() + ";" + "import " + List.class.getCanonicalName() + ";" + @@ -1301,7 +1337,7 @@ public void testNegateFromCollect() throws Exception { " System.out.println(\"fired\");\n" + "end\n"; - KieSession ksession = getKieSession(getCepKieModuleModel(), str); + KieSession ksession = getKieSession(runType, getCepKieModuleModel(), str); SessionPseudoClock clock = ksession.getSessionClock(); ksession.insert( new StockTick( "DROO" ) ); @@ -1316,8 +1352,9 @@ public void testNegateFromCollect() throws Exception { assertThat(ksession.fireAllRules()).isEqualTo(1); } - @Test - public void testNegateFromCollectWithDeclaredTimestamp() throws Exception { + @ParameterizedTest + @MethodSource("parameters") + public void testNegateFromCollectWithDeclaredTimestamp(RUN_TYPE runType) throws Exception { String str = "import " + TransactionHistory.class.getCanonicalName() + ";" + "import " + List.class.getCanonicalName() + ";" + @@ -1332,7 +1369,7 @@ public void testNegateFromCollectWithDeclaredTimestamp() throws Exception { " System.out.println(\"fired\");\n" + "end\n"; - KieSession ksession = getKieSession(getCepKieModuleModel(), str); + KieSession ksession = getKieSession(runType, getCepKieModuleModel(), str); SessionPseudoClock clock = ksession.getSessionClock(); ksession.insert(new TransactionHistory(10, toEpochMilliYMD(2022, 5, 12))); diff --git a/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/ChannelTest.java b/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/ChannelTest.java index a14a545717d..d9dd067d4a2 100644 --- a/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/ChannelTest.java +++ b/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/ChannelTest.java @@ -22,7 +22,8 @@ import java.util.List; import org.drools.model.codegen.execmodel.domain.Person; -import org.junit.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; import org.kie.api.runtime.Channel; import org.kie.api.runtime.KieSession; @@ -31,11 +32,7 @@ public class ChannelTest extends BaseModelTest { - public ChannelTest(RUN_TYPE testRunType) { - super(testRunType); - } - - public void testChannel(boolean isMvel) { + public void testChannel(RUN_TYPE runType, boolean isMvel) { String str = "import " + Person.class.getCanonicalName() + ";" + "rule R \n" + @@ -46,7 +43,7 @@ public void testChannel(boolean isMvel) { " channels[\"testChannel\"].send(\"Test Message\");\n" + "end\n"; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); TestChannel testChannel = new TestChannel(); ksession.registerChannel("testChannel", testChannel); @@ -58,14 +55,16 @@ public void testChannel(boolean isMvel) { assertThat(testChannel.getChannelMessages()).contains("Test Message"); } - @Test - public void testChannelWithJava() { - testChannel(false); + @ParameterizedTest + @MethodSource("parameters") + public void testChannelWithJava(RUN_TYPE runType) { + testChannel(runType, false); } - @Test - public void testChannelWithMvel() { - testChannel(true); + @ParameterizedTest + @MethodSource("parameters") + public void testChannelWithMvel(RUN_TYPE runType) { + testChannel(runType, true); } public static class TestChannel implements Channel { diff --git a/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/CompilationFailuresTest.java b/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/CompilationFailuresTest.java index 398ff751800..8dce6906c13 100644 --- a/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/CompilationFailuresTest.java +++ b/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/CompilationFailuresTest.java @@ -22,7 +22,8 @@ import org.drools.model.codegen.execmodel.domain.Person; import org.drools.model.codegen.execmodel.domain.Result; -import org.junit.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; import org.kie.api.builder.Message; import org.kie.api.builder.Results; @@ -30,12 +31,10 @@ public class CompilationFailuresTest extends BaseModelTest { - public CompilationFailuresTest( RUN_TYPE testRunType ) { - super( testRunType ); - } - @Test - public void testNonQuotedStringComapre() { + @ParameterizedTest + @MethodSource("parameters") + public void testNonQuotedStringComapre(RUN_TYPE runType) { String drl = "declare Fact\n" + " field : String\n" + @@ -45,15 +44,16 @@ public void testNonQuotedStringComapre() { "then\n" + "end\n"; - Results results = getCompilationResults(drl); + Results results = getCompilationResults(runType, drl); assertThat(results.getMessages(Message.Level.ERROR).isEmpty()).isFalse(); // line = -1 even with STANDARD_FROM_DRL (PredicateDescr) assertThat(results.getMessages().get(0).getLine()).isEqualTo(-1); } - @Test - public void testUseNotExistingEnum() { + @ParameterizedTest + @MethodSource("parameters") + public void testUseNotExistingEnum(RUN_TYPE runType) { String drl = "import " + NumberRestriction.class.getCanonicalName() + "\n" + "rule R when\n" + @@ -61,14 +61,14 @@ public void testUseNotExistingEnum() { "then\n" + "end\n"; - Results results = getCompilationResults(drl); + Results results = getCompilationResults(runType, drl); assertThat(results.getMessages(Message.Level.ERROR).isEmpty()).isFalse(); assertThat(results.getMessages().get(0).getLine()).isEqualTo(3); } - private Results getCompilationResults( String drl ) { - return createKieBuilder( drl ).getResults(); + private Results getCompilationResults(RUN_TYPE runType, String drl ) { + return createKieBuilder(runType, drl).getResults(); } public static class NumberRestriction { @@ -96,27 +96,31 @@ public String getValueType() { } } - @Test - public void testMaxIntegerResultOnDoublePatternShouldntCompile() { - checkCompilationFailureOnMismatchingAccumulate("Integer", "max"); + @ParameterizedTest + @MethodSource("parameters") + public void testMaxIntegerResultOnDoublePatternShouldntCompile(RUN_TYPE runType) { + checkCompilationFailureOnMismatchingAccumulate(runType, "Integer", "max"); } - @Test - public void testMinIntegerResultOnDoublePatternShouldntCompile() { - checkCompilationFailureOnMismatchingAccumulate("Integer", "min"); + @ParameterizedTest + @MethodSource("parameters") + public void testMinIntegerResultOnDoublePatternShouldntCompile(RUN_TYPE runType) { + checkCompilationFailureOnMismatchingAccumulate(runType, "Integer", "min"); } - @Test - public void testMaxLongResultOnDoublePatternShouldntCompile() { - checkCompilationFailureOnMismatchingAccumulate("Long", "max"); + @ParameterizedTest + @MethodSource("parameters") + public void testMaxLongResultOnDoublePatternShouldntCompile(RUN_TYPE runType) { + checkCompilationFailureOnMismatchingAccumulate(runType, "Long", "max"); } - @Test - public void testMinLongResultOnDoublePatternShouldntCompile() { - checkCompilationFailureOnMismatchingAccumulate("Long", "min"); + @ParameterizedTest + @MethodSource("parameters") + public void testMinLongResultOnDoublePatternShouldntCompile(RUN_TYPE runType) { + checkCompilationFailureOnMismatchingAccumulate(runType, "Long", "min"); } - private void checkCompilationFailureOnMismatchingAccumulate(String type, String accFunc) { + private void checkCompilationFailureOnMismatchingAccumulate(RUN_TYPE runType, String type, String accFunc) { String drl = "import " + Person.class.getCanonicalName() + ";" + "import " + Result.class.getCanonicalName() + ";" + @@ -128,7 +132,7 @@ private void checkCompilationFailureOnMismatchingAccumulate(String type, String " System.out.println($max);\n" + "end"; - Results results = getCompilationResults(drl); + Results results = getCompilationResults(runType, drl); assertThat(results.getMessages(Message.Level.ERROR).isEmpty()).isFalse(); // line = 1 with STANDARD_FROM_DRL (RuleDescr) @@ -136,8 +140,9 @@ private void checkCompilationFailureOnMismatchingAccumulate(String type, String } - @Test - public void modify_factInScope_java() { + @ParameterizedTest + @MethodSource("parameters") + public void modify_factInScope_java(RUN_TYPE runType) { // DROOLS-5242, DROOLS-7195 String drl = "import " + Person.class.getCanonicalName() + ";" + @@ -148,12 +153,13 @@ public void modify_factInScope_java() { " modify($p) { $p.setName(\"Mark\") }\n" + "end"; - Results results = getCompilationResults(drl); + Results results = getCompilationResults(runType, drl); assertThat(results.getMessages(Message.Level.ERROR).isEmpty()).isFalse(); } - @Test - public void modify_factInScope_mvel() { + @ParameterizedTest + @MethodSource("parameters") + public void modify_factInScope_mvel(RUN_TYPE runType) { // DROOLS-5242, DROOLS-7195 String drl = "import " + Person.class.getCanonicalName() + ";" + @@ -165,12 +171,13 @@ public void modify_factInScope_mvel() { " modify($p) { $p.setName(\"Mark\") }\n" + "end"; - Results results = getCompilationResults(drl); + Results results = getCompilationResults(runType, drl); assertThat(results.getMessages(Message.Level.ERROR).isEmpty()).isFalse(); } - @Test - public void modify_factInScope_nestedPropertySetter_java() { + @ParameterizedTest + @MethodSource("parameters") + public void modify_factInScope_nestedPropertySetter_java(RUN_TYPE runType) { // DROOLS-5242, DROOLS-7195 String drl = "import " + Person.class.getCanonicalName() + ";" + @@ -181,12 +188,13 @@ public void modify_factInScope_nestedPropertySetter_java() { " modify($p) { $p.address.setCity(\"London\") }\n" + "end"; - Results results = getCompilationResults(drl); + Results results = getCompilationResults(runType, drl); assertThat(results.getMessages(Message.Level.ERROR).isEmpty()).isFalse(); } - @Test - public void modify_factInScope_nestedPropertySetter_mvel() { + @ParameterizedTest + @MethodSource("parameters") + public void modify_factInScope_nestedPropertySetter_mvel(RUN_TYPE runType) { // DROOLS-5242, DROOLS-7195 String drl = "import " + Person.class.getCanonicalName() + ";" + @@ -198,12 +206,13 @@ public void modify_factInScope_nestedPropertySetter_mvel() { " modify($p) { $p.address.setCity(\"London\") }\n" + "end"; - Results results = getCompilationResults(drl); + Results results = getCompilationResults(runType, drl); assertThat(results.getMessages(Message.Level.ERROR).isEmpty()).isFalse(); } - @Test - public void modify_factInScope_nestedPropertyAssign_java() { + @ParameterizedTest + @MethodSource("parameters") + public void modify_factInScope_nestedPropertyAssign_java(RUN_TYPE runType) { // DROOLS-5242, DROOLS-7195 String drl = "import " + Person.class.getCanonicalName() + ";" + @@ -214,12 +223,13 @@ public void modify_factInScope_nestedPropertyAssign_java() { " modify($p) { $p.address.city = \"London\" }\n" + "end"; - Results results = getCompilationResults(drl); + Results results = getCompilationResults(runType, drl); assertThat(results.getMessages(Message.Level.ERROR).isEmpty()).isFalse(); } - @Test - public void modify_factInScope_nestedPropertyAssign_mvel() { + @ParameterizedTest + @MethodSource("parameters") + public void modify_factInScope_nestedPropertyAssign_mvel(RUN_TYPE runType) { // DROOLS-5242, DROOLS-7195 String drl = "import " + Person.class.getCanonicalName() + ";" + @@ -231,12 +241,13 @@ public void modify_factInScope_nestedPropertyAssign_mvel() { " modify($p) { $p.address.city = \"London\" }\n" + "end"; - Results results = getCompilationResults(drl); + Results results = getCompilationResults(runType, drl); assertThat(results.getMessages(Message.Level.ERROR).isEmpty()).isFalse(); } - @Test - public void testVariableInsideBinding() { + @ParameterizedTest + @MethodSource("parameters") + public void testVariableInsideBinding(RUN_TYPE runType) { String str = "import " + Person.class.getCanonicalName() + ";" + "import " + NameLengthCount.class.getCanonicalName() + ";" + @@ -246,13 +257,14 @@ public void testVariableInsideBinding() { "then\n" + "end"; - Results results = createKieBuilder(str ).getResults(); + Results results = createKieBuilder(runType, str).getResults(); assertThat(results.getMessages(Message.Level.ERROR).stream().map(Message::getText)) .contains("Variables can not be used inside bindings. Variable [$nlc] is being used in binding '$nlc.self.getNameLength(name)'"); } - @Test - public void testVariableInsideBindingInParameter() { + @ParameterizedTest + @MethodSource("parameters") + public void testVariableInsideBindingInParameter(RUN_TYPE runType) { String str = "import " + Person.class.getCanonicalName() + ";" + "import " + NameLengthCount.class.getCanonicalName() + ";" + @@ -262,7 +274,7 @@ public void testVariableInsideBindingInParameter() { "then\n" + "end"; - Results results = createKieBuilder(str ).getResults(); + Results results = createKieBuilder(runType, str ).getResults(); assertThat(results.getMessages(Message.Level.ERROR).stream().map(Message::getText)) .contains("Variables can not be used inside bindings. Variable [$nlc] is being used in binding 'identityBigDecimal($nlc.fortyTwo)'"); } @@ -282,8 +294,9 @@ public BigDecimal getFortyTwo() { } } - @Test - public void testTypeSafe() { + @ParameterizedTest + @MethodSource("parameters") + public void testTypeSafe(RUN_TYPE runType) { String str = "import " + Parent.class.getCanonicalName() + ";" + "declare\n" + @@ -295,8 +308,8 @@ public void testTypeSafe() { "then\n" + "end\n"; - Results results = createKieBuilder(str).getResults(); - if (testRunType.isExecutableModel()) { + Results results = createKieBuilder(runType, str).getResults(); + if (runType.isExecutableModel()) { assertThat(results.getMessages(Message.Level.ERROR).get(0).getText().contains("@typesafe(false) is not supported in executable model")); } else { assertThat(results.getMessages(Message.Level.ERROR).isEmpty()).isTrue(); diff --git a/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/CompilerTest.java b/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/CompilerTest.java index 8badee9adeb..abe40ca412c 100644 --- a/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/CompilerTest.java +++ b/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/CompilerTest.java @@ -43,10 +43,10 @@ import org.drools.model.codegen.execmodel.domain.StockTick; import org.drools.model.codegen.execmodel.domain.Toy; import org.drools.model.codegen.execmodel.domain.Woman; -import org.junit.Ignore; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.ExpectedException; +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.Timeout; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; import org.kie.api.definition.type.FactType; import org.kie.api.runtime.KieSession; import org.kie.api.runtime.process.ProcessContext; @@ -57,12 +57,10 @@ public class CompilerTest extends BaseModelTest { - public CompilerTest( RUN_TYPE testRunType ) { - super( testRunType ); - } - - @Test(timeout = 5000) - public void testPropertyReactivity() { + @ParameterizedTest + @MethodSource("parameters") + @Timeout(5000) + public void testPropertyReactivity(RUN_TYPE runType) { String str = "import " + Person.class.getCanonicalName() + ";" + "rule R when\n" + @@ -71,7 +69,7 @@ public void testPropertyReactivity() { " modify($p) { setAge($p.getAge()+1) }\n" + "end"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); Person me = new Person( "Mario", 40 ); ksession.insert( me ); @@ -80,8 +78,9 @@ public void testPropertyReactivity() { assertThat(me.getAge()).isEqualTo(41); } - @Test - public void testPropertyReactivityWithArguments() { + @ParameterizedTest + @MethodSource("parameters") + public void testPropertyReactivityWithArguments(RUN_TYPE runType) { String str = "import " + Person.class.getCanonicalName() + ";" + "rule R \n" + @@ -91,7 +90,7 @@ public void testPropertyReactivityWithArguments() { " modify($p) { setLikes( String.valueOf(($p.getAddress().getStreet() + $p.getAddress().getCity()))) };\n" + "end"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); Person me = new Person( "Mario", 40 ); me.setAddress(new Address("street1", 2, "city1")); @@ -101,8 +100,9 @@ public void testPropertyReactivityWithArguments() { assertThat(me.getLikes()).isEqualTo("street1city1"); } - @Test - public void testPropertyReactvityOnFinalField() throws Exception { + @ParameterizedTest + @MethodSource("parameters") + public void testPropertyReactvityOnFinalField(RUN_TYPE runType) throws Exception { String str = "rule R when\n" + " $a : String( length > 3 )\n" + @@ -110,7 +110,7 @@ public void testPropertyReactvityOnFinalField() throws Exception { " System.out.println($a);\n" + "end\n"; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); ksession.insert( "abcd" ); ksession.insert( "xy" ); @@ -118,8 +118,9 @@ public void testPropertyReactvityOnFinalField() throws Exception { assertThat(ksession.fireAllRules()).isEqualTo(1); } - @Test - public void testEqualityCheckOnNull() { + @ParameterizedTest + @MethodSource("parameters") + public void testEqualityCheckOnNull(RUN_TYPE runType) { String str = "import " + Person.class.getCanonicalName() + ";" + "import " + Result.class.getCanonicalName() + ";" + @@ -129,7 +130,7 @@ public void testEqualityCheckOnNull() { " insert(new Result($name));\n" + "end"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); final Person mario = new Person("Mario", 40); final Person luca = new Person(null, 33); @@ -144,8 +145,9 @@ public void testEqualityCheckOnNull() { assertThat(results.iterator().next().getValue()).isEqualTo("Mario"); } - @Test - public void testOrWithFixedLeftOperand() { + @ParameterizedTest + @MethodSource("parameters") + public void testOrWithFixedLeftOperand(RUN_TYPE runType) { String str = "import " + Person.class.getCanonicalName() + ";" + "import " + Result.class.getCanonicalName() + ";" + @@ -155,7 +157,7 @@ public void testOrWithFixedLeftOperand() { " insert(new Result($p));\n" + "end"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); final Person mario = new Person("Mario", 40); final Person luca = new Person("Luca", 33); @@ -174,8 +176,9 @@ public void testOrWithFixedLeftOperand() { assertThat(results.stream().map(r -> r.getValue())).containsExactlyInAnyOrder(mario, luca, edoardo); } - @Test - public void testCapitalLetterProperty() { + @ParameterizedTest + @MethodSource("parameters") + public void testCapitalLetterProperty(RUN_TYPE runType) { String str = "import " + Person.class.getCanonicalName() + ";" + "import " + Result.class.getCanonicalName() + ";" + @@ -185,7 +188,7 @@ public void testCapitalLetterProperty() { " insert(new Result($p));\n" + "end"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); final Person luca = new Person("Luca", 35); final Person leonardo = new Person("Leonardo", 2).setParentP(luca); @@ -202,8 +205,9 @@ public void testCapitalLetterProperty() { assertThat(results.stream().map(Result::getValue)).containsExactlyInAnyOrder(leonardo); } - @Test - public void testBeta() { + @ParameterizedTest + @MethodSource("parameters") + public void testBeta(RUN_TYPE runType) { String str = "import " + Result.class.getCanonicalName() + ";" + "import " + Person.class.getCanonicalName() + ";" + @@ -215,7 +219,7 @@ public void testBeta() { " $r.setValue($olderV.getName() + \" is older than \" + $markV.getName());\n" + "end"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); Result result = new Result(); ksession.insert( result ); @@ -244,8 +248,9 @@ public void testBeta() { } - @Test - public void testBetaMap() { + @ParameterizedTest + @MethodSource("parameters") + public void testBetaMap(RUN_TYPE runType) { String str = "import " + Result.class.getCanonicalName() + ";" + @@ -258,7 +263,7 @@ public void testBetaMap() { " $r.setValue($olderV.get(\"name\") + \" is older than \" + $markV.get(\"name\"));\n" + "end"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); Result result = new Result(); ksession.insert( result ); @@ -287,8 +292,9 @@ public void testBetaMap() { assertThat(result.getValue()).isEqualTo("Edson is older than Mark"); } - @Test - public void testBetaMapComparisonWithLiteral() { + @ParameterizedTest + @MethodSource("parameters") + public void testBetaMapComparisonWithLiteral(RUN_TYPE runType) { String str = "import " + Result.class.getCanonicalName() + ";" + "import " + Map.class.getCanonicalName() + ";" + @@ -299,7 +305,7 @@ public void testBetaMapComparisonWithLiteral() { " $r.setValue($olderV.get(\"name\") + \" is older than Mark\"\n);" + "end"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); Result result = new Result(); ksession.insert( result ); @@ -328,8 +334,9 @@ private Map mapPerson(String name, int age) { return person; } - @Test - public void testRuleExtends() { + @ParameterizedTest + @MethodSource("parameters") + public void testRuleExtends(RUN_TYPE runType) { String str = "import " + Result.class.getCanonicalName() + ";" + "import " + Person.class.getCanonicalName() + ";" + @@ -347,7 +354,7 @@ public void testRuleExtends() { " $r.setValue($p2.getName() + \" is older than \" + $p1.getName());\n" + "end"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); Result result = new Result(); ksession.insert( result ); @@ -363,8 +370,9 @@ public void testRuleExtends() { assertThat(result.getValue()).isEqualTo("Mario is older than Mark"); } - @Test - public void testBetaWithDeclaration() { + @ParameterizedTest + @MethodSource("parameters") + public void testBetaWithDeclaration(RUN_TYPE runType) { String str = "import " + Result.class.getCanonicalName() + ";" + "import " + Person.class.getCanonicalName() + ";" + @@ -376,7 +384,7 @@ public void testBetaWithDeclaration() { " $r.setValue($p2.getName() + \" is older than \" + $p1.getName());\n" + "end"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); Result result = new Result(); ksession.insert( result ); @@ -404,8 +412,9 @@ public void testBetaWithDeclaration() { assertThat(result.getValue()).isEqualTo("Edson is older than Mark"); } - @Test - public void test3Patterns() { + @ParameterizedTest + @MethodSource("parameters") + public void test3Patterns(RUN_TYPE runType) { String str = "import " + Person.class.getCanonicalName() + ";" + "rule R when\n" + @@ -416,7 +425,7 @@ public void test3Patterns() { " System.out.println(\"Found: \" + $s);\n" + "end"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); ksession.insert( "Mario" ); ksession.insert( new Person( "Mark", 37 ) ); @@ -425,8 +434,9 @@ public void test3Patterns() { ksession.fireAllRules(); } - @Test - public void testSimpleInsert() { + @ParameterizedTest + @MethodSource("parameters") + public void testSimpleInsert(RUN_TYPE runType) { String str = "import " + Result.class.getCanonicalName() + ";" + "import " + Person.class.getCanonicalName() + ";" + @@ -437,7 +447,7 @@ public void testSimpleInsert() { " insert(r);\n" + "end"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); ksession.insert( new Person( "Mark", 37 ) ); ksession.insert( new Person( "Mario", 40 ) ); @@ -448,8 +458,9 @@ public void testSimpleInsert() { assertThat(results.iterator().next().getValue()).isEqualTo("Mark"); } - @Test - public void testSimpleInsertWithProperties() { + @ParameterizedTest + @MethodSource("parameters") + public void testSimpleInsertWithProperties(RUN_TYPE runType) { String str = "import " + Result.class.getCanonicalName() + ";" + "import " + Person.class.getCanonicalName() + ";" + @@ -460,7 +471,7 @@ public void testSimpleInsertWithProperties() { " insert(r);\n" + "end"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); ksession.insert( new Person( "Mark", 37, new Address("London")) ); ksession.insert( new Person( "Luca", 32 , new Address("Milan")) ); @@ -471,8 +482,9 @@ public void testSimpleInsertWithProperties() { assertThat(results.iterator().next().getValue()).isEqualTo("Luca"); } - @Test - public void testSimpleDelete() { + @ParameterizedTest + @MethodSource("parameters") + public void testSimpleDelete(RUN_TYPE runType) { String str = "import " + Result.class.getCanonicalName() + ";" + "import " + Person.class.getCanonicalName() + ";" + @@ -484,7 +496,7 @@ public void testSimpleDelete() { " delete($p);\n" + "end"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); ksession.insert( new Person( "Mark", 37 ) ); ksession.insert( new Person( "Mario", 40 ) ); @@ -496,8 +508,9 @@ public void testSimpleDelete() { assertThat(getObjectsIntoList(ksession, Person.class).size()).isEqualTo(1); } - @Test - public void testSimpleInsertDeleteExplicitScope() { + @ParameterizedTest + @MethodSource("parameters") + public void testSimpleInsertDeleteExplicitScope(RUN_TYPE runType) { String str = "import " + Result.class.getCanonicalName() + ";" + "import " + Person.class.getCanonicalName() + ";" + @@ -509,7 +522,7 @@ public void testSimpleInsertDeleteExplicitScope() { " drools.delete($p);\n" + "end"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); ksession.insert( new Person( "Mark", 37 ) ); ksession.insert( new Person( "Mario", 40 ) ); @@ -521,8 +534,9 @@ public void testSimpleInsertDeleteExplicitScope() { assertThat(getObjectsIntoList(ksession, Person.class).size()).isEqualTo(1); } - @Test - public void testSimpleUpdate() { + @ParameterizedTest + @MethodSource("parameters") + public void testSimpleUpdate(RUN_TYPE runType) { String str = "import " + Person.class.getCanonicalName() + ";" + "rule R when\n" + @@ -532,7 +546,7 @@ public void testSimpleUpdate() { " update($p);\n" + "end"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); Person mark = new Person( "Mark", 37 ); Person mario = new Person( "Mario", 40 ); @@ -545,8 +559,9 @@ public void testSimpleUpdate() { assertThat(mario.getAge()).isEqualTo(40); } - @Test - public void testSimpleModify() { + @ParameterizedTest + @MethodSource("parameters") + public void testSimpleModify(RUN_TYPE runType) { String str = "import " + Person.class.getCanonicalName() + ";" + "rule R when\n" + @@ -555,7 +570,7 @@ public void testSimpleModify() { " modify($p) { setAge($p.getAge()+1) }\n" + "end"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); Person mark = new Person( "Mark", 37 ); Person mario = new Person( "Mario", 40 ); @@ -568,8 +583,9 @@ public void testSimpleModify() { assertThat(mario.getAge()).isEqualTo(40); } - @Test - public void testEmptyPattern() { + @ParameterizedTest + @MethodSource("parameters") + public void testEmptyPattern(RUN_TYPE runType) { String str = "import " + Person.class.getCanonicalName() + ";" + "import " + Result.class.getCanonicalName() + ";" + @@ -579,7 +595,7 @@ public void testEmptyPattern() { " insert(new Result(\"ok\"));\n" + "end"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); Person mario = new Person( "Mario", 40 ); @@ -591,8 +607,9 @@ public void testEmptyPattern() { assertThat(results.iterator().next().getValue()).isEqualTo("ok"); } - @Test - public void testEmptyPatternWithBinding() { + @ParameterizedTest + @MethodSource("parameters") + public void testEmptyPatternWithBinding(RUN_TYPE runType) { String str = "import " + Person.class.getCanonicalName() + ";" + "import " + Result.class.getCanonicalName() + ";" + @@ -602,7 +619,7 @@ public void testEmptyPatternWithBinding() { " insert(new Result($p.getName()));\n" + "end"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); Person mario = new Person( "Mario", 40 ); @@ -614,8 +631,9 @@ public void testEmptyPatternWithBinding() { assertThat(results.iterator().next().getValue()).isEqualTo("Mario"); } - @Test - public void testFrom() { + @ParameterizedTest + @MethodSource("parameters") + public void testFrom(RUN_TYPE runType) { String str = "import " + Result.class.getCanonicalName() + ";\n" + "import " + Adult.class.getCanonicalName() + ";\n" + @@ -628,7 +646,7 @@ public void testFrom() { " $r.setValue($c.getName());\n" + "end"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); Result result = new Result(); ksession.insert( result ); @@ -642,17 +660,19 @@ public void testFrom() { assertThat(result.getValue()).isEqualTo("Alan"); } - @Test - public void testConcatenatedFrom() { - checkConcatenatedFrom(true); + @ParameterizedTest + @MethodSource("parameters") + public void testConcatenatedFrom(RUN_TYPE runType) { + checkConcatenatedFrom(runType, true); } - @Test - public void testConcatenatedFromWithCondition() { - checkConcatenatedFrom(false); + @ParameterizedTest + @MethodSource("parameters") + public void testConcatenatedFromWithCondition(RUN_TYPE runType) { + checkConcatenatedFrom(runType, false); } - private void checkConcatenatedFrom(boolean withCondition) { + private void checkConcatenatedFrom(RUN_TYPE runType, boolean withCondition) { String str = "import " + Result.class.getCanonicalName() + ";\n" + "import " + Man.class.getCanonicalName() + ";\n" + @@ -669,7 +689,7 @@ private void checkConcatenatedFrom(boolean withCondition) { " list.add($t.getName());\n" + "end"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); Result result = new Result(); ksession.insert( result ); @@ -696,8 +716,9 @@ private void checkConcatenatedFrom(boolean withCondition) { assertThat(list).containsExactlyInAnyOrder("car", "ball"); } - @Test - public void testAgeWithSum() { + @ParameterizedTest + @MethodSource("parameters") + public void testAgeWithSum(RUN_TYPE runType) { String str = "import " + Result.class.getCanonicalName() + ";" + "import " + Person.class.getCanonicalName() + ";" + @@ -708,7 +729,7 @@ public void testAgeWithSum() { " insert(new Result($plusTwo.getName()));\n" + "end"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); ksession.insert( new Person( "Mario", 40 ) ); ksession.insert( new Person( "Mark", 37 ) ); @@ -720,8 +741,9 @@ public void testAgeWithSum() { assertThat(results.iterator().next().getValue()).isEqualTo("Mark"); } - @Test - public void testAgeWithSumUsing2DeclarationInBeta() { + @ParameterizedTest + @MethodSource("parameters") + public void testAgeWithSumUsing2DeclarationInBeta(RUN_TYPE runType) { String str = "import " + Result.class.getCanonicalName() + ";" + "import " + Person.class.getCanonicalName() + ";" + @@ -732,7 +754,7 @@ public void testAgeWithSumUsing2DeclarationInBeta() { " insert(new Result($plusTwo.getName()));\n" + "end"; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); ksession.insert(new Person("Mario", 40)); ksession.insert(new Person("Mark", 37)); @@ -745,8 +767,9 @@ public void testAgeWithSumUsing2DeclarationInBeta() { assertThat(results.iterator().next().getValue()).isEqualTo("Mark"); } - @Test - public void testFunction3() { + @ParameterizedTest + @MethodSource("parameters") + public void testFunction3(RUN_TYPE runType) { String str = "import " + Result.class.getCanonicalName() + ";" + "import " + Person.class.getCanonicalName() + ";" + @@ -759,7 +782,7 @@ public void testFunction3() { " insert(new Result($p.getName()));\n" + "end"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); ksession.insert( new Person( "Mario", 40 ) ); ksession.insert( new Person( "Mark", 37 ) ); @@ -771,15 +794,16 @@ public void testFunction3() { assertThat(results.iterator().next().getValue()).isEqualTo("Mario"); } - @Test - public void testInsertLogical() { + @ParameterizedTest + @MethodSource("parameters") + public void testInsertLogical(RUN_TYPE runType) { String str = "rule R when\n" + " Integer()" + "then\n" + " insertLogical(\"Hello World\");\n" + "end"; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); FactHandle fh_47 = ksession.insert(47); ksession.fireAllRules(); @@ -794,8 +818,9 @@ public void testInsertLogical() { assertThat(results.contains("Hello World")).isFalse(); } - @Test - public void testModifyRewriteAvoidTwiceThePreceeding() { + @ParameterizedTest + @MethodSource("parameters") + public void testModifyRewriteAvoidTwiceThePreceeding(RUN_TYPE runType) { String str = "import " + Person.class.getCanonicalName() + ";" + "global java.util.List globalA \n" + "global java.util.List globalB \n" + @@ -808,7 +833,7 @@ public void testModifyRewriteAvoidTwiceThePreceeding() { " globalB.add(\"B\");\n" + "end"; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); List globalA = new ArrayList<>(); List globalB = new ArrayList<>(); @@ -822,8 +847,9 @@ public void testModifyRewriteAvoidTwiceThePreceeding() { assertThat(globalB.size()).isEqualTo(1); } - @Test - public void testEmptyModifyRewrite() { + @ParameterizedTest + @MethodSource("parameters") + public void testEmptyModifyRewrite(RUN_TYPE runType) { String str = "rule R \n" + "no-loop \n" + "when\n" + @@ -833,7 +859,7 @@ public void testEmptyModifyRewrite() { " modify( $s ) { }\n" + "end"; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); ksession.insert("Hello World"); int fired = ksession.fireAllRules(); @@ -841,8 +867,9 @@ public void testEmptyModifyRewrite() { assertThat(fired).isEqualTo(1); } - @Test() - public void testModifyRewriteWithComments() { + @ParameterizedTest + @MethodSource("parameters") + public void testModifyRewriteWithComments(RUN_TYPE runType) { String str = "import " + Person.class.getCanonicalName() + ";" + "global java.util.List globalA \n" + "global java.util.List globalB \n" + @@ -861,7 +888,7 @@ public void testModifyRewriteWithComments() { " /* modify ; something */\n" + "end"; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); List globalA = new ArrayList<>(); List globalB = new ArrayList<>(); @@ -877,9 +904,10 @@ public void testModifyRewriteWithComments() { assertThat(person1.getAge()).isEqualTo(47); } - @Test() - @Ignore("fails for exec model, is not recognizing properly start/ends of modify block") - public void testModifyRewriteWithCommentsAbsurd() { + @ParameterizedTest + @MethodSource("parameters") + @Disabled("fails for exec model, is not recognizing properly start/ends of modify block") + public void testModifyRewriteWithCommentsAbsurd(RUN_TYPE runType) { String str = "import " + Person.class.getCanonicalName() + ";" + "global java.util.List globalA \n" + "global java.util.List globalB \n" + @@ -898,7 +926,7 @@ public void testModifyRewriteWithCommentsAbsurd() { " /* modify( $p ) { setAge(2) } */\n" + "end"; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); List globalA = new ArrayList<>(); List globalB = new ArrayList<>(); @@ -914,8 +942,9 @@ public void testModifyRewriteWithCommentsAbsurd() { assertThat(person1.getAge()).isEqualTo(47); } - @Test - public void testConstraintContainingAMethodCallWithParams() { + @ParameterizedTest + @MethodSource("parameters") + public void testConstraintContainingAMethodCallWithParams(RUN_TYPE runType) { String str = "import " + Overloaded.class.getCanonicalName() + ";" + "rule OverloadedMethods\n" + "when\n" + @@ -924,7 +953,7 @@ public void testConstraintContainingAMethodCallWithParams() { " insert(\"matched\");\n" + "end"; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); ksession.insert(new Overloaded()); ksession.fireAllRules(); @@ -933,8 +962,9 @@ public void testConstraintContainingAMethodCallWithParams() { assertThat(results.size()).isEqualTo(1); } - @Test - public void testSimpleModifyUsingNameRefFollowedByMethodCall() { + @ParameterizedTest + @MethodSource("parameters") + public void testSimpleModifyUsingNameRefFollowedByMethodCall(RUN_TYPE runType) { String str = "import " + Person.class.getCanonicalName() + ";" + "rule R when\n" + @@ -943,7 +973,7 @@ public void testSimpleModifyUsingNameRefFollowedByMethodCall() { " modify($p) { setAge($p.getAge()+1) }\n" + "end"; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); Person mark = new Person("Mark", 37); Person mario = new Person("Mario", 40); @@ -956,8 +986,9 @@ public void testSimpleModifyUsingNameRefFollowedByMethodCall() { assertThat(mario.getAge()).isEqualTo(40); } - @Test - public void testChainOfMethodCallInConstraint() { + @ParameterizedTest + @MethodSource("parameters") + public void testChainOfMethodCallInConstraint(RUN_TYPE runType) { String str = "import " + Person.class.getCanonicalName() + ";" + "rule R when\n" + " $p : Person( getAddress().getCity().length() == 5 )\n" + @@ -965,7 +996,7 @@ public void testChainOfMethodCallInConstraint() { " insert(\"matched\");\n" + "end"; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); Person john = new Person("John", 47); Address a = new Address("Italy"); @@ -978,8 +1009,9 @@ public void testChainOfMethodCallInConstraint() { assertThat(results.size()).isEqualTo(1); } - @Test - public void testChainOfMethodCallInConstraintSub() { + @ParameterizedTest + @MethodSource("parameters") + public void testChainOfMethodCallInConstraintSub(RUN_TYPE runType) { String str = "import " + Person.class.getCanonicalName() + ";" + "rule R when\n" + " $p : Person( address.(city.startsWith(\"I\") && city.length() == 5 ) )\n" + // DRL feature "Grouped accessors for nested objects" is addressed by the RuleDescr directly. @@ -987,7 +1019,7 @@ public void testChainOfMethodCallInConstraintSub() { " insert(\"matched\");\n" + "end"; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); Person john = new Person("John", 47); Address a = new Address("Italy"); @@ -1000,8 +1032,9 @@ public void testChainOfMethodCallInConstraintSub() { assertThat(results.size()).isEqualTo(1); } - @Test - public void testChainFieldAccessorsAndMethodCall() { + @ParameterizedTest + @MethodSource("parameters") + public void testChainFieldAccessorsAndMethodCall(RUN_TYPE runType) { String str = "import " + Person.class.getCanonicalName() + ";" + "rule R when\n" + " $p : Person( address.getCity().length == 5 )\n" + @@ -1009,7 +1042,7 @@ public void testChainFieldAccessorsAndMethodCall() { " insert(\"matched\");\n" + "end"; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); Person john = new Person("John", 47); Address a = new Address("Italy"); @@ -1022,8 +1055,9 @@ public void testChainFieldAccessorsAndMethodCall() { assertThat(results.size()).isEqualTo(1); } - @Test - public void testInnerBindingWithOr() { + @ParameterizedTest + @MethodSource("parameters") + public void testInnerBindingWithOr(RUN_TYPE runType) { String str = "global java.util.List list\n" + "\n" + @@ -1033,7 +1067,7 @@ public void testInnerBindingWithOr() { " list.add(s);\n" + "end"; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); List list = new ArrayList(); ksession.setGlobal("list", list); @@ -1045,8 +1079,9 @@ public void testInnerBindingWithOr() { assertThat(list.get(0)).isEqualTo("y"); } - @Test - public void testRHS() { + @ParameterizedTest + @MethodSource("parameters") + public void testRHS(RUN_TYPE runType) { String str = "rule R when\n" + " //conditions\n" + @@ -1060,11 +1095,12 @@ public void testRHS() { " kcontext.getKnowledgeRuntime();\n" + "end"; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); } - @Test - public void testBindWith2Arguments() { + @ParameterizedTest + @MethodSource("parameters") + public void testBindWith2Arguments(RUN_TYPE runType) { String str = "import " + Adult.class.getCanonicalName() + ";\n" + "import " + Child.class.getCanonicalName() + ";\n" + @@ -1075,7 +1111,7 @@ public void testBindWith2Arguments() { " insert(new Result($sum));\n" + "end"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); Adult a = new Adult( "Mario", 43 ); ksession.insert( a ); @@ -1085,8 +1121,9 @@ public void testBindWith2Arguments() { assertThat(((Number) results.iterator().next().getValue()).intValue()).isEqualTo(48); } - @Test - public void testLockOnActiveWithModify() { + @ParameterizedTest + @MethodSource("parameters") + public void testLockOnActiveWithModify(RUN_TYPE runType) { String str = "package org.drools.test; \n" + "import " + Person.class.getCanonicalName() + ";\n" + @@ -1112,7 +1149,7 @@ public void testLockOnActiveWithModify() { " modify ( $p ) { setName( \"john\" ); } \n" + "end"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); ksession.fireAllRules(); @@ -1124,8 +1161,9 @@ public void testLockOnActiveWithModify() { assertThat(p.getName()).isEqualTo("john"); } - @Test - public void testAlphaConstraintOn2Properties() { + @ParameterizedTest + @MethodSource("parameters") + public void testAlphaConstraintOn2Properties(RUN_TYPE runType) { String str = "import " + Person.class.getCanonicalName() + ";" + "rule R when\n" + @@ -1133,15 +1171,16 @@ public void testAlphaConstraintOn2Properties() { "then\n" + "end"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); Person me = new Person( "Mario", 40 ); ksession.insert( me ); ksession.fireAllRules(); } - @Test - public void testAlphaNull() { + @ParameterizedTest + @MethodSource("parameters") + public void testAlphaNull(RUN_TYPE runType) { String str = "import " + Person.class.getCanonicalName() + ";" + "import " + Result.class.getCanonicalName() + ";" + @@ -1162,7 +1201,7 @@ public void testAlphaNull() { " insert(new Result($p.getName()));\n" + "end"; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); Person first = new Person(null, 40); Person second = new Person("Luca", 40); @@ -1179,8 +1218,9 @@ public void testAlphaNull() { assertThat(results).containsExactlyInAnyOrder("Luca", null); } - @Test - public void testAlphaNullBoolean() { + @ParameterizedTest + @MethodSource("parameters") + public void testAlphaNullBoolean(RUN_TYPE runType) { String str = "import " + Person.class.getCanonicalName() + ";" + "import " + Result.class.getCanonicalName() + ";" + @@ -1190,7 +1230,7 @@ public void testAlphaNullBoolean() { " insert(new Result($p.getName()));\n" + "end\n"; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); Person first = new Person("First", 40); first.setEmployed(null); @@ -1207,8 +1247,9 @@ public void testAlphaNullBoolean() { assertThat(results).containsExactlyInAnyOrder("Second"); } - @Test - public void testStringValueOf() { + @ParameterizedTest + @MethodSource("parameters") + public void testStringValueOf(RUN_TYPE runType) { String str = "import " + Person.class.getCanonicalName() + ";\n" + "import " + Result.class.getCanonicalName() + ";\n" + @@ -1219,7 +1260,7 @@ public void testStringValueOf() { " insert(new Result($i));\n" + "end"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); ksession.insert( 44 ); ksession.insert( new Person( "44", 44 ) ); @@ -1229,8 +1270,9 @@ public void testStringValueOf() { assertThat(((Number) results.iterator().next().getValue()).intValue()).isEqualTo(44); } - @Test - public void testBigDecimalBigIntegerCoercion() { + @ParameterizedTest + @MethodSource("parameters") + public void testBigDecimalBigIntegerCoercion(RUN_TYPE runType) { String str = "import " + Person.class.getCanonicalName() + ";\n" + "import " + BigInteger.class.getCanonicalName() + ";\n" + "rule \"rule1\"\n" + @@ -1250,7 +1292,7 @@ public void testBigDecimalBigIntegerCoercion() { "end\n"; - KieSession ksession1 = getKieSession(str); + KieSession ksession1 = getKieSession(runType, str); Person p1 = new Person(); p1.setMoney( new BigDecimal(1 ) ); @@ -1259,8 +1301,9 @@ public void testBigDecimalBigIntegerCoercion() { } - @Test - public void testBigDecimalOperationsInConstraint() { + @ParameterizedTest + @MethodSource("parameters") + public void testBigDecimalOperationsInConstraint(RUN_TYPE runType) { String str = "import " + Person.class.getCanonicalName() + ";\n" + "import " + BigDecimal.class.getCanonicalName() + ";\n" + "global java.util.List results;\n" + @@ -1271,7 +1314,7 @@ public void testBigDecimalOperationsInConstraint() { " results.add($moneyDoubled);\n" + "end\n"; - KieSession ksession1 = getKieSession(str); + KieSession ksession1 = getKieSession(runType, str); ArrayList results = new ArrayList<>(); ksession1.setGlobal("results", results); @@ -1285,8 +1328,9 @@ public void testBigDecimalOperationsInConstraint() { } - @Test - public void testSingleQuoteString() { + @ParameterizedTest + @MethodSource("parameters") + public void testSingleQuoteString(RUN_TYPE runType) { String str = "rule R1 when\n" + " String( this == 'x' )\n" + @@ -1297,15 +1341,16 @@ public void testSingleQuoteString() { "then\n" + "end"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); ksession.insert( "x" ); ksession.insert( "xx" ); assertThat(ksession.fireAllRules()).isEqualTo(2); } - @Test - public void testIntToLongComparison() { + @ParameterizedTest + @MethodSource("parameters") + public void testIntToLongComparison(RUN_TYPE runType) { String str = "rule R when\n" + " $i : Integer()\n" + @@ -1313,7 +1358,7 @@ public void testIntToLongComparison() { "then\n" + "end"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); ksession.insert( 1 ); ksession.insert( 2L ); @@ -1321,8 +1366,9 @@ public void testIntToLongComparison() { } - @Test - public void testUseGlobalInLHS() { + @ParameterizedTest + @MethodSource("parameters") + public void testUseGlobalInLHS(RUN_TYPE runType) { // DROOLS-1025 final String drl1 = "import " + Result.class.getCanonicalName() + ";\n" + @@ -1333,7 +1379,7 @@ public void testUseGlobalInLHS() { " insert(new Result(\"match\"));\n" + "end\n"; - KieSession ksession = getKieSession( drl1 ); + KieSession ksession = getKieSession(runType, drl1); ksession.setGlobal("globalInt", new AtomicInteger(0)); @@ -1343,8 +1389,9 @@ public void testUseGlobalInLHS() { assertThat(results.iterator().next().getValue().toString()).isEqualTo("match"); } - @Test - public void testMapAccess() { + @ParameterizedTest + @MethodSource("parameters") + public void testMapAccess(RUN_TYPE runType) { final String drl1 = "import java.util.Map;\n" + "rule R1 when\n" + @@ -1352,7 +1399,7 @@ public void testMapAccess() { "then\n" + "end\n"; - KieSession ksession = getKieSession( drl1 ); + KieSession ksession = getKieSession(runType, drl1); final Map map = new HashMap<>(); map.put("type", "Goods"); @@ -1361,8 +1408,9 @@ public void testMapAccess() { assertThat(ksession.fireAllRules()).isEqualTo(1); } - @Test - public void testMapAccessBindingConstant() { + @ParameterizedTest + @MethodSource("parameters") + public void testMapAccessBindingConstant(RUN_TYPE runType) { final String drl1 = "import java.util.Map;\n" + "rule R1 when\n" + @@ -1370,7 +1418,7 @@ public void testMapAccessBindingConstant() { "then\n" + "end\n"; - KieSession ksession = getKieSession( drl1 ); + KieSession ksession = getKieSession(runType, drl1); final Map map = new HashMap<>(); map.put("type", "Goods"); @@ -1379,8 +1427,9 @@ public void testMapAccessBindingConstant() { assertThat(ksession.fireAllRules()).isEqualTo(1); } - @Test - public void testMapAccessBindingConstantJoin() { + @ParameterizedTest + @MethodSource("parameters") + public void testMapAccessBindingConstantJoin(RUN_TYPE runType) { final String drl1 = "import java.util.Map;\n" + "import " + Person.class.getCanonicalName() + ";\n" + @@ -1394,7 +1443,7 @@ public void testMapAccessBindingConstantJoin() { " results.add($p.getName());\n" + "end\n"; - KieSession ksession = getKieSession( drl1 ); + KieSession ksession = getKieSession(runType, drl1); ArrayList results = new ArrayList<>(); ksession.setGlobal("results", results); @@ -1413,8 +1462,9 @@ public void testMapAccessBindingConstantJoin() { assertThat(results).containsExactlyInAnyOrder("Andrea", "Luca"); } - @Test - public void testMapAccessBinding() { + @ParameterizedTest + @MethodSource("parameters") + public void testMapAccessBinding(RUN_TYPE runType) { final String drl1 = "import java.util.Map;\n" + "rule R1 when\n" + @@ -1423,7 +1473,7 @@ public void testMapAccessBinding() { "then\n" + "end\n"; - KieSession ksession = getKieSession( drl1 ); + KieSession ksession = getKieSession(runType, drl1); final Map map = new HashMap<>(); map.put("type", "Goods"); @@ -1433,8 +1483,9 @@ public void testMapAccessBinding() { assertThat(ksession.fireAllRules()).isEqualTo(1); } - @Test - public void testStringBinding() { + @ParameterizedTest + @MethodSource("parameters") + public void testStringBinding(RUN_TYPE runType) { final String drl1 = "import " + Result.class.getCanonicalName() + ";\n" + "rule R1 when\n" + @@ -1443,7 +1494,7 @@ public void testStringBinding() { " insert(new Result($t));\n" + "end\n"; - KieSession ksession = getKieSession( drl1 ); + KieSession ksession = getKieSession(runType, drl1); ksession.insert( "whatever" ); assertThat(ksession.fireAllRules()).isEqualTo(1); @@ -1452,8 +1503,9 @@ public void testStringBinding() { assertThat(results.iterator().next().getValue().toString()).isEqualTo("type"); } - @Test - public void testMapAccessProperty() { + @ParameterizedTest + @MethodSource("parameters") + public void testMapAccessProperty(RUN_TYPE runType) { final String drl1 = "import " + Person.class.getCanonicalName() + ";\n" + "import java.util.Map;\n" + @@ -1462,7 +1514,7 @@ public void testMapAccessProperty() { "then\n" + "end\n"; - KieSession ksession = getKieSession( drl1 ); + KieSession ksession = getKieSession(runType, drl1); final Map map = new HashMap<>(); map.put(1, 2000); @@ -1478,8 +1530,9 @@ public void testMapAccessProperty() { assertThat(ksession.fireAllRules()).isEqualTo(1); } - @Test - public void testMapInitialization() { + @ParameterizedTest + @MethodSource("parameters") + public void testMapInitialization(RUN_TYPE runType) { final String drl1 = "import " + Person.class.getCanonicalName() + ";\n" + "import java.util.Map;\n" + @@ -1489,7 +1542,7 @@ public void testMapInitialization() { "then\n" + "end\n"; - KieSession ksession = getKieSession( drl1 ); + KieSession ksession = getKieSession(runType, drl1); final Person luca = new Person("Luca"); luca.setNumberOfItems(2); @@ -1502,8 +1555,9 @@ public void testMapInitialization() { } - @Test - public void testErrorTwoPatterns() { + @ParameterizedTest + @MethodSource("parameters") + public void testErrorTwoPatterns(RUN_TYPE runType) { // DROOLS-3850 final String drl1 = "import " + Person.class.getCanonicalName() + ";\n" + @@ -1515,7 +1569,7 @@ public void testErrorTwoPatterns() { "then\n" + "end\n"; - KieSession ksession = getKieSession( drl1 ); + KieSession ksession = getKieSession(runType, drl1); final Person luca = new Person("Luca"); luca.setNumberOfItems(2); @@ -1528,8 +1582,9 @@ public void testErrorTwoPatterns() { } - @Test - public void testMapWithBinding() { + @ParameterizedTest + @MethodSource("parameters") + public void testMapWithBinding(RUN_TYPE runType) { // DROOLS-3558 final String drl1 = "package org.drools.compiler\n" + "import " + Person.class.getCanonicalName() + ";\n" + @@ -1541,7 +1596,7 @@ public void testMapWithBinding() { " then\n" + "end\n"; - KieSession ksession = getKieSession( drl1 ); + KieSession ksession = getKieSession(runType, drl1); final Person john = new Person("John"); HashMap items = new HashMap(); @@ -1557,8 +1612,9 @@ public void testMapWithBinding() { assertThat(ksession.fireAllRules()).isEqualTo(1); } - @Test - public void testMapAccessPropertyWithCast() { + @ParameterizedTest + @MethodSource("parameters") + public void testMapAccessPropertyWithCast(RUN_TYPE runType) { final String drl1 = "import " + Person.class.getCanonicalName() + ";\n" + "import java.util.Map;\n" + @@ -1567,7 +1623,7 @@ public void testMapAccessPropertyWithCast() { "then\n" + "end\n"; - KieSession ksession = getKieSession( drl1 ); + KieSession ksession = getKieSession(runType, drl1); final Map map = new HashMap<>(); map.put(1, 2000); @@ -1583,8 +1639,9 @@ public void testMapAccessPropertyWithCast() { assertThat(ksession.fireAllRules()).isEqualTo(1); } - @Test - public void testArrayAccess() { + @ParameterizedTest + @MethodSource("parameters") + public void testArrayAccess(RUN_TYPE runType) { final String drl = "package org.drools.compiler.test\n" + "import " + Person.class.getCanonicalName() + "\n" + @@ -1596,13 +1653,14 @@ public void testArrayAccess() { "then\n" + "end\n"; - KieSession ksession = getKieSession(drl); + KieSession ksession = getKieSession(runType, drl); assertThat(ksession.fireAllRules()).isEqualTo(0); } - @Test - public void testInOperators() { + @ParameterizedTest + @MethodSource("parameters") + public void testInOperators(RUN_TYPE runType) { final String drl1 = "package org.drools.compiler\n" + "import " + Person.class.getCanonicalName() + ";\n" + "rule \"eval rewrite with 'in'\"\n" + @@ -1611,7 +1669,7 @@ public void testInOperators() { " then\n" + "end\n"; - KieSession ksession = getKieSession( drl1 ); + KieSession ksession = getKieSession(runType, drl1); final Person luca = new Person("Luca"); luca.setAge(2); @@ -1640,8 +1698,9 @@ public void setaBcde(String aBcde) { } } - @Test - public void testGetterSetterCase() { + @ParameterizedTest + @MethodSource("parameters") + public void testGetterSetterCase(RUN_TYPE runType) { // DROOLS-2724 final String drl = "import " + TestFact.class.getCanonicalName() + ";\n" + @@ -1650,13 +1709,14 @@ public void testGetterSetterCase() { "when \n" + " TestFact(aBcde == \"test\")\n" + "then end"; - KieSession kieSession = getKieSession(drl); + KieSession kieSession = getKieSession(runType, drl); kieSession.insert(new TestFact("test")); assertThat(kieSession.fireAllRules()).isEqualTo(1); } - @Test - public void testCommaInModify() { + @ParameterizedTest + @MethodSource("parameters") + public void testCommaInModify(RUN_TYPE runType) { // DROOLS-3505 final String drl = "import " + Person.class.getCanonicalName() + "\n" + @@ -1667,7 +1727,7 @@ public void testCommaInModify() { "then\n" + " modify($p) { setAge(1), setLikes(\"bread\"); }\n" + "end\n"; - KieSession kieSession = getKieSession(drl); + KieSession kieSession = getKieSession(runType, drl); Person john = new Person("John", 24); kieSession.insert(john); assertThat(kieSession.fireAllRules()).isEqualTo(1); @@ -1701,8 +1761,9 @@ public void setStatus( int status ) { } } - @Test - public void testStaticFieldClashingWithClassName() { + @ParameterizedTest + @MethodSource("parameters") + public void testStaticFieldClashingWithClassName(RUN_TYPE runType) { // DROOLS-3560 final String drl = "import " + Message.class.getCanonicalName() + "\n" + @@ -1723,7 +1784,7 @@ public void testStaticFieldClashingWithClassName() { " System.out.println( myMessage );\n" + "end\n"; - KieSession kieSession = getKieSession(drl); + KieSession kieSession = getKieSession(runType, drl); Message message = new Message(); message.setMessage( "Hi" ); message.setStatus( Message.HELLO ); @@ -1731,8 +1792,9 @@ public void testStaticFieldClashingWithClassName() { assertThat(kieSession.fireAllRules()).isEqualTo(2); } - @Test - public void testDoubleModify() { + @ParameterizedTest + @MethodSource("parameters") + public void testDoubleModify(RUN_TYPE runType) { // DROOLS-3560 final String drl = "import " + Message.class.getCanonicalName() + "\n" + @@ -1754,7 +1816,7 @@ public void testDoubleModify() { " System.out.println( myMessage );\n" + "end\n"; - KieSession kieSession = getKieSession(drl); + KieSession kieSession = getKieSession(runType, drl); Message message = new Message(); message.setMessage( "Hi" ); message.setStatus( Message.HELLO ); @@ -1762,8 +1824,9 @@ public void testDoubleModify() { assertThat(kieSession.fireAllRules()).isEqualTo(2); } - @Test - public void testPrettyPrinterCrashing() { + @ParameterizedTest + @MethodSource("parameters") + public void testPrettyPrinterCrashing(RUN_TYPE runType) { final String drl = "" + "package org.drools.compiler.test \n" + @@ -1801,7 +1864,7 @@ public void testPrettyPrinterCrashing() { "end\n" + "\n"; - KieSession ksession = getKieSession(drl); + KieSession ksession = getKieSession(runType, drl); try { final List list = new ArrayList<>(); ksession.setGlobal("list", list); @@ -1816,8 +1879,9 @@ public void testPrettyPrinterCrashing() { } } - @Test - public void testBetaJoinBigInteger() { + @ParameterizedTest + @MethodSource("parameters") + public void testBetaJoinBigInteger(RUN_TYPE runType) { String str = "import " + Result.class.getCanonicalName() + ";" + "import " + Person.class.getCanonicalName() + ";" + @@ -1829,7 +1893,7 @@ public void testBetaJoinBigInteger() { " $r.setValue($olderV.getName() + \" is older than \" + $markV.getName());\n" + "end"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); Result result = new Result(); ksession.insert( result ); @@ -1846,8 +1910,9 @@ public void testBetaJoinBigInteger() { assertThat(result.getValue()).isEqualTo("Mario is older than Mark"); } - @Test - public void testBetaJoinBigDecimal() { + @ParameterizedTest + @MethodSource("parameters") + public void testBetaJoinBigDecimal(RUN_TYPE runType) { String str = "import " + Result.class.getCanonicalName() + ";" + "import " + Person.class.getCanonicalName() + ";" + @@ -1859,7 +1924,7 @@ public void testBetaJoinBigDecimal() { " $r.setValue($richerV.getName() + \" is richer than \" + $markV.getName());\n" + "end"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); Result result = new Result(); ksession.insert( result ); @@ -1876,8 +1941,9 @@ public void testBetaJoinBigDecimal() { assertThat(result.getValue()).isEqualTo("Mario is richer than Mark"); } - @Test - public void testBetaCast() { + @ParameterizedTest + @MethodSource("parameters") + public void testBetaCast(RUN_TYPE runType) { String str = "import " + Result.class.getCanonicalName() + ";" + "import " + Person.class.getCanonicalName() + ";" + @@ -1890,7 +1956,7 @@ public void testBetaCast() { " $r.setValue($a.getCity() + \" number has the same value of \" + $p.getName() + \" age\");\n" + "end"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); Result result = new Result(); ksession.insert( result ); @@ -1916,8 +1982,9 @@ public void testBetaCast() { assertThat(result.getValue()).isEqualTo("Milan number has the same value of Mark age"); } - @Test - public void testNumericLimitsLiteral() { + @ParameterizedTest + @MethodSource("parameters") + public void testNumericLimitsLiteral(RUN_TYPE runType) { String str = "import " + Result.class.getCanonicalName() + ";" + "import " + Person.class.getCanonicalName() + ";" + @@ -1928,7 +1995,7 @@ public void testNumericLimitsLiteral() { " $r.setValue($p.getName() + \" is very old\");\n" + "end"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); Result result = new Result(); ksession.insert( result ); @@ -1949,8 +2016,9 @@ public void testNumericLimitsLiteral() { - @Test - public void testBetaCastGreaterThan() { + @ParameterizedTest + @MethodSource("parameters") + public void testBetaCastGreaterThan(RUN_TYPE runType) { String str = "import " + Result.class.getCanonicalName() + ";" + "import " + Person.class.getCanonicalName() + ";" + @@ -1963,7 +2031,7 @@ public void testBetaCastGreaterThan() { " $r.setValue($a.getCity() + \" number is greater than \" + $p.getName() + \" age\");\n" + "end"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); Result result = new Result(); ksession.insert( result ); @@ -1995,8 +2063,9 @@ public void testBetaCastGreaterThan() { } - @Test - public void testNumericLimits() { + @ParameterizedTest + @MethodSource("parameters") + public void testNumericLimits(RUN_TYPE runType) { String str = "import " + Result.class.getCanonicalName() + ";" + "import " + Person.class.getCanonicalName() + ";" + @@ -2007,7 +2076,7 @@ public void testNumericLimits() { " $r.setValue($p.getName() + \" is very old\");\n" + "end"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); Result result = new Result(); ksession.insert( result ); @@ -2026,8 +2095,9 @@ public void testNumericLimits() { } - @Test - public void testMapAbbreviatedComparison() { + @ParameterizedTest + @MethodSource("parameters") + public void testMapAbbreviatedComparison(RUN_TYPE runType) { final String drl1 = "import java.util.Map;\n" + "rule R1 when\n" + @@ -2035,7 +2105,7 @@ public void testMapAbbreviatedComparison() { "then\n" + "end\n"; - KieSession ksession = getKieSession( drl1 ); + KieSession ksession = getKieSession(runType, drl1); final Map map = new HashMap<>(); map.put("money", new BigDecimal(70)); @@ -2044,8 +2114,9 @@ public void testMapAbbreviatedComparison() { assertThat(ksession.fireAllRules()).isEqualTo(1); } - @Test - public void testMapPrimitiveComparison() { + @ParameterizedTest + @MethodSource("parameters") + public void testMapPrimitiveComparison(RUN_TYPE runType) { final String drl1 = "import java.util.Map;\n" + "import " + Person.class.getCanonicalName() + ";\n" + @@ -2055,7 +2126,7 @@ public void testMapPrimitiveComparison() { "then\n" + "end\n"; - KieSession ksession = getKieSession( drl1 ); + KieSession ksession = getKieSession(runType, drl1); final Map map = new HashMap<>(); map.put("age", 20); @@ -2068,8 +2139,9 @@ public void testMapPrimitiveComparison() { public static final int CONSTANT = 1; - @Test - public void testMapCheckForExistence() { + @ParameterizedTest + @MethodSource("parameters") + public void testMapCheckForExistence(RUN_TYPE runType) { final String drl1 = "import " + Person.class.getCanonicalName() + ";\n" + "import " + Result.class.getCanonicalName() + ";" + @@ -2079,7 +2151,7 @@ public void testMapCheckForExistence() { " insert(new Result($p.getName()));\n" + "end\n"; - KieSession ksession = getKieSession( drl1 ); + KieSession ksession = getKieSession(runType, drl1); final Map items = new HashMap<>(); items.put(CONSTANT, 2000); @@ -2098,8 +2170,9 @@ public void testMapCheckForExistence() { assertThat(results.iterator().next().getValue()).isEqualTo("Mario"); } - @Test - public void testBigDecimalIntCoercion() { + @ParameterizedTest + @MethodSource("parameters") + public void testBigDecimalIntCoercion(RUN_TYPE runType) { String str = "import " + Result.class.getCanonicalName() + ";\n" + "rule \"rule1\"\n" + "when\n" + @@ -2107,7 +2180,7 @@ public void testBigDecimalIntCoercion() { "then\n" + "end\n"; - KieSession ksession1 = getKieSession(str); + KieSession ksession1 = getKieSession(runType, str); Result fact = new Result(); fact.setValue( new BigDecimal(10) ); @@ -2115,8 +2188,9 @@ public void testBigDecimalIntCoercion() { assertThat(ksession1.fireAllRules()).isEqualTo(1); } - @Test - public void testBooleanCoercion() { + @ParameterizedTest + @MethodSource("parameters") + public void testBooleanCoercion(RUN_TYPE runType) { String str = "import " + Person.class.getCanonicalName() + ";" + "import " + Result.class.getCanonicalName() + ";" + @@ -2125,7 +2199,7 @@ public void testBooleanCoercion() { "then\n" + "end\n"; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); Person first = new Person("First", 40); first.setEmployed(true); @@ -2133,8 +2207,9 @@ public void testBooleanCoercion() { assertThat(ksession.fireAllRules()).isEqualTo(1);; } - @Test - public void testUseMatch() { + @ParameterizedTest + @MethodSource("parameters") + public void testUseMatch(RUN_TYPE runType) { // DROOLS-4579 String str = "import " + Person.class.getCanonicalName() + ";" + @@ -2144,15 +2219,16 @@ public void testUseMatch() { " if ($p != drools.getMatch().getObjects().get(0)) throw new RuntimeException();\n" + "end"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); Person me = new Person( "Mario", 40 ); ksession.insert( me ); assertThat(ksession.fireAllRules()).isEqualTo(1); } - @Test - public void testMultilinePattern() { + @ParameterizedTest + @MethodSource("parameters") + public void testMultilinePattern(RUN_TYPE runType) { String str = "import " + Person.class.getCanonicalName() + ";" + "rule R1 when\n" + @@ -2161,7 +2237,7 @@ public void testMultilinePattern() { "then\n" + "end\n"; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); Person first = new Person("John", 40); first.setEmployed(true); @@ -2169,8 +2245,9 @@ public void testMultilinePattern() { assertThat(ksession.fireAllRules()).isEqualTo(1);; } - @Test - public void testAccumulateWithMax() { + @ParameterizedTest + @MethodSource("parameters") + public void testAccumulateWithMax(RUN_TYPE runType) { String str = "import " + StockTick.class.getCanonicalName() + ";" + "import " + StockTick.class.getCanonicalName() + ";" + @@ -2181,7 +2258,7 @@ public void testAccumulateWithMax() { "then\n" + "end\n"; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); StockTick st = new StockTick("RHT"); st.setTimeField(new Date().getTime()); @@ -2189,8 +2266,9 @@ public void testAccumulateWithMax() { assertThat(ksession.fireAllRules()).isEqualTo(1);; } - @Test() - public void testMultipleModify() { + @ParameterizedTest + @MethodSource("parameters") + public void testMultipleModify(RUN_TYPE runType) { String str = "import " + Person.class.getCanonicalName() + ";" + "rule R when\n" + @@ -2201,7 +2279,7 @@ public void testMultipleModify() { " modify($p2) { setAge($p2.getAge()+5) }\n" + "end"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); Person p1 = new Person( "John", 40 ); Person p2 = new Person( "Paul", 38 ); @@ -2214,8 +2292,9 @@ public void testMultipleModify() { assertThat(p2.getAge()).isEqualTo(43); } - @Test() - public void testMultipleModifyWithDifferentFacts() { + @ParameterizedTest + @MethodSource("parameters") + public void testMultipleModifyWithDifferentFacts(RUN_TYPE runType) { String str = "import " + Person.class.getCanonicalName() + ";" + "import " + Pet.class.getCanonicalName() + ";" + @@ -2233,7 +2312,7 @@ public void testMultipleModifyWithDifferentFacts() { " modify($pet) { setAge($pet.getAge()+1) }\n" + "end"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); Person person = new Person( "John", 40 ); Pet pet = new Pet( Pet.PetType.dog, 3 ); @@ -2341,8 +2420,10 @@ public String getValue(Object o) { } } - @Test // DROOLS-5007 - public void testIntToShortCast() { + // DROOLS-5007 + @ParameterizedTest + @MethodSource("parameters") + public void testIntToShortCast(RUN_TYPE runType) { String str = "import " + Address.class.getCanonicalName() + ";\n" + "rule \"rule1\"\n" + "when\n" + @@ -2353,7 +2434,7 @@ public void testIntToShortCast() { " update($address);\n" + "end\n"; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); Address address = new Address(); address.setNumber(1); @@ -2362,8 +2443,10 @@ public void testIntToShortCast() { } - @Test // DROOLS-5709 // DROOLS-5768 - public void testCastingIntegerToShort() { + // DROOLS-5709 // DROOLS-5768 + @ParameterizedTest + @MethodSource("parameters") + public void testCastingIntegerToShort(RUN_TYPE runType) { String str = "import " + IntegerToShort.class.getCanonicalName() + ";\n " + "rule \"test_rule\"\n" + @@ -2381,7 +2464,7 @@ public void testCastingIntegerToShort() { " update($integerToShort);\n" + "end"; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); IntegerToShort integerToShort = new IntegerToShort(false, Short.MAX_VALUE, (short)0, (double)0); ksession.insert(integerToShort); @@ -2391,8 +2474,10 @@ public void testCastingIntegerToShort() { assertThat(integerToShort).isEqualTo(new IntegerToShort(true, Short.MAX_VALUE, Short.MAX_VALUE, (double)0)); } - @Test // DROOLS-5998 - public void testCastingIntegerToShortWithNegativeNumbers() { + // DROOLS-5998 + @ParameterizedTest + @MethodSource("parameters") + public void testCastingIntegerToShortWithNegativeNumbers(RUN_TYPE runType) { String str = "import " + IntegerToShort.class.getCanonicalName() + ";\n " + "rule \"test_rule\"\n" + @@ -2409,7 +2494,7 @@ public void testCastingIntegerToShortWithNegativeNumbers() { " update($integerToShort);\n" + "end"; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); IntegerToShort integerToShort = new IntegerToShort(false, Short.MAX_VALUE, (short)0, (double)0); ksession.insert(integerToShort); @@ -2419,8 +2504,10 @@ public void testCastingIntegerToShortWithNegativeNumbers() { assertThat(integerToShort).isEqualTo(new IntegerToShort(true, Short.MAX_VALUE, (short)-12, (double)0)); } - @Test // RHDM-1644 // DROOLS-6196 - public void testCastingIntegerToShortWithDoubleVar() { + // RHDM-1644 // DROOLS-6196 + @ParameterizedTest + @MethodSource("parameters") + public void testCastingIntegerToShortWithDoubleVar(RUN_TYPE runType) { String str = "import " + IntegerToShort.class.getCanonicalName() + ";\n " + "rule \"test_rule\"\n" + @@ -2438,7 +2525,7 @@ public void testCastingIntegerToShortWithDoubleVar() { " update($integerToShort);\n" + "end"; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); IntegerToShort integerToShort = new IntegerToShort(false, Short.MAX_VALUE, (short)0, (double)1); ksession.insert(integerToShort); @@ -2448,8 +2535,10 @@ public void testCastingIntegerToShortWithDoubleVar() { assertThat(integerToShort).isEqualTo(new IntegerToShort(true, Short.MAX_VALUE, (short)17, (double)1)); } - @Test // RHDM-1644 // DROOLS-6196 - public void testUseOfVarCreatedAsInputArgInGlobalFuntionAsA_Var() { + // RHDM-1644 // DROOLS-6196 + @ParameterizedTest + @MethodSource("parameters") + public void testUseOfVarCreatedAsInputArgInGlobalFuntionAsA_Var(RUN_TYPE runType) { String str = "import " + IntegerToShort.class.getCanonicalName() + ";\n " + "global " + GlobalFunctions.class.getCanonicalName() + " functions;\n " + @@ -2468,7 +2557,7 @@ public void testUseOfVarCreatedAsInputArgInGlobalFuntionAsA_Var() { " update($integerToShort);\n" + "end"; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); IntegerToShort integerToShort = new IntegerToShort(false, Short.MAX_VALUE, (short)0); ksession.insert(integerToShort); @@ -2479,8 +2568,9 @@ public void testUseOfVarCreatedAsInputArgInGlobalFuntionAsA_Var() { assertThat(integerToShort).isEqualTo(new IntegerToShort(true, 1, (short)0)); } - @Test - public void testConsequenceGetContext() throws Exception { + @ParameterizedTest + @MethodSource("parameters") + public void testConsequenceGetContext(RUN_TYPE runType) throws Exception { String str = "import " + ProcessContext.class.getCanonicalName() + ";" + "rule R when\n" + @@ -2489,12 +2579,14 @@ public void testConsequenceGetContext() throws Exception { " ProcessContext clazz = drools.getContext(ProcessContext.class);\n" + "end"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); assertThat(ksession).isNotNull(); } - @Test // DROOLS-6034 - public void testConsequenceInsertThenUpdate() throws Exception { + // DROOLS-6034 + @ParameterizedTest + @MethodSource("parameters") + public void testConsequenceInsertThenUpdate(RUN_TYPE runType) throws Exception { String str = "global java.util.List children;\n" + "import " + Person.class.getCanonicalName() + ";" + @@ -2508,7 +2600,7 @@ public void testConsequenceInsertThenUpdate() throws Exception { " children.add(andrea.getName());\n" + "end"; - KieSession kSession = getKieSession( str ); + KieSession kSession = getKieSession(runType, str); ArrayList children = new ArrayList<>(); kSession.setGlobal("children", children); @@ -2521,8 +2613,10 @@ public void testConsequenceInsertThenUpdate() throws Exception { assertThat(children).containsOnly("Andrea"); } - @Test // DROOLS-6034 - public void testConsequenceInsertThenModify() throws Exception { + // DROOLS-6034 + @ParameterizedTest + @MethodSource("parameters") + public void testConsequenceInsertThenModify(RUN_TYPE runType) throws Exception { String str = "global java.util.List children;\n" + "import " + Person.class.getCanonicalName() + ";" + @@ -2538,7 +2632,7 @@ public void testConsequenceInsertThenModify() throws Exception { " children.add(andrea.getName());\n" + "end"; - KieSession kSession = getKieSession( str ); + KieSession kSession = getKieSession(runType, str); ArrayList children = new ArrayList<>(); kSession.setGlobal("children", children); @@ -2551,8 +2645,10 @@ public void testConsequenceInsertThenModify() throws Exception { assertThat(children).containsOnly("Andrea"); } - @Test // DROOLS-6034 - public void testConsequenceInsertThenUpdateWithPatternInitializer() throws Exception { + // DROOLS-6034 + @ParameterizedTest + @MethodSource("parameters") + public void testConsequenceInsertThenUpdateWithPatternInitializer(RUN_TYPE runType) throws Exception { String str = "global java.util.List result;\n" + "import " + Person.class.getCanonicalName() + ";" + @@ -2569,7 +2665,7 @@ public void testConsequenceInsertThenUpdateWithPatternInitializer() throws Excep " result.add(fromNameExprTwice.getName());\n" + "end"; - KieSession kSession = getKieSession( str ); + KieSession kSession = getKieSession(runType, str); ArrayList children = new ArrayList<>(); kSession.setGlobal("result", children); @@ -2582,8 +2678,9 @@ public void testConsequenceInsertThenUpdateWithPatternInitializer() throws Excep assertThat(children).containsOnly("Luca"); } - @Test - public void testExtraParenthes() throws Exception { + @ParameterizedTest + @MethodSource("parameters") + public void testExtraParenthes(RUN_TYPE runType) throws Exception { String str = "import " + Person.class.getCanonicalName() + ";" + "rule R when\n" + @@ -2591,7 +2688,7 @@ public void testExtraParenthes() throws Exception { "then\n" + "end"; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); Person person = new Person( "John", 20 ); @@ -2599,8 +2696,9 @@ public void testExtraParenthes() throws Exception { assertThat(ksession.fireAllRules()).isEqualTo(0); } - @Test - public void testNegateBigDecimal() throws Exception { + @ParameterizedTest + @MethodSource("parameters") + public void testNegateBigDecimal(RUN_TYPE runType) throws Exception { String str = "import " + Person.class.getCanonicalName() + ";" + "global java.util.List list;\n" + @@ -2610,7 +2708,7 @@ public void testNegateBigDecimal() throws Exception { " list.add($p.getName());" + "end"; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); final List list = new ArrayList<>(); ksession.setGlobal("list", list); @@ -2626,8 +2724,9 @@ public void testNegateBigDecimal() throws Exception { assertThat(list).containsExactly("John"); } - @Test - public void testNegateJoin() throws Exception { + @ParameterizedTest + @MethodSource("parameters") + public void testNegateJoin(RUN_TYPE runType) throws Exception { String str = "import " + Person.class.getCanonicalName() + ";" + "import " + Address.class.getCanonicalName() + ";" + @@ -2637,7 +2736,7 @@ public void testNegateJoin() throws Exception { "then\n" + "end"; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); Address a = new Address("Milan"); Person p = new Person("Toshiya"); @@ -2649,8 +2748,9 @@ public void testNegateJoin() throws Exception { assertThat(ksession.fireAllRules()).isEqualTo(1); } - @Test - public void testNegateComplex() throws Exception { + @ParameterizedTest + @MethodSource("parameters") + public void testNegateComplex(RUN_TYPE runType) throws Exception { String str = "import " + Person.class.getCanonicalName() + ";" + "global java.util.List list;\n" + @@ -2660,7 +2760,7 @@ public void testNegateComplex() throws Exception { " list.add($p.getName());" + "end"; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); final List list = new ArrayList<>(); ksession.setGlobal("list", list); @@ -2679,8 +2779,9 @@ public void testNegateComplex() throws Exception { assertThat(list).containsExactlyInAnyOrder("John", "George"); } - @Test - public void testMapStringProp() throws Exception { + @ParameterizedTest + @MethodSource("parameters") + public void testMapStringProp(RUN_TYPE runType) throws Exception { final String str = "package org.drools.test;\n" + "import " + Person.class.getCanonicalName() + ";\n" + @@ -2689,7 +2790,7 @@ public void testMapStringProp() throws Exception { "then\n" + "end"; - final KieSession ksession = getKieSession(str); + final KieSession ksession = getKieSession(runType, str); final Person p = new Person("Toshiya"); p.getItemsString().put("AAA", "XXX"); @@ -2698,8 +2799,9 @@ public void testMapStringProp() throws Exception { assertThat(ksession.fireAllRules()).isEqualTo(1); } - @Test - public void testMapString() throws Exception { + @ParameterizedTest + @MethodSource("parameters") + public void testMapString(RUN_TYPE runType) throws Exception { final String str = "package org.drools.test;\n" + "import " + Map.class.getCanonicalName() + ";\n" + @@ -2708,7 +2810,7 @@ public void testMapString() throws Exception { "then\n" + "end"; - final KieSession ksession = getKieSession(str); + final KieSession ksession = getKieSession(runType, str); Map map = new HashMap<>(); map.put("AAA", "XXX"); @@ -2717,8 +2819,9 @@ public void testMapString() throws Exception { assertThat(ksession.fireAllRules()).isEqualTo(1); } - @Test - public void testHashSet() throws Exception { + @ParameterizedTest + @MethodSource("parameters") + public void testHashSet(RUN_TYPE runType) throws Exception { final String str = "package org.drools.test;\n" + "import " + HashSet.class.getCanonicalName() + ";\n" + @@ -2739,7 +2842,7 @@ public void testHashSet() throws Exception { "then\n" + "end"; - final KieSession ksession = getKieSession(str); + final KieSession ksession = getKieSession(runType, str); FactType appType = ksession.getKieBase().getFactType("org.drools.test", "Application"); Object appObj = appType.newInstance(); @@ -2750,8 +2853,9 @@ public void testHashSet() throws Exception { assertThat(ksession.fireAllRules()).isEqualTo(2); } - @Test() - public void testRhsOrderWithModify() { + @ParameterizedTest + @MethodSource("parameters") + public void testRhsOrderWithModify(RUN_TYPE runType) { String str = "import " + Person.class.getCanonicalName() + ";" + "global java.util.List list;\n" + @@ -2769,7 +2873,7 @@ public void testRhsOrderWithModify() { " list.add($p2.getAge());\n" + "end"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); final List list = new ArrayList<>(); ksession.setGlobal("list", list); @@ -2783,8 +2887,9 @@ public void testRhsOrderWithModify() { assertThat(list).containsExactlyInAnyOrder(40, 38, 41, 38, 41, 43); } - @Test() - public void testStringRelationalComparison() { + @ParameterizedTest + @MethodSource("parameters") + public void testStringRelationalComparison(RUN_TYPE runType) { String str = "import " + Person.class.getCanonicalName() + ";" + "global java.util.List list;\n" + @@ -2794,7 +2899,7 @@ public void testStringRelationalComparison() { " list.add($p.getName());" + "end"; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); final List list = new ArrayList<>(); ksession.setGlobal("list", list); @@ -2805,11 +2910,9 @@ public void testStringRelationalComparison() { assertThat(list).containsExactly("John"); } - @Rule - public ExpectedException exceptionRule = ExpectedException.none(); - - @Test - public void testNPEOnConstraint() { + @ParameterizedTest + @MethodSource("parameters") + public void testNPEOnConstraint(RUN_TYPE runType) { String str = "import " + Person.class.getCanonicalName() + ";" + "rule R when\n" + @@ -2817,7 +2920,7 @@ public void testNPEOnConstraint() { "then\n" + "end"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); Person me = new Person( "Luca"); me.setMoney(null); @@ -2826,8 +2929,9 @@ public void testNPEOnConstraint() { .isThrownBy(() -> ksession.fireAllRules()) .withMessage("Error evaluating constraint 'money < salary * 20' in [Rule \"R\" in r0.drl]"); } - @Test - public void testSharedPredicateInformation() { + @ParameterizedTest + @MethodSource("parameters") + public void testSharedPredicateInformation(RUN_TYPE runType) { String str = "import " + Person.class.getCanonicalName() + ";" + "rule R1 when\n" + @@ -2839,7 +2943,7 @@ public void testSharedPredicateInformation() { "then\n" + "end"; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); Person me = new Person("Luca"); me.setSalary(null); @@ -2851,8 +2955,9 @@ public void testSharedPredicateInformation() { .withMessage("Error evaluating constraint 'money < salary * 20' in [Rule \"R1\", \"R2\" in r0.drl]"); } - @Test - public void testSharedPredicateInformationWithNonSharedRule() { + @ParameterizedTest + @MethodSource("parameters") + public void testSharedPredicateInformationWithNonSharedRule(RUN_TYPE runType) { String str = "import " + Person.class.getCanonicalName() + ";" + @@ -2869,7 +2974,7 @@ public void testSharedPredicateInformationWithNonSharedRule() { "then\n" + "end"; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); Person me = new Person("Luca"); me.setSalary(null); @@ -2882,8 +2987,9 @@ public void testSharedPredicateInformationWithNonSharedRule() { } - @Test - public void testSharedPredicateInformationWithMultipleFiles() { + @ParameterizedTest + @MethodSource("parameters") + public void testSharedPredicateInformationWithMultipleFiles(RUN_TYPE runType) { String str1 = "import " + Person.class.getCanonicalName() + ";" + @@ -2906,7 +3012,7 @@ public void testSharedPredicateInformationWithMultipleFiles() { "then\n" + "end"; - KieSession ksession = getKieSession(str1, str2); + KieSession ksession = getKieSession(runType, str1, str2); Person me = new Person("Luca"); me.setSalary(null); @@ -2919,8 +3025,9 @@ public void testSharedPredicateInformationWithMultipleFiles() { } - @Test - public void testSharedBetaPredicateInformationWithMultipleFiles() { + @ParameterizedTest + @MethodSource("parameters") + public void testSharedBetaPredicateInformationWithMultipleFiles(RUN_TYPE runType) { String str1 = "import " + Person.class.getCanonicalName() + ";" + "rule R1 when\n" + @@ -2946,7 +3053,7 @@ public void testSharedBetaPredicateInformationWithMultipleFiles() { "then\n" + "end"; - KieSession ksession = getKieSession(str1, str2); + KieSession ksession = getKieSession(runType, str1, str2); Person me = new Person("Luca"); me.setSalary(null); @@ -2959,8 +3066,9 @@ public void testSharedBetaPredicateInformationWithMultipleFiles() { .withMessage("Error evaluating constraint '$i < salary * 20' in [Rule \"R1\", \"R2\" in r0.drl] [Rule \"R3\", \"R4\" in r1.drl]"); } - @Test - public void testSharedPredicateInformationExceedMaxRuleDefs() { + @ParameterizedTest + @MethodSource("parameters") + public void testSharedPredicateInformationExceedMaxRuleDefs(RUN_TYPE runType) { // shared by 11 rules String str1 = "import " + Person.class.getCanonicalName() + ";" + @@ -3024,7 +3132,7 @@ public void testSharedPredicateInformationExceedMaxRuleDefs() { "then\n" + "end"; - KieSession ksession = getKieSession(str1, str2, str3); + KieSession ksession = getKieSession(runType, str1, str2, str3); Person me = new Person("Luca"); me.setSalary(null); @@ -3039,8 +3147,9 @@ public void testSharedPredicateInformationExceedMaxRuleDefs() { } - @Test - public void testWithQuotedStringConcatenationOnConstraint() { + @ParameterizedTest + @MethodSource("parameters") + public void testWithQuotedStringConcatenationOnConstraint(RUN_TYPE runType) { String str = "import " + Person.class.getCanonicalName() + ";" + "rule R when\n" + @@ -3048,7 +3157,7 @@ public void testWithQuotedStringConcatenationOnConstraint() { "then\n" + "end"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); Person me = new Person( "Luca II"); me.setMoney(null); @@ -3057,8 +3166,9 @@ public void testWithQuotedStringConcatenationOnConstraint() { assertThat(rulesFired).isEqualTo(1); } - @Test - public void testNegatedConstraint() { + @ParameterizedTest + @MethodSource("parameters") + public void testNegatedConstraint(RUN_TYPE runType) { // DROOLS-5791 String str = "rule R when\n" + @@ -3067,15 +3177,16 @@ public void testNegatedConstraint() { "then\n" + "end"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); ksession.insert( 5 ); ksession.insert( "test" ); assertThat(ksession.fireAllRules()).isEqualTo(0); } - @Test - public void testMethodCallWithClass() { + @ParameterizedTest + @MethodSource("parameters") + public void testMethodCallWithClass(RUN_TYPE runType) { final String str = "package org.drools.mvel.compiler\n" + "import " + FactWithMethod.class.getCanonicalName() + ";" + "rule r1\n" + @@ -3084,7 +3195,7 @@ public void testMethodCallWithClass() { "then\n" + "end\n"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); final FactWithMethod fact = new FactWithMethod(); ksession.insert(fact); final int rules = ksession.fireAllRules(); @@ -3108,8 +3219,9 @@ default String getDefaultString() { public static class MyClass implements MyInterface { } - @Test - public void testUseDefaultMethod() { + @ParameterizedTest + @MethodSource("parameters") + public void testUseDefaultMethod(RUN_TYPE runType) { // DROOLS-6358 final String str = "package org.drools.mvel.compiler\n" + @@ -3122,7 +3234,7 @@ public void testUseDefaultMethod() { " list.add(val);" + "end\n"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); final List list = new ArrayList<>(); ksession.setGlobal("list", list); @@ -3133,8 +3245,9 @@ public void testUseDefaultMethod() { assertThat(list.get(0)).isEqualTo("DEFAULT"); } - @Test - public void testSharedConstraintWithExtraParenthesis() { + @ParameterizedTest + @MethodSource("parameters") + public void testSharedConstraintWithExtraParenthesis(RUN_TYPE runType) { // DROOLS-6548 final String str = "package org.drools.mvel.compiler\n" + @@ -3152,7 +3265,7 @@ public void testSharedConstraintWithExtraParenthesis() { " list.add(\"r2\");" + "end\n"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); final List list = new ArrayList<>(); ksession.setGlobal("list", list); @@ -3161,4 +3274,64 @@ public void testSharedConstraintWithExtraParenthesis() { assertThat(list.size()).isEqualTo(1); assertThat(list.get(0)).isEqualTo("r1"); } + + @ParameterizedTest + @MethodSource("parameters") + public void orWithMethodCall(RUN_TYPE runType) { + final String str = + "package org.example\n" + + "import " + MyFact.class.getCanonicalName() + ";" + + "rule r1 when\n" + + " MyFact( value == 10 || someMethod() == 4 )\n" + + "then\n" + + "end\n"; + + KieSession ksession = getKieSession(runType, str); + + ksession.insert(new MyFact(5)); + int fired = ksession.fireAllRules(); + assertThat(fired).isEqualTo(1); + } + + @ParameterizedTest + @MethodSource("parameters") + public void orWithMethodCallWithArg(RUN_TYPE runType) { + final String str = + "package org.example\n" + + "import " + MyFact.class.getCanonicalName() + ";" + + "rule r1 when\n" + + " MyFact( value == 10 || someMethod(2) == 4 )\n" + + "then\n" + + "end\n"; + + KieSession ksession = getKieSession(runType, str); + + ksession.insert(new MyFact(5)); + int fired = ksession.fireAllRules(); + assertThat(fired).isEqualTo(1); + } + + public static class MyFact { + private int value; + + public MyFact(int value) { + this.value = value; + } + + public int getValue() { + return value; + } + + public void setValue(int value) { + this.value = value; + } + + public int someMethod(int input) { + return input * 2; + } + + public int someMethod() { + return 4; + } + } } diff --git a/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/ComplexRulesTest.java b/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/ComplexRulesTest.java index 7853acecf99..adce0b0f321 100644 --- a/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/ComplexRulesTest.java +++ b/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/ComplexRulesTest.java @@ -20,7 +20,6 @@ import java.time.LocalDateTime; import java.util.ArrayList; -import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; @@ -41,19 +40,17 @@ import org.drools.model.codegen.execmodel.domain.Person; import org.drools.model.codegen.execmodel.domain.RootFact; import org.drools.model.codegen.execmodel.domain.SubFact; -import org.junit.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; import org.kie.api.runtime.KieSession; import static org.assertj.core.api.Assertions.assertThat; public class ComplexRulesTest extends BaseModelTest { - public ComplexRulesTest( RUN_TYPE testRunType ) { - super( testRunType ); - } - - @Test - public void test1() { + @ParameterizedTest + @MethodSource("parameters") + public void test1(RUN_TYPE runType) { String str = "import " + EnumFact1.class.getCanonicalName() + ";\n" + "import " + EnumFact2.class.getCanonicalName() + ";\n" + @@ -100,11 +97,12 @@ public void test1() { " list.add($result);\n" + "end\n"; - testComplexRule(str); + testComplexRule(runType, str); } - @Test - public void testNotWithEval() { + @ParameterizedTest + @MethodSource("parameters") + public void testNotWithEval(RUN_TYPE runType) { String str = "import " + EnumFact1.class.getCanonicalName() + ";\n" + "import " + EnumFact2.class.getCanonicalName() + ";\n" + @@ -151,11 +149,11 @@ public void testNotWithEval() { " list.add($result);\n" + "end\n"; - testComplexRule(str); + testComplexRule(runType, str); } - private void testComplexRule(final String rule) { - KieSession ksession = getKieSession( rule ); + private void testComplexRule(RUN_TYPE runType, String rule) { + KieSession ksession = getKieSession(runType, rule); List list = new ArrayList<>(); ksession.setGlobal( "list", list ); @@ -176,8 +174,9 @@ private void testComplexRule(final String rule) { assertThat((int) list.get(0)).isEqualTo(1); } - @Test - public void test2() { + @ParameterizedTest + @MethodSource("parameters") + public void test2(RUN_TYPE runType) { final String drl = " import org.drools.model.codegen.execmodel.domain.*;\n" + " rule \"R1\"\n" + @@ -200,7 +199,7 @@ public void test2() { " update($childFact4);\n" + " end\n"; - KieSession ksession = getKieSession( drl ); + KieSession ksession = getKieSession(runType, drl ); int initialId = 1; final RootFact rootFact = new RootFact(initialId); @@ -220,8 +219,9 @@ public void test2() { assertThat(ksession.fireAllRules()).isEqualTo(0); } - @Test - public void test3() { + @ParameterizedTest + @MethodSource("parameters") + public void test3(RUN_TYPE runType) { String str = "import " + RootFact.class.getCanonicalName() + ";\n" + "import " + ChildFactWithObject.class.getCanonicalName() + ";\n" + @@ -243,7 +243,7 @@ public void test3() { " list.add($result);\n" + "end\n"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); List list = new ArrayList<>(); ksession.setGlobal( "list", list ); @@ -258,8 +258,9 @@ public void test3() { assertThat((int) list.get(0)).isEqualTo(1); } - @Test - public void test4() { + @ParameterizedTest + @MethodSource("parameters") + public void test4(RUN_TYPE runType) { String str = "import " + RootFact.class.getCanonicalName() + ";\n" + "import " + ChildFactWithObject.class.getCanonicalName() + ";\n" + @@ -280,7 +281,7 @@ public void test4() { " list.add($result);\n" + "end\n"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); List list = new ArrayList<>(); ksession.setGlobal( "list", list ); @@ -294,8 +295,9 @@ public void test4() { assertThat((int) list.get(0)).isEqualTo(1); } - @Test - public void testEnum() { + @ParameterizedTest + @MethodSource("parameters") + public void testEnum(RUN_TYPE runType) { String str = "import " + EnumFact1.class.getCanonicalName() + ";\n" + "import " + ChildFactWithEnum1.class.getCanonicalName() + ";\n" + @@ -305,13 +307,14 @@ public void testEnum() { " then\n" + "end\n"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); ksession.insert( new ChildFactWithEnum1(1, 3, EnumFact1.FIRST) ); assertThat(ksession.fireAllRules()).isEqualTo(1); } - @Test - public void testNotInEnum() { + @ParameterizedTest + @MethodSource("parameters") + public void testNotInEnum(RUN_TYPE runType) { String str = "import " + EnumFact1.class.getCanonicalName() + ";\n" + "import " + ChildFactWithEnum1.class.getCanonicalName() + ";\n" + @@ -321,13 +324,14 @@ public void testNotInEnum() { " then\n" + "end\n"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); ksession.insert( new ChildFactWithEnum1(1, 3, EnumFact1.SECOND) ); assertThat(ksession.fireAllRules()).isEqualTo(1); } - @Test - public void testNotInInterfaceAsEnum() { + @ParameterizedTest + @MethodSource("parameters") + public void testNotInInterfaceAsEnum(RUN_TYPE runType) { String str = "import " + InterfaceAsEnum.class.getCanonicalName() + ";\n" + "import " + ChildFactWithEnum1.class.getCanonicalName() + ";\n" + @@ -337,13 +341,14 @@ public void testNotInInterfaceAsEnum() { " then\n" + "end\n"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); ksession.insert( new ChildFactWithEnum1(1, 3, EnumFact1.SECOND) ); assertThat(ksession.fireAllRules()).isEqualTo(1); } - @Test - public void testConstraintWithFunctionUsingThis() { + @ParameterizedTest + @MethodSource("parameters") + public void testConstraintWithFunctionUsingThis(RUN_TYPE runType) { String str = "import " + ChildFactWithObject.class.getCanonicalName() + ";\n" + "import " + BusinessFunctions.class.getCanonicalName() + ";\n" + @@ -356,14 +361,15 @@ public void testConstraintWithFunctionUsingThis() { " then\n" + "end\n"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); ksession.setGlobal( "functions", new BusinessFunctions() ); ksession.insert( new ChildFactWithObject(5, 1, new Object[0]) ); assertThat(ksession.fireAllRules()).isEqualTo(1); } - @Test - public void testConstraintWithTernaryOperator() { + @ParameterizedTest + @MethodSource("parameters") + public void testConstraintWithTernaryOperator(RUN_TYPE runType) { String str = "import " + ChildFactWithObject.class.getCanonicalName() + ";\n" + "import " + BusinessFunctions.class.getCanonicalName() + ";\n" + @@ -377,15 +383,16 @@ public void testConstraintWithTernaryOperator() { " then\n" + "end\n"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); ksession.setGlobal( "functions", new BusinessFunctions() ); ksession.insert( "test" ); ksession.insert( new ChildFactWithObject(5, 1, new Object[0]) ); assertThat(ksession.fireAllRules()).isEqualTo(1); } - @Test - public void testCastInConstraint() { + @ParameterizedTest + @MethodSource("parameters") + public void testCastInConstraint(RUN_TYPE runType) { String str = "import " + ChildFactWithObject.class.getCanonicalName() + ";\n" + "import " + BusinessFunctions.class.getCanonicalName() + ";\n" + @@ -395,14 +402,15 @@ public void testCastInConstraint() { " then\n" + "end\n"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); ksession.setGlobal( "functions", new BusinessFunctions() ); ksession.insert( new ChildFactWithObject(5, 1, new Object[0]) ); assertThat(ksession.fireAllRules()).isEqualTo(1); } - @Test - public void testConstraintWithFunctionAndStringConcatenation() { + @ParameterizedTest + @MethodSource("parameters") + public void testConstraintWithFunctionAndStringConcatenation(RUN_TYPE runType) { String str = "import " + ChildFactWithObject.class.getCanonicalName() + ";\n" + "import " + BusinessFunctions.class.getCanonicalName() + ";\n" + @@ -416,14 +424,15 @@ public void testConstraintWithFunctionAndStringConcatenation() { " then\n" + "end\n"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); ksession.setGlobal( "functions", new BusinessFunctions() ); ksession.insert( new ChildFactWithObject(5, 1, new Object[0]) ); assertThat(ksession.fireAllRules()).isEqualTo(1); } - @Test - public void testEvalWithFunction() { + @ParameterizedTest + @MethodSource("parameters") + public void testEvalWithFunction(RUN_TYPE runType) { String str = "import " + ChildFactWithObject.class.getCanonicalName() + ";\n" + "import " + BusinessFunctions.class.getCanonicalName() + ";\n" + @@ -437,14 +446,15 @@ public void testEvalWithFunction() { " then\n" + "end\n"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); ksession.setGlobal( "functions", new BusinessFunctions() ); ksession.insert( new ChildFactWithObject(5, 1, new Object[0]) ); assertThat(ksession.fireAllRules()).isEqualTo(1); } - @Test - public void testEqualOnShortField() { + @ParameterizedTest + @MethodSource("parameters") + public void testEqualOnShortField(RUN_TYPE runType) { String str = "import " + ChildFactWithObject.class.getCanonicalName() + ";\n" + "rule R when\n" + @@ -453,13 +463,14 @@ public void testEqualOnShortField() { " then\n" + "end\n"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); ksession.insert( new ChildFactWithObject(5, 1, new Object[0]) ); assertThat(ksession.fireAllRules()).isEqualTo(1); } - @Test - public void testGreaterOnShortField() { + @ParameterizedTest + @MethodSource("parameters") + public void testGreaterOnShortField(RUN_TYPE runType) { String str = "import " + ChildFactWithObject.class.getCanonicalName() + ";\n" + "rule R when\n" + @@ -468,13 +479,14 @@ public void testGreaterOnShortField() { " then\n" + "end\n"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); ksession.insert( new ChildFactWithObject(5, 1, new Object[0]) ); assertThat(ksession.fireAllRules()).isEqualTo(1); } - @Test - public void testBooleanField() { + @ParameterizedTest + @MethodSource("parameters") + public void testBooleanField(RUN_TYPE runType) { String str = "import " + ChildFactWithObject.class.getCanonicalName() + ";\n" + "rule R when\n" + @@ -483,13 +495,14 @@ public void testBooleanField() { " then\n" + "end\n"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); ksession.insert( new ChildFactWithObject(5, 1, new Object[0]) ); assertThat(ksession.fireAllRules()).isEqualTo(1); } - @Test - public void testConsequenceThrowingException() { + @ParameterizedTest + @MethodSource("parameters") + public void testConsequenceThrowingException(RUN_TYPE runType) { String str = "import " + ChildFactWithObject.class.getCanonicalName() + ";\n" + "import " + BusinessFunctions.class.getCanonicalName() + ";\n" + @@ -501,14 +514,15 @@ public void testConsequenceThrowingException() { " functions.doSomethingRisky($c);" + "end\n"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); ksession.setGlobal( "functions", new BusinessFunctions() ); ksession.insert( new ChildFactWithObject(5, 1, new Object[0]) ); assertThat(ksession.fireAllRules()).isEqualTo(1); } - @Test - public void testCompareDate() { + @ParameterizedTest + @MethodSource("parameters") + public void testCompareDate(RUN_TYPE runType) { String str = "import " + ChildFactWithObject.class.getCanonicalName() + ";\n" + "rule R when\n" + @@ -518,14 +532,15 @@ public void testCompareDate() { " then\n" + "end\n"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); ksession.insert( new ChildFactWithObject(5, 1, new Object[0]) ); ksession.insert( new ChildFactWithObject(6, 1, new Object[0]) ); assertThat(ksession.fireAllRules()).isEqualTo(1); } - @Test - public void testCompareDateWithString() { + @ParameterizedTest + @MethodSource("parameters") + public void testCompareDateWithString(RUN_TYPE runType) { String str = "import " + ChildFactWithObject.class.getCanonicalName() + ";\n" + "rule R when\n" + @@ -534,13 +549,14 @@ public void testCompareDateWithString() { " then\n" + "end\n"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); ksession.insert( new ChildFactWithObject(5, 1, new Object[0]) ); assertThat(ksession.fireAllRules()).isEqualTo(1); } - @Test - public void test2UpperCaseProp() { + @ParameterizedTest + @MethodSource("parameters") + public void test2UpperCaseProp(RUN_TYPE runType) { String str = "import " + ChildFactWithObject.class.getCanonicalName() + ";\n" + "rule R when\n" + @@ -550,7 +566,7 @@ public void test2UpperCaseProp() { " then\n" + "end\n"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); ksession.insert( new ChildFactWithObject(5, 1, new Object[0]) ); assertThat(ksession.fireAllRules()).isEqualTo(1); } @@ -571,8 +587,9 @@ public List getList() { } } - @Test - public void testNameClashBetweenAttributeAndGlobal() { + @ParameterizedTest + @MethodSource("parameters") + public void testNameClashBetweenAttributeAndGlobal(RUN_TYPE runType) { String str = "import " + ListContainer.class.getCanonicalName() + ";\n" + "global java.util.List list;\n" + @@ -582,7 +599,7 @@ public void testNameClashBetweenAttributeAndGlobal() { " list.add($l);" + "end\n"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); List list = new ArrayList(); ksession.setGlobal( "list", list ); @@ -598,8 +615,9 @@ public char[] getCharArray() { } } - @Test - public void testPrimitiveArray() { + @ParameterizedTest + @MethodSource("parameters") + public void testPrimitiveArray(RUN_TYPE runType) { String str = "import " + Primitives.class.getCanonicalName() + ";\n" + "global java.util.List list;\n" + @@ -609,7 +627,7 @@ public void testPrimitiveArray() { " list.add($c);" + "end\n"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); List list = new ArrayList(); ksession.setGlobal( "list", list ); @@ -619,8 +637,9 @@ public void testPrimitiveArray() { assertThat(list.size()).isEqualTo(1); } - @Test - public void testUseConstructorInConstraint() { + @ParameterizedTest + @MethodSource("parameters") + public void testUseConstructorInConstraint(RUN_TYPE runType) { // DROOLS-2990 String str = "rule R when\n" + @@ -629,15 +648,16 @@ public void testUseConstructorInConstraint() { "then\n" + "end\n"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); ksession.insert( (short) 1 ); ksession.insert( 2.0 ); assertThat(ksession.fireAllRules()).isEqualTo(1); } - @Test - public void testManyPropFactWithNot() { + @ParameterizedTest + @MethodSource("parameters") + public void testManyPropFactWithNot(RUN_TYPE runType) { // DROOLS-4572 try { System.setProperty("drools.propertySpecific", "ALLOWED"); @@ -660,7 +680,7 @@ public void testManyPropFactWithNot() { " update($subFact);\n" + "end"; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); ManyPropFact fact = new ManyPropFact(); fact.setId(1); @@ -698,8 +718,9 @@ public CaseData getMe() { } } - @Test - public void testGetOnMapField() { + @ParameterizedTest + @MethodSource("parameters") + public void testGetOnMapField(RUN_TYPE runType) { // DROOLS-4999 String str = "import " + CaseData.class.getCanonicalName() + ";\n" + @@ -708,15 +729,16 @@ public void testGetOnMapField() { "then\n" + "end\n"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); ksession.insert( new CaseData( 5 ) ); assertThat(ksession.fireAllRules()).isEqualTo(1); } - @Test - public void testEqualsOnMapField() { + @ParameterizedTest + @MethodSource("parameters") + public void testEqualsOnMapField(RUN_TYPE runType) { // DROOLS-4999 String str = "import " + CaseData.class.getCanonicalName() + ";\n" + @@ -725,15 +747,16 @@ public void testEqualsOnMapField() { "then\n" + "end\n"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); ksession.insert( new CaseData( "OK" ) ); assertThat(ksession.fireAllRules()).isEqualTo(1); } - @Test - public void testDoubleNegation() { + @ParameterizedTest + @MethodSource("parameters") + public void testDoubleNegation(RUN_TYPE runType) { // DROOLS-5545 String str = "import " + Person.class.getCanonicalName() + ";\n" + @@ -742,13 +765,14 @@ public void testDoubleNegation() { "then\n" + "end\n"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); ksession.insert( new Person( "Mario", 45 ) ); assertThat(ksession.fireAllRules()).isEqualTo(1); } - @Test - public void testGlobalAsFunctionArgument() { + @ParameterizedTest + @MethodSource("parameters") + public void testGlobalAsFunctionArgument(RUN_TYPE runType) { // DROOLS-5999 String str = "import java.util.*;\n"+ @@ -773,7 +797,7 @@ public void testGlobalAsFunctionArgument() { " result.add(Integer.valueOf(42));\n"+ "end\n"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); List result = new ArrayList<>(); ksession.setGlobal("result", result); diff --git a/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/ConditionalExprTest.java b/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/ConditionalExprTest.java index a8d5908248c..5b08b24674c 100644 --- a/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/ConditionalExprTest.java +++ b/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/ConditionalExprTest.java @@ -22,8 +22,10 @@ import java.util.List; import org.drools.model.codegen.execmodel.domain.Person; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; import org.kie.api.runtime.KieSession; import static org.assertj.core.api.Assertions.assertThat; @@ -47,41 +49,40 @@ public class ConditionalExprTest extends BaseModelTest { private KieSession ksession; private List booleanListGlobal; - public ConditionalExprTest(RUN_TYPE testRunType) { - super(testRunType); - } - - @Before + @BeforeEach public void setup() { - ksession = getKieSession(RULE_STRING); booleanListGlobal = new ArrayList<>(); - ksession.setGlobal("booleanListGlobal", booleanListGlobal); + } + + @AfterEach + public void tearDown() { + if (ksession != null) { + ksession.dispose(); + } } - @Test - public void testConditionalExpressionWithNamedPerson() { - try { - Person person = new Person("someName"); - ksession.insert(person); - int rulesFired = ksession.fireAllRules(); - assertThat(rulesFired).isEqualTo(1); - assertThat(booleanListGlobal).isNotEmpty().containsExactly(Boolean.TRUE); - } finally { - ksession.dispose(); - } + @ParameterizedTest + @MethodSource("parameters") + public void testConditionalExpressionWithNamedPerson(RUN_TYPE runType) { + ksession = getKieSession(runType, RULE_STRING); + ksession.setGlobal("booleanListGlobal", booleanListGlobal); + Person person = new Person("someName"); + ksession.insert(person); + int rulesFired = ksession.fireAllRules(); + assertThat(rulesFired).isEqualTo(1); + assertThat(booleanListGlobal).isNotEmpty().containsExactly(Boolean.TRUE); } - @Test - public void testConditionalExpressionWithUnnamedPerson() { - try { - Person person = new Person(); - ksession.insert(person); - int rulesFired = ksession.fireAllRules(); - assertThat(rulesFired).isEqualTo(1); - assertThat(booleanListGlobal).isNotEmpty().containsExactly(Boolean.FALSE); - } finally { - ksession.dispose(); - } + @ParameterizedTest + @MethodSource("parameters") + public void testConditionalExpressionWithUnnamedPerson(RUN_TYPE runType) { + ksession = getKieSession(runType, RULE_STRING); + ksession.setGlobal("booleanListGlobal", booleanListGlobal); + Person person = new Person(); + ksession.insert(person); + int rulesFired = ksession.fireAllRules(); + assertThat(rulesFired).isEqualTo(1); + assertThat(booleanListGlobal).isNotEmpty().containsExactly(Boolean.FALSE); } } \ No newline at end of file diff --git a/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/ConstraintNormalizationTest.java b/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/ConstraintNormalizationTest.java index 939722b9bee..058242c8cc5 100644 --- a/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/ConstraintNormalizationTest.java +++ b/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/ConstraintNormalizationTest.java @@ -32,7 +32,8 @@ import org.drools.model.codegen.execmodel.domain.Address; import org.drools.model.codegen.execmodel.domain.Person; import org.drools.model.codegen.execmodel.domain.Toy; -import org.junit.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; import org.kie.api.definition.type.FactType; import org.kie.api.runtime.KieSession; @@ -40,12 +41,9 @@ public class ConstraintNormalizationTest extends BaseModelTest { - public ConstraintNormalizationTest(RUN_TYPE testRunType) { - super(testRunType); - } - - @Test - public void testNormalizationForPropertyReactivity() { + @ParameterizedTest + @MethodSource("parameters") + public void testNormalizationForPropertyReactivity(RUN_TYPE runType) { final String str = "package org.drools.test;\n" + "import " + Person.class.getCanonicalName() + ";\n" + @@ -62,7 +60,7 @@ public void testNormalizationForPropertyReactivity() { "then\n" + "end\n"; - final KieSession ksession = getKieSession(str); + final KieSession ksession = getKieSession(runType, str); final Toy t = new Toy("Ball"); t.setOwner("Toshiya"); @@ -72,8 +70,9 @@ public void testNormalizationForPropertyReactivity() { assertThat(ksession.fireAllRules(10)).isEqualTo(2); // no infinite loop } - @Test - public void testNormalizationForPropertyReactivity2() { + @ParameterizedTest + @MethodSource("parameters") + public void testNormalizationForPropertyReactivity2(RUN_TYPE runType) { final String str = "package org.drools.test;\n" + "import " + Person.class.getCanonicalName() + ";\n" + @@ -89,7 +88,7 @@ public void testNormalizationForPropertyReactivity2() { "then\n" + "end\n"; - final KieSession ksession = getKieSession(str); + final KieSession ksession = getKieSession(runType, str); final Person p = new Person("Toshiya", 45); ksession.insert(new Integer(30)); @@ -97,8 +96,9 @@ public void testNormalizationForPropertyReactivity2() { assertThat(ksession.fireAllRules(10)).isEqualTo(2); // no infinite loop } - @Test - public void testNormalizationForAlphaIndexing() { + @ParameterizedTest + @MethodSource("parameters") + public void testNormalizationForAlphaIndexing(RUN_TYPE runType) { final String str = "package org.drools.test;\n" + "import " + Person.class.getCanonicalName() + ";\n" + @@ -115,7 +115,7 @@ public void testNormalizationForAlphaIndexing() { "then\n" + "end\n"; - final KieSession ksession = getKieSession(str); + final KieSession ksession = getKieSession(runType, str); ObjectTypeNode otn = ((NamedEntryPoint) ksession.getEntryPoint("DEFAULT")).getEntryPointNode().getObjectTypeNodes().entrySet() .stream() @@ -134,8 +134,9 @@ public void testNormalizationForAlphaIndexing() { assertThat(ksession.fireAllRules()).isEqualTo(1); } - @Test - public void testNormalizationForNodeSharing() { + @ParameterizedTest + @MethodSource("parameters") + public void testNormalizationForNodeSharing(RUN_TYPE runType) { final String str = "package org.drools.test;\n" + @@ -149,7 +150,7 @@ public void testNormalizationForNodeSharing() { "then\n" + "end\n"; - final KieSession ksession = getKieSession(str); + final KieSession ksession = getKieSession(runType, str); assertThat(ReteDumper.collectNodes(ksession).stream().filter(AlphaNode.class::isInstance).count()).isEqualTo(1); @@ -158,8 +159,9 @@ public void testNormalizationForNodeSharing() { assertThat(ksession.fireAllRules()).isEqualTo(2); } - @Test - public void testOperators() throws Exception { + @ParameterizedTest + @MethodSource("parameters") + public void testOperators(RUN_TYPE runType) throws Exception { final String str = "package org.drools.test;\n" + @@ -176,7 +178,7 @@ public void testOperators() throws Exception { "then\n" + "end"; - final KieSession ksession = getKieSession(str); + final KieSession ksession = getKieSession(runType, str); // Check NodeSharing to verify if normalization works expectedly assertThat(ReteDumper.collectNodes(ksession).stream().filter(AlphaNode.class::isInstance).count()).isEqualTo(4); @@ -189,8 +191,9 @@ public void testOperators() throws Exception { assertThat(ksession.fireAllRules()).isEqualTo(2); } - @Test - public void testNestedProperty() throws Exception { + @ParameterizedTest + @MethodSource("parameters") + public void testNestedProperty(RUN_TYPE runType) throws Exception { final String str = "package org.drools.test;\n" + "import " + Person.class.getCanonicalName() + ";\n" + @@ -204,7 +207,7 @@ public void testNestedProperty() throws Exception { "then\n" + "end"; - final KieSession ksession = getKieSession(str); + final KieSession ksession = getKieSession(runType, str); // Check NodeSharing to verify if normalization works expectedly assertThat(ReteDumper.collectNodes(ksession).stream().filter(AlphaNode.class::isInstance).count()).isEqualTo(1); @@ -216,8 +219,9 @@ public void testNestedProperty() throws Exception { assertThat(ksession.fireAllRules()).isEqualTo(2); } - @Test - public void testComplexMethod() throws Exception { + @ParameterizedTest + @MethodSource("parameters") + public void testComplexMethod(RUN_TYPE runType) throws Exception { final String str = "package org.drools.test;\n" + "import " + Person.class.getCanonicalName() + ";\n" + @@ -232,7 +236,7 @@ public void testComplexMethod() throws Exception { "then\n" + "end"; - final KieSession ksession = getKieSession(str); + final KieSession ksession = getKieSession(runType, str); // Check NodeSharing to verify if normalization works expectedly assertThat(ReteDumper.collectNodes(ksession).stream().filter(AlphaNode.class::isInstance).count()).isEqualTo(1); @@ -244,8 +248,9 @@ public void testComplexMethod() throws Exception { assertThat(ksession.fireAllRules()).isEqualTo(2); } - @Test - public void testPropsOnBothSide() throws Exception { + @ParameterizedTest + @MethodSource("parameters") + public void testPropsOnBothSide(RUN_TYPE runType) throws Exception { final String str = "package org.drools.test;\n" + "import " + Person.class.getCanonicalName() + ";\n" + @@ -259,7 +264,7 @@ public void testPropsOnBothSide() throws Exception { "then\n" + "end"; - final KieSession ksession = getKieSession(str); + final KieSession ksession = getKieSession(runType, str); // Check NodeSharing to verify if normalization works expectedly assertThat(ReteDumper.collectNodes(ksession).stream().filter(AlphaNode.class::isInstance).count()).isEqualTo(1); @@ -271,8 +276,9 @@ public void testPropsOnBothSide() throws Exception { assertThat(ksession.fireAllRules()).isEqualTo(2); } - @Test - public void testExtraParentheses() throws Exception { + @ParameterizedTest + @MethodSource("parameters") + public void testExtraParentheses(RUN_TYPE runType) throws Exception { final String str = "package org.drools.test;\n" + "import " + Person.class.getCanonicalName() + ";\n" + @@ -286,7 +292,7 @@ public void testExtraParentheses() throws Exception { "then\n" + "end"; - final KieSession ksession = getKieSession(str); + final KieSession ksession = getKieSession(runType, str); // Check NodeSharing to verify if normalization works expectedly assertThat(ReteDumper.collectNodes(ksession).stream().filter(AlphaNode.class::isInstance).count()).isEqualTo(1); @@ -297,8 +303,9 @@ public void testExtraParentheses() throws Exception { assertThat(ksession.fireAllRules()).isEqualTo(2); } - @Test - public void testAnd() throws Exception { + @ParameterizedTest + @MethodSource("parameters") + public void testAnd(RUN_TYPE runType) throws Exception { final String str = "package org.drools.test;\n" + "import " + Person.class.getCanonicalName() + ";\n" + @@ -312,10 +319,10 @@ public void testAnd() throws Exception { "then\n" + "end\n"; - final KieSession ksession = getKieSession(str); + final KieSession ksession = getKieSession(runType, str); // Check NodeSharing to verify if normalization works expectedly - if (testRunType == RUN_TYPE.STANDARD_FROM_DRL || testRunType == RUN_TYPE.STANDARD_WITH_ALPHA_NETWORK) { + if (runType == RUN_TYPE.STANDARD_FROM_DRL || runType == RUN_TYPE.STANDARD_WITH_ALPHA_NETWORK) { assertThat(ReteDumper.collectNodes(ksession).stream().filter(AlphaNode.class::isInstance).count()).isEqualTo(2); } else { // && is not split in case of executable-model @@ -329,8 +336,9 @@ public void testAnd() throws Exception { assertThat(ksession.fireAllRules()).isEqualTo(2); } - @Test - public void testOr() throws Exception { + @ParameterizedTest + @MethodSource("parameters") + public void testOr(RUN_TYPE runType) throws Exception { final String str = "package org.drools.test;\n" + "import " + Person.class.getCanonicalName() + ";\n" + @@ -344,7 +352,7 @@ public void testOr() throws Exception { "then\n" + "end"; - final KieSession ksession = getKieSession(str); + final KieSession ksession = getKieSession(runType, str); // Check NodeSharing to verify if normalization works expectedly assertThat(ReteDumper.collectNodes(ksession).stream().filter(AlphaNode.class::isInstance).count()).isEqualTo(1); @@ -356,8 +364,9 @@ public void testOr() throws Exception { assertThat(ksession.fireAllRules()).isEqualTo(2); } - @Test - public void testNegate() throws Exception { + @ParameterizedTest + @MethodSource("parameters") + public void testNegate(RUN_TYPE runType) throws Exception { final String str = "package org.drools.test;\n" + "import " + Person.class.getCanonicalName() + ";\n" + @@ -371,7 +380,7 @@ public void testNegate() throws Exception { "then\n" + "end"; - final KieSession ksession = getKieSession(str); + final KieSession ksession = getKieSession(runType, str); // Check NodeSharing to verify if normalization works expectedly assertThat(ReteDumper.collectNodes(ksession).stream().filter(AlphaNode.class::isInstance).count()).isEqualTo(1); @@ -382,8 +391,9 @@ public void testNegate() throws Exception { assertThat(ksession.fireAllRules()).isEqualTo(2); } - @Test - public void testBigDecimal() throws Exception { + @ParameterizedTest + @MethodSource("parameters") + public void testBigDecimal(RUN_TYPE runType) throws Exception { String str = "import " + Person.class.getCanonicalName() + ";" + "rule R1 when\n" + @@ -396,7 +406,7 @@ public void testBigDecimal() throws Exception { "then\n" + "end"; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); // Check NodeSharing to verify if normalization works expectedly assertThat(ReteDumper.collectNodes(ksession).stream().filter(AlphaNode.class::isInstance).count()).isEqualTo(1); @@ -409,8 +419,9 @@ public void testBigDecimal() throws Exception { assertThat(ksession.fireAllRules()).isEqualTo(2); } - @Test - public void testNegateComplex() throws Exception { + @ParameterizedTest + @MethodSource("parameters") + public void testNegateComplex(RUN_TYPE runType) throws Exception { String str = "import " + Person.class.getCanonicalName() + ";" + "global java.util.List list;\n" + @@ -426,7 +437,7 @@ public void testNegateComplex() throws Exception { " list.add($p.getName());" + "end"; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); // Check NodeSharing to verify if normalization works expectedly assertThat(ReteDumper.collectNodes(ksession).stream().filter(AlphaNode.class::isInstance).count()).isEqualTo(1); @@ -449,8 +460,9 @@ public void testNegateComplex() throws Exception { assertThat(list).containsExactlyInAnyOrder("John", "George", "John", "George"); } - @Test - public void testNegateComplex2() throws Exception { + @ParameterizedTest + @MethodSource("parameters") + public void testNegateComplex2(RUN_TYPE runType) throws Exception { String str = "import " + Person.class.getCanonicalName() + ";" + "global java.util.List list;\n" + @@ -466,7 +478,7 @@ public void testNegateComplex2() throws Exception { " list.add($p.getName());" + "end"; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); // Check NodeSharing to verify if normalization works expectedly assertThat(ReteDumper.collectNodes(ksession).stream().filter(AlphaNode.class::isInstance).count()).isEqualTo(1); @@ -489,8 +501,9 @@ public void testNegateComplex2() throws Exception { assertThat(list).containsExactlyInAnyOrder("John", "George", "John", "George"); } - @Test - public void testDeclaredType() throws Exception { + @ParameterizedTest + @MethodSource("parameters") + public void testDeclaredType(RUN_TYPE runType) throws Exception { final String str = "package org.drools.test;\n" + "declare Person\n" + @@ -507,7 +520,7 @@ public void testDeclaredType() throws Exception { "then\n" + "end"; - final KieSession ksession = getKieSession(str); + final KieSession ksession = getKieSession(runType, str); // Check NodeSharing to verify if normalization works expectedly assertThat(ReteDumper.collectNodes(ksession).stream().filter(AlphaNode.class::isInstance).count()).isEqualTo(2); @@ -520,8 +533,9 @@ public void testDeclaredType() throws Exception { assertThat(ksession.fireAllRules()).isEqualTo(2); } - @Test - public void testMapProp() throws Exception { + @ParameterizedTest + @MethodSource("parameters") + public void testMapProp(RUN_TYPE runType) throws Exception { final String str = "package org.drools.test;\n" + "import " + Person.class.getCanonicalName() + ";\n" + @@ -535,7 +549,7 @@ public void testMapProp() throws Exception { "then\n" + "end"; - final KieSession ksession = getKieSession(str); + final KieSession ksession = getKieSession(runType, str); // Check NodeSharing to verify if normalization works expectedly assertThat(ReteDumper.collectNodes(ksession).stream().filter(AlphaNode.class::isInstance).count()).isEqualTo(1); @@ -547,8 +561,9 @@ public void testMapProp() throws Exception { assertThat(ksession.fireAllRules()).isEqualTo(2); } - @Test - public void testMapStringProp() throws Exception { + @ParameterizedTest + @MethodSource("parameters") + public void testMapStringProp(RUN_TYPE runType) throws Exception { final String str = "package org.drools.test;\n" + "import " + Person.class.getCanonicalName() + ";\n" + @@ -562,7 +577,7 @@ public void testMapStringProp() throws Exception { "then\n" + "end"; - final KieSession ksession = getKieSession(str); + final KieSession ksession = getKieSession(runType, str); // Check NodeSharing to verify if normalization works expectedly assertThat(ReteDumper.collectNodes(ksession).stream().filter(AlphaNode.class::isInstance).count()).isEqualTo(1); @@ -574,8 +589,9 @@ public void testMapStringProp() throws Exception { assertThat(ksession.fireAllRules()).isEqualTo(2); } - @Test - public void testMapStringThis() throws Exception { + @ParameterizedTest + @MethodSource("parameters") + public void testMapStringThis(RUN_TYPE runType) throws Exception { final String str = "package org.drools.test;\n" + "import " + Map.class.getCanonicalName() + ";\n" + @@ -589,7 +605,7 @@ public void testMapStringThis() throws Exception { "then\n" + "end"; - final KieSession ksession = getKieSession(str); + final KieSession ksession = getKieSession(runType, str); // Check NodeSharing to verify if normalization works expectedly assertThat(ReteDumper.collectNodes(ksession).stream().filter(AlphaNode.class::isInstance).count()).isEqualTo(1); diff --git a/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/ConstraintTest.java b/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/ConstraintTest.java index b3475e58c2d..5eced33ee03 100644 --- a/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/ConstraintTest.java +++ b/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/ConstraintTest.java @@ -23,8 +23,10 @@ import java.util.List; import org.drools.model.codegen.execmodel.domain.Person; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; import org.kie.api.runtime.KieSession; import static org.assertj.core.api.Assertions.assertThat; @@ -50,41 +52,40 @@ public class ConstraintTest extends BaseModelTest { private List bigDecimalListGlobal; - public ConstraintTest(RUN_TYPE testRunType) { - super(testRunType); - } - - @Before + @BeforeEach public void setup() { - ksession = getKieSession(RULE_STRING); bigDecimalListGlobal = new ArrayList<>(); - ksession.setGlobal("bigDecimalListGlobal", bigDecimalListGlobal); + } + + @AfterEach + public void tearDown() { + if (ksession != null) { + ksession.dispose(); + } } - @Test - public void testConstraintWithMoney() { - try { - BigDecimal money = BigDecimal.valueOf(34.45); - Person person = new Person("", money); - ksession.insert(person); - int rulesFired = ksession.fireAllRules(); - assertThat(rulesFired).isEqualTo(1); - assertThat(bigDecimalListGlobal).isNotEmpty().containsExactly(money); - } finally { - ksession.dispose(); - } + @ParameterizedTest + @MethodSource("parameters") + public void testConstraintWithMoney(RUN_TYPE runType) { + ksession = getKieSession(runType, RULE_STRING); + ksession.setGlobal("bigDecimalListGlobal", bigDecimalListGlobal); + BigDecimal money = BigDecimal.valueOf(34.45); + Person person = new Person("", money); + ksession.insert(person); + int rulesFired = ksession.fireAllRules(); + assertThat(rulesFired).isEqualTo(1); + assertThat(bigDecimalListGlobal).isNotEmpty().containsExactly(money); } - @Test - public void testConstraintWithoutMoney() { - try { - Person person = new Person(); - ksession.insert(person); - int rulesFired = ksession.fireAllRules(); - assertThat(rulesFired).isEqualTo(1); - assertThat(bigDecimalListGlobal).isNotEmpty().containsExactly(BigDecimal.valueOf(100.0)); - } finally { - ksession.dispose(); - } + @ParameterizedTest + @MethodSource("parameters") + public void testConstraintWithoutMoney(RUN_TYPE runType) { + ksession = getKieSession(runType, RULE_STRING); + ksession.setGlobal("bigDecimalListGlobal", bigDecimalListGlobal); + Person person = new Person(); + ksession.insert(person); + int rulesFired = ksession.fireAllRules(); + assertThat(rulesFired).isEqualTo(1); + assertThat(bigDecimalListGlobal).isNotEmpty().containsExactly(BigDecimal.valueOf(100.0)); } } diff --git a/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/CustomConstraintOperatorTest.java b/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/CustomConstraintOperatorTest.java index d1b5c6f7768..4a5ad46f851 100644 --- a/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/CustomConstraintOperatorTest.java +++ b/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/CustomConstraintOperatorTest.java @@ -37,7 +37,7 @@ import org.drools.model.prototype.PrototypeVariable; import org.drools.modelcompiler.KieBaseBuilder; import org.drools.modelcompiler.constraints.LambdaConstraint; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.kie.api.KieBase; import org.kie.api.prototype.PrototypeFact; import org.kie.api.prototype.PrototypeFactInstance; diff --git a/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/DeclaredTypeDifferentKJarIncludesTest.java b/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/DeclaredTypeDifferentKJarIncludesTest.java index a51146f0c5b..26d837003a5 100644 --- a/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/DeclaredTypeDifferentKJarIncludesTest.java +++ b/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/DeclaredTypeDifferentKJarIncludesTest.java @@ -20,8 +20,9 @@ import org.drools.compiler.kie.builder.impl.DrlProject; import org.drools.model.codegen.ExecutableModelProject; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; import org.drools.io.ByteArrayResource; -import org.junit.Test; import org.kie.api.KieBase; import org.kie.api.KieServices; import org.kie.api.builder.KieBuilder; @@ -49,9 +50,6 @@ public class DeclaredTypeDifferentKJarIncludesTest extends BaseModelTest { private final String SUPER_KBASE_PACKAGE = "org.superkbase"; private final ReleaseIdImpl SUPER_RELEASE_ID = new ReleaseIdImpl(SUPER_KBASE_PACKAGE, "superkbase", "1.0.0"); - public DeclaredTypeDifferentKJarIncludesTest(RUN_TYPE testRunType) { - super(testRunType); - } private static final String SUPER_RULE = "package org.superkbase;\n" + "\n" + @@ -80,9 +78,10 @@ public DeclaredTypeDifferentKJarIncludesTest(RUN_TYPE testRunType) { " delete($s);\n" + "end\n"; - @Test - public void testChildIncludingSuper() { - KieBase kBase = createKieBase(); + @ParameterizedTest + @MethodSource("parameters") + public void testChildIncludingSuper(RUN_TYPE runType) { + KieBase kBase = createKieBase(runType); KieSession newSuperKieBase = kBase.newKieSession(); newSuperKieBase.insert(10); @@ -92,16 +91,16 @@ public void testChildIncludingSuper() { assertThat(newSuperKieBase.getObjects().size()).isEqualTo(0); } - private KieBase createKieBase() { + private KieBase createKieBase(RUN_TYPE runType) { KieServices kieServices = KieServices.Factory.get(); - superKieBase(kieServices); - childKieBase(kieServices); + superKieBase(kieServices, runType); + childKieBase(kieServices, runType); return kieServices.newKieContainer(CHILD_RELEASE_ID).getKieBase(CHILD_KBASE_NAME); } - private void superKieBase(KieServices kieServices) { + private void superKieBase(KieServices kieServices, RUN_TYPE runType) { KieModuleModel superKModule = kieServices.newKieModuleModel(); KieBaseModel superKieBase = superKModule.newKieBaseModel(SUPER_KBASE_NAME); @@ -116,10 +115,10 @@ private void superKieBase(KieServices kieServices) { superFileSystem.writeKModuleXML(superKModule.toXML()); superFileSystem.write("pom.xml", generatePomXmlWithDependencies(SUPER_RELEASE_ID)); - kieServices.newKieBuilder(superFileSystem).buildAll(buildProjectClass()); + kieServices.newKieBuilder(superFileSystem).buildAll(buildProjectClass(runType)); } - private void childKieBase(KieServices kieServices) { + private void childKieBase(KieServices kieServices, RUN_TYPE runType) { KieModuleModel childKModule = kieServices.newKieModuleModel(); KieBaseModel childKbase = childKModule.newKieBaseModel(CHILD_KBASE_NAME) .setDefault(true) @@ -135,7 +134,7 @@ private void childKieBase(KieServices kieServices) { childFileSystem.writeKModuleXML(childKModule.toXML()); childFileSystem.write("pom.xml", generatePomXmlWithDependencies(CHILD_RELEASE_ID, SUPER_RELEASE_ID)); - kieServices.newKieBuilder(childFileSystem).buildAll(buildProjectClass()); + kieServices.newKieBuilder(childFileSystem).buildAll(buildProjectClass(runType)); } private static String generatePomXmlWithDependencies(ReleaseId releaseId, ReleaseId... dependencies) { @@ -176,8 +175,8 @@ private static void toGAV(ReleaseId releaseId, StringBuilder sBuilder) { sBuilder.append(" \n"); } - private Class buildProjectClass() { - if (asList(PATTERN_DSL, PATTERN_WITH_ALPHA_NETWORK).contains(testRunType)) { + private Class buildProjectClass(RUN_TYPE runType) { + if (asList(PATTERN_DSL, PATTERN_WITH_ALPHA_NETWORK).contains(runType)) { return ExecutableModelProject.class; } else { return DrlProject.class; diff --git a/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/DeclaredTypesTest.java b/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/DeclaredTypesTest.java index 664ae7534ed..a6d4ba52f95 100644 --- a/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/DeclaredTypesTest.java +++ b/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/DeclaredTypesTest.java @@ -35,7 +35,8 @@ import org.drools.base.rule.constraint.AlphaNodeFieldConstraint; import org.drools.model.codegen.execmodel.domain.Person; import org.drools.model.codegen.execmodel.domain.Result; -import org.junit.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; import org.kie.api.KieBase; import org.kie.api.definition.type.FactType; import org.kie.api.runtime.KieSession; @@ -44,12 +45,9 @@ public class DeclaredTypesTest extends BaseModelTest { - public DeclaredTypesTest(RUN_TYPE testRunType ) { - super( testRunType ); - } - - @Test - public void testPojo() throws Exception { + @ParameterizedTest + @MethodSource("parameters") + public void testPojo(RUN_TYPE runType) throws Exception { String str = "import " + Result.class.getCanonicalName() + ";" + "import " + Person.class.getCanonicalName() + ";" + @@ -67,7 +65,7 @@ public void testPojo() throws Exception { " insert(new Result(p));\n" + "end"; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); ksession.insert(new Person("Mario", 40)); ksession.insert(new Person("Mark", 37)); @@ -98,8 +96,9 @@ public void testPojo() throws Exception { assertThat(luca.toString()).isEqualTo("POJOPerson( name=Luca, surname=null, age=32 )"); } - @Test - public void testPojoInDifferentPackages() throws Exception { + @ParameterizedTest + @MethodSource("parameters") + public void testPojoInDifferentPackages(RUN_TYPE runType) throws Exception { String ruleWithPojo = "package org.drools.pojo.model;" + "\n" + @@ -128,7 +127,7 @@ public void testPojoInDifferentPackages() throws Exception { " insert(new Result($p));\n" + "end\n"; - KieSession ksession = getKieSession(rule, ruleWithPojo); + KieSession ksession = getKieSession(runType, rule, ruleWithPojo); ksession.insert(new Person("Mario", 40)); ksession.insert(new Person("Mark", 37)); @@ -159,8 +158,9 @@ public void testPojoInDifferentPackages() throws Exception { assertThat(luca.toString()).isEqualTo("POJOPerson( name=Luca, surname=null, age=32 )"); } - @Test - public void testPojoReferencingEachOthers() throws Exception { + @ParameterizedTest + @MethodSource("parameters") + public void testPojoReferencingEachOthers(RUN_TYPE runType) throws Exception { String factA = "package org.kie.test;" + "\n" + @@ -183,13 +183,14 @@ public void testPojoReferencingEachOthers() throws Exception { "then\n" + "end"; - KieSession ksession = getKieSession(rule, factA, factB); + KieSession ksession = getKieSession(runType, rule, factA, factB); ksession.fireAllRules(); } - @Test - public void testDeclaredTypeInLhs() throws Exception { + @ParameterizedTest + @MethodSource("parameters") + public void testDeclaredTypeInLhs(RUN_TYPE runType) throws Exception { String str = "import " + Result.class.getCanonicalName() + ";" + "import " + Person.class.getCanonicalName() + ";" + @@ -212,7 +213,7 @@ public void testDeclaredTypeInLhs() throws Exception { " insert(new Result($p));\n" + "end\n"; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); ksession.insert(new Person("Mario", 40)); ksession.insert(new Person("Mark", 37)); @@ -265,8 +266,9 @@ public String toString() { } } - @Test - public void testPojoPredicateIsUsedAsConstraint() { + @ParameterizedTest + @MethodSource("parameters") + public void testPojoPredicateIsUsedAsConstraint(RUN_TYPE runType) { String str = "import " + MyNumber.class.getCanonicalName() + ";" + "rule R when\n" + " MyNumber(even, $value : value)" + @@ -274,7 +276,7 @@ public void testPojoPredicateIsUsedAsConstraint() { " insert($value);\n" + "end"; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); ksession.insert(new MyNumber(2)); ksession.fireAllRules(); @@ -290,8 +292,9 @@ public void testPojoPredicateIsUsedAsConstraint() { assertThat(results.contains(1)).isFalse(); // This is because MyNumber(1) would fail for "even" predicate/getter used here in pattern as a constraint. } - @Test - public void testPojoPredicateIsUsedAsConstraintOK() { + @ParameterizedTest + @MethodSource("parameters") + public void testPojoPredicateIsUsedAsConstraintOK(RUN_TYPE runType) { String str = "import " + MyNumber.class.getCanonicalName() + ";" + "rule R when\n" + " $n : MyNumber(even, $value : value)" + @@ -299,7 +302,7 @@ public void testPojoPredicateIsUsedAsConstraintOK() { " insert($value);\n" + "end"; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); ksession.insert(new MyNumber(2)); ksession.fireAllRules(); @@ -315,8 +318,9 @@ public void testPojoPredicateIsUsedAsConstraintOK() { assertThat(results.contains(1)).isFalse(); // This is because MyNumber(1) would fail for "even" predicate/getter used here in pattern as a constraint. } - @Test - public void testBindingOfPredicateIsNotUsedAsConstraint() { + @ParameterizedTest + @MethodSource("parameters") + public void testBindingOfPredicateIsNotUsedAsConstraint(RUN_TYPE runType) { String str = "import " + MyNumber.class.getCanonicalName() + ";" + "rule R when\n" + " MyNumber($even : even, $value : value)" + @@ -324,7 +328,7 @@ public void testBindingOfPredicateIsNotUsedAsConstraint() { " insert($value);\n" + "end"; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); ksession.insert(new MyNumber(2)); ksession.fireAllRules(); @@ -340,8 +344,9 @@ public void testBindingOfPredicateIsNotUsedAsConstraint() { assertThat(results.contains(1)).isTrue(); // This is because MyNumber(1) would simply bind for "even" predicate/getter to $even variable, and not used as a constraint. } - @Test - public void testDeclaredWithAllPrimitives() { + @ParameterizedTest + @MethodSource("parameters") + public void testDeclaredWithAllPrimitives(RUN_TYPE runType) { String str = "declare DeclaredAllPrimitives\n" + " my_byte : byte \n" + " my_short : short \n" + @@ -358,7 +363,7 @@ public void testDeclaredWithAllPrimitives() { " insert(new DeclaredAllPrimitives((byte) 1, (short) 1, 1, 1L, 1f, 1d, 'x', true));\n" + "end"; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); ksession.fireAllRules(); @@ -366,8 +371,9 @@ public void testDeclaredWithAllPrimitives() { assertThat(results.size()).isEqualTo(1); } - @Test - public void testFactType() throws Exception { + @ParameterizedTest + @MethodSource("parameters") + public void testFactType(RUN_TYPE runType) throws Exception { // DROOLS-4784 String str = "package org.test;\n" + @@ -381,7 +387,7 @@ public void testFactType() throws Exception { " insert($v);" + "end"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); FactType nameType = ksession.getKieBase().getFactType("org.test", "Name"); Object name = nameType.newInstance(); @@ -408,8 +414,9 @@ public void testFactType() throws Exception { assertThat(index >= 0).isTrue(); } - @Test - public void testFactTypeNotUsedInRule() throws Exception { + @ParameterizedTest + @MethodSource("parameters") + public void testFactTypeNotUsedInRule(RUN_TYPE runType) throws Exception { String str = "package org.test;\n" + "import " + Person.class.getCanonicalName() + ";" + @@ -424,7 +431,7 @@ public void testFactTypeNotUsedInRule() throws Exception { " insert($v);" + "end"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); FactType nameType = ksession.getKieBase().getFactType("org.test", "ExtendedName"); Object name = nameType.newInstance(); @@ -440,8 +447,9 @@ public void testFactTypeNotUsedInRule() throws Exception { assertThat(results.iterator().next()).isEqualTo("Mario"); } - @Test - public void testTypeDeclarationsInheritance() throws Exception { + @ParameterizedTest + @MethodSource("parameters") + public void testTypeDeclarationsInheritance(RUN_TYPE runType) throws Exception { String str = "declare Person\n" + " id : int @key\n" + @@ -463,11 +471,12 @@ public void testTypeDeclarationsInheritance() throws Exception { " Person pe = new Employee();\n" + "end"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); } - @Test - public void testEnum() { + @ParameterizedTest + @MethodSource("parameters") + public void testEnum(RUN_TYPE runType) { String str = "import " + Result.class.getCanonicalName() + ";" + "import " + Person.class.getCanonicalName() + ";" + @@ -485,7 +494,7 @@ public void testEnum() { " insert(new Result($p));\n" + "end\n"; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); ksession.insert(new Person("Mario")); ksession.fireAllRules(); @@ -496,8 +505,9 @@ public void testEnum() { assertThat(p.getAge()).isEqualTo(11); } - @Test - public void testDeclaredSlidingWindowOnEventInTypeDeclaration() throws Exception { + @ParameterizedTest + @MethodSource("parameters") + public void testDeclaredSlidingWindowOnEventInTypeDeclaration(RUN_TYPE runType) throws Exception { String str = "package org.test;\n" + "declare MyPojo\n" + @@ -505,7 +515,7 @@ public void testDeclaredSlidingWindowOnEventInTypeDeclaration() throws Exception "end\n" + "rule R when then insert(new MyPojo()); end\n"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); ksession.fireAllRules(); Object pojo = getObjectsIntoList(ksession, Object.class).iterator().next(); @@ -514,8 +524,9 @@ public void testDeclaredSlidingWindowOnEventInTypeDeclaration() throws Exception assertThat((long) f.get(pojo)).isEqualTo(42L); } - @Test - public void testNestedDateConstraint() throws Exception { + @ParameterizedTest + @MethodSource("parameters") + public void testNestedDateConstraint(RUN_TYPE runType) throws Exception { String str = "package org.test;\n" + "declare Fact\n" + @@ -530,7 +541,7 @@ public void testNestedDateConstraint() throws Exception { "then\n" + "end"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); KieBase kbase = ksession.getKieBase(); FactType factType = kbase.getFactType("org.test", "Fact"); @@ -548,8 +559,9 @@ public void testNestedDateConstraint() throws Exception { assertThat(ksession.fireAllRules()).isEqualTo(1); } - @Test - public void testExtendPojo() throws Exception { + @ParameterizedTest + @MethodSource("parameters") + public void testExtendPojo(RUN_TYPE runType) throws Exception { String str = "package org.test;\n" + "import " + Person.class.getCanonicalName() + ";" + @@ -562,7 +574,7 @@ public void testExtendPojo() throws Exception { "then\n" + "end"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); KieBase kbase = ksession.getKieBase(); FactType factType = kbase.getFactType("org.test", "MyPerson"); diff --git a/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/DowncastTest.java b/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/DowncastTest.java index 477e120af45..981768ef1ca 100644 --- a/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/DowncastTest.java +++ b/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/DowncastTest.java @@ -20,19 +20,17 @@ import java.math.BigDecimal; -import org.junit.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; import org.kie.api.runtime.KieSession; import static org.assertj.core.api.Assertions.assertThat; public class DowncastTest extends BaseModelTest { - public DowncastTest( RUN_TYPE testRunType ) { - super( testRunType ); - } - - @Test - public void testDowncast() { + @ParameterizedTest + @MethodSource("parameters") + public void testDowncast(RUN_TYPE runType) { // DROOLS-6520 String str = "import " + Product.class.getCanonicalName() + ";" + @@ -48,7 +46,7 @@ public void testDowncast() { " update($lp);\n" + "end"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); Proposal cashProposal = new Proposal(new CashProduct(new BigDecimal(2))); Proposal loanProposal = new Proposal(new LoanProduct(new BigDecimal(12))); diff --git a/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/DroolsContextTest.java b/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/DroolsContextTest.java index 7a29973489d..9e6e502cf61 100644 --- a/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/DroolsContextTest.java +++ b/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/DroolsContextTest.java @@ -21,19 +21,17 @@ import java.util.ArrayList; import java.util.List; -import org.junit.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; import org.kie.api.runtime.KieSession; import static org.assertj.core.api.Assertions.assertThat; public class DroolsContextTest extends BaseModelTest { - public DroolsContextTest(final RUN_TYPE testRunType ) { - super( testRunType ); - } - - @Test - public void testDroolsContext() { + @ParameterizedTest + @MethodSource("parameters") + public void testDroolsContext(RUN_TYPE runType) { final String str = "global java.util.List list\n" + "global java.util.List list2\n" + @@ -43,7 +41,7 @@ public void testDroolsContext() { " list.add(list2.add(kcontext));\n" + "end"; - final KieSession ksession = getKieSession(str); + final KieSession ksession = getKieSession(runType, str); final List list = new ArrayList<>(); ksession.setGlobal("list", list); @@ -56,8 +54,9 @@ public void testDroolsContext() { assertThat(list.size()).isEqualTo(1); } - @Test - public void testDroolsContextInString() { + @ParameterizedTest + @MethodSource("parameters") + public void testDroolsContextInString(RUN_TYPE runType) { final String str = "global java.util.List list\n" + "global java.util.List list2\n" + @@ -67,7 +66,7 @@ public void testDroolsContextInString() { " list.add(list2.add(\"something\" + kcontext));\n" + "end"; - final KieSession ksession = getKieSession(str); + final KieSession ksession = getKieSession(runType, str); final List list = new ArrayList<>(); ksession.setGlobal("list", list); @@ -80,8 +79,9 @@ public void testDroolsContextInString() { assertThat(list.size()).isEqualTo(1); } - @Test - public void testDroolsContextWithoutReplacingStrings() { + @ParameterizedTest + @MethodSource("parameters") + public void testDroolsContextWithoutReplacingStrings(RUN_TYPE runType) { final String str = "global java.util.List list\n" + "\n" + @@ -90,7 +90,7 @@ public void testDroolsContextWithoutReplacingStrings() { " list.add(\"this kcontext shoudln't be replaced\");\n" + "end"; - final KieSession ksession = getKieSession(str); + final KieSession ksession = getKieSession(runType, str); final List list = new ArrayList<>(); ksession.setGlobal("list", list); @@ -100,8 +100,9 @@ public void testDroolsContextWithoutReplacingStrings() { assertThat(list.get(0)).isEqualTo("this kcontext shoudln't be replaced"); } - @Test - public void testRuleContext() { + @ParameterizedTest + @MethodSource("parameters") + public void testRuleContext(RUN_TYPE runType) { final String str = "import " + FactWithRuleContext.class.getCanonicalName() + ";\n" + "global java.util.List list\n" + @@ -112,7 +113,7 @@ public void testRuleContext() { " list.add($factWithRuleContext.getRuleName(kcontext));\n" + "end"; - final KieSession ksession = getKieSession(str); + final KieSession ksession = getKieSession(runType, str); final List list = new ArrayList<>(); ksession.setGlobal("list", list); diff --git a/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/EnumTest.java b/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/EnumTest.java index 12be270f641..e95e6146fd0 100644 --- a/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/EnumTest.java +++ b/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/EnumTest.java @@ -18,19 +18,18 @@ */ package org.drools.model.codegen.execmodel; -import org.junit.Test; import org.kie.api.runtime.KieSession; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; + import static org.assertj.core.api.Assertions.assertThat; public class EnumTest extends BaseModelTest { - public EnumTest( RUN_TYPE testRunType ) { - super( testRunType ); - } - - @Test - public void testMatchEnum() { + @ParameterizedTest + @MethodSource("parameters") + public void testMatchEnum(RUN_TYPE runType) { String str = "import " + Bus.class.getCanonicalName() + ";" + "rule bus2 when\n" + @@ -39,7 +38,7 @@ public void testMatchEnum() { " System.out.println(\"bus=\" + $bus + \", maker=\" + $maker);\n" + "end"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str ); Bus a = new Bus("blue", 25, Bus.Maker.HINO); ksession.insert(a); @@ -49,8 +48,9 @@ public void testMatchEnum() { assertThat(ksession.fireAllRules()).isEqualTo(1); } - @Test - public void testBindEnum() { + @ParameterizedTest + @MethodSource("parameters") + public void testBindEnum(RUN_TYPE runType) { // DROOLS-5851 String str = "import " + Bus.class.getCanonicalName() + ";" + @@ -60,7 +60,7 @@ public void testBindEnum() { " System.out.println(\"bus=\" + $bus + \", maker=\" + $maker);\n" + "end"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); Bus a = new Bus("blue", 25, Bus.Maker.HINO); ksession.insert(a); diff --git a/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/EvalTest.java b/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/EvalTest.java index 95562316462..6e307f092c0 100644 --- a/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/EvalTest.java +++ b/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/EvalTest.java @@ -24,19 +24,18 @@ import org.drools.model.codegen.execmodel.domain.Overloaded; import org.drools.model.codegen.execmodel.domain.Person; import org.drools.model.codegen.execmodel.domain.Result; -import org.junit.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; import org.kie.api.runtime.KieSession; import static org.assertj.core.api.Assertions.assertThat; public class EvalTest extends BaseModelTest { - public EvalTest( RUN_TYPE testRunType ) { - super( testRunType ); - } - @Test - public void testEval() { + @ParameterizedTest + @MethodSource("parameters") + public void testEval(RUN_TYPE runType) { String str = "import " + Result.class.getCanonicalName() + ";" + "import " + Person.class.getCanonicalName() + ";" + @@ -47,7 +46,7 @@ public void testEval() { " insert(new Result($p.getName()));\n" + "end"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); ksession.insert( new Person( "Mario", 40 ) ); ksession.insert( new Person( "Mark", 37 ) ); @@ -59,8 +58,9 @@ public void testEval() { assertThat(results.iterator().next().getValue()).isEqualTo("Mario"); } - @Test - public void testEvalWithMethodInvocation() { + @ParameterizedTest + @MethodSource("parameters") + public void testEvalWithMethodInvocation(RUN_TYPE runType) { String str = "import " + Result.class.getCanonicalName() + ";" + "import " + Person.class.getCanonicalName() + ";" + @@ -71,7 +71,7 @@ public void testEvalWithMethodInvocation() { " insert(new Result($p.getName()));\n" + "end"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); ksession.insert( new Person( "Mario", 40 ) ); ksession.insert( new Person( "Mark", 37 ) ); @@ -83,56 +83,61 @@ public void testEvalWithMethodInvocation() { assertThat(results.iterator().next().getValue()).isEqualTo("Edson"); } - @Test - public void testEvalTrue() { + @ParameterizedTest + @MethodSource("parameters") + public void testEvalTrue(RUN_TYPE runType) { String str = "rule R when\n" + " eval( true )\n" + "then\n" + "end"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); assertThat(ksession.fireAllRules()).isEqualTo(1); } - @Test - public void testEvalFalse() { + @ParameterizedTest + @MethodSource("parameters") + public void testEvalFalse(RUN_TYPE runType) { String str = "rule R when\n" + " eval( false )\n" + "then\n" + "end"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); assertThat(ksession.fireAllRules()).isEqualTo(0); } - @Test - public void testEvalOr() { + @ParameterizedTest + @MethodSource("parameters") + public void testEvalOr(RUN_TYPE runType) { String str = "rule R when\n" + " eval( true ) or eval( false )\n" + "then\n" + "end"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); assertThat(ksession.fireAllRules()).isEqualTo(1); } - @Test - public void testEvalIdentity() { + @ParameterizedTest + @MethodSource("parameters") + public void testEvalIdentity(RUN_TYPE runType) { String str = "rule R when\n" + " eval( 1 == 1 )\n" + "then\n" + "end"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); assertThat(ksession.fireAllRules()).isEqualTo(1); } - @Test - public void testFunction() { + @ParameterizedTest + @MethodSource("parameters") + public void testFunction(RUN_TYPE runType) { String str = "import " + Result.class.getCanonicalName() + ";" + "import " + Person.class.getCanonicalName() + ";" + @@ -146,7 +151,7 @@ public void testFunction() { " insert(new Result(hello($p.getName())));\n" + "end"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); ksession.insert( new Person( "Mario", 40 ) ); ksession.insert( new Person( "Mark", 37 ) ); @@ -158,8 +163,9 @@ public void testFunction() { assertThat(results.iterator().next().getValue()).isEqualTo("Hello Mario!"); } - @Test - public void testFunction2() { + @ParameterizedTest + @MethodSource("parameters") + public void testFunction2(RUN_TYPE runType) { String str = "import " + Result.class.getCanonicalName() + ";" + "import " + Person.class.getCanonicalName() + ";" + @@ -173,7 +179,7 @@ public void testFunction2() { " insert(new Result($p.getName()));\n" + "end"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); ksession.insert( new Person( "Mario", 40 ) ); ksession.insert( new Person( "Mark", 37 ) ); @@ -185,8 +191,9 @@ public void testFunction2() { assertThat(results.iterator().next().getValue()).isEqualTo("Mario"); } - @Test - public void testEvalWith2Bindings() { + @ParameterizedTest + @MethodSource("parameters") + public void testEvalWith2Bindings(RUN_TYPE runType) { String str = "import " + Result.class.getCanonicalName() + ";" + "import " + Person.class.getCanonicalName() + ";" + @@ -198,7 +205,7 @@ public void testEvalWith2Bindings() { " insert(new Result($p1.getName()));\n" + "end"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); ksession.insert( new Person( "Mario", 40 ) ); ksession.insert( new Person( "Mark", 38 ) ); @@ -210,8 +217,9 @@ public void testEvalWith2Bindings() { assertThat(results.iterator().next().getValue()).isEqualTo("Mario"); } - @Test - public void testEvalWith2BindingsInvokingMethod() { + @ParameterizedTest + @MethodSource("parameters") + public void testEvalWith2BindingsInvokingMethod(RUN_TYPE runType) { String str = "import " + Result.class.getCanonicalName() + ";" + "import " + Person.class.getCanonicalName() + ";" + @@ -223,7 +231,7 @@ public void testEvalWith2BindingsInvokingMethod() { " insert(new Result($p1.getName()));\n" + "end"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); ksession.insert( new Person( "Mario", 40 ) ); ksession.insert( new Person( "Mario", 38 ) ); @@ -235,8 +243,9 @@ public void testEvalWith2BindingsInvokingMethod() { assertThat(results.iterator().next().getValue()).isEqualTo("Mario"); } - @Test - public void testEvalWithDeclaration() { + @ParameterizedTest + @MethodSource("parameters") + public void testEvalWithDeclaration(RUN_TYPE runType) { String str = "import " + Result.class.getCanonicalName() + ";" + "import " + Person.class.getCanonicalName() + ";" + @@ -247,7 +256,7 @@ public void testEvalWithDeclaration() { " insert(new Result($p1.getName()));\n" + "end"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); ksession.insert( new Person( "Mario", 40 ) ); ksession.insert( new Person( "Mark", 38 ) ); @@ -259,8 +268,9 @@ public void testEvalWithDeclaration() { assertThat(results.iterator().next().getValue()).isEqualTo("Mario"); } - @Test - public void testEvalWith2Declarations() { + @ParameterizedTest + @MethodSource("parameters") + public void testEvalWith2Declarations(RUN_TYPE runType) { String str = "import " + Result.class.getCanonicalName() + ";" + "import " + Person.class.getCanonicalName() + ";" + @@ -272,7 +282,7 @@ public void testEvalWith2Declarations() { " insert(new Result($p1.getName()));\n" + "end"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); ksession.insert( new Person( "Mario", 40 ) ); ksession.insert( new Person( "Mark", 38 ) ); @@ -284,8 +294,9 @@ public void testEvalWith2Declarations() { assertThat(results.iterator().next().getValue()).isEqualTo("Mario"); } - @Test - public void testEvalWithBinary() { + @ParameterizedTest + @MethodSource("parameters") + public void testEvalWithBinary(RUN_TYPE runType) { String str = "import " + Result.class.getCanonicalName() + ";" + "import " + Person.class.getCanonicalName() + ";" + "rule R when\n" + @@ -295,7 +306,7 @@ public void testEvalWithBinary() { " insert(new Result($p.getName()));\n" + "end"; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); ksession.insert(new Person("Mario", 40)); ksession.insert(new Person("Mark", 37)); @@ -307,8 +318,9 @@ public void testEvalWithBinary() { assertThat(results.iterator().next().getValue()).isEqualTo("Mario"); } - @Test - public void testEvalInvokingMethod() { + @ParameterizedTest + @MethodSource("parameters") + public void testEvalInvokingMethod(RUN_TYPE runType) { String str = "import " + Overloaded.class.getCanonicalName() + ";" + "rule OverloadedMethods\n" + "when\n" + @@ -318,7 +330,7 @@ public void testEvalInvokingMethod() { " insert(\"matched\");\n" + "end"; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); ksession.insert(new Overloaded()); ksession.fireAllRules(); @@ -327,8 +339,9 @@ public void testEvalInvokingMethod() { assertThat(results.size()).isEqualTo(1); } - @Test - public void testEvalInvokingMethod2() { + @ParameterizedTest + @MethodSource("parameters") + public void testEvalInvokingMethod2(RUN_TYPE runType) { String str = "import " + Overloaded.class.getCanonicalName() + ";" + "rule OverloadedMethods\n" + "when\n" + @@ -338,7 +351,7 @@ public void testEvalInvokingMethod2() { " insert(\"matched\");\n" + "end"; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); ksession.insert(new Overloaded()); ksession.fireAllRules(); @@ -348,8 +361,9 @@ public void testEvalInvokingMethod2() { } - @Test - public void testEvalInvokingFunction() { + @ParameterizedTest + @MethodSource("parameters") + public void testEvalInvokingFunction(RUN_TYPE runType) { String str = "function boolean isPositive(int i){\n" + " return i > 0;\n" + @@ -361,7 +375,7 @@ public void testEvalInvokingFunction() { " insert(\"matched\");\n" + "end"; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); ksession.insert(42); ksession.fireAllRules(); @@ -370,8 +384,9 @@ public void testEvalInvokingFunction() { assertThat(results.size()).isEqualTo(1); } - @Test - public void testEvalWithGlobal() { + @ParameterizedTest + @MethodSource("parameters") + public void testEvalWithGlobal(RUN_TYPE runType) { final String drl1 = "import " + Result.class.getCanonicalName() + ";\n" + "global java.lang.Integer globalInt\n" + @@ -381,7 +396,7 @@ public void testEvalWithGlobal() { " insert(new Result(\"match\"));\n" + "end\n"; - KieSession ksession = getKieSession( drl1 ); + KieSession ksession = getKieSession(runType, drl1); ksession.setGlobal("globalInt", 1); ksession.insert(1); @@ -394,8 +409,9 @@ public void testEvalWithGlobal() { assertThat(results.iterator().next().getValue().toString()).isEqualTo("match"); } - @Test - public void testEvalWithGlobal2() { + @ParameterizedTest + @MethodSource("parameters") + public void testEvalWithGlobal2(RUN_TYPE runType) { final String drl1 = "import " + Result.class.getCanonicalName() + ";\n" + "global java.lang.Integer globalInt\n" + @@ -405,7 +421,7 @@ public void testEvalWithGlobal2() { " insert(new Result(\"match\"));\n" + "end\n"; - KieSession ksession = getKieSession( drl1 ); + KieSession ksession = getKieSession(runType, drl1); ksession.setGlobal("globalInt", 1); ksession.insert(1); @@ -419,8 +435,9 @@ public void testEvalWithGlobal2() { } - @Test - public void testEvalExprWithFunctionCall() { + @ParameterizedTest + @MethodSource("parameters") + public void testEvalExprWithFunctionCall(RUN_TYPE runType) { String str = "import " + Person.class.getCanonicalName() + ";" + "global " + GlobalFunctions.class.getCanonicalName() + " functions;" + @@ -430,7 +447,7 @@ public void testEvalExprWithFunctionCall() { "then\n" + "end\n"; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); GlobalFunctions gf = new GlobalFunctions(); ksession.setGlobal("functions", gf); @@ -445,8 +462,9 @@ public Integer add(int a, int b) { } } - @Test - public void testEvalCalculationWithParenthesis() { + @ParameterizedTest + @MethodSource("parameters") + public void testEvalCalculationWithParenthesis(RUN_TYPE runType) { String str = "import " + CalcFact.class.getCanonicalName() + ";" + "rule R when\n" + @@ -455,7 +473,7 @@ public void testEvalCalculationWithParenthesis() { "then\n" + "end"; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); ksession.insert(new CalcFact(1.0d, 1.0d)); // (1.0 / (1.0 * 10) * 10) is 1. So this rule should not fire @@ -464,8 +482,9 @@ public void testEvalCalculationWithParenthesis() { assertThat(fired).isEqualTo(0); } - @Test - public void testParseIntStringConcatenation() throws Exception { + @ParameterizedTest + @MethodSource("parameters") + public void testParseIntStringConcatenation(RUN_TYPE runType) throws Exception { String str = "rule R when\n" + " $s : String()\n" + @@ -473,7 +492,7 @@ public void testParseIntStringConcatenation() throws Exception { "then\n" + "end\n"; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); ksession.insert("5"); assertThat(ksession.fireAllRules()).isEqualTo(1); } @@ -502,8 +521,9 @@ public void setT(String t) { } } - @Test - public void testModifyEvalAfterJoin() { + @ParameterizedTest + @MethodSource("parameters") + public void testModifyEvalAfterJoin(RUN_TYPE runType) { // DROOLS-7255 String str = "import " + Dt1.class.getCanonicalName() + ";" + @@ -534,7 +554,7 @@ public void testModifyEvalAfterJoin() { " }\n" + "end\n"; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); Dt1 dt1 = new Dt1(); dt1.setA(1); diff --git a/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/ExisistentialTest.java b/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/ExisistentialTest.java index 38cc55ca3fa..f5de60b45ac 100644 --- a/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/ExisistentialTest.java +++ b/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/ExisistentialTest.java @@ -25,7 +25,8 @@ import org.assertj.core.api.Assertions; import org.drools.model.codegen.execmodel.domain.Person; import org.drools.model.codegen.execmodel.domain.Result; -import org.junit.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; import org.kie.api.runtime.KieSession; import org.kie.api.runtime.rule.FactHandle; import org.kie.api.runtime.rule.Match; @@ -38,12 +39,9 @@ public class ExisistentialTest extends BaseModelTest { - public ExisistentialTest( RUN_TYPE testRunType ) { - super( testRunType ); - } - - @Test - public void testNot() { + @ParameterizedTest + @MethodSource("parameters") + public void testNot(RUN_TYPE runType) { String str = "import " + Person.class.getCanonicalName() + ";" + "import " + Result.class.getCanonicalName() + ";" + @@ -53,7 +51,7 @@ public void testNot() { " insert(new Result(\"ok\"));\n" + "end"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); Person mario = new Person( "Mario", 40 ); @@ -65,8 +63,9 @@ public void testNot() { assertThat(results.iterator().next().getValue()).isEqualTo("ok"); } - @Test - public void testNotEmptyPredicate() { + @ParameterizedTest + @MethodSource("parameters") + public void testNotEmptyPredicate(RUN_TYPE runType) { String str = "import " + Person.class.getCanonicalName() + ";" + "import " + Result.class.getCanonicalName() + ";" + @@ -76,7 +75,7 @@ public void testNotEmptyPredicate() { " insert(new Result(\"ok\"));\n" + "end"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); Person mario = new Person( "Mario", 40 ); @@ -87,8 +86,9 @@ public void testNotEmptyPredicate() { assertThat(results.size()).isEqualTo(0); } - @Test - public void testExists() { + @ParameterizedTest + @MethodSource("parameters") + public void testExists(RUN_TYPE runType) { String str = "import " + Person.class.getCanonicalName() + ";" + "import " + Result.class.getCanonicalName() + ";" + @@ -98,7 +98,7 @@ public void testExists() { " insert(new Result(\"ok\"));\n" + "end"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); Person mario = new Person( "Mario", 40 ); @@ -110,8 +110,9 @@ public void testExists() { assertThat(results.iterator().next().getValue()).isEqualTo("ok"); } - @Test - public void testForall() { + @ParameterizedTest + @MethodSource("parameters") + public void testForall(RUN_TYPE runType) { String str = "import " + Person.class.getCanonicalName() + ";" + "import " + Result.class.getCanonicalName() + ";" + @@ -122,7 +123,7 @@ public void testForall() { " insert(new Result(\"ok\"));\n" + "end"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); ksession.insert( new Person( "Mario", 41 ) ); ksession.insert( new Person( "Mark", 39 ) ); @@ -134,8 +135,9 @@ public void testForall() { assertThat(results.iterator().next().getValue()).isEqualTo("ok"); } - @Test - public void testForallInQuery() { + @ParameterizedTest + @MethodSource("parameters") + public void testForallInQuery(RUN_TYPE runType) { String str = "import " + Person.class.getCanonicalName() + ";" + "query ifAllPersonsAreOlderReturnThem (int pAge)\n" + @@ -143,7 +145,7 @@ public void testForallInQuery() { " $person : Person()\n" + "end"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); ksession.insert( new Person( "Mario", 41 ) ); ksession.insert( new Person( "Mark", 39 ) ); @@ -155,8 +157,9 @@ public void testForallInQuery() { assertThat(results.size()).isEqualTo(3); } - @Test - public void testForallSingleConstraint() { + @ParameterizedTest + @MethodSource("parameters") + public void testForallSingleConstraint(RUN_TYPE runType) { String str = "import " + Person.class.getCanonicalName() + ";" + "import " + Result.class.getCanonicalName() + ";" + @@ -166,7 +169,7 @@ public void testForallSingleConstraint() { " insert(new Result(\"ok\"));\n" + "end"; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); ksession.insert(new Person("Mario")); ksession.insert(new Person("Edson")); @@ -177,8 +180,9 @@ public void testForallSingleConstraint() { assertThat(results.iterator().next().getValue()).isEqualTo("ok"); } - @Test - public void testForallEmptyConstraint() { + @ParameterizedTest + @MethodSource("parameters") + public void testForallEmptyConstraint(RUN_TYPE runType) { String str = "import " + Person.class.getCanonicalName() + ";" + "import " + Result.class.getCanonicalName() + ";" + @@ -188,7 +192,7 @@ public void testForallEmptyConstraint() { " insert(new Result(\"ok\"));\n" + "end"; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); ksession.insert(new Person("Mario")); ksession.insert(new Person("Mark")); @@ -200,8 +204,9 @@ public void testForallEmptyConstraint() { assertThat(results.iterator().next().getValue()).isEqualTo("ok"); } - @Test - public void testExistsEmptyPredicate() { + @ParameterizedTest + @MethodSource("parameters") + public void testExistsEmptyPredicate(RUN_TYPE runType) { String str = "import " + Person.class.getCanonicalName() + ";" + "import " + Result.class.getCanonicalName() + ";" + @@ -211,7 +216,7 @@ public void testExistsEmptyPredicate() { " insert(new Result(\"ok\"));\n" + "end"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); Person mark = new Person( "Mark", 37 ); Person mario = new Person( "Mario", 40 ); @@ -225,8 +230,9 @@ public void testExistsEmptyPredicate() { assertThat(results.iterator().next().getValue()).isEqualTo("ok"); } - @Test - public void testComplexNots() throws Exception { + @ParameterizedTest + @MethodSource("parameters") + public void testComplexNots(RUN_TYPE runType) throws Exception { String str = "package org.drools.testcoverage.regression;\n" + "\n" + @@ -270,13 +276,14 @@ public void testComplexNots() throws Exception { "end\n" + ""; - KieSession ksession = getKieSession( getCepKieModuleModel(), str ); + KieSession ksession = getKieSession(runType, getCepKieModuleModel(), str ); assertThat(ksession.fireAllRules()).isEqualTo(2); } - @Test - public void testDuplicateBindingNameInDifferentScope() { + @ParameterizedTest + @MethodSource("parameters") + public void testDuplicateBindingNameInDifferentScope(RUN_TYPE runType) { final String drl1 = "package org.drools.compiler\n" + "import " + Person.class.getCanonicalName() + ";\n" + @@ -286,15 +293,16 @@ public void testDuplicateBindingNameInDifferentScope() { "then\n" + "end\n"; - KieSession ksession = getKieSession( drl1 ); + KieSession ksession = getKieSession(runType, drl1); ksession.insert( "test" ); ksession.insert( new Person("test", 18) ); assertThat(ksession.fireAllRules()).isEqualTo(1); } - @Test - public void testNotWithDereferencingConstraint() { + @ParameterizedTest + @MethodSource("parameters") + public void testNotWithDereferencingConstraint(RUN_TYPE runType) { final String drl1 = "package org.drools.compiler\n" + "import " + Person.class.getCanonicalName() + ";\n" + @@ -304,14 +312,15 @@ public void testNotWithDereferencingConstraint() { "then\n" + "end\n"; - KieSession ksession = getKieSession( drl1 ); + KieSession ksession = getKieSession(runType, drl1); ksession.insert( new Person("test", 18) ); assertThat(ksession.fireAllRules()).isEqualTo(0); } - @Test - public void test2NotsWithAnd() { + @ParameterizedTest + @MethodSource("parameters") + public void test2NotsWithAnd(RUN_TYPE runType) { final String drl1 = "package org.drools.compiler\n" + "rule R when\n" + @@ -326,13 +335,14 @@ public void test2NotsWithAnd() { "then\n" + "end\n"; - KieSession ksession = getKieSession( drl1 ); + KieSession ksession = getKieSession(runType, drl1); assertThat(ksession.fireAllRules()).isEqualTo(1); } - @Test - public void testExistsWithAJoin() { + @ParameterizedTest + @MethodSource("parameters") + public void testExistsWithAJoin(RUN_TYPE runType) { // DROOLS-7065 final String drl1 = "package org.drools.compiler\n" + @@ -344,7 +354,7 @@ public void testExistsWithAJoin() { "then\n" + "end\n"; - KieSession ksession = getKieSession( drl1 ); + KieSession ksession = getKieSession(runType, drl1); AtomicInteger matchCount = new AtomicInteger(0); // Atomic only so that I get an effectively-final int. ((RuleEventManager) ksession).addEventListener(new RuleEventListener() { diff --git a/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/ExternalisedLambdaTest.java b/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/ExternalisedLambdaTest.java index b0a31db75dc..a97c79568b2 100644 --- a/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/ExternalisedLambdaTest.java +++ b/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/ExternalisedLambdaTest.java @@ -30,9 +30,10 @@ import org.drools.model.codegen.execmodel.domain.StockTick; import org.drools.model.codegen.execmodel.domain.Woman; import org.drools.model.codegen.execmodel.util.lambdareplace.NonExternalisedLambdaFoundException; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; import org.kie.api.KieServices; import org.kie.api.builder.model.KieModuleModel; import org.kie.api.conf.EventProcessingOption; @@ -53,23 +54,20 @@ public class ExternalisedLambdaTest extends BaseModelTest { private boolean checkNonExternalisedLambdaOrig; - public ExternalisedLambdaTest(RUN_TYPE testRunType) { - super(testRunType); - } - - @Before + @BeforeEach public void init() { checkNonExternalisedLambdaOrig = RuleWriter.isCheckNonExternalisedLambda(); RuleWriter.setCheckNonExternalisedLambda(true); } - @After + @AfterEach public void clear() { RuleWriter.setCheckNonExternalisedLambda(checkNonExternalisedLambdaOrig); } - @Test - public void testConsequenceNoVariable() throws Exception { + @ParameterizedTest + @MethodSource("parameters") + public void testConsequenceNoVariable(RUN_TYPE runType) { // DROOLS-4924 String str = "package defaultpkg;\n" + @@ -82,7 +80,7 @@ public void testConsequenceNoVariable() throws Exception { KieSession ksession = null; try { - ksession = getKieSession(str); + ksession = getKieSession(runType, str); } catch (NonExternalisedLambdaFoundException e) { fail(e.getMessage()); } @@ -93,8 +91,9 @@ public void testConsequenceNoVariable() throws Exception { assertThat(ksession.fireAllRules()).isEqualTo(1); } - @Test - public void testExternalizeBindingVariableLambda() throws Exception { + @ParameterizedTest + @MethodSource("parameters") + public void testExternalizeBindingVariableLambda(RUN_TYPE runType) { String str = "package defaultpkg;\n" + "import " + Person.class.getCanonicalName() + ";" + @@ -107,7 +106,7 @@ public void testExternalizeBindingVariableLambda() throws Exception { KieSession ksession = null; try { - ksession = getKieSession(str); + ksession = getKieSession(runType, str); } catch (NonExternalisedLambdaFoundException e) { fail(e.getMessage()); } @@ -122,8 +121,9 @@ public void testExternalizeBindingVariableLambda() throws Exception { assertThat(list).containsExactlyInAnyOrder("Mario"); } - @Test - public void testExternalizeLambdaPredicate() throws Exception { + @ParameterizedTest + @MethodSource("parameters") + public void testExternalizeLambdaPredicate(RUN_TYPE runType) { String str = "package defaultpkg;\n" + "import " + Person.class.getCanonicalName() + ";" + @@ -136,7 +136,7 @@ public void testExternalizeLambdaPredicate() throws Exception { KieSession ksession = null; try { - ksession = getKieSession(str); + ksession = getKieSession(runType, str); } catch (NonExternalisedLambdaFoundException e) { fail(e.getMessage()); } @@ -151,8 +151,9 @@ public void testExternalizeLambdaPredicate() throws Exception { assertThat(list).containsExactlyInAnyOrder("Mario"); } - @Test - public void testExternalizeLambdaUsingVariable() throws Exception { + @ParameterizedTest + @MethodSource("parameters") + public void testExternalizeLambdaUsingVariable(RUN_TYPE runType) { String str = "package defaultpkg;\n" + "import " + Person.class.getCanonicalName() + ";\n" + @@ -166,7 +167,7 @@ public void testExternalizeLambdaUsingVariable() throws Exception { KieSession ksession = null; try { - ksession = getKieSession(str); + ksession = getKieSession(runType, str); } catch (NonExternalisedLambdaFoundException e) { fail(e.getMessage()); } @@ -181,8 +182,9 @@ public void testExternalizeLambdaUsingVariable() throws Exception { assertThat(list).containsExactlyInAnyOrder(43); } - @Test - public void testEval() { + @ParameterizedTest + @MethodSource("parameters") + public void testEval(RUN_TYPE runType) { String str = "import " + Result.class.getCanonicalName() + ";" + "import " + Person.class.getCanonicalName() + ";" + @@ -195,7 +197,7 @@ public void testEval() { KieSession ksession = null; try { - ksession = getKieSession(str); + ksession = getKieSession(runType, str); } catch (NonExternalisedLambdaFoundException e) { fail(e.getMessage()); } @@ -210,8 +212,9 @@ public void testEval() { assertThat(results.iterator().next().getValue()).isEqualTo("Mario"); } - @Test - public void testFromExpression() { + @ParameterizedTest + @MethodSource("parameters") + public void testFromExpression(RUN_TYPE runType) { final String str = "import org.drools.model.codegen.execmodel.domain.*;\n" + "global java.util.List list\n" + @@ -225,7 +228,7 @@ public void testFromExpression() { KieSession ksession = null; try { - ksession = getKieSession(str); + ksession = getKieSession(runType, str); } catch (NonExternalisedLambdaFoundException e) { fail(e.getMessage()); } @@ -248,8 +251,9 @@ public void testFromExpression() { assertThat(list).containsExactlyInAnyOrder("Charles"); } - @Test - public void testAccumulateWithBinaryExpr() { + @ParameterizedTest + @MethodSource("parameters") + public void testAccumulateWithBinaryExpr(RUN_TYPE runType) { String str = "import " + Person.class.getCanonicalName() + ";" + "import " + Result.class.getCanonicalName() + ";" + @@ -264,7 +268,7 @@ public void testAccumulateWithBinaryExpr() { KieSession ksession = null; try { - ksession = getKieSession(str); + ksession = getKieSession(runType, str); } catch (NonExternalisedLambdaFoundException e) { fail(e.getMessage()); } @@ -281,8 +285,9 @@ public void testAccumulateWithBinaryExpr() { assertThat(((Number) results.iterator().next().getValue()).intValue()).isEqualTo(77); } - @Test - public void testOOPath() { + @ParameterizedTest + @MethodSource("parameters") + public void testOOPath(RUN_TYPE runType) { final String str = "import org.drools.model.codegen.execmodel.domain.*;\n" + "global java.util.List list\n" + @@ -295,7 +300,7 @@ public void testOOPath() { KieSession ksession = null; try { - ksession = getKieSession(str); + ksession = getKieSession(runType, str); } catch (NonExternalisedLambdaFoundException e) { fail(e.getMessage()); } @@ -320,8 +325,9 @@ public void testOOPath() { assertThat(list).containsExactlyInAnyOrder("Bob"); } - @Test - public void testCep() throws Exception { + @ParameterizedTest + @MethodSource("parameters") + public void testCep(RUN_TYPE runType) { String str = "import " + StockTick.class.getCanonicalName() + ";" + "rule R when\n" + @@ -339,7 +345,7 @@ public void testCep() throws Exception { .setDefault( true ).setClockType( ClockTypeOption.get( ClockType.PSEUDO_CLOCK.getId() ) ); KieSession ksession = null; try { - ksession = getKieSession(kmodel, str); + ksession = getKieSession(runType, kmodel, str); } catch (NonExternalisedLambdaFoundException e) { fail(e.getMessage()); } diff --git a/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/FromTest.java b/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/FromTest.java index afbcfe18403..770896c5e90 100644 --- a/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/FromTest.java +++ b/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/FromTest.java @@ -29,7 +29,9 @@ import org.drools.model.codegen.execmodel.domain.Toy; import org.drools.model.codegen.execmodel.domain.ToysStore; import org.drools.model.codegen.execmodel.domain.Woman; -import org.junit.Test; +import org.junit.jupiter.api.Timeout; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; import org.kie.api.KieServices; import org.kie.api.builder.model.KieModuleModel; import org.kie.api.runtime.KieSession; @@ -54,12 +56,9 @@ public class FromTest extends BaseModelTest { - public FromTest( RUN_TYPE testRunType ) { - super( testRunType ); - } - - @Test - public void testFromGlobal() throws Exception { + @ParameterizedTest + @MethodSource("parameters") + public void testFromGlobal(RUN_TYPE runType) throws Exception { String str = "global java.util.List list \n" + "rule R when \n" + " $o : String(length > 3) from list\n" + @@ -67,7 +66,7 @@ public void testFromGlobal() throws Exception { " insert($o); \n" + "end "; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); List strings = Arrays.asList("a", "Hello World!", "xyz"); @@ -81,8 +80,9 @@ public void testFromGlobal() throws Exception { assertThat(results.contains("xyz")).isFalse(); } - @Test - public void testFromVariable() { + @ParameterizedTest + @MethodSource("parameters") + public void testFromVariable(RUN_TYPE runType) { final String str = "import org.drools.model.codegen.execmodel.domain.*;\n" + "global java.util.List list\n" + @@ -94,7 +94,7 @@ public void testFromVariable() { " list.add( $child.getName() );\n" + "end\n"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); final List list = new ArrayList<>(); ksession.setGlobal( "list", list ); @@ -114,8 +114,9 @@ public void testFromVariable() { assertThat(list).containsExactlyInAnyOrder("Charles"); } - @Test - public void testFromExpression() { + @ParameterizedTest + @MethodSource("parameters") + public void testFromExpression(RUN_TYPE runType) { final String str = "import org.drools.model.codegen.execmodel.domain.*;\n" + "global java.util.List list\n" + @@ -127,7 +128,7 @@ public void testFromExpression() { " list.add( $child.getName() );\n" + "end\n"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); final List list = new ArrayList<>(); ksession.setGlobal( "list", list ); @@ -147,8 +148,9 @@ public void testFromExpression() { assertThat(list).containsExactlyInAnyOrder("Charles"); } - @Test - public void testModifyWithFrom() { + @ParameterizedTest + @MethodSource("parameters") + public void testModifyWithFrom(RUN_TYPE runType) { // DROOLS-6486 final String str = "import org.drools.model.codegen.execmodel.domain.*;\n" + @@ -160,7 +162,7 @@ public void testModifyWithFrom() { " modify( $child ) { setName($child.getName() + \"x\") };\n" + "end\n"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); final Woman alice = new Woman( "Alice", 38 ); final Man bob = new Man( "Bob", 40 ); @@ -178,8 +180,9 @@ public void testModifyWithFrom() { assertThat(charlie.getName()).isEqualTo("Charlesx"); } - @Test - public void testModifyWithFromAndReevaluate() { + @ParameterizedTest + @MethodSource("parameters") + public void testModifyWithFromAndReevaluate(RUN_TYPE runType) { // DROOLS-7203 final String str = "import org.drools.model.codegen.execmodel.domain.*;\n" + @@ -208,7 +211,7 @@ public void testModifyWithFromAndReevaluate() { " delete($s);\n" + "end\n"; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); List results = new ArrayList<>(); ksession.setGlobal("results", results); @@ -241,8 +244,10 @@ public void testModifyWithFromAndReevaluate() { assertThat(results).containsExactly("executed"); // R1 should not be executed twice because age is modified to 13 } - @Test(timeout = 20000) - public void testModifyWithFromSudoku() { + @ParameterizedTest + @MethodSource("parameters") + @Timeout(20000) + public void testModifyWithFromSudoku(RUN_TYPE runType) { // DROOLS-7203 : Slimmed down Sudoku final String str = "import " + Setting.class.getCanonicalName() + ";\n" + @@ -297,7 +302,7 @@ public void testModifyWithFromSudoku() { " insert( new Setting( $rn, $cn, i ) );\n" + "end\n"; - KieSession ksession = getKieSession(getDisablePropertyReactivityKieModuleModel(), str); + KieSession ksession = getKieSession(runType, getDisablePropertyReactivityKieModuleModel(), str); Cell c1 = new Cell(0, 0, null); c1.setFree(new HashSet<>(Arrays.asList(1, 2, 3))); @@ -496,8 +501,9 @@ public static Integer getLength(String ignoredParameter, String s, Integer offse return s.length() + offset; } - @Test - public void testFromExternalFunction() { + @ParameterizedTest + @MethodSource("parameters") + public void testFromExternalFunction(RUN_TYPE runType) { final String str = "import " + FromTest.class.getCanonicalName() + ";\n" + "global java.util.List list\n" + @@ -509,7 +515,7 @@ public void testFromExternalFunction() { " list.add( \"received long message: \" + $s);\n" + "end\n"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); final List list = new ArrayList<>(); ksession.setGlobal( "list", list ); @@ -520,8 +526,9 @@ public void testFromExternalFunction() { assertThat(list).containsExactlyInAnyOrder("received long message: Hello World!"); } - @Test - public void testFromExternalFunctionMultipleBindingArguments() { + @ParameterizedTest + @MethodSource("parameters") + public void testFromExternalFunctionMultipleBindingArguments(RUN_TYPE runType) { final String str = "import " + FromTest.class.getCanonicalName() + ";\n" + "global java.util.List list\n" + @@ -534,7 +541,7 @@ public void testFromExternalFunctionMultipleBindingArguments() { " list.add( \"received long message: \" + $s);\n" + "end\n"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); final List list = new ArrayList<>(); ksession.setGlobal( "list", list ); @@ -546,8 +553,9 @@ public void testFromExternalFunctionMultipleBindingArguments() { assertThat(list).containsExactlyInAnyOrder("received long message: Hello!"); } - @Test - public void testFromConstant() { + @ParameterizedTest + @MethodSource("parameters") + public void testFromConstant(RUN_TYPE runType) { String str = "package org.drools.compiler.test \n" + "global java.util.List list\n" + @@ -558,7 +566,7 @@ public void testFromConstant() { " list.add( $s );\n" + "end \n"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); final List list = new ArrayList<>(); ksession.setGlobal("list", list); @@ -568,8 +576,9 @@ public void testFromConstant() { assertThat(list.get(0)).isEqualTo("test"); } - @Test - public void testFromConstructor() { + @ParameterizedTest + @MethodSource("parameters") + public void testFromConstructor(RUN_TYPE runType) { String str = "package org.drools.compiler.test \n" + "import " + Person.class.getCanonicalName() + "\n" + @@ -583,7 +592,7 @@ public void testFromConstructor() { " list.add( $p );\n" + "end \n"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); final List list = new ArrayList<>(); ksession.setGlobal("list", list); @@ -597,8 +606,9 @@ public void testFromConstructor() { assertThat(list.get(0)).isEqualTo(new Person("Mario", 44)); } - @Test - public void testFromMapValues() { + @ParameterizedTest + @MethodSource("parameters") + public void testFromMapValues(RUN_TYPE runType) { // DROOLS-3661 String str = "package org.drools.compiler.test \n" + @@ -611,7 +621,7 @@ public void testFromMapValues() { "then\n" + "end \n"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); PetPerson petPerson = new PetPerson( "me" ); Map petMap = new HashMap<>(); @@ -623,8 +633,9 @@ public void testFromMapValues() { assertThat(ksession.fireAllRules()).isEqualTo(1); } - @Test - public void testGlobalInFromExpression() { + @ParameterizedTest + @MethodSource("parameters") + public void testGlobalInFromExpression(RUN_TYPE runType) { // DROOLS-4999 String str = "package org.drools.compiler.test \n" + @@ -638,7 +649,7 @@ public void testGlobalInFromExpression() { "then\n" + "end \n"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); ksession.setGlobal( "petName", "Dog" ); @@ -652,8 +663,9 @@ public void testGlobalInFromExpression() { assertThat(ksession.fireAllRules()).isEqualTo(1); } - @Test - public void testLiteralFrom() { + @ParameterizedTest + @MethodSource("parameters") + public void testLiteralFrom(RUN_TYPE runType) { // DROOLS-5217 String str = "package com.sample\n" + @@ -665,15 +677,16 @@ public void testLiteralFrom() { "then\n" + "end"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); ksession.insert( new Pojo( Arrays.asList(1,2,3) ) ); int rulesFired = ksession.fireAllRules(); assertThat(rulesFired).isEqualTo(2); } - @Test - public void testLiteralFrom2() { + @ParameterizedTest + @MethodSource("parameters") + public void testLiteralFrom2(RUN_TYPE runType) { // DROOLS-5217 String str = "package com.sample\n" + @@ -685,15 +698,16 @@ public void testLiteralFrom2() { "then\n" + "end"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); ksession.insert( new Pojo( Arrays.asList(1,2,3) ) ); int rulesFired = ksession.fireAllRules(); assertThat(rulesFired).isEqualTo(1); } - @Test - public void testFromCollect() { + @ParameterizedTest + @MethodSource("parameters") + public void testFromCollect(RUN_TYPE runType) { String str = "package org.drools.compiler.test \n" + "import " + Person.class.getCanonicalName() + "\n" + @@ -704,7 +718,7 @@ public void testFromCollect() { "then\n" + "end \n"; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); Person p1 = new Person("John", 32); Person p2 = new Person("Paul", 30); @@ -717,8 +731,9 @@ public void testFromCollect() { assertThat(ksession.fireAllRules()).isEqualTo(1); } - @Test - public void testFromCollectCustomSet() { + @ParameterizedTest + @MethodSource("parameters") + public void testFromCollectCustomSet(RUN_TYPE runType) { // DROOLS-7534 String str = "package org.drools.compiler.test \n" + @@ -732,7 +747,7 @@ public void testFromCollectCustomSet() { " FromTest.printPersons($set);" + "end \n"; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); Person p1 = new Person("John", 32); Person p1a = new Person("John", 32); @@ -758,8 +773,9 @@ public MyHashSet() { } } - @Test - public void testThisArray() { + @ParameterizedTest + @MethodSource("parameters") + public void testThisArray(RUN_TYPE runType) { // This test verifies the behavior when ArrayType is used as "_this" (which $childrenA is converted to) in from clause. String str = "package org.drools.compiler.test \n" + @@ -773,7 +789,7 @@ public void testThisArray() { " list.add($i);\n" + "end \n"; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); List list = new ArrayList<>(); ksession.setGlobal("list", list); @@ -786,8 +802,9 @@ public void testThisArray() { assertThat(list).containsExactlyInAnyOrder(2); } - @Test - public void testFromArray() { + @ParameterizedTest + @MethodSource("parameters") + public void testFromArray(RUN_TYPE runType) { // This test verifies the behavior when the return type is ArrayType String str = "package org.drools.compiler.test \n" + @@ -802,7 +819,7 @@ public void testFromArray() { " list.add($p.getName());\n" + "end \n"; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); List list = new ArrayList<>(); ksession.setGlobal("list", list); @@ -815,8 +832,9 @@ public void testFromArray() { assertThat(list).containsExactlyInAnyOrder("Julian", "Sean"); } - @Test - public void testInnerClassCollection() { + @ParameterizedTest + @MethodSource("parameters") + public void testInnerClassCollection(RUN_TYPE runType) { String str = "package org.drools.compiler.test \n" + "import " + MyPerson.class.getCanonicalName() + "\n" + @@ -827,7 +845,7 @@ public void testInnerClassCollection() { "then\n" + "end \n"; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); MyPerson john = new MyPerson("John"); Collection kids = new ArrayList<>(); @@ -840,8 +858,9 @@ public void testInnerClassCollection() { assertThat(ksession.fireAllRules()).isEqualTo(2); } - @Test - public void testInnerClassWithInstanceMethod() { + @ParameterizedTest + @MethodSource("parameters") + public void testInnerClassWithInstanceMethod(RUN_TYPE runType) { String str = "package org.drools.compiler.test \n" + "import " + MyPerson.class.getCanonicalName() + "\n" + @@ -854,7 +873,7 @@ public void testInnerClassWithInstanceMethod() { " list.add($d.getName());" + "end \n"; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); List list = new ArrayList<>(); ksession.setGlobal("list", list); @@ -865,8 +884,9 @@ public void testInnerClassWithInstanceMethod() { assertThat(list).containsExactlyInAnyOrder("Dummy"); } - @Test - public void testInnerClassWithStaticMethod() { + @ParameterizedTest + @MethodSource("parameters") + public void testInnerClassWithStaticMethod(RUN_TYPE runType) { String str = "package org.drools.compiler.test \n" + "import " + MyPerson.class.getCanonicalName() + "\n" + @@ -878,7 +898,7 @@ public void testInnerClassWithStaticMethod() { " list.add($d.getName());" + "end \n"; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); List list = new ArrayList<>(); ksession.setGlobal("list", list); @@ -886,8 +906,9 @@ public void testInnerClassWithStaticMethod() { assertThat(list).containsExactlyInAnyOrder("Dummy"); } - @Test - public void testInnerClassWithStaticMethodWithArg() { + @ParameterizedTest + @MethodSource("parameters") + public void testInnerClassWithStaticMethodWithArg(RUN_TYPE runType) { String str = "package org.drools.compiler.test \n" + "import " + MyPerson.class.getCanonicalName() + "\n" + @@ -900,7 +921,7 @@ public void testInnerClassWithStaticMethodWithArg() { " list.add($d.getName());" + "end \n"; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); List list = new ArrayList<>(); ksession.setGlobal("list", list); @@ -965,8 +986,9 @@ public static MyPerson getDummyPersonStatic(String name) { } } - @Test - public void testNew() { + @ParameterizedTest + @MethodSource("parameters") + public void testNew(RUN_TYPE runType) { String str = "package org.drools.compiler.test \n" + "import " + Person.class.getCanonicalName() + "\n" + @@ -978,7 +1000,7 @@ public void testNew() { " list.add($p);\n" + "end \n"; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); List list = new ArrayList<>(); ksession.setGlobal("list", list); @@ -987,8 +1009,9 @@ public void testNew() { assertThat(list.size()).isEqualTo(1); } - @Test - public void testFromOr() { + @ParameterizedTest + @MethodSource("parameters") + public void testFromOr(RUN_TYPE runType) { String str = "package org.drools.compiler.test \n" + "import " + Person.class.getCanonicalName() + "\n" + @@ -1008,7 +1031,7 @@ public void testFromOr() { " list.add($store.getStoreName());\n" + "end \n"; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); List list = new ArrayList<>(); ksession.setGlobal("list", list); @@ -1066,8 +1089,9 @@ public Object getSomethingBy(Object o) { } } - @Test - public void testFromFunctionCall() { + @ParameterizedTest + @MethodSource("parameters") + public void testFromFunctionCall(RUN_TYPE runType) { // DROOLS-5548 String str = "package com.sample;" + @@ -1101,7 +1125,7 @@ public void testFromFunctionCall() { " controlSet.add($colorVal);\n" + "end"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); HashSet hashSet = new HashSet<>(); ksession.setGlobal("controlSet", hashSet); @@ -1114,8 +1138,9 @@ public void testFromFunctionCall() { assertThat(hashSet.iterator().next()).isEqualTo("red"); } - @Test - public void testFromMap() { + @ParameterizedTest + @MethodSource("parameters") + public void testFromMap(RUN_TYPE runType) { // DROOLS-5549 String str = "package com.sample;" + @@ -1137,7 +1162,7 @@ public void testFromMap() { " controlSet.add($colorVal);\n" + "end"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); HashSet hashSet = new HashSet<>(); ksession.setGlobal("controlSet", hashSet); @@ -1150,8 +1175,9 @@ public void testFromMap() { assertThat(hashSet.iterator().next()).isEqualTo("red"); } - @Test - public void testFromChainedCall() { + @ParameterizedTest + @MethodSource("parameters") + public void testFromChainedCall(RUN_TYPE runType) { // DROOLS-5608 String str = "package com.sample;" + @@ -1170,7 +1196,7 @@ public void testFromChainedCall() { " controlSet.add($colorVal);\n" + "end"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); HashSet hashSet = new HashSet<>(); ksession.setGlobal("controlSet", hashSet); @@ -1200,8 +1226,9 @@ public static Map.Entry mapEntry(K key, V value) { } } - @Test - public void testNestedService() { + @ParameterizedTest + @MethodSource("parameters") + public void testNestedService(RUN_TYPE runType) { // DROOLS-5609 String str = "package com.sample;" + @@ -1218,7 +1245,7 @@ public void testNestedService() { " controlSet.add($colorVal);\n" + "end"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); HashSet hashSet = new HashSet<>(); ksession.setGlobal("controlSet", hashSet); @@ -1233,8 +1260,9 @@ public void testNestedService() { } - @Test - public void testMultipleFrom() { + @ParameterizedTest + @MethodSource("parameters") + public void testMultipleFrom(RUN_TYPE runType) { // DROOLS-5542 String str = "package com.sample;" + @@ -1254,7 +1282,7 @@ public void testMultipleFrom() { " controlSet.add($colorVal);\n" + "end"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); HashSet hashSet = new HashSet<>(); ksession.setGlobal("controlSet", hashSet); @@ -1268,8 +1296,9 @@ public void testMultipleFrom() { assertThat(hashSet.iterator().next()).isEqualTo("red"); } - @Test - public void testMultipleFromFromBinding() { + @ParameterizedTest + @MethodSource("parameters") + public void testMultipleFromFromBinding(RUN_TYPE runType) { // DROOLS-5591 String str = "package com.sample;" + @@ -1286,7 +1315,7 @@ public void testMultipleFromFromBinding() { " controlSet.add($colorVal);\n" + "end"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); HashSet hashSet = new HashSet<>(); ksession.setGlobal("controlSet", hashSet); @@ -1300,8 +1329,9 @@ public void testMultipleFromFromBinding() { assertThat(hashSet.iterator().next()).isEqualTo("red"); } - @Test - public void testMultipleFromList() { + @ParameterizedTest + @MethodSource("parameters") + public void testMultipleFromList(RUN_TYPE runType) { // DROOLS-5590 String str = "package com.sample;" + @@ -1324,7 +1354,7 @@ public void testMultipleFromList() { " controlSet.add($colorVal);\n" + "end"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); HashSet hashSet = new HashSet<>(); ksession.setGlobal("controlSet", hashSet); @@ -1338,8 +1368,9 @@ public void testMultipleFromList() { assertThat(hashSet.iterator().next()).isEqualTo("red"); } - @Test - public void tesFromMethodCall() { + @ParameterizedTest + @MethodSource("parameters") + public void tesFromMethodCall(RUN_TYPE runType) { // DROOLS-5641 String str = "package com.sample;" + @@ -1361,7 +1392,7 @@ public void tesFromMethodCall() { " controlSet.add($colorVal);\n" + "end"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); HashSet hashSet = new HashSet<>(); ksession.setGlobal("controlSet", hashSet); @@ -1376,8 +1407,9 @@ public void tesFromMethodCall() { assertThat(hashSet.iterator().next()).isEqualTo("red"); } - @Test - public void testFromStringConcatenation() { + @ParameterizedTest + @MethodSource("parameters") + public void testFromStringConcatenation(RUN_TYPE runType) { // DROOLS-5640 String str = "global java.util.List list;\n" + @@ -1389,7 +1421,7 @@ public void testFromStringConcatenation() { " list.add($c);\n" + "end"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); final List list = new ArrayList<>(); ksession.setGlobal("list", list); @@ -1400,8 +1432,9 @@ public void testFromStringConcatenation() { assertThat(list).containsExactlyInAnyOrder("AA", "AB", "BA", "BB"); } - @Test - public void testFromBoolean() { + @ParameterizedTest + @MethodSource("parameters") + public void testFromBoolean(RUN_TYPE runType) { // DROOLS-5830 String str = "rule R when\n" + @@ -1411,14 +1444,15 @@ public void testFromBoolean() { "then\n" + "end"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); ksession.insert( "A" ); assertThat(ksession.fireAllRules()).isEqualTo(1); } - @Test - public void testFromCollectWithOr() { + @ParameterizedTest + @MethodSource("parameters") + public void testFromCollectWithOr(RUN_TYPE runType) { // DROOLS-6531 String str = "import java.util.List;\n" + @@ -1432,7 +1466,7 @@ public void testFromCollectWithOr() { " $list.addAll($values);\n" + "end"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); List list = new ArrayList<>(); ksession.insert(list); @@ -1444,8 +1478,9 @@ public void testFromCollectWithOr() { assertThat(list.size()).isEqualTo(2); } - @Test - public void fromWithTernaryExpressionBoolean() { + @ParameterizedTest + @MethodSource("parameters") + public void fromWithTernaryExpressionBoolean(RUN_TYPE runType) { // DROOLS-7236 String str = "global java.util.List results;\n" + @@ -1457,7 +1492,7 @@ public void fromWithTernaryExpressionBoolean() { " results.add($bar);\n" + "end"; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); List results = new ArrayList<>(); ksession.setGlobal("results", results); @@ -1467,8 +1502,9 @@ public void fromWithTernaryExpressionBoolean() { assertThat(results).containsExactly(true); } - @Test - public void fromWithTernaryExpressionBooleanWithMethodCall() { + @ParameterizedTest + @MethodSource("parameters") + public void fromWithTernaryExpressionBooleanWithMethodCall(RUN_TYPE runType) { // DROOLS-7236 String str = "import " + MyFact.class.getCanonicalName() + ";\n" + @@ -1481,7 +1517,7 @@ public void fromWithTernaryExpressionBooleanWithMethodCall() { " results.add($bar);\n" + "end"; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); List results = new ArrayList<>(); ksession.setGlobal("results", results); @@ -1491,8 +1527,9 @@ public void fromWithTernaryExpressionBooleanWithMethodCall() { assertThat(results).containsExactly(true); } - @Test - public void fromWithTernaryExpressionStringWithMethodCall() { + @ParameterizedTest + @MethodSource("parameters") + public void fromWithTernaryExpressionStringWithMethodCall(RUN_TYPE runType) { // DROOLS-7236 String str = "import " + MyFact.class.getCanonicalName() + ";\n" + @@ -1505,7 +1542,7 @@ public void fromWithTernaryExpressionStringWithMethodCall() { " results.add($bar);\n" + "end"; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); List results = new ArrayList<>(); ksession.setGlobal("results", results); @@ -1544,8 +1581,9 @@ public void setStrValue(String strValue) { } - @Test - public void testFromGlobalWithDuplicates() { + @ParameterizedTest + @MethodSource("parameters") + public void testFromGlobalWithDuplicates(RUN_TYPE runType) { String str = "import java.util.concurrent.atomic.AtomicInteger;\n" + "import " + NamedPerson.class.getCanonicalName() + ";\n" + @@ -1557,7 +1595,7 @@ public void testFromGlobalWithDuplicates() { " insert($o); \n" + "end "; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); List strings = Arrays.asList(new NamedPerson("Mario", 1), new NamedPerson("Mario", 2)); diff --git a/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/FunctionsTest.java b/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/FunctionsTest.java index 04af90eab76..6fb44fa32dd 100644 --- a/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/FunctionsTest.java +++ b/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/FunctionsTest.java @@ -24,19 +24,17 @@ import org.drools.model.codegen.execmodel.domain.Person; import org.drools.model.codegen.execmodel.domain.Result; -import org.junit.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; import org.kie.api.runtime.KieSession; import static org.assertj.core.api.Assertions.assertThat; public class FunctionsTest extends BaseModelTest { - public FunctionsTest( RUN_TYPE testRunType ) { - super( testRunType ); - } - - @Test - public void testFunctionWithEquals() { + @ParameterizedTest + @MethodSource("parameters") + public void testFunctionWithEquals(RUN_TYPE runType) { // DROOLS-3653 String str = "package com.sample\n" + "import " + Person.class.getName() + ";\n" + @@ -58,15 +56,16 @@ public void testFunctionWithEquals() { " then\n" + "end"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); ksession.insert(new Person("John", 10)); int rulesFired = ksession.fireAllRules(); assertThat(rulesFired).isEqualTo(1); // only R1 should fire } - @Test - public void testConstraintCallingStaticFunctionInsideEnum() { + @ParameterizedTest + @MethodSource("parameters") + public void testConstraintCallingStaticFunctionInsideEnum(RUN_TYPE runType) { String str = "import " + Person.class.getName() + ";\n" + "import " + FunctionEnum.class.getCanonicalName() + ";\n" + @@ -76,7 +75,7 @@ public void testConstraintCallingStaticFunctionInsideEnum() { " then\n" + "end\n"; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); Person john = new Person("John", 10); @@ -88,8 +87,9 @@ public void testConstraintCallingStaticFunctionInsideEnum() { assertThat(rulesFired).isEqualTo(1); } - @Test - public void testConstraintCallingImportedStaticFunction() { + @ParameterizedTest + @MethodSource("parameters") + public void testConstraintCallingImportedStaticFunction(RUN_TYPE runType) { String str = "import " + Person.class.getName() + ";\n" + "import " + FunctionEnum.class.getCanonicalName() + ";\n" + @@ -100,7 +100,7 @@ public void testConstraintCallingImportedStaticFunction() { " then\n" + "end\n"; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); Person john = new Person("John", 10); @@ -121,8 +121,9 @@ public static FunctionEnum constantEnumValue(String input) { } - @Test - public void testStaticMethodCall1() { + @ParameterizedTest + @MethodSource("parameters") + public void testStaticMethodCall1(RUN_TYPE runType) { // DROOLS-5214 String str = "package com.sample\n" + @@ -134,15 +135,16 @@ public void testStaticMethodCall1() { "then\n" + "end"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); ksession.insert( new Pojo( Arrays.asList(1,3) ) ); int rulesFired = ksession.fireAllRules(); assertThat(rulesFired).isEqualTo(1); } - @Test - public void testStaticMethodCall2() { + @ParameterizedTest + @MethodSource("parameters") + public void testStaticMethodCall2(RUN_TYPE runType) { // DROOLS-5214 String str = "package com.sample\n" + @@ -154,15 +156,16 @@ public void testStaticMethodCall2() { "then\n" + "end"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); ksession.insert( new Pojo( Arrays.asList(1,2,3) ) ); int rulesFired = ksession.fireAllRules(); assertThat(rulesFired).isEqualTo(1); } - @Test - public void testFQNStaticMethodCall1() { + @ParameterizedTest + @MethodSource("parameters") + public void testFQNStaticMethodCall1(RUN_TYPE runType) { // DROOLS-5214 String str = "package com.sample\n" + @@ -173,15 +176,16 @@ public void testFQNStaticMethodCall1() { "then\n" + "end"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); ksession.insert( new Pojo( Arrays.asList(1,3) ) ); int rulesFired = ksession.fireAllRules(); assertThat(rulesFired).isEqualTo(1); } - @Test - public void testFQNStaticMethodCall2() { + @ParameterizedTest + @MethodSource("parameters") + public void testFQNStaticMethodCall2(RUN_TYPE runType) { // DROOLS-5214 String str = "package com.sample\n" + @@ -192,7 +196,7 @@ public void testFQNStaticMethodCall2() { "then\n" + "end"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); ksession.insert( new Pojo( Arrays.asList(1,2,3) ) ); int rulesFired = ksession.fireAllRules(); @@ -211,8 +215,9 @@ public List getIntList() { } } - @Test - public void testInvokeFunctionWithDroolsKeyword() { + @ParameterizedTest + @MethodSource("parameters") + public void testInvokeFunctionWithDroolsKeyword(RUN_TYPE runType) { // DROOLS-5215 String str = "package com.sample\n" + @@ -226,14 +231,15 @@ public void testInvokeFunctionWithDroolsKeyword() { " printRuleName(drools.getRule().getName());\n" + " end"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); int rulesFired = ksession.fireAllRules(); assertThat(rulesFired).isEqualTo(1); } - @Test - public void testBindingFieldsIndexedWithSquareBrackets() { + @ParameterizedTest + @MethodSource("parameters") + public void testBindingFieldsIndexedWithSquareBrackets(RUN_TYPE runType) { // DROOLS-5216 String str = "package com.sample\n" + @@ -245,7 +251,7 @@ public void testBindingFieldsIndexedWithSquareBrackets() { "then\n" + "end"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); ksession.insert( new Pojo( Arrays.asList(1,3) ) ); int rulesFired = ksession.fireAllRules(); @@ -256,8 +262,9 @@ public static String constantValue(String input) { return "whatever"; } - @Test - public void testExternalFunctionJoin() { + @ParameterizedTest + @MethodSource("parameters") + public void testExternalFunctionJoin(RUN_TYPE runType) { // DROOLS-5288 String str = "import " + Person.class.getCanonicalName() + ";" + @@ -273,7 +280,7 @@ public void testExternalFunctionJoin() { " insert(new Result($p2.getName()));\n" + "end"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); ksession.insert(new Person("Luca")); ksession.insert(new Person("whatever")); diff --git a/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/GeneratedClassNamesTest.java b/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/GeneratedClassNamesTest.java index 97e765af554..4453582a29f 100644 --- a/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/GeneratedClassNamesTest.java +++ b/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/GeneratedClassNamesTest.java @@ -20,6 +20,7 @@ import java.util.Set; import java.util.UUID; +import java.util.stream.Stream; import org.drools.compiler.compiler.io.memory.MemoryFileSystem; import org.drools.compiler.kie.builder.impl.InternalKieModule; @@ -30,10 +31,10 @@ import org.drools.modelcompiler.CanonicalKieModule; import org.drools.wiring.api.classloader.ProjectClassLoader; import org.drools.wiring.api.classloader.ProjectClassLoaderTestUtil; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; -import org.junit.runners.Parameterized.Parameters; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; import org.kie.api.KieBase; import org.kie.api.KieServices; import org.kie.api.builder.KieBuilder; @@ -54,28 +55,24 @@ public class GeneratedClassNamesTest extends BaseModelTest { private boolean enableStoreFirstOrig; - public GeneratedClassNamesTest(RUN_TYPE testRunType) { - super(testRunType); + public static Stream parameters() { + return Stream.of(RUN_TYPE.PATTERN_DSL); } - @Parameters(name = "{0}") - public static Object[] params() { - return new Object[]{RUN_TYPE.PATTERN_DSL}; - } - - @Before - public void init() { + @BeforeEach + public void setUp() { enableStoreFirstOrig = ProjectClassLoader.isEnableStoreFirst(); ProjectClassLoaderTestUtil.setEnableStoreFirst(true); } - @After - public void clear() { + @AfterEach + public void tearDown() { ProjectClassLoaderTestUtil.setEnableStoreFirst(enableStoreFirstOrig); } - @Test - public void testGeneratedClassNames() { + @ParameterizedTest + @MethodSource("parameters") + public void testGeneratedClassNames(RUN_TYPE runType) { String str = "import " + Person.class.getCanonicalName() + ";" + "rule R when\n" + @@ -87,7 +84,7 @@ public void testGeneratedClassNames() { KieServices ks = KieServices.get(); ReleaseId releaseId = ks.newReleaseId("org.kie", "kjar-test-" + UUID.randomUUID(), "1.0"); - createKieBuilder(ks, getDefaultKieModuleModel( ks ), releaseId, toKieFiles(new String[]{str})); + createKieBuilder(runType, ks, getDefaultKieModuleModel( ks ), releaseId, toKieFiles(new String[]{str})); KieContainer kcontainer = ks.newKieContainer(releaseId); KieModule kieModule = ((KieContainerImpl) kcontainer).getKieModuleForKBase("kbase"); @@ -123,12 +120,14 @@ private void assertGeneratedClassNames(Set generatedClassNames) { } } - @Test + @ParameterizedTest + @MethodSource("parameters") public void testModuleWithDepWithoutClassLoader() throws Exception { testModuleWithDep(null); } - @Test + @ParameterizedTest + @MethodSource("parameters") public void testModuleWithDepWithClassLoader() throws Exception { ProjectClassLoader projectClassLoader = ProjectClassLoader.createProjectClassLoader(Thread.currentThread().getContextClassLoader()); testModuleWithDep(projectClassLoader); @@ -266,8 +265,9 @@ private void assertGeneratedClassNamesWithDep(Set generatedClassNames) { } } - @Test - public void testKjarWithoutGeneratedClassNames() { + @ParameterizedTest + @MethodSource("parameters") + public void testKjarWithoutGeneratedClassNames(RUN_TYPE runType) { // Build a kjar without generated-class-names file (= simulating a build by old drools version) ProjectClassLoaderTestUtil.setEnableStoreFirst(false); @@ -283,7 +283,7 @@ public void testKjarWithoutGeneratedClassNames() { KieServices ks = KieServices.get(); ReleaseId releaseId = ks.newReleaseId("org.kie", "kjar-test-" + UUID.randomUUID(), "1.0"); - KieBuilder kieBuilder = createKieBuilder(ks, getDefaultKieModuleModel( ks ), releaseId, toKieFiles(new String[]{str})); + KieBuilder kieBuilder = createKieBuilder(runType, ks, getDefaultKieModuleModel( ks ), releaseId, toKieFiles(new String[]{str})); final InternalKieModule kieModule = (InternalKieModule) kieBuilder.getKieModule(); byte[] kjar = kieModule.getBytes(); diff --git a/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/GenericsTest.java b/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/GenericsTest.java index c08544f01e9..a2bccfaaece 100644 --- a/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/GenericsTest.java +++ b/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/GenericsTest.java @@ -24,19 +24,17 @@ import org.drools.model.codegen.execmodel.domain.Address; import org.drools.model.codegen.execmodel.domain.Person; -import org.junit.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; import org.kie.api.runtime.KieSession; import static org.assertj.core.api.Assertions.assertThat; public class GenericsTest extends BaseModelTest { - public GenericsTest(RUN_TYPE testRunType) { - super(testRunType); - } - - @Test - public void testGenericsAccumulateInlineCode() { + @ParameterizedTest + @MethodSource("parameters") + public void testGenericsAccumulateInlineCode(RUN_TYPE runType) { // accumulate inline code supports generics String str = "import " + Person.class.getCanonicalName() + ";\n" + @@ -55,7 +53,7 @@ public void testGenericsAccumulateInlineCode() { " results.add($l);\n" + "end"; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); List> results = new ArrayList<>(); ksession.setGlobal("results", results); @@ -94,8 +92,9 @@ public void setExtendedAddress(final P extendedAddress) { } } - @Test - public void testClassWithGenericField() { + @ParameterizedTest + @MethodSource("parameters") + public void testClassWithGenericField(RUN_TYPE runType) { // KIE-1077 String str = "import " + ClassWithGenericField.class.getCanonicalName() + ";\n " + @@ -107,7 +106,7 @@ public void testClassWithGenericField() { " results.add($addressStreet);\n " + "end"; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); List results = new ArrayList<>(); ksession.setGlobal("results", results); @@ -118,8 +117,9 @@ public void testClassWithGenericField() { assertThat(ksession.fireAllRules()).isEqualTo(1); } - @Test - public void testGenericsOnSuperclass() { + @ParameterizedTest + @MethodSource("parameters") + public void testGenericsOnSuperclass(RUN_TYPE runType) { // KIE-DROOLS-5925 String str = "import " + DieselCar.class.getCanonicalName() + ";\n " + @@ -143,11 +143,12 @@ public void testGenericsOnSuperclass() { " update($v);\n" + "end"; - runTestWithGenerics(str); + runTestWithGenerics(runType, str); } - @Test - public void testGenericsOnSuperclassWithRedundantVariableDeclaration() { + @ParameterizedTest + @MethodSource("parameters") + public void testGenericsOnSuperclassWithRedundantVariableDeclaration(RUN_TYPE runType) { // KIE-DROOLS-5925 String str = "import " + DieselCar.class.getCanonicalName() + ";\n " + @@ -171,11 +172,11 @@ public void testGenericsOnSuperclassWithRedundantVariableDeclaration() { " update($v);\n" + "end"; - runTestWithGenerics(str); + runTestWithGenerics(runType, str); } - private void runTestWithGenerics(String str) { - KieSession ksession = getKieSession(str); + private void runTestWithGenerics(RUN_TYPE runType, String str) { + KieSession ksession = getKieSession(runType, str); DieselCar vehicle1 = new DieselCar("Volkswagen", "Passat", 100); vehicle1.setFrameMaxTorque(500); diff --git a/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/GetterOverloadingTest.java b/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/GetterOverloadingTest.java index 5c72aa7700a..d4408ce55e3 100644 --- a/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/GetterOverloadingTest.java +++ b/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/GetterOverloadingTest.java @@ -20,7 +20,8 @@ import java.util.List; -import org.junit.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; import org.kie.api.KieServices; import org.kie.api.builder.KieBuilder; import org.kie.api.builder.Message.Level; @@ -31,10 +32,6 @@ public class GetterOverloadingTest extends BaseModelTest { - public GetterOverloadingTest(RUN_TYPE testRunType) { - super(testRunType); - } - // NOTE: Drools/Mvel accepts 5 kinds of getters // e.g. for "resource" property, // @@ -46,8 +43,9 @@ public GetterOverloadingTest(RUN_TYPE testRunType) { // // If a class has multiple getters of those 5, one getter has to be chosen based on the above priority order - @Test - public void testDuplicateDifferentPropertyInClassHierarchy() { + @ParameterizedTest + @MethodSource("parameters") + public void testDuplicateDifferentPropertyInClassHierarchy(RUN_TYPE runType) { // ClassA.resource is boolean : isResource() // ClassB.resource is String : getResource() // Mvel picks a method from getResource or isResoure depending on the order of Class.getMethods() -> unreliable. So let's make this ERROR @@ -59,7 +57,7 @@ public void testDuplicateDifferentPropertyInClassHierarchy() { "then\n" + "end\n"; - KieBuilder kieBuilder = createKieBuilder(str); + KieBuilder kieBuilder = createKieBuilder(runType, str); List messages = kieBuilder.getResults().getMessages(Level.ERROR); assertThat(messages.get(0).getText()).contains("Incompatible Getter overloading detected"); } @@ -90,8 +88,9 @@ public void setResource(String resource) { } } - @Test - public void testBooleanAccessorOverload() { + @ParameterizedTest + @MethodSource("parameters") + public void testBooleanAccessorOverload(RUN_TYPE runType) { // ClassC implements both isResource() and getResource() for boolean (This is acceptable according to Javabeans spec) // isResource() has to be prioritized per Javabeans spec. // No Warning @@ -103,7 +102,7 @@ public void testBooleanAccessorOverload() { "then\n" + "end\n"; - KieBuilder kieBuilder = createKieBuilder(str); + KieBuilder kieBuilder = createKieBuilder(runType, str); List messages = kieBuilder.getResults().getMessages(); assertThat(messages).isEmpty(); @@ -135,8 +134,9 @@ public void setResource(boolean resource) { } } - @Test - public void testAccessorInMultipleInterfaces() { + @ParameterizedTest + @MethodSource("parameters") + public void testAccessorInMultipleInterfaces(RUN_TYPE runType) { // 2 super interfaces have the same abstract method // Valid overriding. No warning. final String str = @@ -147,7 +147,7 @@ public void testAccessorInMultipleInterfaces() { "then\n" + "end\n"; - KieBuilder kieBuilder = createKieBuilder(str); + KieBuilder kieBuilder = createKieBuilder(runType, str); List messages = kieBuilder.getResults().getMessages(); assertThat(messages).isEmpty(); @@ -189,8 +189,9 @@ public String getName() { } } - @Test - public void testAccessorInSuperClassAndInterface() { + @ParameterizedTest + @MethodSource("parameters") + public void testAccessorInSuperClassAndInterface(RUN_TYPE runType) { // Valid overriding from super class and interface. No Warning final String str = "import " + ClassF.class.getCanonicalName() + ";" + @@ -200,7 +201,7 @@ public void testAccessorInSuperClassAndInterface() { "then\n" + "end\n"; - KieBuilder kieBuilder = createKieBuilder(str); + KieBuilder kieBuilder = createKieBuilder(runType, str); List messages = kieBuilder.getResults().getMessages(); assertThat(messages).isEmpty(); @@ -240,8 +241,9 @@ public String getName() { } } - @Test - public void testAcceptableStringAccessorOverload() { + @ParameterizedTest + @MethodSource("parameters") + public void testAcceptableStringAccessorOverload(RUN_TYPE runType) { // ClassG implements getName(), getname() and name() for String // This is acceptable overloading and getName() has to be prioritized. No Warning. final String str = @@ -252,7 +254,7 @@ public void testAcceptableStringAccessorOverload() { "then\n" + "end\n"; - KieBuilder kieBuilder = createKieBuilder(str); + KieBuilder kieBuilder = createKieBuilder(runType, str); List messages = kieBuilder.getResults().getMessages(); assertThat(messages).isEmpty(); @@ -287,8 +289,9 @@ public String name() { } } - @Test - public void testCovariantOverload() { + @ParameterizedTest + @MethodSource("parameters") + public void testCovariantOverload(RUN_TYPE runType) { // ClassH : getValue() returns Number // ClassI : getValue() returns Integer // a more specialized getter (covariant overload) is preferred. @@ -300,7 +303,7 @@ public void testCovariantOverload() { "then\n" + "end\n"; - KieBuilder kieBuilder = createKieBuilder(str); + KieBuilder kieBuilder = createKieBuilder(runType, str); List messages = kieBuilder.getResults().getMessages(); assertThat(messages).isEmpty(); @@ -339,8 +342,9 @@ public Integer getValue() { } } - @Test - public void testContravariantOverload() { + @ParameterizedTest + @MethodSource("parameters") + public void testContravariantOverload(RUN_TYPE runType) { // ClassJ : getValue() returns Integer // ClassK : getvalue() returns Number // a more specialized getter (covariant overload) is preferred regardless of class hierarchy. @@ -352,7 +356,7 @@ public void testContravariantOverload() { "then\n" + "end\n"; - KieBuilder kieBuilder = createKieBuilder(str); + KieBuilder kieBuilder = createKieBuilder(runType, str); List messages = kieBuilder.getResults().getMessages(); assertThat(messages).isEmpty(); @@ -390,8 +394,9 @@ public Number getvalue() { // cannot define Number getValue() } } - @Test - public void testPossibleBooleanAccessorOverload() { + @ParameterizedTest + @MethodSource("parameters") + public void testPossibleBooleanAccessorOverload(RUN_TYPE runType) { // ClassL implements 5 possible getters // This is acceptable overloading and isResource() has to be prioritized. No Warning. final String str = @@ -402,7 +407,7 @@ public void testPossibleBooleanAccessorOverload() { "then\n" + "end\n"; - KieBuilder kieBuilder = createKieBuilder(str); + KieBuilder kieBuilder = createKieBuilder(runType, str); List messages = kieBuilder.getResults().getMessages(); assertThat(messages).isEmpty(); diff --git a/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/GlobalTest.java b/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/GlobalTest.java index 190a6bc792a..b3bf58b9c81 100644 --- a/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/GlobalTest.java +++ b/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/GlobalTest.java @@ -25,7 +25,8 @@ import org.drools.model.codegen.execmodel.domain.InputDataTypes; import org.drools.model.codegen.execmodel.domain.Person; import org.drools.model.codegen.execmodel.domain.Result; -import org.junit.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; import org.kie.api.KieBase; import org.kie.api.builder.Message; import org.kie.api.builder.Results; @@ -36,12 +37,9 @@ public class GlobalTest extends BaseModelTest { - public GlobalTest( RUN_TYPE testRunType ) { - super( testRunType ); - } - - @Test - public void testGlobalInConsequence() { + @ParameterizedTest + @MethodSource("parameters") + public void testGlobalInConsequence(RUN_TYPE runType) { String str = "package org.mypkg;" + "import " + Person.class.getCanonicalName() + ";" + @@ -53,7 +51,7 @@ public void testGlobalInConsequence() { " globalResult.setValue($p1.getName() + \" is \" + $p1.getAge());\n" + "end"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); Result result = new Result(); ksession.setGlobal("globalResult", result); @@ -67,8 +65,9 @@ public void testGlobalInConsequence() { assertThat(result.getValue()).isEqualTo("Mark is 37"); } - @Test - public void testGlobalInConstraint() { + @ParameterizedTest + @MethodSource("parameters") + public void testGlobalInConstraint(RUN_TYPE runType) { String str = "package org.mypkg;" + "import " + Person.class.getCanonicalName() + ";" + @@ -81,7 +80,7 @@ public void testGlobalInConstraint() { " resultG.setValue($p1.getName() + \" is \" + $p1.getAge());\n" + "end"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); ksession.setGlobal("nameG", "Mark"); @@ -164,8 +163,9 @@ public Double sumOf(Object[] objects) { } - @Test - public void testGlobalBooleanFunction() { + @ParameterizedTest + @MethodSource("parameters") + public void testGlobalBooleanFunction(RUN_TYPE runType) { String str = "package org.mypkg;" + "import " + Person.class.getCanonicalName() + ";" + @@ -179,7 +179,7 @@ public void testGlobalBooleanFunction() { " resultG.setValue($p1.getName() + \" is \" + $p1.getAge());\n" + "end"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); ksession.setGlobal("functions", new Functions()); @@ -195,8 +195,9 @@ public void testGlobalBooleanFunction() { assertThat(result.getValue()).isEqualTo("Mark is 37"); } - @Test - public void testGlobalFunctionOnLeft() { + @ParameterizedTest + @MethodSource("parameters") + public void testGlobalFunctionOnLeft(RUN_TYPE runType) { String str = "package org.mypkg;" + "import " + Person.class.getCanonicalName() + ";" + @@ -210,7 +211,7 @@ public void testGlobalFunctionOnLeft() { " resultG.setValue($p1.getName() + \" is \" + $p1.getAge());\n" + "end"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); ksession.setGlobal("functions", new Functions()); @@ -226,8 +227,9 @@ public void testGlobalFunctionOnLeft() { assertThat(result.getValue()).isEqualTo("Mark is 37"); } - @Test - public void testGlobalFunctionOnRight() { + @ParameterizedTest + @MethodSource("parameters") + public void testGlobalFunctionOnRight(RUN_TYPE runType) { String str = "package org.mypkg;" + "import " + Person.class.getCanonicalName() + ";" + @@ -241,7 +243,7 @@ public void testGlobalFunctionOnRight() { " resultG.setValue($p1.getName() + \" is \" + $p1.getAge());\n" + "end"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); ksession.setGlobal("functions", new Functions()); @@ -263,8 +265,9 @@ public Object getPersons() { } } - @Test - public void testComplexGlobalFunction() { + @ParameterizedTest + @MethodSource("parameters") + public void testComplexGlobalFunction(RUN_TYPE runType) { String str = "package org.mypkg;" + "import " + Family.class.getCanonicalName() + ";" + @@ -277,15 +280,16 @@ public void testComplexGlobalFunction() { "then\n" + "end"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); ksession.setGlobal("functions", new Functions()); ksession.insert(new Family()); assertThat(ksession.fireAllRules()).isEqualTo(1); } - @Test - public void testComplexGlobalFunctionWithShort() { + @ParameterizedTest + @MethodSource("parameters") + public void testComplexGlobalFunctionWithShort(RUN_TYPE runType) { String str = "package org.mypkg;" + "import " + Family.class.getCanonicalName() + ";" + @@ -298,15 +302,16 @@ public void testComplexGlobalFunctionWithShort() { "then\n" + "end"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); ksession.setGlobal("functions", new Functions()); ksession.insert(new Family()); assertThat(ksession.fireAllRules()).isEqualTo(1); } - @Test - public void testComplexGlobalFunctionWithShortEvalOnJoin() { + @ParameterizedTest + @MethodSource("parameters") + public void testComplexGlobalFunctionWithShortEvalOnJoin(RUN_TYPE runType) { String str = "package org.mypkg;" + "import " + Family.class.getCanonicalName() + ";" + @@ -320,7 +325,7 @@ public void testComplexGlobalFunctionWithShortEvalOnJoin() { "then\n" + "end"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); ksession.setGlobal("functions", new Functions()); ksession.insert(new Family()); ksession.insert("test"); @@ -328,8 +333,9 @@ public void testComplexGlobalFunctionWithShortEvalOnJoin() { assertThat(ksession.fireAllRules()).isEqualTo(1); } - @Test - public void testComplexGlobalFunctionWithShortNotFiring() { + @ParameterizedTest + @MethodSource("parameters") + public void testComplexGlobalFunctionWithShortNotFiring(RUN_TYPE runType) { String str = "package org.mypkg;" + "import " + Family.class.getCanonicalName() + ";" + @@ -342,7 +348,7 @@ public void testComplexGlobalFunctionWithShortNotFiring() { "then\n" + "end"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); ksession.setGlobal("functions", new Functions()); ksession.insert(new Family()); @@ -350,17 +356,19 @@ public void testComplexGlobalFunctionWithShortNotFiring() { } - @Test - public void testGlobalOnTypeDeclaration() throws Exception { + @ParameterizedTest + @MethodSource("parameters") + public void testGlobalOnTypeDeclaration(RUN_TYPE runType) throws Exception { String str = "declare MyObject end\n" + "global MyObject event;"; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); } - @Test - public void testGlobalFunctionWithArrayInput() { + @ParameterizedTest + @MethodSource("parameters") + public void testGlobalFunctionWithArrayInput(RUN_TYPE runType) { String str = "package org.mypkg;" + "import " + InputDataTypes.class.getCanonicalName() + ";" + @@ -384,15 +392,16 @@ public void testGlobalFunctionWithArrayInput() { " update($input);\n" + "end"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); ksession.setGlobal("functions", new Functions()); ksession.insert(new InputDataTypes()); assertThat(ksession.fireAllRules()).isEqualTo(1); } - @Test - public void testGlobalFunctionWithLargeArrayInput() { + @ParameterizedTest + @MethodSource("parameters") + public void testGlobalFunctionWithLargeArrayInput(RUN_TYPE runType) { String str = "package org.mypkg;" + "import " + InputDataTypes.class.getCanonicalName() + ";" + @@ -453,15 +462,16 @@ public void testGlobalFunctionWithLargeArrayInput() { " update($input);\n" + "end"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); ksession.setGlobal("functions", new Functions()); ksession.insert(new InputDataTypes()); assertThat(ksession.fireAllRules()).isEqualTo(1); } - @Test - public void testGlobalInDifferentPackage() throws InstantiationException, IllegalAccessException { + @ParameterizedTest + @MethodSource("parameters") + public void testGlobalInDifferentPackage(RUN_TYPE runType) throws InstantiationException, IllegalAccessException { // DROOLS-6657 String def = "package org.drools.reproducer.definitions\n" + @@ -482,7 +492,7 @@ public void testGlobalInDifferentPackage() throws InstantiationException, Illega " globalList.add(\"FOO matched\");\n" + "end\n"; - KieSession ksession = getKieSession( rule, def ); + KieSession ksession = getKieSession(runType, rule, def); KieBase kb = ksession.getKieBase(); assertThat(ksession.fireAllRules()).isEqualTo(0); @@ -502,8 +512,9 @@ public void testGlobalInDifferentPackage() throws InstantiationException, Illega assertThat(globalList.get(0)).isEqualTo("FOO matched"); } - @Test - public void testGenericOnGlobal() { + @ParameterizedTest + @MethodSource("parameters") + public void testGenericOnGlobal(RUN_TYPE runType) { // DROOLS-7155 String def = "package org.drools.reproducer\n" + @@ -513,14 +524,15 @@ public void testGenericOnGlobal() { " globalList.add(\"test\");\n" + "end\n"; - KieSession ksession = getKieSession( def ); + KieSession ksession = getKieSession(runType, def); ksession.setGlobal("globalList", new ArrayList()); assertThat(ksession.fireAllRules()).isEqualTo(1); } - @Test - public void testWrongGenericOnGlobal() { + @ParameterizedTest + @MethodSource("parameters") + public void testWrongGenericOnGlobal(RUN_TYPE runType) { // DROOLS-7155 String def = "package org.drools.reproducer\n" + @@ -530,7 +542,7 @@ public void testWrongGenericOnGlobal() { " globalList.add(\"test\");\n" + "end\n"; - Results results = createKieBuilder(def).getResults(); + Results results = createKieBuilder(runType, def).getResults(); assertThat(results.getMessages(Message.Level.ERROR)).isNotEmpty(); assertThat(results.getMessages(Message.Level.ERROR).stream().map(Message::getText) .anyMatch(s -> s.contains("The method add(Integer) in the type List is not applicable for the arguments (String)"))).isTrue(); diff --git a/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/GroupByTest.java b/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/GroupByTest.java index 020cbce685e..1adc41e23d6 100644 --- a/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/GroupByTest.java +++ b/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/GroupByTest.java @@ -25,7 +25,8 @@ import org.drools.model.codegen.execmodel.domain.Parent; import org.drools.model.codegen.execmodel.domain.Person; import org.drools.model.functions.accumulate.GroupKey; -import org.junit.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; import org.kie.api.runtime.KieSession; import org.kie.api.runtime.rule.FactHandle; import org.kie.api.runtime.rule.Match; @@ -49,28 +50,25 @@ public class GroupByTest extends BaseModelTest { - public GroupByTest( RUN_TYPE testRunType ) { - super( testRunType ); - } - - public void assertSessionHasProperties(String ruleString, Consumer kieSessionConsumer) { + public void assertSessionHasProperties(RUN_TYPE testRunType, String ruleString, Consumer kieSessionConsumer) { if (testRunType.isExecutableModel()) { - KieSession ksession = getKieSession( ruleString ); + KieSession ksession = getKieSession(testRunType, ruleString); kieSessionConsumer.accept(ksession); } else { assertAll(() -> { - KieSession ksession = getKieSession( "dialect \"java\";\n" + ruleString); + KieSession ksession = getKieSession(testRunType, "dialect \"java\";\n" + ruleString); kieSessionConsumer.accept(ksession); }, () -> { - KieSession ksession = getKieSession( "dialect \"mvel\";\n" + ruleString); + KieSession ksession = getKieSession(testRunType, "dialect \"mvel\";\n" + ruleString); kieSessionConsumer.accept(ksession); }); } } - @Test - public void providedInstance() { + @ParameterizedTest + @MethodSource("parameters") + public void providedInstance(RUN_TYPE runType) { String str = "import " + Person.class.getCanonicalName() + ";\n" + "import " + Map.class.getCanonicalName() + ";\n" + "global Map results;\n" + @@ -83,7 +81,7 @@ public void providedInstance() { " results.put($key, $sumOfAges);\n" + "end"; - assertSessionHasProperties(str, ksession -> { + assertSessionHasProperties(runType, str, ksession -> { Map results = new HashMap(); ksession.setGlobal( "results", results ); @@ -117,8 +115,9 @@ public void providedInstance() { }); } - @Test - public void testSumPersonAgeGroupByInitialWithAcc() { + @ParameterizedTest + @MethodSource("parameters") + public void testSumPersonAgeGroupByInitialWithAcc(RUN_TYPE runType) { String str = "import " + Person.class.getCanonicalName() + ";" + "import " + GroupKey.class.getCanonicalName() + ";" + @@ -146,7 +145,7 @@ public void testSumPersonAgeGroupByInitialWithAcc() { " results.put($key, $sumOfAges);\n" + "end"; - assertSessionHasProperties(str, ksession -> { + assertSessionHasProperties(runType, str, ksession -> { Map results = new HashMap(); ksession.setGlobal( "results", results ); @@ -181,8 +180,9 @@ public void testSumPersonAgeGroupByInitialWithAcc() { }); } - @Test - public void testGroupPersonsInitial() { + @ParameterizedTest + @MethodSource("parameters") + public void testGroupPersonsInitial(RUN_TYPE runType) { String str = "import " + Person.class.getCanonicalName() + ";" + "import " + List.class.getCanonicalName() + ";" + @@ -194,7 +194,7 @@ public void testGroupPersonsInitial() { " results.add($key);\n" + "end"; - assertSessionHasProperties(str, ksession -> { + assertSessionHasProperties(runType, str, ksession -> { List results = new ArrayList<>(); ksession.setGlobal( "results", results ); @@ -229,8 +229,9 @@ public void testGroupPersonsInitial() { }); } - @Test - public void testSumPersonAgeGroupByInitial() { + @ParameterizedTest + @MethodSource("parameters") + public void testSumPersonAgeGroupByInitial(RUN_TYPE runType) { // Note: this appears to be a duplicate of providedInstance String str = "import " + Person.class.getCanonicalName() + ";" + @@ -244,7 +245,7 @@ public void testSumPersonAgeGroupByInitial() { "then\n" + " results.put($key, $sumOfAges);\n" + "end"; - assertSessionHasProperties(str, ksession -> { + assertSessionHasProperties(runType, str, ksession -> { Map results = new HashMap(); ksession.setGlobal( "results", results ); @@ -279,8 +280,9 @@ public void testSumPersonAgeGroupByInitial() { }); } - @Test - public void testSumPersonAgeGroupByInitialWithBetaFilter() { + @ParameterizedTest + @MethodSource("parameters") + public void testSumPersonAgeGroupByInitialWithBetaFilter(RUN_TYPE runType) { // TODO: For some reason, the compiled class expression thinks $p should be an integer? String str = "import " + Person.class.getCanonicalName() + ";" + @@ -295,7 +297,7 @@ public void testSumPersonAgeGroupByInitialWithBetaFilter() { " results.put($key, $sum);\n" + "end"; - assertSessionHasProperties(str, ksession -> { + assertSessionHasProperties(runType, str, ksession -> { Map results = new HashMap(); ksession.setGlobal("results", results); @@ -331,8 +333,9 @@ public void testSumPersonAgeGroupByInitialWithBetaFilter() { }); } - @Test - public void testSumPersonAgeGroupByInitialWithExists() { + @ParameterizedTest + @MethodSource("parameters") + public void testSumPersonAgeGroupByInitialWithExists(RUN_TYPE runType) { // TODO: For some reason, the compiled class expression thinks $p should be an integer? String str = "import " + Person.class.getCanonicalName() + ";" + @@ -348,7 +351,7 @@ public void testSumPersonAgeGroupByInitialWithExists() { " results.put($key, $sum);\n" + "end"; - assertSessionHasProperties(str, ksession -> { + assertSessionHasProperties(runType, str, ksession -> { Map results = new HashMap(); ksession.setGlobal("results", results); @@ -405,8 +408,9 @@ public MyType getNested() { } } - @Test - public void testWithNull() { + @ParameterizedTest + @MethodSource("parameters") + public void testWithNull(RUN_TYPE runType) { String str = "import " + MyType.class.getCanonicalName() + ";" + "import " + List.class.getCanonicalName() + ";" + @@ -421,7 +425,7 @@ public void testWithNull() { " result.add($key);\n" + "end"; - assertSessionHasProperties(str, ksession -> { + assertSessionHasProperties(runType, str, ksession -> { AtomicInteger mappingFunctionCallCounter = new AtomicInteger(); List result = new ArrayList<>(); ksession.setGlobal("mappingFunctionCallCounter", mappingFunctionCallCounter); @@ -440,8 +444,9 @@ public void testWithNull() { }); } - @Test - public void testWithGroupByAfterExists() { + @ParameterizedTest + @MethodSource("parameters") + public void testWithGroupByAfterExists(RUN_TYPE runType) { String str = "import " + Map.class.getCanonicalName() + ";" + "import " + Math.class.getCanonicalName() + ";" + @@ -454,7 +459,7 @@ public void testWithGroupByAfterExists() { " glob.put($key, $count.intValue());\n" + "end"; - assertSessionHasProperties(str, session -> { + assertSessionHasProperties(runType, str, session -> { Map global = new HashMap<>(); session.setGlobal("glob", global); @@ -470,8 +475,9 @@ public void testWithGroupByAfterExists() { }); } - @Test - public void testWithGroupByAfterExistsWithFrom() { + @ParameterizedTest + @MethodSource("parameters") + public void testWithGroupByAfterExistsWithFrom(RUN_TYPE runType) { // Note: this looks exactly the same as testWithGroupByAfterExists String str = "import " + Map.class.getCanonicalName() + ";" + @@ -485,7 +491,7 @@ public void testWithGroupByAfterExistsWithFrom() { " glob.put($key, $count.intValue());\n" + "end"; - assertSessionHasProperties(str, session -> { + assertSessionHasProperties(runType, str, session -> { Map global = new HashMap<>(); session.setGlobal("glob", global); @@ -501,8 +507,9 @@ public void testWithGroupByAfterExistsWithFrom() { }); } - @Test - public void testGroupBy2Vars() { + @ParameterizedTest + @MethodSource("parameters") + public void testGroupBy2Vars(RUN_TYPE runType) { // TODO: For some reason, the compiled class expression thinks $p should be an integer? String str = "import " + Person.class.getCanonicalName() + ";" + @@ -516,7 +523,7 @@ public void testGroupBy2Vars() { " results.put($key, $sum);\n" + "end"; - assertSessionHasProperties(str, ksession -> { + assertSessionHasProperties(runType, str, ksession -> { Map results = new HashMap(); ksession.setGlobal("results", results); @@ -560,8 +567,9 @@ public void testGroupBy2Vars() { }); } - @Test - public void testUnexpectedRuleMatch() { + @ParameterizedTest + @MethodSource("parameters") + public void testUnexpectedRuleMatch(RUN_TYPE runType) { String str = "import " + Parent.class.getCanonicalName() + ";" + "import " + Child.class.getCanonicalName() + ";" + @@ -578,7 +586,7 @@ public void testUnexpectedRuleMatch() { " results.add(Arrays.asList($child, $count));\n" + "end"; - assertSessionHasProperties(str, ksession -> { + assertSessionHasProperties(runType, str, ksession -> { List results = new ArrayList(); ksession.setGlobal("results", results); @@ -603,8 +611,9 @@ public void testUnexpectedRuleMatch() { }); } - @Test - public void testCompositeKey() { + @ParameterizedTest + @MethodSource("parameters") + public void testCompositeKey(RUN_TYPE runType) { // TODO: For some reason, the compiled class expression thinks $p should be an integer? String str = "import " + Person.class.getCanonicalName() + ";" + @@ -623,7 +632,7 @@ public void testCompositeKey() { " results.put($key1, $sum);\n" + "end"; - assertSessionHasProperties(str, ksession -> { + assertSessionHasProperties(runType, str, ksession -> { Map results = new HashMap(); ksession.setGlobal("results", results); @@ -698,8 +707,9 @@ public String toString() { } } - @Test - public void testTwoExpressionsOnSecondPattern() { + @ParameterizedTest + @MethodSource("parameters") + public void testTwoExpressionsOnSecondPattern(RUN_TYPE runType) { // DROOLS-5704 // TODO: For some reason, the compiled class expression thinks $p should be an integer? String str = @@ -716,7 +726,7 @@ public void testTwoExpressionsOnSecondPattern() { " results.add($key);\n" + "end"; - assertSessionHasProperties(str, ksession -> { + assertSessionHasProperties(runType, str, ksession -> { Set results = new LinkedHashSet<>(); ksession.setGlobal("results", results); @@ -730,8 +740,9 @@ public void testTwoExpressionsOnSecondPattern() { }); } - @Test - public void testFromAfterGroupBy() { + @ParameterizedTest + @MethodSource("parameters") + public void testFromAfterGroupBy(RUN_TYPE runType) { String str = "import " + Person.class.getCanonicalName() + ";" + "import " + Set.class.getCanonicalName() + ";" + @@ -750,7 +761,7 @@ public void testFromAfterGroupBy() { " typeChecker.accept($remappedKey);\n" + "end"; - assertSessionHasProperties(str, ksession -> { + assertSessionHasProperties(runType, str, ksession -> { Set results = new LinkedHashSet<>(); ksession.setGlobal("results", results); @@ -768,8 +779,9 @@ public void testFromAfterGroupBy() { }); } - @Test - public void testBindingRemappedAfterGroupBy() { + @ParameterizedTest + @MethodSource("parameters") + public void testBindingRemappedAfterGroupBy(RUN_TYPE runType) { String str = "import " + Person.class.getCanonicalName() + ";" + "import " + Set.class.getCanonicalName() + ";" + @@ -788,7 +800,7 @@ public void testBindingRemappedAfterGroupBy() { " typeChecker.accept($remappedKey);\n" + "end"; - assertSessionHasProperties(str, ksession -> { + assertSessionHasProperties(runType, str, ksession -> { Set results = new LinkedHashSet<>(); ksession.setGlobal("results", results); @@ -806,8 +818,9 @@ public void testBindingRemappedAfterGroupBy() { }); } - @Test - public void testGroupByUpdatingKey() { + @ParameterizedTest + @MethodSource("parameters") + public void testGroupByUpdatingKey(RUN_TYPE runType) { String str = "import " + Person.class.getCanonicalName() + ";" + "import " + Map.class.getCanonicalName() + ";" + @@ -823,7 +836,7 @@ public void testGroupByUpdatingKey() { " results.put($key, $sumOfAges + $countOfPersons.intValue());" + "end"; - assertSessionHasProperties(str, ksession -> { + assertSessionHasProperties(runType, str, ksession -> { Map results = new HashMap(); ksession.setGlobal("results", results); @@ -851,8 +864,9 @@ public void testGroupByUpdatingKey() { }); } - @Test - public void doesNotRemoveProperly() { + @ParameterizedTest + @MethodSource("parameters") + public void doesNotRemoveProperly(RUN_TYPE runType) { String str = "import " + Person.class.getCanonicalName() + ";" + "import " + Set.class.getCanonicalName() + ";" + @@ -867,7 +881,7 @@ public void doesNotRemoveProperly() { " results.add($key);" + "end"; - assertSessionHasProperties(str, ksession -> { + assertSessionHasProperties(runType, str, ksession -> { Set results = new LinkedHashSet<>(); @@ -911,8 +925,9 @@ public void onUpdateMatch(Match match) { }); } - @Test - public void testTwoGroupBy() { + @ParameterizedTest + @MethodSource("parameters") + public void testTwoGroupBy(RUN_TYPE runType) { // DROOLS-5697 // TODO: For some reason, the compiled class expression thinks $p should be an integer? String str = @@ -936,7 +951,7 @@ public void testTwoGroupBy() { " results.put($key, $maxOfValues);\n" + "end"; - assertSessionHasProperties(str, ksession -> { + assertSessionHasProperties(runType, str, ksession -> { Map results = new HashMap(); ksession.setGlobal("results", results); @@ -991,8 +1006,9 @@ public void testTwoGroupBy() { }); } - @Test - public void testTwoGroupByUsingBindings() { + @ParameterizedTest + @MethodSource("parameters") + public void testTwoGroupByUsingBindings(RUN_TYPE runType) { // DROOLS-5697 // TODO: For some reason, the compiled class expression thinks $p should be an integer? String str = @@ -1016,7 +1032,7 @@ public void testTwoGroupByUsingBindings() { " results.put($key, $maxOfValues);\n" + "end"; - assertSessionHasProperties(str, ksession -> { + assertSessionHasProperties(runType, str, ksession -> { Map results = new HashMap(); ksession.setGlobal("results", results); @@ -1089,8 +1105,9 @@ public Object getValue() { } } - @Test - public void testEmptyPatternOnGroupByKey() { + @ParameterizedTest + @MethodSource("parameters") + public void testEmptyPatternOnGroupByKey(RUN_TYPE runType) { // DROOLS-6031 String str = "import " + Person.class.getCanonicalName() + ";" + @@ -1107,7 +1124,7 @@ public void testEmptyPatternOnGroupByKey() { " results.add($key);" + "end"; - assertSessionHasProperties(str, ksession -> { + assertSessionHasProperties(runType, str, ksession -> { List results = new ArrayList(); ksession.setGlobal("results", results); @@ -1122,8 +1139,9 @@ public void testEmptyPatternOnGroupByKey() { }); } - @Test - public void testFilterOnGroupByKey() { + @ParameterizedTest + @MethodSource("parameters") + public void testFilterOnGroupByKey(RUN_TYPE runType) { // DROOLS-6031 String str = "import " + Person.class.getCanonicalName() + ";" + @@ -1141,7 +1159,7 @@ public void testFilterOnGroupByKey() { " results.add($key);" + "end"; - assertSessionHasProperties(str, ksession -> { + assertSessionHasProperties(runType, str, ksession -> { List results = new ArrayList(); ksession.setGlobal("results", results); @@ -1156,8 +1174,9 @@ public void testFilterOnGroupByKey() { }); } - @Test - public void testDecomposedGroupByKey() { + @ParameterizedTest + @MethodSource("parameters") + public void testDecomposedGroupByKey(RUN_TYPE runType) { // DROOLS-6031 String str = "import " + Person.class.getCanonicalName() + ";" + @@ -1177,7 +1196,7 @@ public void testDecomposedGroupByKey() { " results.add($subkeyB);" + "end"; - assertSessionHasProperties(str, ksession -> { + assertSessionHasProperties(runType, str, ksession -> { final List results = new ArrayList<>(); ksession.setGlobal("results", results); @@ -1192,8 +1211,9 @@ public void testDecomposedGroupByKey() { }); } - @Test - public void testDecomposedGroupByKeyAndAccumulate() { + @ParameterizedTest + @MethodSource("parameters") + public void testDecomposedGroupByKeyAndAccumulate(RUN_TYPE runType) { // DROOLS-6031 String str = "import " + Person.class.getCanonicalName() + ";" + @@ -1215,7 +1235,7 @@ public void testDecomposedGroupByKeyAndAccumulate() { " results.add($accresult);\n" + "end"; - assertSessionHasProperties(str, ksession -> { + assertSessionHasProperties(runType, str, ksession -> { final List results = new ArrayList<>(); ksession.setGlobal("results", results); @@ -1231,8 +1251,9 @@ public void testDecomposedGroupByKeyAndAccumulate() { }); } - @Test - public void testDecomposedGroupByKeyAnd2Accumulates() { + @ParameterizedTest + @MethodSource("parameters") + public void testDecomposedGroupByKeyAnd2Accumulates(RUN_TYPE runType) { // DROOLS-6031 String str = "import " + Person.class.getCanonicalName() + ";" + @@ -1254,7 +1275,7 @@ public void testDecomposedGroupByKeyAnd2Accumulates() { " results.add($accresult);\n" + "end"; - assertSessionHasProperties(str, ksession -> { + assertSessionHasProperties(runType, str, ksession -> { final List results = new ArrayList<>(); ksession.setGlobal("results", results); @@ -1269,8 +1290,9 @@ public void testDecomposedGroupByKeyAnd2Accumulates() { }); } - @Test - public void testDecomposedGroupByKeyAnd2AccumulatesInConsequence() { + @ParameterizedTest + @MethodSource("parameters") + public void testDecomposedGroupByKeyAnd2AccumulatesInConsequence(RUN_TYPE runType) { // DROOLS-6031 String str = "import " + Person.class.getCanonicalName() + ";" + @@ -1288,7 +1310,7 @@ public void testDecomposedGroupByKeyAnd2AccumulatesInConsequence() { " results.add($key);\n" + "end"; - assertSessionHasProperties(str, ksession -> { + assertSessionHasProperties(runType, str, ksession -> { final List results = new ArrayList<>(); ksession.setGlobal("results", results); @@ -1301,8 +1323,9 @@ public void testDecomposedGroupByKeyAnd2AccumulatesInConsequence() { }); } - @Test - public void testNestedGroupBy1a() { + @ParameterizedTest + @MethodSource("parameters") + public void testNestedGroupBy1a(RUN_TYPE runType) { // DROOLS-6045 String str = "import " + Person.class.getCanonicalName() + ";" + @@ -1317,7 +1340,7 @@ public void testNestedGroupBy1a() { " results.add($accresult);\n" + "end"; - assertSessionHasProperties(str, ksession -> { + assertSessionHasProperties(runType, str, ksession -> { final List results = new ArrayList<>(); ksession.setGlobal("results", results); @@ -1329,8 +1352,9 @@ public void testNestedGroupBy1a() { }); } - @Test - public void testNestedGroupBy1b() { + @ParameterizedTest + @MethodSource("parameters") + public void testNestedGroupBy1b(RUN_TYPE runType) { // DROOLS-6045 String str = "import " + Person.class.getCanonicalName() + ";" + @@ -1345,7 +1369,7 @@ public void testNestedGroupBy1b() { " results.add($accresult);\n" + "end"; - assertSessionHasProperties(str, ksession -> { + assertSessionHasProperties(runType, str, ksession -> { final List results = new ArrayList<>(); ksession.setGlobal("results", results); @@ -1356,8 +1380,9 @@ public void testNestedGroupBy1b() { }); } - @Test - public void testNestedGroupBy2() { + @ParameterizedTest + @MethodSource("parameters") + public void testNestedGroupBy2(RUN_TYPE runType) { // DROOLS-6045 String str = "import " + Person.class.getCanonicalName() + ";" + @@ -1374,7 +1399,7 @@ public void testNestedGroupBy2() { "then\n" + " results.add($accresult);\n" + "end"; - assertSessionHasProperties(str, ksession -> { + assertSessionHasProperties(runType, str, ksession -> { final List results = new ArrayList<>(); ksession.setGlobal("results", results); @@ -1386,8 +1411,9 @@ public void testNestedGroupBy2() { }); } - @Test - public void testNestedGroupBy3() { + @ParameterizedTest + @MethodSource("parameters") + public void testNestedGroupBy3(RUN_TYPE runType) { // DROOLS-6045 // TODO: For some reason, the compiled class expression thinks $p should be an integer? String str = @@ -1404,7 +1430,7 @@ public void testNestedGroupBy3() { "then\n" + " results.add($keyOuter);\n" + "end"; - assertSessionHasProperties(str, ksession -> { + assertSessionHasProperties(runType, str, ksession -> { final List results = new ArrayList<>(); ksession.setGlobal("results", results); @@ -1417,8 +1443,9 @@ public void testNestedGroupBy3() { }); } - @Test - public void testFilterOnAccumulateResultWithDecomposedGroupByKey() { + @ParameterizedTest + @MethodSource("parameters") + public void testFilterOnAccumulateResultWithDecomposedGroupByKey(RUN_TYPE runType) { // DROOLS-6045 // TODO: For some reason, the compiled class expression thinks $p should be an integer? String str = @@ -1441,7 +1468,7 @@ public void testFilterOnAccumulateResultWithDecomposedGroupByKey() { " results.add($accresult);\n" + "end"; - assertSessionHasProperties(str, ksession -> { + assertSessionHasProperties(runType, str, ksession -> { final List results = new ArrayList<>(); ksession.setGlobal("results", results); @@ -1524,8 +1551,9 @@ public void testFilterOnAccumulateResultWithDecomposedGroupByKey() { // } // } - @Test - public void testNestedRewrite() { + @ParameterizedTest + @MethodSource("parameters") + public void testNestedRewrite(RUN_TYPE runType) { // DROOLS-5697 String str = "import " + Person.class.getCanonicalName() + ";" + @@ -1544,7 +1572,7 @@ public void testNestedRewrite() { " results.add($maxOfValues);\n" + "end"; - assertSessionHasProperties(str, ksession -> { + assertSessionHasProperties(runType, str, ksession -> { List results = new ArrayList(); ksession.setGlobal("results", results); diff --git a/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/HalfBinaryTest.java b/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/HalfBinaryTest.java index f4514a36bde..df52b350958 100644 --- a/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/HalfBinaryTest.java +++ b/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/HalfBinaryTest.java @@ -23,26 +23,24 @@ import org.drools.model.codegen.execmodel.domain.Address; import org.drools.model.codegen.execmodel.domain.Person; -import org.junit.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; import org.kie.api.runtime.KieSession; import static org.assertj.core.api.Assertions.assertThat; public class HalfBinaryTest extends BaseModelTest { - public HalfBinaryTest( RUN_TYPE testRunType ) { - super( testRunType ); - } - - @Test - public void testHalfBinary() { + @ParameterizedTest + @MethodSource("parameters") + public void testHalfBinary(RUN_TYPE runType) { final String drl1 = "rule R1 when\n" + " Integer(this > 2 && < 5)\n" + "then\n" + "end\n"; - KieSession ksession = getKieSession( drl1 ); + KieSession ksession = getKieSession(runType, drl1); ksession.insert( 3 ); ksession.insert( 4 ); @@ -50,8 +48,9 @@ public void testHalfBinary() { assertThat(ksession.fireAllRules()).isEqualTo(2); } - @Test - public void testHalfBinaryWithParenthesis() { + @ParameterizedTest + @MethodSource("parameters") + public void testHalfBinaryWithParenthesis(RUN_TYPE runType) { // DROOLS-6006 final String drl1 = "rule R1 when\n" + @@ -59,7 +58,7 @@ public void testHalfBinaryWithParenthesis() { "then\n" + "end\n"; - KieSession ksession = getKieSession( drl1 ); + KieSession ksession = getKieSession(runType, drl1); ksession.insert( 3 ); ksession.insert( 4 ); @@ -67,8 +66,9 @@ public void testHalfBinaryWithParenthesis() { assertThat(ksession.fireAllRules()).isEqualTo(2); } - @Test - public void testHalfBinaryOrWithParenthesis() { + @ParameterizedTest + @MethodSource("parameters") + public void testHalfBinaryOrWithParenthesis(RUN_TYPE runType) { // DROOLS-6006 final String drl1 = "rule R1 when\n" + @@ -76,7 +76,7 @@ public void testHalfBinaryOrWithParenthesis() { "then\n" + "end\n"; - KieSession ksession = getKieSession( drl1 ); + KieSession ksession = getKieSession(runType, drl1); ksession.insert( 3 ); ksession.insert( 4 ); @@ -84,8 +84,9 @@ public void testHalfBinaryOrWithParenthesis() { assertThat(ksession.fireAllRules()).isEqualTo(1); } - @Test - public void testComplexHalfBinary() { + @ParameterizedTest + @MethodSource("parameters") + public void testComplexHalfBinary(RUN_TYPE runType) { // DROOLS-6006 final String drl1 = "rule R1 when\n" + @@ -93,7 +94,7 @@ public void testComplexHalfBinary() { "then\n" + "end\n"; - KieSession ksession = getKieSession( drl1 ); + KieSession ksession = getKieSession(runType, drl1); ksession.insert( 3 ); ksession.insert( 4 ); @@ -101,8 +102,9 @@ public void testComplexHalfBinary() { assertThat(ksession.fireAllRules()).isEqualTo(2); } - @Test - public void testHalfBinaryOnComparable() { + @ParameterizedTest + @MethodSource("parameters") + public void testHalfBinaryOnComparable(RUN_TYPE runType) { // DROOLS-6421 final String drl1 = "rule R1 when\n" + @@ -110,7 +112,7 @@ public void testHalfBinaryOnComparable() { "then\n" + "end\n"; - KieSession ksession = getKieSession( drl1 ); + KieSession ksession = getKieSession(runType, drl1); ksession.insert( "B" ); ksession.insert( "D" ); @@ -119,8 +121,9 @@ public void testHalfBinaryOnComparable() { assertThat(ksession.fireAllRules()).isEqualTo(2); } - @Test - public void testHalfBinaryOrOnComparable() { + @ParameterizedTest + @MethodSource("parameters") + public void testHalfBinaryOrOnComparable(RUN_TYPE runType) { // DROOLS-6421 final String drl1 = "rule R1 when\n" + @@ -128,7 +131,7 @@ public void testHalfBinaryOrOnComparable() { "then\n" + "end\n"; - KieSession ksession = getKieSession( drl1 ); + KieSession ksession = getKieSession(runType, drl1); ksession.insert( "B" ); ksession.insert( "D" ); @@ -137,8 +140,9 @@ public void testHalfBinaryOrOnComparable() { assertThat(ksession.fireAllRules()).isEqualTo(2); } - @Test - public void testComplexHalfBinaryOnComparable() { + @ParameterizedTest + @MethodSource("parameters") + public void testComplexHalfBinaryOnComparable(RUN_TYPE runType) { // DROOLS-6421 final String drl1 = "rule R1 when\n" + @@ -146,7 +150,7 @@ public void testComplexHalfBinaryOnComparable() { "then\n" + "end\n"; - KieSession ksession = getKieSession( drl1 ); + KieSession ksession = getKieSession(runType, drl1); ksession.insert( "B" ); ksession.insert( "D" ); @@ -155,8 +159,9 @@ public void testComplexHalfBinaryOnComparable() { assertThat(ksession.fireAllRules()).isEqualTo(2); } - @Test - public void testComplexHalfBinaryOnComparableField() { + @ParameterizedTest + @MethodSource("parameters") + public void testComplexHalfBinaryOnComparableField(RUN_TYPE runType) { // DROOLS-6421 final String drl1 = "import " + Person.class.getCanonicalName() + ";\n" + @@ -165,7 +170,7 @@ public void testComplexHalfBinaryOnComparableField() { "then\n" + "end\n"; - KieSession ksession = getKieSession( drl1 ); + KieSession ksession = getKieSession(runType, drl1); ksession.insert( new Person("B") ); ksession.insert( new Person("D") ); @@ -174,8 +179,9 @@ public void testComplexHalfBinaryOnComparableField() { assertThat(ksession.fireAllRules()).isEqualTo(2); } - @Test - public void testComplexHalfBinaryOnComparableInternalField() { + @ParameterizedTest + @MethodSource("parameters") + public void testComplexHalfBinaryOnComparableInternalField(RUN_TYPE runType) { // DROOLS-6421 final String drl1 = "import " + Person.class.getCanonicalName() + ";\n" + @@ -184,7 +190,7 @@ public void testComplexHalfBinaryOnComparableInternalField() { "then\n" + "end\n"; - KieSession ksession = getKieSession( drl1 ); + KieSession ksession = getKieSession(runType, drl1); Person b = new Person("B"); b.setAddress(new Address("B")); @@ -202,8 +208,9 @@ public void testComplexHalfBinaryOnComparableInternalField() { assertThat(ksession.fireAllRules()).isEqualTo(2); } - @Test - public void testComplexHalfBinaryOnComparableInternalNullSafeField() { + @ParameterizedTest + @MethodSource("parameters") + public void testComplexHalfBinaryOnComparableInternalNullSafeField(RUN_TYPE runType) { // DROOLS-6421 final String drl1 = "import " + Person.class.getCanonicalName() + ";\n" + @@ -212,7 +219,7 @@ public void testComplexHalfBinaryOnComparableInternalNullSafeField() { "then\n" + "end\n"; - KieSession ksession = getKieSession( drl1 ); + KieSession ksession = getKieSession(runType, drl1); Person a = new Person("A"); a.setAddress(new Address(null)); @@ -233,8 +240,9 @@ public void testComplexHalfBinaryOnComparableInternalNullSafeField() { assertThat(ksession.fireAllRules()).isEqualTo(2); } - @Test - public void testHalfBinaryOrAndAmpersand() { + @ParameterizedTest + @MethodSource("parameters") + public void testHalfBinaryOrAndAmpersand(RUN_TYPE runType) { final String drl = "import " + Person.class.getCanonicalName() + ";\n" + "global java.util.List result;\n" + @@ -244,7 +252,7 @@ public void testHalfBinaryOrAndAmpersand() { " result.add($p.getName());\n" + "end\n"; - KieSession ksession = getKieSession(drl); + KieSession ksession = getKieSession(runType, drl); List result = new ArrayList<>(); ksession.setGlobal("result", result); @@ -257,8 +265,9 @@ public void testHalfBinaryOrAndAmpersand() { assertThat(result).containsExactlyInAnyOrder("A", "C"); } - @Test - public void testNestedHalfBinaryOrAndAmpersand() { + @ParameterizedTest + @MethodSource("parameters") + public void testNestedHalfBinaryOrAndAmpersand(RUN_TYPE runType) { final String drl = "import " + Person.class.getCanonicalName() + ";\n" + "global java.util.List result;\n" + @@ -268,7 +277,7 @@ public void testNestedHalfBinaryOrAndAmpersand() { " result.add($p.getName());\n" + "end\n"; - KieSession ksession = getKieSession(drl); + KieSession ksession = getKieSession(runType, drl); List result = new ArrayList<>(); ksession.setGlobal("result", result); diff --git a/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/HierarchyRulesTest.java b/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/HierarchyRulesTest.java index 173f3c1fdbf..5ff5d6627a1 100644 --- a/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/HierarchyRulesTest.java +++ b/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/HierarchyRulesTest.java @@ -18,19 +18,18 @@ */ package org.drools.model.codegen.execmodel; -import org.junit.Test; import org.kie.api.runtime.KieSession; import static org.assertj.core.api.Assertions.assertThat; -public class HierarchyRulesTest extends BaseModelTest { +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; - public HierarchyRulesTest(RUN_TYPE testRunType ) { - super( testRunType ); - } +public class HierarchyRulesTest extends BaseModelTest { - @Test - public void test() { + @ParameterizedTest + @MethodSource("parameters") + public void test(RUN_TYPE runType) { // DROOLS-7470 String str = "rule R1 when \n" + @@ -105,7 +104,7 @@ public void test() { "then\n" + "end\n"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); assertThat( ksession.fireAllRules() ).isEqualTo(4); } } diff --git a/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/InTest.java b/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/InTest.java index 04cf9c53038..dafc5be0272 100644 --- a/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/InTest.java +++ b/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/InTest.java @@ -24,45 +24,45 @@ import org.drools.model.codegen.execmodel.domain.Address; import org.drools.model.codegen.execmodel.domain.Child; import org.drools.model.codegen.execmodel.domain.Person; -import org.junit.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; import org.kie.api.runtime.KieSession; import static org.assertj.core.api.Assertions.assertThat; public class InTest extends BaseModelTest { - public InTest(RUN_TYPE testRunType ) { - super( testRunType ); - } - - @Test - public void testInWithNullFire() { + @ParameterizedTest + @MethodSource("parameters") + public void testInWithNullFire(RUN_TYPE runType) { String str = "import " + Child.class.getCanonicalName() + "; \n" + "rule R when \n" + " $c : Child(parent in (\"Gustav\", \"Alice\", null))\n" + "then \n" + "end "; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); ksession.insert(new Child("Ben", 10)); assertThat(ksession.fireAllRules()).isEqualTo(1); } - @Test - public void testInWithNullNoFire() { + @ParameterizedTest + @MethodSource("parameters") + public void testInWithNullNoFire(RUN_TYPE runType) { String str = "import " + Child.class.getCanonicalName() + "; \n" + "rule R when \n" + " $c : Child(parent in (\"Gustav\", \"Alice\"))\n" + "then \n" + "end "; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); ksession.insert(new Child("Ben", 10)); assertThat(ksession.fireAllRules()).isEqualTo(0); } - @Test - public void testInWithNullComments() { + @ParameterizedTest + @MethodSource("parameters") + public void testInWithNullComments(RUN_TYPE runType) { String str = "import " + Child.class.getCanonicalName() + "; \n" + "global java.util.List results; \n" + "global java.util.List results; \n" + @@ -75,7 +75,7 @@ public void testInWithNullComments() { " results.add($c);\n" + "end "; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); List results = new ArrayList<>(); ksession.setGlobal("results", results); @@ -88,16 +88,17 @@ public void testInWithNullComments() { assertThat(results).containsExactly(ben); } - @Test - public void testInWithJoin() { + @ParameterizedTest + @MethodSource("parameters") + public void testInWithJoin(RUN_TYPE runType) { String str = "import " + Address.class.getCanonicalName() + "; \n" + "rule R when \n" + " $a1: Address($street: street, city in (\"Brno\", \"Milan\", \"Bratislava\")) \n" + " $a2: Address(city in (\"Krakow\", \"Paris\", $a1.city)) \n" + "then \n" + - "end\n"; + "end\n"; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); ksession.insert(new Address("Brno")); ksession.insert(new Address("Milan")); assertThat(ksession.fireAllRules()).isEqualTo(2); diff --git a/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/IncrementalCompilationTest.java b/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/IncrementalCompilationTest.java index 0908ce636fa..a060f4eef7b 100644 --- a/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/IncrementalCompilationTest.java +++ b/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/IncrementalCompilationTest.java @@ -24,7 +24,8 @@ import org.drools.model.codegen.execmodel.domain.Address; import org.drools.model.codegen.execmodel.domain.Person; -import org.junit.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; import org.kie.api.KieServices; import org.kie.api.builder.ReleaseId; import org.kie.api.builder.model.KieModuleModel; @@ -36,9 +37,6 @@ public class IncrementalCompilationTest extends BaseModelTest { - public IncrementalCompilationTest( RUN_TYPE testRunType ) { - super( testRunType ); - } public class Message implements Serializable { private final String value; @@ -52,8 +50,9 @@ public String getValue() { } } - @Test - public void testKJarUpgradeSameAndDifferentSessions() throws Exception { + @ParameterizedTest + @MethodSource("parameters") + public void testKJarUpgradeSameAndDifferentSessions(RUN_TYPE runType) throws Exception { String drl1 = "package org.drools.incremental\n" + "import " + Message.class.getCanonicalName() + ";\n" + "rule R1 when\n" + @@ -80,7 +79,7 @@ public void testKJarUpgradeSameAndDifferentSessions() throws Exception { // Create an in-memory jar for version 1.0.0 ReleaseId releaseId1 = ks.newReleaseId( "org.kie", "test-upgrade", "1.0.0" ); - createAndDeployJar( ks, releaseId1, drl1, drl2_1 ); + createAndDeployJar(runType, ks, releaseId1, drl1, drl2_1 ); // Create a session and fire rules KieContainer kc = ks.newKieContainer( releaseId1 ); @@ -90,7 +89,7 @@ public void testKJarUpgradeSameAndDifferentSessions() throws Exception { // Create a new jar for version 1.1.0 ReleaseId releaseId2 = ks.newReleaseId( "org.kie", "test-upgrade", "1.1.0" ); - createAndDeployJar( ks, releaseId2, drl1, drl2_2 ); + createAndDeployJar(runType, ks, releaseId2, drl1, drl2_2 ); // try to update the container to version 1.1.0 kc.updateToVersion( releaseId2 ); @@ -105,8 +104,9 @@ public void testKJarUpgradeSameAndDifferentSessions() throws Exception { assertThat(ksession2.fireAllRules()).isEqualTo(2); } - @Test - public void testKJarUpgradeWithDeclaredType() throws Exception { + @ParameterizedTest + @MethodSource("parameters") + public void testKJarUpgradeWithDeclaredType(RUN_TYPE runType) throws Exception { String drl1 = "package org.drools.incremental\n" + "declare Message value : String end\n" + "rule Init when then insert(new Message( \"Hello World\" )); end\n" + @@ -141,10 +141,10 @@ public void testKJarUpgradeWithDeclaredType() throws Exception { ReleaseId releaseId1 = ks.newReleaseId( "org.kie", "test-upgrade", "1.0.0" ); KieModuleModel kieModuleModel = ks.newKieModuleModel(); - if(this.testRunType.isAlphaNetworkCompiler()) { + if(runType.isAlphaNetworkCompiler()) { kieModuleModel.setConfigurationProperty("drools.alphaNetworkCompiler", AlphaNetworkCompilerOption.INMEMORY.toString()); } - createAndDeployJar( ks, kieModuleModel, releaseId1, drl1, drl2_1 ); + createAndDeployJar(runType, ks, kieModuleModel, releaseId1, drl1, drl2_1 ); KieContainer kc = ks.newKieContainer( releaseId1 ); @@ -154,7 +154,7 @@ public void testKJarUpgradeWithDeclaredType() throws Exception { // Create a new jar for version 1.1.0 ReleaseId releaseId2 = ks.newReleaseId( "org.kie", "test-upgrade", "1.1.0" ); - createAndDeployJar( ks, kieModuleModel, releaseId2, drl1, drl2_2 ); + createAndDeployJar(runType, ks, kieModuleModel, releaseId2, drl1, drl2_2 ); // try to update the container to version 1.1.0 kc.updateToVersion( releaseId2 ); @@ -165,7 +165,7 @@ public void testKJarUpgradeWithDeclaredType() throws Exception { // Create a new jar for version 1.2.0 ReleaseId releaseId3 = ks.newReleaseId( "org.kie", "test-upgrade", "1.2.0" ); - createAndDeployJar( ks, kieModuleModel, releaseId3, drl1, drl2_3 ); + createAndDeployJar(runType, ks, kieModuleModel, releaseId3, drl1, drl2_3 ); // try to update the container to version 1.2.0 kc.updateToVersion( releaseId3 ); @@ -178,8 +178,9 @@ public void testKJarUpgradeWithDeclaredType() throws Exception { assertThat(list.get(0)).isEqualTo("Hello World"); } - @Test - public void testKJarUpgradeWithChangedDeclaredType() throws Exception { + @ParameterizedTest + @MethodSource("parameters") + public void testKJarUpgradeWithChangedDeclaredType(RUN_TYPE runType) throws Exception { String drl1a = "package org.drools.incremental\n" + "declare Message value : String end\n" + "rule Init when then insert(new Message( \"Hello World\" )); end\n" + @@ -202,7 +203,7 @@ public void testKJarUpgradeWithChangedDeclaredType() throws Exception { // Create an in-memory jar for version 1.0.0 ReleaseId releaseId1 = ks.newReleaseId( "org.kie", "test-upgrade", "1.0.0" ); - createAndDeployJar( ks, releaseId1, drl1a ); + createAndDeployJar(runType, ks, releaseId1, drl1a ); // Create a session and fire rules KieContainer kc = ks.newKieContainer( releaseId1 ); @@ -211,7 +212,7 @@ public void testKJarUpgradeWithChangedDeclaredType() throws Exception { // Create a new jar for version 1.1.0 ReleaseId releaseId2 = ks.newReleaseId( "org.kie", "test-upgrade", "1.1.0" ); - createAndDeployJar( ks, releaseId2, drl1b ); + createAndDeployJar(runType, ks, releaseId2, drl1b ); // try to update the container to version 1.1.0 kc.updateToVersion( releaseId2 ); @@ -224,8 +225,9 @@ public void testKJarUpgradeWithChangedDeclaredType() throws Exception { assertThat(ksession2.fireAllRules()).isEqualTo(2); } - @Test - public void testIdenticalConsequenceButImportChange() { + @ParameterizedTest + @MethodSource("parameters") + public void testIdenticalConsequenceButImportChange(RUN_TYPE runType) { final String drl1 = "package org.drools.test\n" + "import " + Person.class.getCanonicalName() + "\n" + "rule R\n" + @@ -249,7 +251,7 @@ public void testIdenticalConsequenceButImportChange() { final KieServices ks = KieServices.Factory.get(); final ReleaseId releaseId1 = ks.newReleaseId("org.kie", "test-upgrade", "1.0.0"); - createAndDeployJar(ks, releaseId1, drl1); + createAndDeployJar(runType, ks, releaseId1, drl1); final KieContainer kc = ks.newKieContainer(releaseId1); final KieSession kieSession = kc.newKieSession(); @@ -259,7 +261,7 @@ public void testIdenticalConsequenceButImportChange() { assertThat(kieSession.fireAllRules()).isEqualTo(1); final ReleaseId releaseId2 = ks.newReleaseId("org.kie", "test-upgrade", "2.0.0"); - createAndDeployJar(ks, releaseId2, drl2); + createAndDeployJar(runType, ks, releaseId2, drl2); kc.updateToVersion(releaseId2); @@ -270,8 +272,9 @@ public void testIdenticalConsequenceButImportChange() { assertThat(kieSession.fireAllRules()).isEqualTo(1); } - @Test - public void testIdenticalPredicateButImportChange() { + @ParameterizedTest + @MethodSource("parameters") + public void testIdenticalPredicateButImportChange(RUN_TYPE runType) { // This test also verifies LambdaExtractor final String drl1 = "package org.drools.test\n" + "import " + Person.class.getCanonicalName() + "\n" + @@ -296,7 +299,7 @@ public void testIdenticalPredicateButImportChange() { final KieServices ks = KieServices.Factory.get(); final ReleaseId releaseId1 = ks.newReleaseId("org.kie", "test-upgrade", "1.0.0"); - createAndDeployJar(ks, releaseId1, drl1); + createAndDeployJar(runType, ks, releaseId1, drl1); final KieContainer kc = ks.newKieContainer(releaseId1); final KieSession kieSession = kc.newKieSession(); @@ -306,7 +309,7 @@ public void testIdenticalPredicateButImportChange() { assertThat(kieSession.fireAllRules()).isEqualTo(0); final ReleaseId releaseId2 = ks.newReleaseId("org.kie", "test-upgrade", "2.0.0"); - createAndDeployJar(ks, releaseId2, drl2); + createAndDeployJar(runType, ks, releaseId2, drl2); kc.updateToVersion(releaseId2); @@ -317,8 +320,9 @@ public void testIdenticalPredicateButImportChange() { assertThat(kieSession.fireAllRules()).isEqualTo(1); } - @Test - public void testKJarUpgradeWithChangedFunctionForRHSWithoutExternalizeLambda() throws Exception { + @ParameterizedTest + @MethodSource("parameters") + public void testKJarUpgradeWithChangedFunctionForRHSWithoutExternalizeLambda(RUN_TYPE runType) throws Exception { String drl1a = "package org.drools.incremental\n" + "import " + Person.class.getCanonicalName() + "\n" + @@ -346,7 +350,7 @@ public void testKJarUpgradeWithChangedFunctionForRHSWithoutExternalizeLambda() t ReleaseId releaseId1 = ks.newReleaseId("org.kie", "test-upgrade", "1.0.0"); KieModuleModel model1 = ks.newKieModuleModel(); model1.setConfigurationProperty("drools.externaliseCanonicalModelLambda", Boolean.FALSE.toString()); - createAndDeployJar(ks, model1, releaseId1, drl1a); + createAndDeployJar(runType, ks, model1, releaseId1, drl1a); // Create a session and fire rules KieContainer kc = ks.newKieContainer(releaseId1); @@ -362,7 +366,7 @@ public void testKJarUpgradeWithChangedFunctionForRHSWithoutExternalizeLambda() t ReleaseId releaseId2 = ks.newReleaseId("org.kie", "test-upgrade", "1.1.0"); KieModuleModel model2 = ks.newKieModuleModel(); model2.setConfigurationProperty("drools.externaliseCanonicalModelLambda", Boolean.FALSE.toString()); - createAndDeployJar(ks, model2, releaseId2, drl1b); + createAndDeployJar(runType, ks, model2, releaseId2, drl1b); // try to update the container to version 1.1.0 kc.updateToVersion(releaseId2); @@ -382,8 +386,9 @@ public void testKJarUpgradeWithChangedFunctionForRHSWithoutExternalizeLambda() t assertThat(list2).containsExactlyInAnyOrder("Good bye George"); } - @Test - public void testKJarUpgradeWithChangedFunctionForRHSWithExternalizeLambda() throws Exception { + @ParameterizedTest + @MethodSource("parameters") + public void testKJarUpgradeWithChangedFunctionForRHSWithExternalizeLambda(RUN_TYPE runType) throws Exception { String drl1a = "package org.drools.incremental\n" + "import " + Person.class.getCanonicalName() + "\n" + @@ -411,7 +416,7 @@ public void testKJarUpgradeWithChangedFunctionForRHSWithExternalizeLambda() thro ReleaseId releaseId1 = ks.newReleaseId("org.kie", "test-upgrade", "1.0.0"); KieModuleModel model1 = ks.newKieModuleModel(); model1.setConfigurationProperty("drools.externaliseCanonicalModelLambda", Boolean.TRUE.toString()); - createAndDeployJar(ks, model1, releaseId1, drl1a); + createAndDeployJar(runType, ks, model1, releaseId1, drl1a); // Create a session and fire rules KieContainer kc = ks.newKieContainer(releaseId1); @@ -427,7 +432,7 @@ public void testKJarUpgradeWithChangedFunctionForRHSWithExternalizeLambda() thro ReleaseId releaseId2 = ks.newReleaseId("org.kie", "test-upgrade", "1.1.0"); KieModuleModel model2 = ks.newKieModuleModel(); model2.setConfigurationProperty("drools.externaliseCanonicalModelLambda", Boolean.TRUE.toString()); - createAndDeployJar(ks, model2, releaseId2, drl1b); + createAndDeployJar(runType, ks, model2, releaseId2, drl1b); // try to update the container to version 1.1.0 kc.updateToVersion(releaseId2); @@ -447,8 +452,9 @@ public void testKJarUpgradeWithChangedFunctionForRHSWithExternalizeLambda() thro assertThat(list2).containsExactlyInAnyOrder("Good bye George"); } - @Test - public void testKJarUpgradeWithChangedJavaFunctionForRHSWithoutExternalizeLambda() throws Exception { + @ParameterizedTest + @MethodSource("parameters") + public void testKJarUpgradeWithChangedJavaFunctionForRHSWithoutExternalizeLambda(RUN_TYPE runType) throws Exception { String java1 = "package org.drools.test;\n" + "public class MyFunction {\n" + @@ -480,7 +486,7 @@ public void testKJarUpgradeWithChangedJavaFunctionForRHSWithoutExternalizeLambda ReleaseId releaseId1 = ks.newReleaseId("org.kie", "test-upgrade", "1.0.0"); KieModuleModel model1 = ks.newKieModuleModel(); model1.setConfigurationProperty("drools.externaliseCanonicalModelLambda", Boolean.FALSE.toString()); - createAndDeployJar(ks, model1, releaseId1, + createAndDeployJar(runType, ks, model1, releaseId1, new KieFile("src/main/java/org/drools/test/MyFunction.java", java1), new KieFile("src/main/resources/org/drools/incremental/r1.drl", drl)); @@ -498,7 +504,7 @@ public void testKJarUpgradeWithChangedJavaFunctionForRHSWithoutExternalizeLambda ReleaseId releaseId2 = ks.newReleaseId("org.kie", "test-upgrade", "1.1.0"); KieModuleModel model2 = ks.newKieModuleModel(); model2.setConfigurationProperty("drools.externaliseCanonicalModelLambda", Boolean.FALSE.toString()); - createAndDeployJar(ks, model2, releaseId2, + createAndDeployJar(runType, ks, model2, releaseId2, new KieFile("src/main/java/org/drools/test/MyFunction.java", java2), new KieFile("src/main/resources/org/drools/incremental/r1.drl", drl)); // try to update the container to version 1.1.0 @@ -519,8 +525,9 @@ public void testKJarUpgradeWithChangedJavaFunctionForRHSWithoutExternalizeLambda assertThat(list2).containsExactlyInAnyOrder("Good bye George"); } - @Test - public void testKJarUpgradeWithChangedJavaFunctionForRHSWithExternalizeLambda() throws Exception { + @ParameterizedTest + @MethodSource("parameters") + public void testKJarUpgradeWithChangedJavaFunctionForRHSWithExternalizeLambda(RUN_TYPE runType) throws Exception { String java1 = "package org.drools.test;\n" + "public class MyFunction {\n" + @@ -552,7 +559,7 @@ public void testKJarUpgradeWithChangedJavaFunctionForRHSWithExternalizeLambda() ReleaseId releaseId1 = ks.newReleaseId("org.kie", "test-upgrade", "1.0.0"); KieModuleModel model1 = ks.newKieModuleModel(); model1.setConfigurationProperty("drools.externaliseCanonicalModelLambda", Boolean.TRUE.toString()); - createAndDeployJar(ks, model1, releaseId1, + createAndDeployJar(runType, ks, model1, releaseId1, new KieFile("src/main/java/org/drools/test/MyFunction.java", java1), new KieFile("src/main/resources/org/drools/incremental/r1.drl", drl)); @@ -570,7 +577,7 @@ public void testKJarUpgradeWithChangedJavaFunctionForRHSWithExternalizeLambda() ReleaseId releaseId2 = ks.newReleaseId("org.kie", "test-upgrade", "1.1.0"); KieModuleModel model2 = ks.newKieModuleModel(); model2.setConfigurationProperty("drools.externaliseCanonicalModelLambda", Boolean.TRUE.toString()); - createAndDeployJar(ks, model2, releaseId2, + createAndDeployJar(runType, ks, model2, releaseId2, new KieFile("src/main/java/org/drools/test/MyFunction.java", java2), new KieFile("src/main/resources/org/drools/incremental/r1.drl", drl)); @@ -592,8 +599,9 @@ public void testKJarUpgradeWithChangedJavaFunctionForRHSWithExternalizeLambda() assertThat(list2).containsExactlyInAnyOrder("Good bye George"); } - @Test - public void testKJarUpgradeWithChangedFunctionForLHSWithoutExternalizeLambda() throws Exception { + @ParameterizedTest + @MethodSource("parameters") + public void testKJarUpgradeWithChangedFunctionForLHSWithoutExternalizeLambda(RUN_TYPE runType) throws Exception { String drl1a = "package org.drools.incremental\n" + "import " + Person.class.getCanonicalName() + "\n" + @@ -621,7 +629,7 @@ public void testKJarUpgradeWithChangedFunctionForLHSWithoutExternalizeLambda() t ReleaseId releaseId1 = ks.newReleaseId("org.kie", "test-upgrade", "1.0.0"); KieModuleModel model1 = ks.newKieModuleModel(); model1.setConfigurationProperty("drools.externaliseCanonicalModelLambda", Boolean.FALSE.toString()); - createAndDeployJar(ks, model1, releaseId1, drl1a); + createAndDeployJar(runType, ks, model1, releaseId1, drl1a); // Create a session and fire rules KieContainer kc = ks.newKieContainer(releaseId1); @@ -638,7 +646,7 @@ public void testKJarUpgradeWithChangedFunctionForLHSWithoutExternalizeLambda() t ReleaseId releaseId2 = ks.newReleaseId("org.kie", "test-upgrade", "1.1.0"); KieModuleModel model2 = ks.newKieModuleModel(); model2.setConfigurationProperty("drools.externaliseCanonicalModelLambda", Boolean.FALSE.toString()); - createAndDeployJar(ks, model2, releaseId2, drl1b); + createAndDeployJar(runType, ks, model2, releaseId2, drl1b); // try to update the container to version 1.1.0 System.out.println("=== updateToVersion ==="); @@ -660,8 +668,9 @@ public void testKJarUpgradeWithChangedFunctionForLHSWithoutExternalizeLambda() t assertThat(list2).containsExactlyInAnyOrder("John"); } - @Test - public void testKJarUpgradeWithChangedFunctionForLHSWithExternalizeLambda() throws Exception { + @ParameterizedTest + @MethodSource("parameters") + public void testKJarUpgradeWithChangedFunctionForLHSWithExternalizeLambda(RUN_TYPE runType) throws Exception { String drl1a = "package org.drools.incremental\n" + "import " + Person.class.getCanonicalName() + "\n" + @@ -689,7 +698,7 @@ public void testKJarUpgradeWithChangedFunctionForLHSWithExternalizeLambda() thro ReleaseId releaseId1 = ks.newReleaseId("org.kie", "test-upgrade", "1.0.0"); KieModuleModel model1 = ks.newKieModuleModel(); model1.setConfigurationProperty("drools.externaliseCanonicalModelLambda", Boolean.TRUE.toString()); - createAndDeployJar(ks, model1, releaseId1, drl1a); + createAndDeployJar(runType, ks, model1, releaseId1, drl1a); // Create a session and fire rules KieContainer kc = ks.newKieContainer(releaseId1); @@ -706,7 +715,7 @@ public void testKJarUpgradeWithChangedFunctionForLHSWithExternalizeLambda() thro ReleaseId releaseId2 = ks.newReleaseId("org.kie", "test-upgrade", "1.1.0"); KieModuleModel model2 = ks.newKieModuleModel(); model2.setConfigurationProperty("drools.externaliseCanonicalModelLambda", Boolean.TRUE.toString()); - createAndDeployJar(ks, model2, releaseId2, drl1b); + createAndDeployJar(runType, ks, model2, releaseId2, drl1b); // try to update the container to version 1.1.0 System.out.println("=== updateToVersion ==="); @@ -728,8 +737,9 @@ public void testKJarUpgradeWithChangedFunctionForLHSWithExternalizeLambda() thro assertThat(list2).containsExactlyInAnyOrder("John"); } - @Test - public void testKJarUpgradeWithChangedJavaFunctionForLHSWithoutExternalizeLambda() throws Exception { + @ParameterizedTest + @MethodSource("parameters") + public void testKJarUpgradeWithChangedJavaFunctionForLHSWithoutExternalizeLambda(RUN_TYPE runType) throws Exception { String java1 = "package org.drools.test;\n" + "public class MyFunction {\n" + @@ -763,7 +773,7 @@ public void testKJarUpgradeWithChangedJavaFunctionForLHSWithoutExternalizeLambda ReleaseId releaseId1 = ks.newReleaseId("org.kie", "test-upgrade", "1.0.0"); KieModuleModel model1 = ks.newKieModuleModel(); model1.setConfigurationProperty("drools.externaliseCanonicalModelLambda", Boolean.FALSE.toString()); - createAndDeployJar(ks, model1, releaseId1, + createAndDeployJar(runType, ks, model1, releaseId1, new KieFile("src/main/java/org/drools/test/MyFunction.java", java1), new KieFile("src/main/resources/org/drools/incremental/r1.drl", drl)); @@ -782,7 +792,7 @@ public void testKJarUpgradeWithChangedJavaFunctionForLHSWithoutExternalizeLambda ReleaseId releaseId2 = ks.newReleaseId("org.kie", "test-upgrade", "1.1.0"); KieModuleModel model2 = ks.newKieModuleModel(); model2.setConfigurationProperty("drools.externaliseCanonicalModelLambda", Boolean.FALSE.toString()); - createAndDeployJar(ks, model2, releaseId2, + createAndDeployJar(runType, ks, model2, releaseId2, new KieFile("src/main/java/org/drools/test/MyFunction.java", java2), new KieFile("src/main/resources/org/drools/incremental/r1.drl", drl)); @@ -806,8 +816,9 @@ public void testKJarUpgradeWithChangedJavaFunctionForLHSWithoutExternalizeLambda assertThat(list2).containsExactlyInAnyOrder("John"); } - @Test - public void testKJarUpgradeWithChangedJavaFunctionForLHSWithExternalizeLambda() throws Exception { + @ParameterizedTest + @MethodSource("parameters") + public void testKJarUpgradeWithChangedJavaFunctionForLHSWithExternalizeLambda(RUN_TYPE runType) throws Exception { String java1 = "package org.drools.test;\n" + "public class MyFunction {\n" + @@ -841,7 +852,7 @@ public void testKJarUpgradeWithChangedJavaFunctionForLHSWithExternalizeLambda() ReleaseId releaseId1 = ks.newReleaseId("org.kie", "test-upgrade", "1.0.0"); KieModuleModel model1 = ks.newKieModuleModel(); model1.setConfigurationProperty("drools.externaliseCanonicalModelLambda", Boolean.TRUE.toString()); - createAndDeployJar(ks, model1, releaseId1, + createAndDeployJar(runType, ks, model1, releaseId1, new KieFile("src/main/java/org/drools/test/MyFunction.java", java1), new KieFile("src/main/resources/org/drools/incremental/r1.drl", drl)); @@ -860,7 +871,7 @@ public void testKJarUpgradeWithChangedJavaFunctionForLHSWithExternalizeLambda() ReleaseId releaseId2 = ks.newReleaseId("org.kie", "test-upgrade", "1.1.0"); KieModuleModel model2 = ks.newKieModuleModel(); model2.setConfigurationProperty("drools.externaliseCanonicalModelLambda", Boolean.TRUE.toString()); - createAndDeployJar(ks, model2, releaseId2, + createAndDeployJar(runType, ks, model2, releaseId2, new KieFile("src/main/java/org/drools/test/MyFunction.java", java2), new KieFile("src/main/resources/org/drools/incremental/r1.drl", drl)); diff --git a/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/IndexTest.java b/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/IndexTest.java index 67b8177bd58..fb7e1e4edd3 100644 --- a/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/IndexTest.java +++ b/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/IndexTest.java @@ -32,7 +32,8 @@ import org.drools.kiesession.rulebase.InternalKnowledgeBase; import org.drools.model.codegen.execmodel.domain.Person; import org.drools.util.DateUtils; -import org.junit.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; import org.kie.api.KieBase; import org.kie.api.definition.rule.Rule; import org.kie.api.runtime.KieSession; @@ -41,12 +42,9 @@ public class IndexTest extends BaseModelTest { - public IndexTest( RUN_TYPE testRunType ) { - super( testRunType ); - } - - @Test - public void testBetaIndexOnDeclaration() { + @ParameterizedTest + @MethodSource("parameters") + public void testBetaIndexOnDeclaration(RUN_TYPE runType) { String str = "import " + Person.class.getCanonicalName() + ";" + "rule R1 when\n" + @@ -55,7 +53,7 @@ public void testBetaIndexOnDeclaration() { "then\n" + "end"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); ObjectTypeNode otn = getObjectTypeNodeForClass( ksession, Person.class ); BetaNode beta = (BetaNode) otn.getObjectSinkPropagator().getSinks()[0]; @@ -68,8 +66,9 @@ public void testBetaIndexOnDeclaration() { assertThat(ksession.fireAllRules()).isEqualTo(1); } - @Test - public void testBetaIndexWithAccessor() { + @ParameterizedTest + @MethodSource("parameters") + public void testBetaIndexWithAccessor(RUN_TYPE runType) { String str = "import " + Person.class.getCanonicalName() + ";" + "rule R1 when\n" + @@ -78,7 +77,7 @@ public void testBetaIndexWithAccessor() { "then\n" + "end"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); ksession.insert( "test" ); ksession.insert( new Person("Sofia", 4) ); @@ -110,8 +109,9 @@ public Integer getInteger() { } } - @Test - public void testBetaIndexWithImplicitDowncast() { + @ParameterizedTest + @MethodSource("parameters") + public void testBetaIndexWithImplicitDowncast(RUN_TYPE runType) { // DROOLS-5614 String str = "import " + ObjectWrapper.class.getCanonicalName() + ";" + @@ -122,7 +122,7 @@ public void testBetaIndexWithImplicitDowncast() { "then\n" + "end"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); ksession.insert( new ObjectWrapper( 42 ) ); ksession.insert( new IntegerWrapper( 42 ) ); @@ -130,8 +130,9 @@ public void testBetaIndexWithImplicitDowncast() { assertThat(ksession.fireAllRules()).isEqualTo(1); } - @Test - public void testAlphaIndexWithDateEqual() { + @ParameterizedTest + @MethodSource("parameters") + public void testAlphaIndexWithDateEqual(RUN_TYPE runType) { String str = "import " + Person.class.getCanonicalName() + ";" + "rule R1 when\n" + @@ -147,7 +148,7 @@ public void testAlphaIndexWithDateEqual() { "then\n" + "end\n"; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); assertConstraintType(ksession.getKieBase(), Person.class, "R1", ConstraintTypeOperator.EQUAL); assertConstraintType(ksession.getKieBase(), Person.class, "R2", ConstraintTypeOperator.EQUAL); @@ -160,8 +161,9 @@ public void testAlphaIndexWithDateEqual() { assertThat(ksession.fireAllRules()).isEqualTo(1); } - @Test - public void testAlphaIndexWithDateRelation() { + @ParameterizedTest + @MethodSource("parameters") + public void testAlphaIndexWithDateRelation(RUN_TYPE runType) { String str = "import " + Person.class.getCanonicalName() + ";" + "rule R1 when\n" + @@ -177,7 +179,7 @@ public void testAlphaIndexWithDateRelation() { "then\n" + "end\n"; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); assertConstraintType(ksession.getKieBase(), Person.class, "R1", ConstraintTypeOperator.GREATER_THAN); assertConstraintType(ksession.getKieBase(), Person.class, "R2", ConstraintTypeOperator.LESS_OR_EQUAL); @@ -207,8 +209,9 @@ private void assertConstraintType(KieBase kbase, Class factClass, String rule assertThat(asserted).isTrue(); } - @Test - public void testBetaIndexOn2ValuesOnLeftTuple() { + @ParameterizedTest + @MethodSource("parameters") + public void testBetaIndexOn2ValuesOnLeftTuple(RUN_TYPE runType) { // DROOLS-5995 String str = "import " + Person.class.getCanonicalName() + ";" + @@ -219,12 +222,12 @@ public void testBetaIndexOn2ValuesOnLeftTuple() { "then\n" + "end"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); ObjectTypeNode otn = getObjectTypeNodeForClass( ksession, Person.class ); BetaNode beta = (BetaNode) otn.getObjectSinkPropagator().getSinks()[0]; // this beta index is only supported by executable model - assertThat(beta.getRawConstraints().isIndexed()).isEqualTo(this.testRunType.isExecutableModel()); + assertThat(beta.getRawConstraints().isIndexed()).isEqualTo(runType.isExecutableModel()); ksession.insert( 5 ); ksession.insert( "test" ); @@ -233,8 +236,9 @@ public void testBetaIndexOn2ValuesOnLeftTuple() { assertThat(ksession.fireAllRules()).isEqualTo(1); } - @Test - public void testNoBetaIndexWithThisPropertyOnRight() { + @ParameterizedTest + @MethodSource("parameters") + public void testNoBetaIndexWithThisPropertyOnRight(RUN_TYPE runType) { // DROOLS-5995 String str = "import " + Person.class.getCanonicalName() + ";" + @@ -245,7 +249,7 @@ public void testNoBetaIndexWithThisPropertyOnRight() { "then\n" + "end"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); ksession.insert( 5 ); ksession.insert( "test" ); @@ -254,8 +258,9 @@ public void testNoBetaIndexWithThisPropertyOnRight() { assertThat(ksession.fireAllRules()).isEqualTo(1); } - @Test - public void testNoBetaIndexWithThisOperationOnLeft() { + @ParameterizedTest + @MethodSource("parameters") + public void testNoBetaIndexWithThisOperationOnLeft(RUN_TYPE runType) { // DROOLS-5995 String str = "import " + Person.class.getCanonicalName() + ";" + @@ -266,7 +271,7 @@ public void testNoBetaIndexWithThisOperationOnLeft() { "then\n" + "end"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); ksession.insert( 5 ); ksession.insert( "test" ); @@ -275,8 +280,9 @@ public void testNoBetaIndexWithThisOperationOnLeft() { assertThat(ksession.fireAllRules()).isEqualTo(1); } - @Test - public void testNoBetaIndexWithThisOperationOnLeft2() { + @ParameterizedTest + @MethodSource("parameters") + public void testNoBetaIndexWithThisOperationOnLeft2(RUN_TYPE runType) { // DROOLS-5995 String str = "import " + Person.class.getCanonicalName() + ";" + @@ -287,7 +293,7 @@ public void testNoBetaIndexWithThisOperationOnLeft2() { "then\n" + "end"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); ksession.insert( 5 ); ksession.insert( "test" ); @@ -296,8 +302,9 @@ public void testNoBetaIndexWithThisOperationOnLeft2() { assertThat(ksession.fireAllRules()).isEqualTo(1); } - @Test - public void testNoBetaIndexWithThisMethodInvocationOnLeft() { + @ParameterizedTest + @MethodSource("parameters") + public void testNoBetaIndexWithThisMethodInvocationOnLeft(RUN_TYPE runType) { // DROOLS-5995 String str = "import " + List.class.getCanonicalName() + ";" + @@ -307,12 +314,13 @@ public void testNoBetaIndexWithThisMethodInvocationOnLeft() { "then\n" + "end"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); assertThat(ksession.fireAllRules()).isEqualTo(0); } - @Test - public void testBetaIndexOn3ValuesOnLeftTuple() { + @ParameterizedTest + @MethodSource("parameters") + public void testBetaIndexOn3ValuesOnLeftTuple(RUN_TYPE runType) { // DROOLS-5995 String str = "import " + Person.class.getCanonicalName() + ";" + @@ -324,12 +332,12 @@ public void testBetaIndexOn3ValuesOnLeftTuple() { "then\n" + "end"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); ObjectTypeNode otn = getObjectTypeNodeForClass( ksession, Person.class ); BetaNode beta = (BetaNode) otn.getObjectSinkPropagator().getSinks()[0]; // this beta index is only supported by executable model - assertThat(beta.getRawConstraints().isIndexed()).isEqualTo(this.testRunType.isExecutableModel()); + assertThat(beta.getRawConstraints().isIndexed()).isEqualTo(runType.isExecutableModel()); ksession.insert( 2L ); ksession.insert( 3 ); @@ -339,8 +347,9 @@ public void testBetaIndexOn3ValuesOnLeftTuple() { assertThat(ksession.fireAllRules()).isEqualTo(1); } - @Test - public void testBetaIndexOn4ValuesOnLeftTuple() { + @ParameterizedTest + @MethodSource("parameters") + public void testBetaIndexOn4ValuesOnLeftTuple(RUN_TYPE runType) { // DROOLS-5995 String str = "import " + Person.class.getCanonicalName() + ";" + @@ -353,12 +362,12 @@ public void testBetaIndexOn4ValuesOnLeftTuple() { "then\n" + "end"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); ObjectTypeNode otn = getObjectTypeNodeForClass( ksession, Person.class ); BetaNode beta = (BetaNode) otn.getObjectSinkPropagator().getSinks()[0]; // this beta index is only supported by executable model - assertThat(beta.getRawConstraints().isIndexed()).isEqualTo(this.testRunType.isExecutableModel()); + assertThat(beta.getRawConstraints().isIndexed()).isEqualTo(runType.isExecutableModel()); ksession.insert( (short)1 ); ksession.insert( 1L ); @@ -369,8 +378,9 @@ public void testBetaIndexOn4ValuesOnLeftTuple() { assertThat(ksession.fireAllRules()).isEqualTo(1); } - @Test - public void testAlphaIndexHashed() { + @ParameterizedTest + @MethodSource("parameters") + public void testAlphaIndexHashed(RUN_TYPE runType) { String str = "import " + Person.class.getCanonicalName() + ";" + "rule R1 when\n" + @@ -386,13 +396,14 @@ public void testAlphaIndexHashed() { "then\n" + "end\n"; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); assertHashIndex(ksession, Person.class, 3); } - @Test - public void testAlphaIndexHashedNonGetter() { + @ParameterizedTest + @MethodSource("parameters") + public void testAlphaIndexHashedNonGetter(RUN_TYPE runType) { String str = "import " + Person.class.getCanonicalName() + ";" + "rule R1 when\n" + @@ -408,7 +419,7 @@ public void testAlphaIndexHashedNonGetter() { "then\n" + "end\n"; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); assertHashIndex(ksession, Person.class, 3); } @@ -422,8 +433,9 @@ private void assertHashIndex(KieSession ksession, Class factClass, int expect assertThat(compositeObjectSinkAdapter.getHashedSinkMap().size()).isEqualTo(expectedHashedSinkMapSize); } - @Test - public void testAlphaIndexHashedPrimitiveWrapper() { + @ParameterizedTest + @MethodSource("parameters") + public void testAlphaIndexHashedPrimitiveWrapper(RUN_TYPE runType) { String str = "import " + Integer.class.getCanonicalName() + ";\n" + "rule R1 when\n" + @@ -439,13 +451,14 @@ public void testAlphaIndexHashedPrimitiveWrapper() { "then\n" + "end\n"; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); assertHashIndex(ksession, Integer.class, 3); } - @Test - public void testAlphaIndexHashedNumberInterface() { + @ParameterizedTest + @MethodSource("parameters") + public void testAlphaIndexHashedNumberInterface(RUN_TYPE runType) { String str = "import " + Integer.class.getCanonicalName() + ";\n" + "rule R1 when\n" + @@ -461,7 +474,7 @@ public void testAlphaIndexHashedNumberInterface() { "then\n" + "end\n"; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); assertHashIndex(ksession, Number.class, 3); @@ -470,8 +483,9 @@ public void testAlphaIndexHashedNumberInterface() { assertThat(fired).isEqualTo(1); } - @Test - public void testAlphaIndexWithDeclarationInPattern() { + @ParameterizedTest + @MethodSource("parameters") + public void testAlphaIndexWithDeclarationInPattern(RUN_TYPE runType) { final String str = "package org.drools.mvel.compiler\n" + "import " + Person.class.getCanonicalName() + ";" + @@ -481,7 +495,7 @@ public void testAlphaIndexWithDeclarationInPattern() { "then\n" + "end\n"; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); ObjectTypeNode otn = getObjectTypeNodeForClass(ksession, Person.class); ObjectSink sink = otn.getObjectSinkPropagator().getSinks()[0]; @@ -494,8 +508,9 @@ public void testAlphaIndexWithDeclarationInPattern() { assertThat(fired).isEqualTo(1); } - @Test - public void testAlphaIndexWithDeclarationInPatternWithSameNameProp() { + @ParameterizedTest + @MethodSource("parameters") + public void testAlphaIndexWithDeclarationInPatternWithSameNameProp(RUN_TYPE runType) { final String str = "package org.drools.mvel.compiler\n" + "import " + Person.class.getCanonicalName() + ";" + @@ -506,7 +521,7 @@ public void testAlphaIndexWithDeclarationInPatternWithSameNameProp() { "then\n" + "end\n"; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); ObjectTypeNode otn = getObjectTypeNodeForClass(ksession, Person.class); ObjectSink sink = otn.getObjectSinkPropagator().getSinks()[0]; diff --git a/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/InternalMatchGroupTest.java b/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/InternalMatchGroupTest.java index 01e88262e71..defa110bc45 100644 --- a/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/InternalMatchGroupTest.java +++ b/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/InternalMatchGroupTest.java @@ -22,7 +22,8 @@ import java.util.List; import org.drools.commands.runtime.rule.ClearActivationGroupCommand; -import org.junit.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; import org.kie.api.KieServices; import org.kie.api.command.BatchExecutionCommand; import org.kie.api.command.Command; @@ -39,12 +40,10 @@ public class InternalMatchGroupTest extends OnlyPatternTest { private static final String KIE_SESSION = "ksession1"; private static final String ACTIVATION_GROUP = "first-group"; - public InternalMatchGroupTest(RUN_TYPE testRunType) { - super(testRunType); - } - @Test - public void testClearActivationGroup() { + @ParameterizedTest + @MethodSource("parameters") + public void testClearActivationGroup(RUN_TYPE runType) { // DROOLS-5685 ClearActivationGroup command changed its behaviour String str = "import java.util.List;\n" + "\n" + @@ -75,7 +74,7 @@ public void testClearActivationGroup() { List> commands = new ArrayList>(); - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); KieCommands commandsFactory = KieServices.get().getCommands(); BatchExecutionCommand batchExecution = commandsFactory.newBatchExecution(commands, KIE_SESSION); diff --git a/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/KieBaseBuilderTest.java b/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/KieBaseBuilderTest.java index eaea5f9930b..fe231cdac2a 100644 --- a/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/KieBaseBuilderTest.java +++ b/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/KieBaseBuilderTest.java @@ -22,14 +22,15 @@ import java.util.List; import java.util.UUID; import java.util.stream.Collectors; +import java.util.stream.Stream; import org.drools.compiler.compiler.io.memory.MemoryFileSystem; import org.drools.compiler.kie.builder.impl.KieBuilderImpl; import org.drools.model.Model; import org.drools.model.codegen.execmodel.domain.Person; import org.drools.modelcompiler.KieBaseBuilder; -import org.junit.Test; -import org.junit.runners.Parameterized.Parameters; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; import org.kie.api.KieBase; import org.kie.api.KieBaseConfiguration; import org.kie.api.KieServices; @@ -46,17 +47,13 @@ public class KieBaseBuilderTest extends BaseModelTest { // Only exec-model test - @Parameters(name = "{0}") - public static Object[] params() { - return new Object[]{RUN_TYPE.PATTERN_DSL}; + public static Stream parameters() { + return Stream.of(RUN_TYPE.PATTERN_DSL); } - public KieBaseBuilderTest(RUN_TYPE testRunType) { - super(testRunType); - } - - @Test - public void createKieBaseWithKnowledgeBuilderConfiguration() { + @ParameterizedTest + @MethodSource("parameters") + public void createKieBaseWithKnowledgeBuilderConfiguration(RUN_TYPE runType) { // DROOLS-7239 final String str = "import " + Person.class.getCanonicalName() + ";\n" + @@ -73,7 +70,7 @@ public void createKieBaseWithKnowledgeBuilderConfiguration() { ReleaseId releaseId = ks.newReleaseId("org.kie", "kjar-test-" + UUID.randomUUID(), "1.0"); KieModuleModel model = ks.newKieModuleModel(); model.setConfigurationProperty(option.getPropertyName(), option.name()); - KieBuilder kieBuilder = createKieBuilder(ks, model, releaseId, toKieFiles(new String[]{str})); + KieBuilder kieBuilder = createKieBuilder(runType, ks, model, releaseId, toKieFiles(new String[]{str})); // 2nd round: Create a kbase with generated classes and PropertySpecificOption.DISABLED KnowledgeBuilderConfiguration knowledgeBuilderConf = KnowledgeBuilderFactory.newKnowledgeBuilderConfiguration(); diff --git a/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/KieBuilderTest.java b/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/KieBuilderTest.java index 6d766f53f52..e36dd7e6db9 100644 --- a/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/KieBuilderTest.java +++ b/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/KieBuilderTest.java @@ -26,7 +26,7 @@ import org.drools.kiesession.rulebase.InternalKnowledgeBase; import org.drools.model.codegen.ExecutableModelProject; import org.drools.modelcompiler.constraints.LambdaConstraint; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.kie.api.KieServices; import org.kie.api.builder.KieBuilder; import org.kie.api.builder.KieFileSystem; diff --git a/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/KjarBuildTest.java b/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/KjarBuildTest.java index 4d663ec33ff..49baf35bde9 100644 --- a/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/KjarBuildTest.java +++ b/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/KjarBuildTest.java @@ -19,7 +19,7 @@ package org.drools.model.codegen.execmodel; import org.drools.model.codegen.ExecutableModelProject; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.kie.api.KieServices; import org.kie.api.builder.KieBuilder; import org.kie.api.builder.KieFileSystem; diff --git a/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/ListenersTest.java b/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/ListenersTest.java index 3c893c3deb9..6d87f35295c 100644 --- a/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/ListenersTest.java +++ b/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/ListenersTest.java @@ -21,7 +21,8 @@ import java.util.ArrayList; import java.util.List; -import org.junit.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; import org.kie.api.event.rule.ObjectDeletedEvent; import org.kie.api.event.rule.ObjectInsertedEvent; import org.kie.api.event.rule.ObjectUpdatedEvent; @@ -32,12 +33,9 @@ public class ListenersTest extends BaseModelTest { - public ListenersTest( RUN_TYPE testRunType ) { - super( testRunType ); - } - - @Test - public void testInsert() { + @ParameterizedTest + @MethodSource("parameters") + public void testInsert(RUN_TYPE runType) { String str = "rule R\n" + "when\n" + @@ -46,7 +44,7 @@ public void testInsert() { " insert(\"\" + $i);\n" + "end"; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); List results = new ArrayList<>(); diff --git a/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/MapInitializationDrools3800Test.java b/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/MapInitializationDrools3800Test.java index d760d2fd8b0..672dc20e7cf 100644 --- a/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/MapInitializationDrools3800Test.java +++ b/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/MapInitializationDrools3800Test.java @@ -21,17 +21,14 @@ import java.util.Map; import java.util.Objects; -import org.junit.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; import org.kie.api.runtime.KieSession; import static org.assertj.core.api.Assertions.assertThat; public class MapInitializationDrools3800Test extends BaseModelTest { - public MapInitializationDrools3800Test(BaseModelTest.RUN_TYPE testRunType) { - super(testRunType); - } - public static boolean calc(Map params) { return Objects.equals(params.get("src"), params.get("target")); } @@ -57,8 +54,9 @@ public void setResult(String result) { } } - @Test - public void testMapInitialization() { + @ParameterizedTest + @MethodSource("parameters") + public void testMapInitialization(RUN_TYPE runType) { StringBuilder r = new StringBuilder(); r.append("package ").append(getClass().getPackage().getName()).append("\n"); r.append("\n"); @@ -76,7 +74,7 @@ public void testMapInitialization() { r.append(" }").append("\n"); r.append("end").append("\n"); - KieSession ksession = getKieSession(r.toString() ); + KieSession ksession = getKieSession(runType, r.toString()); Fact fact = new Fact(); @@ -88,8 +86,9 @@ public void testMapInitialization() { assertThat(fact.getResult()).isEqualTo("OK"); } - @Test - public void testPropertyReactivityHanging() { + @ParameterizedTest + @MethodSource("parameters") + public void testPropertyReactivityHanging(RUN_TYPE runType) { // DROOLS-3849 String rule = "package " + getClass().getPackage().getName() + "\n" + @@ -107,7 +106,7 @@ public void testPropertyReactivityHanging() { " }\n" + "end"; - KieSession ksession = getKieSession(rule); + KieSession ksession = getKieSession(runType, rule); Fact fact = new Fact(); fact.setName("TEST"); diff --git a/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/MaterializedLambdaTest.java b/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/MaterializedLambdaTest.java index eb807e427e5..eb756552f5a 100644 --- a/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/MaterializedLambdaTest.java +++ b/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/MaterializedLambdaTest.java @@ -22,19 +22,17 @@ import java.util.Date; import org.drools.model.codegen.execmodel.domain.Result; -import org.junit.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; import org.kie.api.runtime.KieSession; import static org.assertj.core.api.Assertions.assertThat; public class MaterializedLambdaTest extends BaseModelTest { - public MaterializedLambdaTest(RUN_TYPE testRunType) { - super(testRunType); - } - - @Test - public void testMaterializeLambda() { + @ParameterizedTest + @MethodSource("parameters") + public void testMaterializeLambda(RUN_TYPE runType) { String str = "import " + DataType.class.getCanonicalName() + ";\n" + @@ -57,7 +55,7 @@ public void testMaterializeLambda() { " result.setValue(0);\n" + "end\n"; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); DataType st = new DataType("FF", "BBB"); DataType st2 = new DataType("FF", "CCC"); @@ -81,8 +79,9 @@ public static void execute(Runnable r) { } // DROOLS-4858 - @Test - public void testMaterializeLambdaWithNested() { + @ParameterizedTest + @MethodSource("parameters") + public void testMaterializeLambdaWithNested(RUN_TYPE runType) { String str = "import " + Executor.class.getCanonicalName() + ";\n" + "import " + Result.class.getCanonicalName() + ";\n" + @@ -97,7 +96,7 @@ public void testMaterializeLambdaWithNested() { " });" + "end"; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); ksession.insert(42); diff --git a/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/ModelBuilderImplTest.java b/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/ModelBuilderImplTest.java index 76adb83215a..90d4bb047e4 100644 --- a/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/ModelBuilderImplTest.java +++ b/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/ModelBuilderImplTest.java @@ -24,8 +24,8 @@ import org.drools.core.reteoo.CoreComponentFactory; import org.drools.drl.ast.descr.GlobalDescr; import org.drools.drl.ast.descr.PackageDescr; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.kie.api.builder.ReleaseId; import org.kie.internal.builder.KnowledgeBuilderFactory; import org.kie.util.maven.support.ReleaseIdImpl; @@ -42,7 +42,7 @@ public class ModelBuilderImplTest { private PackageRegistry packageRegistry; private ModelBuilderImpl modelBuilder; - @Before + @BeforeEach public void setup() { internalKnowledgePackage = CoreComponentFactory.get().createKnowledgePackage("apackage"); modelBuilder = new ModelBuilderImpl<>(PackageSources::dumpSources, CONFIGURATION, RELEASE_ID, false); diff --git a/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/ModelSourceClassTest.java b/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/ModelSourceClassTest.java index 82189b9a4ce..e3438136f67 100644 --- a/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/ModelSourceClassTest.java +++ b/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/ModelSourceClassTest.java @@ -24,15 +24,15 @@ import java.util.Map; import org.drools.compiler.kproject.models.KieBaseModelImpl; - -import static org.assertj.core.api.Assertions.assertThat; import org.drools.compiler.kproject.models.KieModuleModelImpl; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.kie.api.builder.ReleaseId; import org.kie.api.builder.model.KieBaseModel; import org.kie.api.builder.model.KieModuleModel; import org.kie.util.maven.support.ReleaseIdImpl; +import static org.assertj.core.api.Assertions.assertThat; + public class ModelSourceClassTest { diff --git a/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/MultiKieBaseTest.java b/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/MultiKieBaseTest.java index a59086ab697..4f02e0c197f 100644 --- a/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/MultiKieBaseTest.java +++ b/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/MultiKieBaseTest.java @@ -18,7 +18,6 @@ */ package org.drools.model.codegen.execmodel; -import org.junit.Test; import org.kie.api.KieServices; import org.kie.api.builder.ReleaseId; import org.kie.api.builder.model.KieModuleModel; @@ -27,14 +26,14 @@ import static org.assertj.core.api.Assertions.assertThat; -public class MultiKieBaseTest extends BaseModelTest { +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; - public MultiKieBaseTest( RUN_TYPE testRunType ) { - super( testRunType ); - } +public class MultiKieBaseTest extends BaseModelTest { - @Test - public void testHelloWorldWithPackagesAnd2KieBases() throws Exception { + @ParameterizedTest + @MethodSource("parameters") + public void testHelloWorldWithPackagesAnd2KieBases(RUN_TYPE runType) throws Exception { String drl1a = "package org.pkg1\n" + "rule R1 when\n" + " $m : String( this == \"Hello World\" )\n" + @@ -69,7 +68,7 @@ public void testHelloWorldWithPackagesAnd2KieBases() throws Exception { // Create an in-memory jar for version 1.0.0 ReleaseId releaseId1 = ks.newReleaseId( "org.kie", "test-upgrade", "1.0.0" ); - createAndDeployJar( ks, createKieProjectWithPackagesAnd2KieBases(), releaseId1, + createAndDeployJar(runType, ks, createKieProjectWithPackagesAnd2KieBases(), releaseId1, new KieFile( "src/main/resources/org/pkg1/r1.drl", drl1a ), new KieFile( "src/main/resources/org/pkg2/r2.drl", drl2a ) ); @@ -97,7 +96,7 @@ public void testHelloWorldWithPackagesAnd2KieBases() throws Exception { assertThat(ksession2.fireAllRules()).isEqualTo(1); ReleaseId releaseId2 = ks.newReleaseId( "org.kie", "test-upgrade", "1.1.0" ); - createAndDeployJar( ks, createKieProjectWithPackagesAnd2KieBases(), releaseId2, + createAndDeployJar(runType, ks, createKieProjectWithPackagesAnd2KieBases(), releaseId2, new KieFile( "src/main/resources/org/pkg1/r1.drl", drl1a ), new KieFile( "src/main/resources/org/pkg2/r2.drl", drl2b ) ); @@ -122,8 +121,9 @@ private KieModuleModel createKieProjectWithPackagesAnd2KieBases() { return kproj; } - @Test - public void testFoldersVsPackages() throws Exception { + @ParameterizedTest + @MethodSource("parameters") + public void testFoldersVsPackages(RUN_TYPE runType) throws Exception { String drl1 = "//package org.commented1\n" + "package org.pkg1\n" + @@ -166,7 +166,7 @@ public void testFoldersVsPackages() throws Exception { .newKieSessionModel("KSession4"); ReleaseId releaseId1 = ks.newReleaseId( "org.kie", "test-pkgs", "1.0.0" ); - createAndDeployJar( ks, kproj, releaseId1, + createAndDeployJar(runType, ks, kproj, releaseId1, new KieFile( "src/main/resources/org/pkg1/r1.drl", drl1 ), new KieFile( "src/main/resources/rules/r2.drl", drl2 ) ); @@ -190,8 +190,9 @@ public void testFoldersVsPackages() throws Exception { assertThat(ks4.fireAllRules()).isEqualTo(0); // there is no "rules" package and folder is not relevant } - @Test - public void testDotInKieBaseName() throws Exception { + @ParameterizedTest + @MethodSource("parameters") + public void testDotInKieBaseName(RUN_TYPE runType) throws Exception { // DROOLS-5845 String drl1 = "package org.pkg1\n" + @@ -209,7 +210,7 @@ public void testDotInKieBaseName() throws Exception { .newKieSessionModel("Kie.Session"); ReleaseId releaseId1 = ks.newReleaseId( "org.kie", "test-dor", "1.0.0" ); - createAndDeployJar( ks, kproj, releaseId1, + createAndDeployJar(runType, ks, kproj, releaseId1, new KieFile( "src/main/resources/org/pkg1/r1.drl", drl1 ) ); // Create a session and fire rules @@ -220,8 +221,9 @@ public void testDotInKieBaseName() throws Exception { assertThat(ks2.fireAllRules()).isEqualTo(1); // only rule in org.pkg1 should fire } - @Test - public void testHelloMultiKieBasesWithSharedDeclaredType() throws Exception { + @ParameterizedTest + @MethodSource("parameters") + public void testHelloMultiKieBasesWithSharedDeclaredType(RUN_TYPE runType) throws Exception { // DROOLS-6331 String drlType = "package org.pkg.type\n" + @@ -270,7 +272,7 @@ public void testHelloMultiKieBasesWithSharedDeclaredType() throws Exception { // Create an in-memory jar for version 1.0.0 ReleaseId releaseId1 = ks.newReleaseId( "org.kie", "test-types", "1.0.0" ); - createAndDeployJar( ks, kproj, releaseId1, + createAndDeployJar(runType, ks, kproj, releaseId1, new KieFile( "src/main/resources/org/pkg/type/r0.drl", drlType ), new KieFile( "src/main/resources/org/pkg1/r1.drl", drl1 ), new KieFile( "src/main/resources/org/pkg2/r2.drl", drl2 ), diff --git a/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/MvelDialectMapTest.java b/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/MvelDialectMapTest.java index b96dce0a1a4..fdcb919b12a 100644 --- a/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/MvelDialectMapTest.java +++ b/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/MvelDialectMapTest.java @@ -22,20 +22,17 @@ import java.util.List; import org.drools.model.codegen.execmodel.domain.Person; -import org.junit.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; import org.kie.api.runtime.KieSession; import static org.assertj.core.api.Assertions.assertThat; public class MvelDialectMapTest extends BaseModelTest { - public MvelDialectMapTest(RUN_TYPE testRunType ) { - super( testRunType ); - } - - - @Test - public void testMapAccessorWithBind() { + @ParameterizedTest + @MethodSource("parameters") + public void testMapAccessorWithBind(RUN_TYPE runType) { final String drl = "" + "import java.util.*;\n" + "import " + Person.class.getCanonicalName() + ";\n" + @@ -51,7 +48,7 @@ public void testMapAccessorWithBind() { " results.add($i.length());" + "end"; - KieSession ksession = getKieSession(drl); + KieSession ksession = getKieSession(runType, drl); List results = new ArrayList<>(); ksession.setGlobal("results", results); @@ -67,8 +64,9 @@ public void testMapAccessorWithBind() { assertThat(results).containsExactly(5); // item1.length() } - @Test - public void testMapAccessorWithBindFieldAccessor() { + @ParameterizedTest + @MethodSource("parameters") + public void testMapAccessorWithBindFieldAccessor(RUN_TYPE runType) { final String drl = "" + "import java.util.*;\n" + "import " + Person.class.getCanonicalName() + ";\n" + @@ -84,7 +82,7 @@ public void testMapAccessorWithBindFieldAccessor() { " results.add($childName.length());" + "end"; - KieSession ksession = getKieSession(drl); + KieSession ksession = getKieSession(runType, drl); List results = new ArrayList<>(); ksession.setGlobal("results", results); diff --git a/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/MvelDialectTest.java b/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/MvelDialectTest.java index 087dece997d..90308ac94a0 100644 --- a/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/MvelDialectTest.java +++ b/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/MvelDialectTest.java @@ -36,7 +36,8 @@ import org.drools.model.codegen.execmodel.domain.InternationalAddress; import org.drools.model.codegen.execmodel.domain.Person; import org.drools.model.codegen.execmodel.domain.ValueHolder; -import org.junit.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; import org.kie.api.builder.Message; import org.kie.api.builder.Results; import org.kie.api.definition.rule.Rule; @@ -51,12 +52,9 @@ public class MvelDialectTest extends BaseModelTest { - public MvelDialectTest( RUN_TYPE testRunType ) { - super( testRunType ); - } - - @Test - public void testMVELinsert() { + @ParameterizedTest + @MethodSource("parameters") + public void testMVELinsert(RUN_TYPE runType) { String str = "rule R\n" + "dialect \"mvel\"\n" + "when\n" + @@ -66,7 +64,7 @@ public void testMVELinsert() { " insert(\"Hello World\");\n" + "end"; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); FactHandle fh_47 = ksession.insert(47); ksession.fireAllRules(); @@ -75,8 +73,9 @@ public void testMVELinsert() { assertThat(results.contains("Hello World")).isTrue(); } - @Test - public void testMVELMapSyntax() { + @ParameterizedTest + @MethodSource("parameters") + public void testMVELMapSyntax(RUN_TYPE runType) { final String drl = "" + "import java.util.*;\n" + "import " + Person.class.getCanonicalName() + ";\n" + @@ -102,7 +101,7 @@ public void testMVELMapSyntax() { " update(m);\n" + "end"; - KieSession ksession = getKieSession(drl); + KieSession ksession = getKieSession(runType, drl); Person p = new Person("Luca"); @@ -115,8 +114,9 @@ public void testMVELMapSyntax() { assertThat(itemsString.keySet().size()).isEqualTo(4); } - @Test - public void testMVELmodify() { + @ParameterizedTest + @MethodSource("parameters") + public void testMVELmodify(RUN_TYPE runType) { String str = "import " + Person.class.getCanonicalName() + ";\n" + "rule R\n" + "dialect \"mvel\"\n" + @@ -126,7 +126,7 @@ public void testMVELmodify() { " modify($p) { setAge(1); }\n" + "end"; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); ksession.insert(new Person("Matteo", 47)); ksession.fireAllRules(); @@ -136,8 +136,9 @@ public void testMVELmodify() { results.forEach(System.out::println); } - @Test - public void testMVELmultiple() { + @ParameterizedTest + @MethodSource("parameters") + public void testMVELmultiple(RUN_TYPE runType) { String str = "package mypackage;" + "dialect \"mvel\"\n" + // MVEL dialect defined at package level. "import " + Person.class.getCanonicalName() + ";\n" + @@ -164,7 +165,7 @@ public void testMVELmultiple() { " retract($s)" + "end\n"; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); FactHandle fh_47 = ksession.insert(47); ksession.fireAllRules(); @@ -175,8 +176,9 @@ public void testMVELmultiple() { assertThat(results.contains("Modified person age to 1 for: Matteo")).isTrue(); } - @Test - public void testMVELmultipleStatements() { + @ParameterizedTest + @MethodSource("parameters") + public void testMVELmultipleStatements(RUN_TYPE runType) { String str = "import " + Person.class.getPackage().getName() + ".*;\n" + // keep the package.* in order for Address to be resolvable in the RHS. "rule R\n" + @@ -188,7 +190,7 @@ public void testMVELmultipleStatements() { " insert(a);\n" + "end"; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); ksession.insert(new Person("Matteo", 47)); ksession.fireAllRules(); @@ -208,8 +210,9 @@ public static class TempDecl8 {} public static class TempDecl9 {} public static class TempDecl10 {} - @Test - public void testMVEL10declarations() { + @ParameterizedTest + @MethodSource("parameters") + public void testMVEL10declarations(RUN_TYPE runType) { String str = "\n" + "import " + TempDecl1.class.getCanonicalName() + ";\n" + "import " + TempDecl2.class.getCanonicalName() + ";\n" + @@ -238,7 +241,7 @@ public void testMVEL10declarations() { " insert(\"matched\");\n" + "end"; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); ksession.insert(new TempDecl1()); ksession.insert(new TempDecl2()); @@ -256,8 +259,9 @@ public void testMVEL10declarations() { assertThat(results.size()).isEqualTo(1); } - @Test - public void testMVEL10declarationsBis() { + @ParameterizedTest + @MethodSource("parameters") + public void testMVEL10declarationsBis(RUN_TYPE runType) { String str = "\n" + "import " + TempDecl1.class.getCanonicalName() + ";\n" + "import " + TempDecl2.class.getCanonicalName() + ";\n" + @@ -301,7 +305,7 @@ public void testMVEL10declarationsBis() { " insert(\"matched\");\n" + "end"; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); ksession.fireAllRules(); @@ -309,8 +313,9 @@ public void testMVEL10declarationsBis() { assertThat(results.size()).isEqualTo(1); } - @Test - public void testMvelFunctionWithClassArg() { + @ParameterizedTest + @MethodSource("parameters") + public void testMvelFunctionWithClassArg(RUN_TYPE runType) { final String drl = "package org.drools.compiler.integrationtests.drl; \n" + "import " + Person.class.getCanonicalName() + ";\n" + @@ -333,7 +338,7 @@ public void testMvelFunctionWithClassArg() { " value.append( getFieldValue($bean) ); \n" + "end"; - KieSession ksession = getKieSession(drl); + KieSession ksession = getKieSession(runType, drl); try { final StringBuilder sb = new StringBuilder(); @@ -346,8 +351,9 @@ public void testMvelFunctionWithClassArg() { } } - @Test - public void testMvelFunctionWithDeclaredTypeArg() { + @ParameterizedTest + @MethodSource("parameters") + public void testMvelFunctionWithDeclaredTypeArg(RUN_TYPE runType) { final String drl = "package org.drools.compiler.integrationtests.drl; \n" + "dialect \"mvel\"\n" + @@ -372,7 +378,7 @@ public void testMvelFunctionWithDeclaredTypeArg() { " value.append( getFieldValue($bean) ); \n" + "end"; - KieSession ksession = getKieSession(drl); + KieSession ksession = getKieSession(runType, drl); try { final StringBuilder sb = new StringBuilder(); @@ -385,8 +391,9 @@ public void testMvelFunctionWithDeclaredTypeArg() { } } - @Test - public void testMultiDrlWithSamePackageMvel() throws Exception { + @ParameterizedTest + @MethodSource("parameters") + public void testMultiDrlWithSamePackageMvel(RUN_TYPE runType) throws Exception { // DROOLS-3508 String drl1 = "package org.pkg\n" + "import " + Person.class.getCanonicalName() + "\n" + @@ -402,7 +409,7 @@ public void testMultiDrlWithSamePackageMvel() throws Exception { " update($p);\n" + "end\n"; - KieSession ksession = getKieSession(drl1, drl2); + KieSession ksession = getKieSession(runType, drl1, drl2); Person john = new Person("John", 24); ksession.insert(john); @@ -410,8 +417,9 @@ public void testMultiDrlWithSamePackageMvel() throws Exception { assertThat(john.getAge()).isEqualTo(1); } - @Test - public void testMVELNonExistingMethod() { + @ParameterizedTest + @MethodSource("parameters") + public void testMVELNonExistingMethod(RUN_TYPE runType) { // DROOLS-3559 String drl = "import " + Person.class.getCanonicalName() + "\n" + @@ -423,12 +431,13 @@ public void testMVELNonExistingMethod() { " modify($p) {likes = nonExistingMethod()};\n" + "end"; - Results results = createKieBuilder( drl ).getResults(); + Results results = createKieBuilder(runType, drl).getResults(); assertThat(results.getMessages(Message.Level.ERROR).isEmpty()).isFalse(); } - @Test - public void testBinaryOperationOnBigDecimal() throws Exception { + @ParameterizedTest + @MethodSource("parameters") + public void testBinaryOperationOnBigDecimal(RUN_TYPE runType) throws Exception { // RHDM-1421 String drl = "import " + Person.class.getCanonicalName() + "\n" + @@ -440,7 +449,7 @@ public void testBinaryOperationOnBigDecimal() throws Exception { " $p.money = $p.money + 50000;\n" + "end"; - KieSession ksession = getKieSession(drl); + KieSession ksession = getKieSession(runType, drl); Person john = new Person("John", 30); john.setMoney( new BigDecimal( 70000 ) ); @@ -450,8 +459,9 @@ public void testBinaryOperationOnBigDecimal() throws Exception { assertThat(john.getMoney()).isEqualTo(new BigDecimal( 120000 )); } - @Test - public void testAdditionMultiplication() throws Exception { + @ParameterizedTest + @MethodSource("parameters") + public void testAdditionMultiplication(RUN_TYPE runType) throws Exception { // DROOLS-6089 String drl = "import " + Person.class.getCanonicalName() + "\n" + @@ -466,7 +476,7 @@ public void testAdditionMultiplication() throws Exception { " $p.money = $p.money + (bd1.multiply(bd2));" + "end"; - KieSession ksession = getKieSession(drl); + KieSession ksession = getKieSession(runType, drl); Person john = new Person("John", 30); john.setMoney( new BigDecimal( 70000 ) ); @@ -476,8 +486,9 @@ public void testAdditionMultiplication() throws Exception { assertThat(john.getMoney()).isEqualTo(new BigDecimal( 70200 )); } - @Test - public void testBigDecimalModuloConsequence() { + @ParameterizedTest + @MethodSource("parameters") + public void testBigDecimalModuloConsequence(RUN_TYPE runType) { // DROOLS-5959 String drl = "import " + Person.class.getCanonicalName() + "\n" + @@ -493,7 +504,7 @@ public void testBigDecimalModuloConsequence() { " results.add(moduloPromotedToBigDecimal);\n" + "end"; - KieSession ksession = getKieSession(drl); + KieSession ksession = getKieSession(runType, drl); List results = new ArrayList<>(); ksession.setGlobal("results", results); @@ -507,8 +518,9 @@ public void testBigDecimalModuloConsequence() { assertThat(results).containsExactly(valueOf(1), valueOf(2)); } - @Test - public void testBigDecimalModulo() { + @ParameterizedTest + @MethodSource("parameters") + public void testBigDecimalModulo(RUN_TYPE runType) { // DROOLS-5959 String drl = "import " + Person.class.getCanonicalName() + "\n" + @@ -521,7 +533,7 @@ public void testBigDecimalModulo() { " results.add($m);\n" + "end"; - KieSession ksession = getKieSession(drl); + KieSession ksession = getKieSession(runType, drl); List results = new ArrayList<>(); ksession.setGlobal("results", results); @@ -539,8 +551,9 @@ public void testBigDecimalModulo() { assertThat(results.iterator().next()).isEqualTo(new BigDecimal( 70000 )); } - @Test - public void testBigDecimalModuloBetweenFields() { + @ParameterizedTest + @MethodSource("parameters") + public void testBigDecimalModuloBetweenFields(RUN_TYPE runType) { // DROOLS-5959 String drl = "import " + Person.class.getCanonicalName() + "\n" + @@ -553,7 +566,7 @@ public void testBigDecimalModuloBetweenFields() { " results.add($m);\n" + "end"; - KieSession ksession = getKieSession(drl); + KieSession ksession = getKieSession(runType, drl); List results = new ArrayList<>(); ksession.setGlobal("results", results); @@ -571,8 +584,9 @@ public void testBigDecimalModuloBetweenFields() { assertThat(results.iterator().next()).isEqualTo(new BigDecimal( 80 )); } - @Test - public void testBigDecimalPatternWithString() { + @ParameterizedTest + @MethodSource("parameters") + public void testBigDecimalPatternWithString(RUN_TYPE runType) { // DROOLS-6356 // DROOLS-6361 String drl = "import " + Person.class.getCanonicalName() + "\n" + @@ -593,7 +607,7 @@ public void testBigDecimalPatternWithString() { " $p.name = 144B;\n" + "end"; - KieSession ksession = getKieSession(drl); + KieSession ksession = getKieSession(runType, drl); List results = new ArrayList<>(); ksession.setGlobal("results", results); @@ -612,8 +626,9 @@ public void testBigDecimalPatternWithString() { assertThat(results.iterator().next().getName()).isEqualTo("144"); } - @Test - public void testBigDecimalAccumulate() { + @ParameterizedTest + @MethodSource("parameters") + public void testBigDecimalAccumulate(RUN_TYPE runType) { // DROOLS-6366 String drl = "import " + Person.class.getCanonicalName() + "\n" + @@ -628,7 +643,7 @@ public void testBigDecimalAccumulate() { " results.add($john);\n" + "end"; - KieSession ksession = getKieSession(drl); + KieSession ksession = getKieSession(runType, drl); List results = new ArrayList<>(); ksession.setGlobal("results", results); @@ -646,8 +661,9 @@ public void testBigDecimalAccumulate() { assertThat(results).containsExactly(john); } - @Test - public void testBigDecimalAccumulateWithFrom() { + @ParameterizedTest + @MethodSource("parameters") + public void testBigDecimalAccumulateWithFrom(RUN_TYPE runType) { // DROOLS-6366 String drl = "import " + Person.class.getCanonicalName() + "\n" + @@ -662,7 +678,7 @@ public void testBigDecimalAccumulateWithFrom() { " results.add($john);\n" + "end"; - KieSession ksession = getKieSession(drl); + KieSession ksession = getKieSession(runType, drl); List results = new ArrayList<>(); ksession.setGlobal("results", results); @@ -680,8 +696,9 @@ public void testBigDecimalAccumulateWithFrom() { assertThat(results).containsExactly(john); } - @Test - public void testCompoundOperatorBigDecimalConstant() throws Exception { + @ParameterizedTest + @MethodSource("parameters") + public void testCompoundOperatorBigDecimalConstant(RUN_TYPE runType) throws Exception { // DROOLS-5894 String drl = "import " + Person.class.getCanonicalName() + "\n" + @@ -700,7 +717,7 @@ public void testCompoundOperatorBigDecimalConstant() throws Exception { " $p.money = result;" + "end"; - KieSession ksession = getKieSession(drl); + KieSession ksession = getKieSession(runType, drl); Person john = new Person("John", 30); john.setMoney( new BigDecimal( 70000 ) ); @@ -710,8 +727,9 @@ public void testCompoundOperatorBigDecimalConstant() throws Exception { assertThat(john.getMoney()).isEqualTo(new BigDecimal( 400000 )); } - @Test - public void testCompoundOperatorBigDecimalConstantWithoutLiterals() { + @ParameterizedTest + @MethodSource("parameters") + public void testCompoundOperatorBigDecimalConstantWithoutLiterals(RUN_TYPE runType) { // DROOLS-5894 // DROOLS-5901 String drl = "import " + Person.class.getCanonicalName() + "\n" + @@ -738,7 +756,7 @@ public void testCompoundOperatorBigDecimalConstantWithoutLiterals() { " $p.money = result;" + "end"; - KieSession ksession = getKieSession(drl); + KieSession ksession = getKieSession(runType, drl); Person john = new Person("John", 30); john.setMoney( new BigDecimal( 70000 ) ); @@ -748,8 +766,9 @@ public void testCompoundOperatorBigDecimalConstantWithoutLiterals() { assertThat(john.getMoney()).isEqualTo(new BigDecimal( 0 )); } - @Test - public void testArithmeticOperationsOnBigDecimal() { + @ParameterizedTest + @MethodSource("parameters") + public void testArithmeticOperationsOnBigDecimal(RUN_TYPE runType) { String drl = "import " + Person.class.getCanonicalName() + "\n" + "import " + BigDecimal.class.getCanonicalName() + "\n" + @@ -762,7 +781,7 @@ public void testArithmeticOperationsOnBigDecimal() { " $p.money = operation;\n" + "end"; - KieSession ksession = getKieSession(drl); + KieSession ksession = getKieSession(runType, drl); Person john = new Person("John", 30); john.setMoney( new BigDecimal( 70000 ) ); @@ -773,8 +792,9 @@ public void testArithmeticOperationsOnBigDecimal() { assertThat(john.getMoney()).isEqualTo(new BigDecimal( 7002 )); } - @Test - public void testCompoundOperatorOnfield() throws Exception { + @ParameterizedTest + @MethodSource("parameters") + public void testCompoundOperatorOnfield(RUN_TYPE runType) throws Exception { // DROOLS-5895 String drl = @@ -787,7 +807,7 @@ public void testCompoundOperatorOnfield() throws Exception { " $p.money += $p.money;\n" + "end"; - KieSession ksession = getKieSession(drl); + KieSession ksession = getKieSession(runType, drl); Person john = new Person("John", 30); john.setMoney( new BigDecimal( 70000 ) ); @@ -797,8 +817,9 @@ public void testCompoundOperatorOnfield() throws Exception { assertThat(john.getMoney()).isEqualTo(new BigDecimal( 140000 )); } - @Test - public void testModifyOnBigDecimal() { + @ParameterizedTest + @MethodSource("parameters") + public void testModifyOnBigDecimal(RUN_TYPE runType) { // DROOLS-5889 String drl = "import " + Person.class.getCanonicalName() + "\n" + @@ -815,7 +836,7 @@ public void testModifyOnBigDecimal() { " list.add(\"after \" + $p + \", money = \" + $p.money);" + "end"; - KieSession ksession = getKieSession(drl); + KieSession ksession = getKieSession(runType, drl); ArrayList logMessages = new ArrayList<>(); ksession.setGlobal("list", logMessages); @@ -831,8 +852,9 @@ public void testModifyOnBigDecimal() { "after John, money = 30000"); } - @Test - public void testModifyOnBigDecimalWithLiteral() { + @ParameterizedTest + @MethodSource("parameters") + public void testModifyOnBigDecimalWithLiteral(RUN_TYPE runType) { // DROOLS-5891 String drl = "import " + Person.class.getCanonicalName() + "\n" + @@ -846,7 +868,7 @@ public void testModifyOnBigDecimalWithLiteral() { " } " + "end"; - KieSession ksession = getKieSession(drl); + KieSession ksession = getKieSession(runType, drl); Person john = new Person("John", 30); john.setMoney( new BigDecimal( 70000 ) ); @@ -860,8 +882,9 @@ public void testModifyOnBigDecimalWithLiteral() { assertThat(leonardo.getMoney()).isEqualTo(new BigDecimal( 500 )); } - @Test - public void testBinaryOperationOnInteger() { + @ParameterizedTest + @MethodSource("parameters") + public void testBinaryOperationOnInteger(RUN_TYPE runType) { // RHDM-1421 String drl = "import " + Person.class.getCanonicalName() + "\n" + @@ -873,7 +896,7 @@ public void testBinaryOperationOnInteger() { " $p.salary = $p.salary + 50000;\n" + "end"; - KieSession ksession = getKieSession(drl); + KieSession ksession = getKieSession(runType, drl); Person john = new Person("John", 30); john.setSalary( 70000 ); @@ -883,8 +906,9 @@ public void testBinaryOperationOnInteger() { assertThat((int) john.getSalary()).isEqualTo(120000); } - @Test - public void testSetOnInteger() { + @ParameterizedTest + @MethodSource("parameters") + public void testSetOnInteger(RUN_TYPE runType) { // RHDM-1421 String drl = "import " + Person.class.getCanonicalName() + "\n" + @@ -896,7 +920,7 @@ public void testSetOnInteger() { " $p.salary = 50000;\n" + "end"; - KieSession ksession = getKieSession(drl); + KieSession ksession = getKieSession(runType, drl); Person john = new Person("John", 30); john.setSalary( 70000 ); @@ -906,8 +930,9 @@ public void testSetOnInteger() { assertThat((int) john.getSalary()).isEqualTo(50000); } - @Test - public void testCollectSubtypeInConsequence() { + @ParameterizedTest + @MethodSource("parameters") + public void testCollectSubtypeInConsequence(RUN_TYPE runType) { // DROOLS-5887 String drl = "import " + Person.class.getCanonicalName() + "\n" + @@ -923,7 +948,7 @@ public void testCollectSubtypeInConsequence() { " }\n" + "end"; - KieSession ksession = getKieSession(drl); + KieSession ksession = getKieSession(runType, drl); List names = new ArrayList<>(); ksession.setGlobal("names", names); @@ -938,8 +963,9 @@ public void testCollectSubtypeInConsequence() { assertThat(names).containsExactlyInAnyOrder("Mario", "Luca", "Leonardo"); } - @Test - public void testCollectSubtypeInConsequenceNested() { + @ParameterizedTest + @MethodSource("parameters") + public void testCollectSubtypeInConsequenceNested(RUN_TYPE runType) { // DROOLS-5887 String drl = "import " + Person.class.getCanonicalName() + "\n" + @@ -961,7 +987,7 @@ public void testCollectSubtypeInConsequenceNested() { " }\n" + "end"; - KieSession ksession = getKieSession(drl); + KieSession ksession = getKieSession(runType, drl); List names = new ArrayList<>(); ksession.setGlobal("names", names); @@ -984,8 +1010,9 @@ public void testCollectSubtypeInConsequenceNested() { assertThat(addresses).contains("Milan"); } - @Test - public void testSetOnMvel() { + @ParameterizedTest + @MethodSource("parameters") + public void testSetOnMvel(RUN_TYPE runType) { // RHDM-1550 String drl = "import " + Person.class.getCanonicalName() + "\n" + @@ -998,7 +1025,7 @@ public void testSetOnMvel() { ");\n" + "end"; - KieSession ksession = getKieSession(drl); + KieSession ksession = getKieSession(runType, drl); Person mario = new Person(); ksession.insert( mario ); @@ -1008,8 +1035,9 @@ public void testSetOnMvel() { assertThat(mario.getAge()).isEqualTo(46); } - @Test - public void testCompoundOperator() throws Exception { + @ParameterizedTest + @MethodSource("parameters") + public void testCompoundOperator(RUN_TYPE runType) throws Exception { // DROOLS-5894 // DROOLS-5901 // DROOLS-5897 String drl = "import " + Person.class.getCanonicalName() + "\n" + @@ -1040,7 +1068,7 @@ public void testCompoundOperator() throws Exception { " $p.money -= intVar;\n" + // 0 "end"; - KieSession ksession = getKieSession(drl); + KieSession ksession = getKieSession(runType, drl); Person john = new Person("John", 30); john.setMoney( new BigDecimal( 70000 ) ); @@ -1050,8 +1078,9 @@ public void testCompoundOperator() throws Exception { assertThat(john.getMoney()).isEqualTo(new BigDecimal( 0 )); } - @Test - public void testKcontext() { + @ParameterizedTest + @MethodSource("parameters") + public void testKcontext(RUN_TYPE runType) { String str = "global java.util.List result;" + "rule R\n" + @@ -1062,7 +1091,7 @@ public void testKcontext() { " result.add(kcontext.getRule().getName());\n" + "end"; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); List result = new ArrayList<>(); ksession.setGlobal("result", result); @@ -1072,8 +1101,9 @@ public void testKcontext() { assertThat(result.contains("R")).isTrue(); } - @Test - public void testLineBreakAtTheEndOfStatementWithoutSemicolon() { + @ParameterizedTest + @MethodSource("parameters") + public void testLineBreakAtTheEndOfStatementWithoutSemicolon(RUN_TYPE runType) { final String str = "import " + Person.class.getCanonicalName() + ";\n" + "\n" + @@ -1087,7 +1117,7 @@ public void testLineBreakAtTheEndOfStatementWithoutSemicolon() { " insert(p2);\n" + "end"; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); Person p = new Person("Mario", 40); ksession.insert(p); @@ -1096,8 +1126,9 @@ public void testLineBreakAtTheEndOfStatementWithoutSemicolon() { assertThat(fired).isEqualTo(1); } - @Test - public void testSetNullInModify() { + @ParameterizedTest + @MethodSource("parameters") + public void testSetNullInModify(RUN_TYPE runType) { // RHDM-1713 String str = "dialect \"mvel\"\n" + @@ -1112,15 +1143,16 @@ public void testSetNullInModify() { "then\n" + "end"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); Person me = new Person( "Mario", 47 ); ksession.insert( me ); assertThat(ksession.fireAllRules()).isEqualTo(2); } - @Test - public void testSetSubclassInModify() { + @ParameterizedTest + @MethodSource("parameters") + public void testSetSubclassInModify(RUN_TYPE runType) { // RHDM-1713 String str = "dialect \"mvel\"\n" + @@ -1136,15 +1168,16 @@ public void testSetSubclassInModify() { "then\n" + "end"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); Person me = new Person( "Mario", 47 ); ksession.insert( me ); assertThat(ksession.fireAllRules()).isEqualTo(2); } - @Test - public void testForEachAccessor() { + @ParameterizedTest + @MethodSource("parameters") + public void testForEachAccessor(RUN_TYPE runType) { // DROOLS-6298 String str = "import " + Person.class.getCanonicalName() + ";" + @@ -1160,7 +1193,7 @@ public void testForEachAccessor() { "}\n" + "end\n"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); ArrayList results = new ArrayList<>(); ksession.setGlobal("results", results); @@ -1175,8 +1208,9 @@ public void testForEachAccessor() { assertThat(results).containsOnly("Address"); } - @Test - public void testBigDecimalPromotionUsedAsArgument() { + @ParameterizedTest + @MethodSource("parameters") + public void testBigDecimalPromotionUsedAsArgument(RUN_TYPE runType) { // DROOLS-6362 String str = "import " + Person.class.getCanonicalName() + ";" + @@ -1219,7 +1253,7 @@ public void testBigDecimalPromotionUsedAsArgument() { "}\n" + "end\n"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); ArrayList results = new ArrayList<>(); ksession.setGlobal("results", results); @@ -1243,8 +1277,9 @@ public static BigDecimal bigDecimalFunc( BigDecimal bd){ return new BigDecimal(bd.toString()); } - @Test - public void testBigDecimalPromotionWithExternalFunction() { + @ParameterizedTest + @MethodSource("parameters") + public void testBigDecimalPromotionWithExternalFunction(RUN_TYPE runType) { // DROOLS-6410 String str = "import " + Person.class.getCanonicalName() + ";" + @@ -1266,7 +1301,7 @@ public void testBigDecimalPromotionWithExternalFunction() { "results.add(bigDecimalFunc($bd) * 100 + 12);\n" + // 101212 "end\n"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); ArrayList results = new ArrayList<>(); ksession.setGlobal("results", results); @@ -1281,8 +1316,9 @@ public void testBigDecimalPromotionWithExternalFunction() { assertThat(results).containsExactly(valueOf(1012), valueOf(1012), valueOf(1012), valueOf(101212)); } - @Test - public void testBigDecimalPromotionUsingDefinedFunctionAndDeclaredType() { + @ParameterizedTest + @MethodSource("parameters") + public void testBigDecimalPromotionUsingDefinedFunctionAndDeclaredType(RUN_TYPE runType) { // DROOLS-6362 String str = "package com.sample\n" + "import " + Person.class.getName() + ";\n" + @@ -1316,7 +1352,7 @@ public void testBigDecimalPromotionUsingDefinedFunctionAndDeclaredType() { "end\n"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); ArrayList results = new ArrayList<>(); ksession.setGlobal("results", results); @@ -1332,8 +1368,9 @@ public void testBigDecimalPromotionUsingDefinedFunctionAndDeclaredType() { assertThat(results).containsExactly("John"); } - @Test - public void testMVELMapRHSGetAndAssign() { + @ParameterizedTest + @MethodSource("parameters") + public void testMVELMapRHSGetAndAssign(RUN_TYPE runType) { String str = "package com.example.reproducer\n" + "import " + Person.class.getCanonicalName() + ";\n" + "dialect \"mvel\"\n" + @@ -1346,7 +1383,7 @@ public void testMVELMapRHSGetAndAssign() { " result.add(i);\n" + "end"; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); List result = new ArrayList<>(); ksession.setGlobal("result", result); @@ -1357,8 +1394,9 @@ public void testMVELMapRHSGetAndAssign() { assertThat(result).containsExactly(100); } - @Test - public void testRHSMapGetAsParam() { + @ParameterizedTest + @MethodSource("parameters") + public void testRHSMapGetAsParam(RUN_TYPE runType) { String str = "package com.example.reproducer\n" + "import " + Person.class.getCanonicalName() + ";\n" + "dialect \"mvel\"\n" + @@ -1370,7 +1408,7 @@ public void testRHSMapGetAsParam() { " result.add($p.itemsString[$name]);\n" + "end"; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); List result = new ArrayList<>(); ksession.setGlobal("result", result); @@ -1381,8 +1419,9 @@ public void testRHSMapGetAsParam() { assertThat(result).containsExactly("OK"); } - @Test - public void testRHSMapNestedProperty() { + @ParameterizedTest + @MethodSource("parameters") + public void testRHSMapNestedProperty(RUN_TYPE runType) { String str = "package com.example.reproducer\n" + "import " + Person.class.getCanonicalName() + ";\n" + "dialect \"mvel\"\n" + @@ -1394,7 +1433,7 @@ public void testRHSMapNestedProperty() { " result.add($p.childrenMap[$name].age);\n" + "end"; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); List result = new ArrayList<>(); ksession.setGlobal("result", result); @@ -1407,8 +1446,9 @@ public void testRHSMapNestedProperty() { assertThat(result).containsExactly(5); } - @Test - public void testRHSListNestedProperty() { + @ParameterizedTest + @MethodSource("parameters") + public void testRHSListNestedProperty(RUN_TYPE runType) { String str = "package com.example.reproducer\n" + "import " + Person.class.getCanonicalName() + ";\n" + "dialect \"mvel\"\n" + @@ -1420,7 +1460,7 @@ public void testRHSListNestedProperty() { " result.add($p.addresses[$age].city);\n" + "end"; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); List result = new ArrayList<>(); ksession.setGlobal("result", result); @@ -1433,8 +1473,9 @@ public void testRHSListNestedProperty() { assertThat(result).containsExactly("London"); } - @Test - public void testRHSMapMethod() { + @ParameterizedTest + @MethodSource("parameters") + public void testRHSMapMethod(RUN_TYPE runType) { String str = "package com.example.reproducer\n" + "import " + Person.class.getCanonicalName() + ";\n" + "dialect \"mvel\"\n" + @@ -1446,7 +1487,7 @@ public void testRHSMapMethod() { " result.add($p.itemsString.size);\n" + "end"; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); List result = new ArrayList<>(); ksession.setGlobal("result", result); @@ -1457,8 +1498,9 @@ public void testRHSMapMethod() { assertThat(result).containsExactly(1); } - @Test - public void testMVELBigIntegerLiteralRHS() { + @ParameterizedTest + @MethodSource("parameters") + public void testMVELBigIntegerLiteralRHS(RUN_TYPE runType) { String str = "package com.example.reproducer\n" + "import " + Person.class.getCanonicalName() + ";\n" + "rule R\n" + @@ -1469,7 +1511,7 @@ public void testMVELBigIntegerLiteralRHS() { " $p.setAgeInSeconds(10000I);\n" + "end"; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); Person p = new Person(); ksession.insert(p); @@ -1478,8 +1520,9 @@ public void testMVELBigIntegerLiteralRHS() { assertThat(p.getAgeInSeconds().equals(new BigInteger("10000"))).isTrue(); } - @Test - public void testMVELBigDecimalLiteralRHS() { + @ParameterizedTest + @MethodSource("parameters") + public void testMVELBigDecimalLiteralRHS(RUN_TYPE runType) { String str = "package com.example.reproducer\n" + "import " + Person.class.getCanonicalName() + ";\n" + "rule R\n" + @@ -1490,7 +1533,7 @@ public void testMVELBigDecimalLiteralRHS() { " $p.setMoney(10000B);\n" + "end"; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); Person p = new Person(); ksession.insert(p); @@ -1499,8 +1542,9 @@ public void testMVELBigDecimalLiteralRHS() { assertThat(p.getMoney().equals(new BigDecimal("10000"))).isTrue(); } - @Test - public void testMVELBigIntegerLiteralLHS() { + @ParameterizedTest + @MethodSource("parameters") + public void testMVELBigIntegerLiteralLHS(RUN_TYPE runType) { String str = "package com.example.reproducer\n" + "import " + Person.class.getCanonicalName() + ";\n" + "rule R\n" + @@ -1510,7 +1554,7 @@ public void testMVELBigIntegerLiteralLHS() { "then\n" + "end"; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); Person p = new Person(); p.setAgeInSeconds(new BigInteger("10000")); @@ -1520,8 +1564,9 @@ public void testMVELBigIntegerLiteralLHS() { assertThat(fired).isEqualTo(1); } - @Test - public void testMVELModifyPropMethodCall() { + @ParameterizedTest + @MethodSource("parameters") + public void testMVELModifyPropMethodCall(RUN_TYPE runType) { String str = "package com.example.reproducer\n" + "import " + Person.class.getCanonicalName() + ";\n" + "rule R\n" + @@ -1535,7 +1580,7 @@ public void testMVELModifyPropMethodCall() { " }\n" + "end"; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); Person p = new Person("John"); List
addresses = new ArrayList<>(); @@ -1549,8 +1594,9 @@ public void testMVELModifyPropMethodCall() { assertThat(fired).isEqualTo(1); } - @Test - public void assign_primitiveBooleanProperty() { + @ParameterizedTest + @MethodSource("parameters") + public void assign_primitiveBooleanProperty(RUN_TYPE runType) { // DROOLS-7250 String str = "package com.example.reproducer\n" + "import " + ValueHolder.class.getCanonicalName() + ";\n" + @@ -1562,7 +1608,7 @@ public void assign_primitiveBooleanProperty() { " $holder.primitiveBooleanValue = true;\n" + "end"; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); ValueHolder holder = new ValueHolder(); holder.setPrimitiveBooleanValue(false); @@ -1572,8 +1618,9 @@ public void assign_primitiveBooleanProperty() { assertThat(holder.isPrimitiveBooleanValue()).isTrue(); } - @Test - public void assign_wrapperBooleanProperty() { + @ParameterizedTest + @MethodSource("parameters") + public void assign_wrapperBooleanProperty(RUN_TYPE runType) { // DROOLS-7250 String str = "package com.example.reproducer\n" + "import " + ValueHolder.class.getCanonicalName() + ";\n" + @@ -1585,7 +1632,7 @@ public void assign_wrapperBooleanProperty() { " $holder.wrapperBooleanValue = true;\n" + "end"; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); ValueHolder holder = new ValueHolder(); holder.setWrapperBooleanValue(false); @@ -1595,7 +1642,7 @@ public void assign_wrapperBooleanProperty() { assertThat(holder.getWrapperBooleanValue()).isTrue(); } - public void assign_nestedProperty() { + public void assign_nestedProperty(RUN_TYPE runType) { // DROOLS-7195 String str = "package com.example.reproducer\n" + "import " + Person.class.getCanonicalName() + ";\n" + @@ -1607,7 +1654,7 @@ public void assign_nestedProperty() { " $p.address.city = \"Tokyo\";\n" + "end"; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); Person p = new Person("John"); p.setAddress(new Address("London")); @@ -1617,8 +1664,9 @@ public void assign_nestedProperty() { assertThat(p.getAddress().getCity()).isEqualTo("Tokyo"); } - @Test - public void assign_nestedPropertyInModify() { + @ParameterizedTest + @MethodSource("parameters") + public void assign_nestedPropertyInModify(RUN_TYPE runType) { // DROOLS-7195 String str = "package com.example.reproducer\n" + "import " + Person.class.getCanonicalName() + ";\n" + @@ -1632,7 +1680,7 @@ public void assign_nestedPropertyInModify() { " }\n" + "end"; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); Person p = new Person("John"); p.setAddress(new Address("London")); @@ -1642,8 +1690,9 @@ public void assign_nestedPropertyInModify() { assertThat(p.getAddress().getCity()).isEqualTo("Tokyo"); } - @Test - public void setter_nestedPropertyInModify() { + @ParameterizedTest + @MethodSource("parameters") + public void setter_nestedPropertyInModify(RUN_TYPE runType) { // DROOLS-7195 String str = "package com.example.reproducer\n" + "import " + Person.class.getCanonicalName() + ";\n" + @@ -1657,7 +1706,7 @@ public void setter_nestedPropertyInModify() { " }\n" + "end"; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); Person p = new Person("John"); p.setAddress(new Address("London")); @@ -1667,8 +1716,9 @@ public void setter_nestedPropertyInModify() { assertThat(p.getAddress().getCity()).isEqualTo("Tokyo"); } - @Test - public void assign_deepNestedPropertyInModify() { + @ParameterizedTest + @MethodSource("parameters") + public void assign_deepNestedPropertyInModify(RUN_TYPE runType) { // DROOLS-7195 String str = "package com.example.reproducer\n" + "import " + Person.class.getCanonicalName() + ";\n" + @@ -1682,7 +1732,7 @@ public void assign_deepNestedPropertyInModify() { " }\n" + "end"; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); Person person = new Person("John"); Address address = new Address("London"); @@ -1696,8 +1746,9 @@ public void assign_deepNestedPropertyInModify() { assertThat(person.getAddress().getVisitorCounter().getValue()).isEqualTo(1); } - @Test - public void setter_deepNestedPropertyInModify() { + @ParameterizedTest + @MethodSource("parameters") + public void setter_deepNestedPropertyInModify(RUN_TYPE runType) { // DROOLS-7195 String str = "package com.example.reproducer\n" + "import " + Person.class.getCanonicalName() + ";\n" + @@ -1711,7 +1762,7 @@ public void setter_deepNestedPropertyInModify() { " }\n" + "end"; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); Person person = new Person("John"); Address address = new Address("London"); @@ -1725,8 +1776,9 @@ public void setter_deepNestedPropertyInModify() { assertThat(person.getAddress().getVisitorCounter().getValue()).isEqualTo(1); } - @Test - public void drools_workingMemory_setGlobal() { + @ParameterizedTest + @MethodSource("parameters") + public void drools_workingMemory_setGlobal(RUN_TYPE runType) { // DROOLS-7338 String str = "package com.example.reproducer\n" + "import " + Logger.class.getCanonicalName() + ";\n" + @@ -1738,7 +1790,7 @@ public void drools_workingMemory_setGlobal() { " drools.workingMemory.setGlobal(\"logger\", org.slf4j.LoggerFactory.getLogger(getClass()));\n" + "end"; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); ksession.fireAllRules(); @@ -1746,8 +1798,9 @@ public void drools_workingMemory_setGlobal() { assertThat(logger).isInstanceOf(Logger.class); } - @Test - public void drools_fieldAccess() { + @ParameterizedTest + @MethodSource("parameters") + public void drools_fieldAccess(RUN_TYPE runType) { String str = "package com.example.reproducer\n" + "global java.util.Map results;\n" + "rule R\n" + @@ -1762,7 +1815,7 @@ public void drools_fieldAccess() { " results.put(\"kieRuntime\", drools.kieRuntime);\n" + "end"; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); Map results = new HashMap<>(); ksession.setGlobal("results", results); @@ -1776,8 +1829,9 @@ public void drools_fieldAccess() { assertThat(results.get("kieRuntime")).isInstanceOf(KieRuntime.class); } - @Test - public void integerToBigDecimalBindVariableCoercion_shouldNotCoerceToInteger() { + @ParameterizedTest + @MethodSource("parameters") + public void integerToBigDecimalBindVariableCoercion_shouldNotCoerceToInteger(RUN_TYPE runType) { // DROOLS-7540 String str = "package com.example.reproducer\n" + "import " + Person.class.getCanonicalName() + ";\n" + @@ -1791,7 +1845,7 @@ public void integerToBigDecimalBindVariableCoercion_shouldNotCoerceToInteger() { " results.add($money);\n" + "end"; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); List results = new ArrayList<>(); ksession.setGlobal("results", results); @@ -1804,8 +1858,9 @@ public void integerToBigDecimalBindVariableCoercion_shouldNotCoerceToInteger() { assertThat(results).contains(new BigDecimal("5")); } - @Test - public void integerToBigDecimalVariableCoercionTwice_shouldNotCoerceToInteger() { + @ParameterizedTest + @MethodSource("parameters") + public void integerToBigDecimalVariableCoercionTwice_shouldNotCoerceToInteger(RUN_TYPE runType) { // DROOLS-7540 String str = "package com.example.reproducer\n" + "import " + Person.class.getCanonicalName() + ";\n" + @@ -1821,7 +1876,7 @@ public void integerToBigDecimalVariableCoercionTwice_shouldNotCoerceToInteger() " results.add($var1);\n" + "end"; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); List results = new ArrayList<>(); ksession.setGlobal("results", results); @@ -1834,8 +1889,9 @@ public void integerToBigDecimalVariableCoercionTwice_shouldNotCoerceToInteger() assertThat(results).contains(new BigDecimal("5")); } - @Test - public void integerToBigDecimalBindVariableCoercionAndAddition_shouldNotThrowClassCastException() { + @ParameterizedTest + @MethodSource("parameters") + public void integerToBigDecimalBindVariableCoercionAndAddition_shouldNotThrowClassCastException(RUN_TYPE runType) { // DROOLS-7540 String str = "package com.example.reproducer\n" + "import " + Person.class.getCanonicalName() + ";\n" + @@ -1850,7 +1906,7 @@ public void integerToBigDecimalBindVariableCoercionAndAddition_shouldNotThrowCla " results.add($total);\n" + "end"; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); List results = new ArrayList<>(); ksession.setGlobal("results", results); @@ -1863,8 +1919,9 @@ public void integerToBigDecimalBindVariableCoercionAndAddition_shouldNotThrowCla assertThat(results).contains(new BigDecimal("15")); } - @Test - public void integerToBigDecimalVaribleSetFromBindVariableCoercionAndAddition_shouldNotThrowClassCastException() { + @ParameterizedTest + @MethodSource("parameters") + public void integerToBigDecimalVaribleSetFromBindVariableCoercionAndAddition_shouldNotThrowClassCastException(RUN_TYPE runType) { // DROOLS-7540 String str = "package com.example.reproducer\n" + "import " + Person.class.getCanonicalName() + ";\n" + @@ -1882,7 +1939,7 @@ public void integerToBigDecimalVaribleSetFromBindVariableCoercionAndAddition_sho " results.add($total);\n" + "end"; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); List results = new ArrayList<>(); ksession.setGlobal("results", results); diff --git a/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/MvelOperatorsTest.java b/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/MvelOperatorsTest.java index 9aa6b4fb81c..9986cba4046 100644 --- a/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/MvelOperatorsTest.java +++ b/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/MvelOperatorsTest.java @@ -24,7 +24,8 @@ import java.util.Map; import org.drools.model.codegen.execmodel.domain.Person; -import org.junit.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; import org.kie.api.builder.Message; import org.kie.api.builder.Results; import org.kie.api.runtime.KieSession; @@ -34,47 +35,46 @@ public class MvelOperatorsTest extends BaseModelTest { - public MvelOperatorsTest( RUN_TYPE testRunType ) { - super( testRunType ); - } - - @Test - public void testIn() { + @ParameterizedTest + @MethodSource("parameters") + public void testIn(RUN_TYPE runType) { String str = "rule R when\n" + " String(this in (\"a\", \"b\"))" + "then\n" + "end "; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); ksession.insert( "b" ); assertThat(ksession.fireAllRules()).isEqualTo(1); } - @Test - public void testStr() { + @ParameterizedTest + @MethodSource("parameters") + public void testStr(RUN_TYPE runType) { String str = "rule R when\n" + " String(this str[startsWith] \"M\")" + "then\n" + "end "; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); ksession.insert( "Mario" ); assertThat(ksession.fireAllRules()).isEqualTo(1); } - @Test - public void testStrNot() { + @ParameterizedTest + @MethodSource("parameters") + public void testStrNot(RUN_TYPE runType) { String str = "rule R when\n" + " String(this not str[startsWith] \"M\")" + "then\n" + "end "; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); ksession.insert( "Mario" ); ksession.insert( "Luca" ); @@ -82,15 +82,16 @@ public void testStrNot() { assertThat(ksession.fireAllRules()).isEqualTo(2); } - @Test - public void testStrHalf() { + @ParameterizedTest + @MethodSource("parameters") + public void testStrHalf(RUN_TYPE runType) { String str = "rule R when\n" + " String(this str[startsWith] \"M\" || str[endsWith] \"a\" || str[length] 10)"+ "then\n" + "end "; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); ksession.insert( "Mario" ); ksession.insert( "Luca" ); @@ -99,15 +100,16 @@ public void testStrHalf() { assertThat(ksession.fireAllRules()).isEqualTo(3); } - @Test - public void testStrHalfOrAndAmpersand() { + @ParameterizedTest + @MethodSource("parameters") + public void testStrHalfOrAndAmpersand(RUN_TYPE runType) { String str = "rule R when\n" + " String(this str[startsWith] \"M\" || str[endsWith] \"a\" && str[length] 4)"+ "then\n" + "end "; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); ksession.insert( "Mario" ); ksession.insert( "Luca" ); @@ -116,8 +118,9 @@ public void testStrHalfOrAndAmpersand() { assertThat(ksession.fireAllRules()).isEqualTo(2); } - @Test - public void testRange() { + @ParameterizedTest + @MethodSource("parameters") + public void testRange(RUN_TYPE runType) { String str = "import " + Person.class.getCanonicalName() + "\n" + "global java.util.List list\n" + @@ -127,7 +130,7 @@ public void testRange() { " list.add($name);" + "end "; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); List list = new ArrayList<>(); ksession.setGlobal( "list", list ); @@ -142,8 +145,9 @@ public void testRange() { assertThat(list.containsAll(asList("Mark", "Edson"))).isTrue(); } - @Test - public void testExcludedRange() { + @ParameterizedTest + @MethodSource("parameters") + public void testExcludedRange(RUN_TYPE runType) { String str = "import " + Person.class.getCanonicalName() + "\n" + "global java.util.List list\n" + @@ -153,7 +157,7 @@ public void testExcludedRange() { " list.add($name);" + "end "; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); List list = new ArrayList<>(); ksession.setGlobal( "list", list ); @@ -168,8 +172,9 @@ public void testExcludedRange() { assertThat(list.containsAll(asList("Luca", "Mario"))).isTrue(); } - @Test - public void testBinding() { + @ParameterizedTest + @MethodSource("parameters") + public void testBinding(RUN_TYPE runType) { String str = "import " + Person.class.getCanonicalName() + "\n" + "global java.util.List list\n" + @@ -179,7 +184,7 @@ public void testBinding() { " list.add($name);" + "end "; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); List list = new ArrayList<>(); ksession.setGlobal( "list", list ); @@ -192,22 +197,24 @@ public void testBinding() { assertThat(list.get(0)).isEqualTo("Mario"); } - @Test - public void testMatches() { + @ParameterizedTest + @MethodSource("parameters") + public void testMatches(RUN_TYPE runType) { String str = "rule R when\n" + " String(this matches \"\\\\w\")" + "then\n" + "end "; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); ksession.insert( "b" ); assertThat(ksession.fireAllRules()).isEqualTo(1); } - @Test - public void testExcludes() { + @ParameterizedTest + @MethodSource("parameters") + public void testExcludes(RUN_TYPE runType) { String str = "import java.util.List\n" + "rule R when\n" + @@ -215,15 +222,16 @@ public void testExcludes() { "then\n" + "end "; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); ksession.insert( asList("ciao", "test") ); assertThat(ksession.fireAllRules()).isEqualTo(0); ksession.insert( asList("hello", "world") ); assertThat(ksession.fireAllRules()).isEqualTo(1); } - @Test - public void testNotContains() { + @ParameterizedTest + @MethodSource("parameters") + public void testNotContains(RUN_TYPE runType) { String str = "import java.util.List\n" + "rule R when\n" + @@ -231,15 +239,16 @@ public void testNotContains() { "then\n" + "end "; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); ksession.insert( asList("ciao", "test") ); assertThat(ksession.fireAllRules()).isEqualTo(0); ksession.insert( asList("hello", "world") ); assertThat(ksession.fireAllRules()).isEqualTo(1); } - @Test - public void testStartsWithWithChar() { + @ParameterizedTest + @MethodSource("parameters") + public void testStartsWithWithChar(RUN_TYPE runType) { String str = "import " + Person.class.getCanonicalName() + "\n" + "global java.util.List list\n" + @@ -250,7 +259,7 @@ public void testStartsWithWithChar() { " list.add($p.getName());" + "end"; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); List list = new ArrayList<>(); ksession.setGlobal( "list", list ); @@ -263,8 +272,9 @@ public void testStartsWithWithChar() { assertThat(list.get(0)).isEqualTo("Luca"); } - @Test - public void testNotIn() { + @ParameterizedTest + @MethodSource("parameters") + public void testNotIn(RUN_TYPE runType) { String str = "import " + Person.class.getCanonicalName() + "\n" + "global java.util.List list\n" + @@ -274,7 +284,7 @@ public void testNotIn() { " list.add($name);" + "end "; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); List list = new ArrayList<>(); ksession.setGlobal( "list", list ); @@ -288,8 +298,9 @@ public void testNotIn() { assertThat(list.get(0)).isEqualTo("Mario"); } - @Test - public void testNotInUsingShort() { + @ParameterizedTest + @MethodSource("parameters") + public void testNotInUsingShort(RUN_TYPE runType) { String str = "import " + Person.class.getCanonicalName() + "\n" + "global java.util.List list\n" + @@ -299,7 +310,7 @@ public void testNotInUsingShort() { " list.add($name);" + "end "; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); List list = new ArrayList<>(); ksession.setGlobal( "list", list ); @@ -313,8 +324,9 @@ public void testNotInUsingShort() { assertThat(list.get(0)).isEqualTo("Mario"); } - @Test - public void testMatchesWithFunction() { + @ParameterizedTest + @MethodSource("parameters") + public void testMatchesWithFunction(RUN_TYPE runType) { // DROOLS-4382 String str = "import " + Person.class.getCanonicalName() + "\n" + @@ -324,7 +336,7 @@ public void testMatchesWithFunction() { "then\n" + "end "; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); Person p = new Person("Mark", 40); p.setLikes( "M." ); @@ -332,8 +344,9 @@ public void testMatchesWithFunction() { assertThat(ksession.fireAllRules()).isEqualTo(1); } - @Test - public void testMatchesOnNullString() { + @ParameterizedTest + @MethodSource("parameters") + public void testMatchesOnNullString(RUN_TYPE runType) { // DROOLS-4525 String str = "import " + Person.class.getCanonicalName() + ";" + @@ -346,7 +359,7 @@ public void testMatchesOnNullString() { "then\n" + "end\n"; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); Person first = new Person("686878"); ksession.insert(first); @@ -377,8 +390,9 @@ public String toString() { } } - @Test - public void testInDouble() { + @ParameterizedTest + @MethodSource("parameters") + public void testInDouble(RUN_TYPE runType) { // DROOLS-4892 String str = "import " + DoubleFact.class.getCanonicalName() + ";" + @@ -406,10 +420,10 @@ public void testInDouble() { " System.out.println(\"Rule[\"+kcontext.getRule().getName()+\"] fires.\");\n" + "end"; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); DoubleFact f = new DoubleFact(); - f.setDoubleVal(new Double(100)); + f.setDoubleVal(Double.valueOf(100.0)); f.setPrimitiveDoubleVal(200); ksession.insert(f); assertThat(ksession.fireAllRules()).isEqualTo(4); @@ -432,8 +446,9 @@ public List getIntList() { } } - @Test - public void testContainsOnNull() { + @ParameterizedTest + @MethodSource("parameters") + public void testContainsOnNull(RUN_TYPE runType) { // DROOLS-5315 String str = "import " + ListContainer.class.getCanonicalName() + ";" + @@ -442,7 +457,7 @@ public void testContainsOnNull() { "then\n" + "end "; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); ksession.insert( new ListContainer() ); assertThat(ksession.fireAllRules()).isEqualTo(0); @@ -451,8 +466,9 @@ public void testContainsOnNull() { assertThat(ksession.fireAllRules()).isEqualTo(1); } - @Test - public void testNumericStringsWithLeadingZero() { + @ParameterizedTest + @MethodSource("parameters") + public void testNumericStringsWithLeadingZero(RUN_TYPE runType) { // DROOLS-5926 String str = "rule R when\n" + @@ -460,14 +476,15 @@ public void testNumericStringsWithLeadingZero() { "then\n" + "end "; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); ksession.insert( 800 ); assertThat(ksession.fireAllRules()).isEqualTo(1); } - @Test - public void testNumericHexadecimal() { + @ParameterizedTest + @MethodSource("parameters") + public void testNumericHexadecimal(RUN_TYPE runType) { // DROOLS-5926 String str = "rule R when\n" + @@ -475,14 +492,15 @@ public void testNumericHexadecimal() { "then\n" + "end "; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); ksession.insert( 2048 ); assertThat(ksession.fireAllRules()).isEqualTo(1); } - @Test - public void testListLiteralCreation() { + @ParameterizedTest + @MethodSource("parameters") + public void testListLiteralCreation(RUN_TYPE runType) { String str = "import " + Person.class.getCanonicalName() + ";" + "global java.util.List result;" + @@ -492,7 +510,7 @@ public void testListLiteralCreation() { " result.add($myList);" + "end "; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); List result = new ArrayList<>(); ksession.setGlobal("result", result); ksession.insert( new Person() ); @@ -503,8 +521,9 @@ public void testListLiteralCreation() { assertThat((List)obj).containsExactlyInAnyOrder("aaa", "bbb", "ccc"); } - @Test - public void testMapLiteralCreation() { + @ParameterizedTest + @MethodSource("parameters") + public void testMapLiteralCreation(RUN_TYPE runType) { String str = "import " + Person.class.getCanonicalName() + ";" + "global java.util.List result;" + @@ -514,7 +533,7 @@ public void testMapLiteralCreation() { " result.add($myMap);" + "end "; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); List result = new ArrayList<>(); ksession.setGlobal("result", result); ksession.insert(new Person()); @@ -525,8 +544,9 @@ public void testMapLiteralCreation() { assertThat(((Map) obj).get("key")).isEqualTo("value"); } - @Test - public void testEmptySingleApexString() { + @ParameterizedTest + @MethodSource("parameters") + public void testEmptySingleApexString(RUN_TYPE runType) { // DROOLS-6057 String str = "import " + Person.class.getCanonicalName() + "\n" + @@ -537,7 +557,7 @@ public void testEmptySingleApexString() { " list.add($name);" + "end "; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); List list = new ArrayList<>(); ksession.setGlobal( "list", list ); @@ -550,8 +570,9 @@ public void testEmptySingleApexString() { assertThat(list.get(0)).isEqualTo(""); } - @Test - public void testContainsOnString() { + @ParameterizedTest + @MethodSource("parameters") + public void testContainsOnString(RUN_TYPE runType) { String str = "import " + Person.class.getCanonicalName() + "\n" + "rule R when\n" + @@ -559,7 +580,7 @@ public void testContainsOnString() { "then\n" + "end "; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); Person person1 = new Person(""); ksession.insert(new Person("mario", 47)); @@ -567,8 +588,9 @@ public void testContainsOnString() { assertThat(ksession.fireAllRules()).isEqualTo(1); } - @Test - public void testContainsOnMapShouldntCompile() { + @ParameterizedTest + @MethodSource("parameters") + public void testContainsOnMapShouldntCompile(RUN_TYPE runType) { // BAPL-1957 String str = "import " + Person.class.getCanonicalName() + "\n" + @@ -577,12 +599,13 @@ public void testContainsOnMapShouldntCompile() { "then\n" + "end "; - Results results = createKieBuilder( str ).getResults(); + Results results = createKieBuilder(runType, str).getResults(); assertThat(results.getMessages(Message.Level.ERROR).isEmpty()).isFalse(); } - @Test - public void testContainsOnIntShouldntCompile() { + @ParameterizedTest + @MethodSource("parameters") + public void testContainsOnIntShouldntCompile(RUN_TYPE runType) { // BAPL-1957 String str = "import " + Person.class.getCanonicalName() + "\n" + @@ -591,7 +614,7 @@ public void testContainsOnIntShouldntCompile() { "then\n" + "end "; - Results results = createKieBuilder( str ).getResults(); + Results results = createKieBuilder(runType, str).getResults(); assertThat(results.getMessages(Message.Level.ERROR).isEmpty()).isFalse(); } } diff --git a/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/NamedConsequencesTest.java b/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/NamedConsequencesTest.java index 6a764ebcb07..80ec5862f25 100644 --- a/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/NamedConsequencesTest.java +++ b/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/NamedConsequencesTest.java @@ -26,7 +26,8 @@ import org.drools.model.codegen.execmodel.domain.Cheese; import org.drools.model.codegen.execmodel.domain.Person; import org.drools.model.codegen.execmodel.domain.Result; -import org.junit.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; import org.kie.api.builder.Message.Level; import org.kie.api.builder.Results; import org.kie.api.runtime.KieSession; @@ -37,12 +38,9 @@ public class NamedConsequencesTest extends BaseModelTest { - public NamedConsequencesTest( RUN_TYPE testRunType ) { - super( testRunType ); - } - - @Test - public void testNamedConsequence() { + @ParameterizedTest + @MethodSource("parameters") + public void testNamedConsequence(RUN_TYPE runType) { String str = "import " + Result.class.getCanonicalName() + ";\n" + "import " + Person.class.getCanonicalName() + ";\n" + @@ -57,7 +55,7 @@ public void testNamedConsequence() { " $r.addValue(\"Found \" + $p1.getName());\n" + "end"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); Result result = new Result(); ksession.insert( result ); @@ -72,8 +70,9 @@ public void testNamedConsequence() { assertThat(results.containsAll(asList("Found Mark", "Mario is older than Mark"))).isTrue(); } - @Test - public void testBreakingNamedConsequence() { + @ParameterizedTest + @MethodSource("parameters") + public void testBreakingNamedConsequence(RUN_TYPE runType) { String str = "import " + Result.class.getCanonicalName() + ";\n" + "import " + Person.class.getCanonicalName() + ";\n" + @@ -94,7 +93,7 @@ public void testBreakingNamedConsequence() { " $r.addValue(\"Found \" + $p1.getName());\n" + "end"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); Result result = new Result(); ksession.insert( result ); @@ -110,8 +109,9 @@ public void testBreakingNamedConsequence() { assertThat(results.iterator().next()).isEqualTo("Found Mark"); } - @Test - public void testNonBreakingNamedConsequence() { + @ParameterizedTest + @MethodSource("parameters") + public void testNonBreakingNamedConsequence(RUN_TYPE runType) { String str = "import " + Result.class.getCanonicalName() + ";\n" + "import " + Person.class.getCanonicalName() + ";\n" + @@ -132,7 +132,7 @@ public void testNonBreakingNamedConsequence() { " $r.addValue(\"Found \" + $p1.getName());\n" + "end"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); Result result = new Result(); ksession.insert( result ); @@ -148,8 +148,9 @@ public void testNonBreakingNamedConsequence() { assertThat(results.containsAll(asList("Found Mark", "Mario is older than Mark"))).isTrue(); } - @Test - public void testIfAfterAccumulate() { + @ParameterizedTest + @MethodSource("parameters") + public void testIfAfterAccumulate(RUN_TYPE runType) { String str = "import " + Result.class.getCanonicalName() + ";\n" + "import " + Person.class.getCanonicalName() + ";\n" + @@ -166,7 +167,7 @@ public void testIfAfterAccumulate() { " $r.addValue(\"greater\");\n" + "end"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); Result result = new Result(); ksession.insert( result ); @@ -180,8 +181,9 @@ public void testIfAfterAccumulate() { assertThat(results.get(0)).isEqualTo("greater"); } - @Test - public void testNonCompilingIFAfterOR() { + @ParameterizedTest + @MethodSource("parameters") + public void testNonCompilingIFAfterOR(RUN_TYPE runType) { String str = "import " + Cheese.class.getCanonicalName() + ";\n " + "global java.util.List results;\n" + "\n" + @@ -197,12 +199,13 @@ public void testNonCompilingIFAfterOR() { " results.add( $a.getType() );\n" + "end\n"; - Results results = createKieBuilder(str).getResults(); + Results results = createKieBuilder(runType, str).getResults(); assertThat(results.hasMessages(Level.ERROR)).isTrue(); } - @Test - public void testIfElseWithMvelAccessor() { + @ParameterizedTest + @MethodSource("parameters") + public void testIfElseWithMvelAccessor(RUN_TYPE runType) { String str = "import " + Cheese.class.getCanonicalName() + ";\n " + "global java.util.List results;\n" + "\n" + @@ -218,7 +221,7 @@ public void testIfElseWithMvelAccessor() { " results.add( $a.getType().toUpperCase() );\n" + "end\n"; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); List results = new ArrayList(); ksession.setGlobal("results", results); @@ -237,8 +240,9 @@ public void testIfElseWithMvelAccessor() { assertThat(results.contains("STILTON")).isTrue(); } - @Test - public void testWrongConsequenceName() { + @ParameterizedTest + @MethodSource("parameters") + public void testWrongConsequenceName(RUN_TYPE runType) { String str = "import " + Cheese.class.getCanonicalName() + ";\n " + "global java.util.List results;\n" + "\n" + @@ -252,12 +256,13 @@ public void testWrongConsequenceName() { " results.add( $a.getType().toUpperCase() );\n" + "end\n"; - Results results = createKieBuilder(str).getResults(); + Results results = createKieBuilder(runType, str).getResults(); assertThat(results.hasMessages(Level.ERROR)).isTrue(); } - @Test - public void testMvelInsertWithNamedConsequence() { + @ParameterizedTest + @MethodSource("parameters") + public void testMvelInsertWithNamedConsequence(RUN_TYPE runType) { String drl = "package org.drools.compiler\n" + "global java.util.concurrent.atomic.AtomicInteger counter\n" + @@ -283,7 +288,7 @@ public void testMvelInsertWithNamedConsequence() { " counter.incrementAndGet();\n" + "end\n"; - KieSession kSession = getKieSession(drl); + KieSession kSession = getKieSession(runType, drl); AtomicInteger counter = new AtomicInteger(0); kSession.setGlobal("counter", counter); @@ -298,8 +303,9 @@ public void testMvelInsertWithNamedConsequence() { assertThat(counter.get()).isEqualTo(2); } - @Test - public void testMVELBreak() { + @ParameterizedTest + @MethodSource("parameters") + public void testMVELBreak(RUN_TYPE runType) { String str = "import " + Cheese.class.getCanonicalName() + ";\n " + "global java.util.List results;\n" + "\n" + @@ -313,7 +319,7 @@ public void testMVELBreak() { " results.add( $a.type.toUpperCase() );\n" + "end\n"; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); List results = new ArrayList(); ksession.setGlobal("results", results); @@ -331,8 +337,9 @@ public void testMVELBreak() { assertThat(results.contains("STILTON")).isTrue(); } - @Test - public void testMVELNoBreak() { + @ParameterizedTest + @MethodSource("parameters") + public void testMVELNoBreak(RUN_TYPE runType) { String str = "import " + Cheese.class.getCanonicalName() + ";\n " + "global java.util.List results;\n" + "\n" + @@ -346,7 +353,7 @@ public void testMVELNoBreak() { " results.add( $a.type.toUpperCase() );\n" + "end\n"; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); List results = new ArrayList(); ksession.setGlobal("results", results); @@ -365,8 +372,9 @@ public void testMVELNoBreak() { assertThat(results.contains("cheddar")).isTrue(); } - @Test - public void testMultipleIfElseInARow() { + @ParameterizedTest + @MethodSource("parameters") + public void testMultipleIfElseInARow(RUN_TYPE runType) { String str = "import " + Person.class.getCanonicalName() + ";\n" + "global java.util.List result;\n" + @@ -394,7 +402,7 @@ public void testMultipleIfElseInARow() { " result.add(\"Age100\");\n" + "end"; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); List result = new ArrayList<>(); ksession.setGlobal("result", result); @@ -408,8 +416,9 @@ public void testMultipleIfElseInARow() { assertThat(result.containsAll(asList("Default", "Mark", "Edson", "Age35", "Age37"))).isTrue(); } - @Test - public void testMultipleIfElseInARowWithJoin() { + @ParameterizedTest + @MethodSource("parameters") + public void testMultipleIfElseInARowWithJoin(RUN_TYPE runType) { String str = "import " + Result.class.getCanonicalName() + ";\n" + "import " + Person.class.getCanonicalName() + ";\n" + @@ -432,7 +441,7 @@ public void testMultipleIfElseInARowWithJoin() { " $r.addValue(\"Age37\");\n" + "end"; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); Result result = new Result(); ksession.insert(result); @@ -448,8 +457,9 @@ public void testMultipleIfElseInARowWithJoin() { assertThat(results.containsAll(asList("Default", "Mark", "Edson", "Age35", "Age37"))).isTrue(); } - @Test - public void testMultipleIfElseInARowWithJoin2() { + @ParameterizedTest + @MethodSource("parameters") + public void testMultipleIfElseInARowWithJoin2(RUN_TYPE runType) { String str = "import " + Result.class.getCanonicalName() + ";\n" + "import " + Person.class.getCanonicalName() + ";\n" + @@ -473,7 +483,7 @@ public void testMultipleIfElseInARowWithJoin2() { " $r.addValue(\"Age37\");\n" + "end"; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); Result result = new Result(); ksession.insert(result); @@ -490,7 +500,7 @@ public void testMultipleIfElseInARowWithJoin2() { assertThat(results.containsAll(asList("DefaultMario", "Mark", "Edson", "Age35", "Age37"))).isTrue(); } - public void testModifyInNamedConsequence() { + public void testModifyInNamedConsequence(RUN_TYPE runType) { String str = "import " + Cheese.class.getCanonicalName() + ";\n " + "global java.util.List results;\n" + "\n" + @@ -504,7 +514,7 @@ public void testModifyInNamedConsequence() { " modify( $a ) { setPrice(15) };\n" + "end\n"; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); List results = new ArrayList(); ksession.setGlobal("results", results); @@ -522,8 +532,9 @@ public void testModifyInNamedConsequence() { assertThat(results.contains("stilton")).isTrue(); } - @Test - public void test2ModifyBlocksInNamedConsequences() { + @ParameterizedTest + @MethodSource("parameters") + public void test2ModifyBlocksInNamedConsequences(RUN_TYPE runType) { String str = "import " + Cheese.class.getCanonicalName() + ";\n " + "global java.util.List results;\n" + "\n" + @@ -538,7 +549,7 @@ public void test2ModifyBlocksInNamedConsequences() { " results.add( $a.getPrice() );\n" + "end\n"; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); List results = new ArrayList<>(); ksession.setGlobal("results", results); @@ -554,8 +565,9 @@ public void test2ModifyBlocksInNamedConsequences() { assertThat(results).containsExactlyInAnyOrder(10, 15); } - @Test - public void testMultipleIfAfterEval() { + @ParameterizedTest + @MethodSource("parameters") + public void testMultipleIfAfterEval(RUN_TYPE runType) { String str = "import " + Cheese.class.getCanonicalName() + ";\n " + "global java.util.List results;\n" + "\n" + @@ -573,7 +585,7 @@ public void testMultipleIfAfterEval() { " results.add( $a.getType() );\n" + "end\n"; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); List results = new ArrayList<>(); ksession.setGlobal("results", results); @@ -590,7 +602,7 @@ public void testMultipleIfAfterEval() { assertThat(results.contains("stilton")).isTrue(); } - public void testIfTrue() { + public void testIfTrue(RUN_TYPE runType) { String str = "import " + Person.class.getCanonicalName() + ";\n" + "global java.util.List result;\n" + @@ -603,7 +615,7 @@ public void testIfTrue() { " result.add(\"t1\");\n" + "end"; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); List result = new ArrayList<>(); ksession.setGlobal("result", result); diff --git a/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/NativeCompilerTest.java b/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/NativeCompilerTest.java index 12860f98815..3f9bd8d9376 100644 --- a/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/NativeCompilerTest.java +++ b/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/NativeCompilerTest.java @@ -20,7 +20,9 @@ import org.drools.compiler.compiler.JavaDialectConfiguration; import org.drools.model.codegen.execmodel.domain.Person; -import org.junit.Test; +import org.junit.jupiter.api.Timeout; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; import org.kie.api.runtime.KieSession; import org.kie.memorycompiler.JavaConfiguration; @@ -28,12 +30,10 @@ public class NativeCompilerTest extends BaseModelTest { - public NativeCompilerTest(RUN_TYPE testRunType ) { - super( testRunType ); - } - - @Test(timeout = 5000) - public void testPropertyReactivity() { + @ParameterizedTest + @MethodSource("parameters") + @Timeout(5000) + public void testPropertyReactivity(RUN_TYPE runType) { // DROOLS-6580 // Since ecj is transitively imported by drools-compiler (we may want to review this with drools 8) // by default the executable model compiler always use it. This test also tries it with the native compiler. @@ -50,7 +50,7 @@ public void testPropertyReactivity() { " modify($p) { setAge($p.getAge()+1) }\n" + "end"; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); Person me = new Person("Mario", 40); ksession.insert(me); diff --git a/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/NodeSharingTest.java b/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/NodeSharingTest.java index 65eef03f77f..2cf30843a3b 100644 --- a/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/NodeSharingTest.java +++ b/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/NodeSharingTest.java @@ -41,7 +41,8 @@ import org.drools.model.codegen.execmodel.domain.Person; import org.drools.model.codegen.execmodel.domain.Result; import org.drools.model.codegen.execmodel.domain.StockTick; -import org.junit.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; import org.kie.api.KieBase; import org.kie.api.runtime.KieSession; import org.kie.api.time.SessionPseudoClock; @@ -50,12 +51,9 @@ public class NodeSharingTest extends BaseModelTest { - public NodeSharingTest( RUN_TYPE testRunType ) { - super( testRunType ); - } - - @Test - public void testShareAlpha() { + @ParameterizedTest + @MethodSource("parameters") + public void testShareAlpha(RUN_TYPE runType) { String str = "import " + Result.class.getCanonicalName() + ";" + "import " + Person.class.getCanonicalName() + ";" + @@ -69,7 +67,7 @@ public void testShareAlpha() { " $r.add($p3);\n" + "end"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); Set result = new HashSet<>(); ksession.insert( result ); @@ -91,8 +89,9 @@ public void testShareAlpha() { assertThat(ReteDumper.collectNodes(ksession).stream().filter(AlphaNode.class::isInstance).count()).isEqualTo(2); } - @Test - public void testShareAlphaInDifferentRules() { + @ParameterizedTest + @MethodSource("parameters") + public void testShareAlphaInDifferentRules(RUN_TYPE runType) { String str = "import " + Person.class.getCanonicalName() + ";" + "rule R1 when\n" + @@ -104,13 +103,14 @@ public void testShareAlphaInDifferentRules() { "then\n" + "end"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); assertThat(ReteDumper.collectNodes(ksession).stream().filter(AlphaNode.class::isInstance).count()).isEqualTo(1); } - @Test - public void testShareAlphaInDifferentPackages() { + @ParameterizedTest + @MethodSource("parameters") + public void testShareAlphaInDifferentPackages(RUN_TYPE runType) { String str1 = "package org.drools.a\n" + "import " + Person.class.getCanonicalName() + ";" + @@ -126,13 +126,14 @@ public void testShareAlphaInDifferentPackages() { "then\n" + "end"; - KieSession ksession = getKieSession( str1, str2 ); + KieSession ksession = getKieSession(runType, str1, str2); assertThat(ReteDumper.collectNodes(ksession).stream().filter(AlphaNode.class::isInstance).count()).isEqualTo(1); } - @Test - public void testShareBetaWithConstraintReordering() { + @ParameterizedTest + @MethodSource("parameters") + public void testShareBetaWithConstraintReordering(RUN_TYPE runType) { String str = "import " + Person.class.getCanonicalName() + ";" + "rule R1 when\n" + @@ -146,7 +147,7 @@ public void testShareBetaWithConstraintReordering() { "then\n" + "end"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); assertThat(ReteDumper.collectNodes(ksession).stream().filter(BetaNode.class::isInstance).count()).isEqualTo(1); @@ -155,8 +156,9 @@ public void testShareBetaWithConstraintReordering() { assertThat(otn.getSinks().length).isEqualTo(1); } - @Test - public void testTrimmedConstraint() { + @ParameterizedTest + @MethodSource("parameters") + public void testTrimmedConstraint(RUN_TYPE runType) { String str = "import " + Person.class.getCanonicalName() + ";" + @@ -169,13 +171,14 @@ public void testTrimmedConstraint() { "then\n" + "end\n"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); assertThat(ReteDumper.collectNodes(ksession).stream().filter(AlphaNode.class::isInstance).count()).isEqualTo(1); } - @Test - public void testOrWithTrimmedConstraint() { + @ParameterizedTest + @MethodSource("parameters") + public void testOrWithTrimmedConstraint(RUN_TYPE runType) { String str = "import " + Person.class.getCanonicalName() + ";" + "global java.util.List list\n" + @@ -193,7 +196,7 @@ public void testOrWithTrimmedConstraint() { " list.add( $p + \" has \" + $age + \" years\");\n" + "end\n"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); assertThat(ReteDumper.collectNodes(ksession).stream().filter(AlphaNode.class::isInstance).count()).isEqualTo(2); @@ -212,8 +215,9 @@ public void testOrWithTrimmedConstraint() { assertThat(results.contains("Mario has 40 years")).isTrue(); } - @Test - public void testShareAlphaHashable() { + @ParameterizedTest + @MethodSource("parameters") + public void testShareAlphaHashable(RUN_TYPE runType) { String str = "import " + Factor.class.getCanonicalName() + ";\n" + "rule R1 when\n" + @@ -223,7 +227,7 @@ public void testShareAlphaHashable() { " Factor( factorAmt == 10.0 )\n" + "then end\n"; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); ksession.insert(new Factor(10.0)); assertThat(ksession.fireAllRules()).isEqualTo(2); @@ -231,8 +235,9 @@ public void testShareAlphaHashable() { assertThat(ReteDumper.collectNodes(ksession).stream().filter(AlphaNode.class::isInstance).count()).isEqualTo(1); } - @Test - public void testShareAlphaRangeIndexable() { + @ParameterizedTest + @MethodSource("parameters") + public void testShareAlphaRangeIndexable(RUN_TYPE runType) { String str = "import " + Factor.class.getCanonicalName() + ";\n" + "rule R1 when\n" + @@ -242,7 +247,7 @@ public void testShareAlphaRangeIndexable() { " Factor( factorAmt > 10.0 )\n" + "then end\n"; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); ksession.insert(new Factor(25.0)); assertThat(ksession.fireAllRules()).isEqualTo(2); @@ -263,8 +268,9 @@ public double getFactorAmt() { } } - @Test - public void testShareEval() { + @ParameterizedTest + @MethodSource("parameters") + public void testShareEval(RUN_TYPE runType) { final String str = "package myPkg;\n" + "rule R1 when\n" + " i : Integer()\n" + @@ -278,7 +284,7 @@ public void testShareEval() { "end\n" + ""; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); KieBase kbase = ksession.getKieBase(); EntryPointNode epn = ((InternalKnowledgeBase) kbase).getRete().getEntryPointNodes().values().iterator().next(); @@ -287,7 +293,7 @@ public void testShareEval() { assertThat(lian.getSinks().length).isEqualTo(1); } - public void testShareFrom() { + public void testShareFrom(RUN_TYPE runType) { String str = "import " + Person.class.getCanonicalName() + ";\n" + "import " + Address.class.getCanonicalName() + ";\n" + @@ -305,7 +311,7 @@ public void testShareFrom() { " list.add($a);\n" + "end\n"; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); List
list = new ArrayList<>(); ksession.setGlobal("list", list); @@ -322,8 +328,9 @@ public void testShareFrom() { assertThat(ReteDumper.collectNodes(ksession).stream().filter(FromNode.class::isInstance).count()).isEqualTo(1); } - @Test - public void testShareAccumulate() { + @ParameterizedTest + @MethodSource("parameters") + public void testShareAccumulate(RUN_TYPE runType) { String str = "import " + Person.class.getCanonicalName() + ";" + "import " + Result.class.getCanonicalName() + ";" + @@ -342,7 +349,7 @@ public void testShareAccumulate() { " insert(new Result($sum));\n" + "end"; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); ksession.insert(new Person("Mark", 37)); ksession.insert(new Person("Edson", 35)); @@ -357,8 +364,9 @@ public void testShareAccumulate() { assertThat(ReteDumper.collectNodes(ksession).stream().filter(AccumulateNode.class::isInstance).count()).isEqualTo(1); } - @Test - public void testShareFromAccumulate() { + @ParameterizedTest + @MethodSource("parameters") + public void testShareFromAccumulate(RUN_TYPE runType) { String str = "import " + Person.class.getCanonicalName() + ";" + "import " + Result.class.getCanonicalName() + ";" + @@ -377,7 +385,7 @@ public void testShareFromAccumulate() { " insert(new Result($sum));\n" + "end"; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); ksession.insert(new Person("Mark", 37)); ksession.insert(new Person("Edson", 35)); @@ -392,8 +400,9 @@ public void testShareFromAccumulate() { assertThat(ReteDumper.collectNodes(ksession).stream().filter(AccumulateNode.class::isInstance).count()).isEqualTo(1); } - @Test - public void testShareExists() { + @ParameterizedTest + @MethodSource("parameters") + public void testShareExists(RUN_TYPE runType) { String str = "import " + Person.class.getCanonicalName() + ";" + "import " + Result.class.getCanonicalName() + ";" + @@ -408,7 +417,7 @@ public void testShareExists() { " insert(new Result(\"ok\"));\n" + "end"; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); Person mario = new Person("Mario", 40); @@ -422,8 +431,9 @@ public void testShareExists() { assertThat(ReteDumper.collectNodes(ksession).stream().filter(ExistsNode.class::isInstance).count()).isEqualTo(1); } - @Test - public void testShareNot() { + @ParameterizedTest + @MethodSource("parameters") + public void testShareNot(RUN_TYPE runType) { String str = "import " + Person.class.getCanonicalName() + ";" + "import " + Result.class.getCanonicalName() + ";" + @@ -438,7 +448,7 @@ public void testShareNot() { " insert(new Result(\"ok\"));\n" + "end"; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); Person mario = new Person("Mario", 40); @@ -452,8 +462,9 @@ public void testShareNot() { assertThat(ReteDumper.collectNodes(ksession).stream().filter(NotNode.class::isInstance).count()).isEqualTo(1); } - @Test - public void testShareCombinedConstraintAnd() throws Exception { + @ParameterizedTest + @MethodSource("parameters") + public void testShareCombinedConstraintAnd(RUN_TYPE runType) throws Exception { // DROOLS-6330 // Note: if DROOLS-6329 is resolved, this test may not produce CombinedConstraint String str = @@ -471,7 +482,7 @@ public void testShareCombinedConstraintAnd() throws Exception { " System.out.println(\"fired\");\n" + "end\n"; - KieSession ksession = getKieSession(CepTest.getCepKieModuleModel(), str); + KieSession ksession = getKieSession(runType, CepTest.getCepKieModuleModel(), str); SessionPseudoClock clock = ksession.getSessionClock(); @@ -489,8 +500,9 @@ public void testShareCombinedConstraintAnd() throws Exception { assertThat(ReteDumper.collectNodes(ksession).stream().filter(JoinNode.class::isInstance).count()).isEqualTo(1); } - @Test - public void testShareCombinedConstraintOr() throws Exception { + @ParameterizedTest + @MethodSource("parameters") + public void testShareCombinedConstraintOr(RUN_TYPE runType) throws Exception { // DROOLS-6330 String str = "import " + StockTick.class.getCanonicalName() + ";" + @@ -507,7 +519,7 @@ public void testShareCombinedConstraintOr() throws Exception { " System.out.println(\"fired\");\n" + "end\n"; - KieSession ksession = getKieSession(CepTest.getCepKieModuleModel(), str); + KieSession ksession = getKieSession(runType, CepTest.getCepKieModuleModel(), str); SessionPseudoClock clock = ksession.getSessionClock(); diff --git a/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/NullSafeDereferencingTest.java b/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/NullSafeDereferencingTest.java index 536af82f868..a442f36b28c 100644 --- a/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/NullSafeDereferencingTest.java +++ b/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/NullSafeDereferencingTest.java @@ -26,19 +26,17 @@ import org.drools.model.codegen.execmodel.domain.MysteriousMan; import org.drools.model.codegen.execmodel.domain.Person; import org.drools.model.codegen.execmodel.domain.Result; -import org.junit.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; import org.kie.api.runtime.KieSession; import static org.assertj.core.api.Assertions.assertThat; public class NullSafeDereferencingTest extends BaseModelTest { - public NullSafeDereferencingTest( RUN_TYPE testRunType ) { - super( testRunType ); - } - - @Test - public void testNullSafeDereferncing() { + @ParameterizedTest + @MethodSource("parameters") + public void testNullSafeDereferncing(RUN_TYPE runType) { String str = "import " + Result.class.getCanonicalName() + ";" + "import " + Person.class.getCanonicalName() + ";" + @@ -49,7 +47,7 @@ public void testNullSafeDereferncing() { " $r.setValue(\"Found: \" + $p);\n" + "end"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); Result result = new Result(); ksession.insert( result ); @@ -115,8 +113,9 @@ public void setSomething(String something) { } } - @Test - public void testNullSafeMultiple() { + @ParameterizedTest + @MethodSource("parameters") + public void testNullSafeMultiple(RUN_TYPE runType) { String str = "import " + NullUnsafeA.class.getCanonicalName() + ";" + "import " + NullUnsafeB.class.getCanonicalName() + ";" + "import " + NullUnsafeD.class.getCanonicalName() + ";" + @@ -127,7 +126,7 @@ public void testNullSafeMultiple() { "end"; for (int i = 0; i <= 4; i++) { - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); NullUnsafeA a = new NullUnsafeA(); NullUnsafeB b = new NullUnsafeB(); @@ -162,8 +161,9 @@ public void testNullSafeMultiple() { } } - @Test - public void testNullSafeDereferncingOnFieldWithMethodInvocation() { + @ParameterizedTest + @MethodSource("parameters") + public void testNullSafeDereferncingOnFieldWithMethodInvocation(RUN_TYPE runType) { String str = "import " + Result.class.getCanonicalName() + ";" + "import " + Person.class.getCanonicalName() + ";" + "rule R when\n" + @@ -173,7 +173,7 @@ public void testNullSafeDereferncingOnFieldWithMethodInvocation() { " insert(r);\n" + "end"; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); ksession.insert(new Person("John1", 41, (Address) null)); ksession.insert(new Person("John2", 42, new Address("Milan"))); @@ -184,8 +184,9 @@ public void testNullSafeDereferncingOnFieldWithMethodInvocation() { assertThat(results.get(0).getValue()).isEqualTo("John2"); } - @Test - public void testNullSafeDereferncingOnMethodInvocation() { + @ParameterizedTest + @MethodSource("parameters") + public void testNullSafeDereferncingOnMethodInvocation(RUN_TYPE runType) { String str = "import " + Result.class.getCanonicalName() + ";" + "import " + Person.class.getCanonicalName() + ";" + "rule R when\n" + @@ -195,7 +196,7 @@ public void testNullSafeDereferncingOnMethodInvocation() { " insert(r);\n" + "end"; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); ksession.insert(new Person("John1", 41, new Address(null))); ksession.insert(new Person("John2", 42, new Address("Milan"))); @@ -206,8 +207,9 @@ public void testNullSafeDereferncingOnMethodInvocation() { assertThat(results.get(0).getValue()).isEqualTo("John2"); } - @Test - public void testNullSafeDereferncingOnFirstField() { + @ParameterizedTest + @MethodSource("parameters") + public void testNullSafeDereferncingOnFirstField(RUN_TYPE runType) { String str = "import " + Result.class.getCanonicalName() + ";" + "import " + Person.class.getCanonicalName() + ";" + "rule R when\n" + @@ -217,7 +219,7 @@ public void testNullSafeDereferncingOnFirstField() { " insert(r);\n" + "end"; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); ksession.insert(new Person("John1", 41, (Address) null)); ksession.insert(new Person("John2", 42, new Address("Milan"))); @@ -228,8 +230,9 @@ public void testNullSafeDereferncingOnFirstField() { assertThat(results.get(0).getValue()).isEqualTo("John2"); } - @Test - public void testNullSafeDereferncingOnSecondField() { + @ParameterizedTest + @MethodSource("parameters") + public void testNullSafeDereferncingOnSecondField(RUN_TYPE runType) { String str = "import " + Result.class.getCanonicalName() + ";" + "import " + Person.class.getCanonicalName() + ";" + "rule R when\n" + @@ -239,7 +242,7 @@ public void testNullSafeDereferncingOnSecondField() { " insert(r);\n" + "end"; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); ksession.insert(new Person("John1", 41, new Address(null))); ksession.insert(new Person("John2", 42, new Address("Milan"))); @@ -250,8 +253,9 @@ public void testNullSafeDereferncingOnSecondField() { assertThat(results.get(0).getValue()).isEqualTo("John2"); } - @Test - public void testNullSafeDereferncingWithOrHalfBinary() { + @ParameterizedTest + @MethodSource("parameters") + public void testNullSafeDereferncingWithOrHalfBinary(RUN_TYPE runType) { String str = "import " + Person.class.getCanonicalName() + ";\n" + "global java.util.List result;\n" + @@ -262,7 +266,7 @@ public void testNullSafeDereferncingWithOrHalfBinary() { " result.add($p.getName());\n" + "end"; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); List result = new ArrayList<>(); ksession.setGlobal("result", result); @@ -274,8 +278,9 @@ public void testNullSafeDereferncingWithOrHalfBinary() { assertThat(result).containsExactlyInAnyOrder("John", "George"); } - @Test - public void testNullSafeDereferencingNonPredicate() { + @ParameterizedTest + @MethodSource("parameters") + public void testNullSafeDereferencingNonPredicate(RUN_TYPE runType) { String str = "import " + Person.class.getCanonicalName() + ";\n" + "global java.util.List result;\n" + @@ -285,7 +290,7 @@ public void testNullSafeDereferencingNonPredicate() { " result.add($cityName);\n" + "end"; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); List result = new ArrayList<>(); ksession.setGlobal("result", result); @@ -297,8 +302,9 @@ public void testNullSafeDereferencingNonPredicate() { assertThat(result).containsExactlyInAnyOrder("London", "Tokyo"); } - @Test - public void testMultipleNullSafeDereferencingNonPredicate() { + @ParameterizedTest + @MethodSource("parameters") + public void testMultipleNullSafeDereferencingNonPredicate(RUN_TYPE runType) { String str = "import " + Person.class.getCanonicalName() + ";\n" + "global java.util.List result;\n" + @@ -308,7 +314,7 @@ public void testMultipleNullSafeDereferencingNonPredicate() { " result.add($cityNameLength);\n" + "end"; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); List result = new ArrayList<>(); ksession.setGlobal("result", result); @@ -320,8 +326,9 @@ public void testMultipleNullSafeDereferencingNonPredicate() { assertThat(result).containsExactlyInAnyOrder(6); } - @Test - public void testNullSafeDereferencingPredicateMethod() { + @ParameterizedTest + @MethodSource("parameters") + public void testNullSafeDereferencingPredicateMethod(RUN_TYPE runType) { String str = "import " + Person.class.getCanonicalName() + ";\n" + "global java.util.List result;\n" + @@ -331,7 +338,7 @@ public void testNullSafeDereferencingPredicateMethod() { " result.add($containsL);\n" + "end"; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); List result = new ArrayList<>(); ksession.setGlobal("result", result); @@ -343,8 +350,9 @@ public void testNullSafeDereferencingPredicateMethod() { assertThat(result).containsExactlyInAnyOrder(true, false); } - @Test - public void testNullSafeIndex() { + @ParameterizedTest + @MethodSource("parameters") + public void testNullSafeIndex(RUN_TYPE runType) { String str = "import " + Person.class.getCanonicalName() + ";\n" + "rule R1 when\n" + " $city : String()\n"+ @@ -352,7 +360,7 @@ public void testNullSafeIndex() { "then\n" + "end"; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); ksession.insert(new Person("Mario", 38)); @@ -369,8 +377,9 @@ public void testNullSafeIndex() { ksession.dispose(); } - @Test - public void testNullSafeDereferncingWithOr() { + @ParameterizedTest + @MethodSource("parameters") + public void testNullSafeDereferncingWithOr(RUN_TYPE runType) { String str = "import " + Person.class.getCanonicalName() + ";\n" + "global java.util.List result;\n" + @@ -381,7 +390,7 @@ public void testNullSafeDereferncingWithOr() { " result.add($p.getName());\n" + "end"; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); List result = new ArrayList<>(); ksession.setGlobal("result", result); @@ -400,8 +409,9 @@ public void testNullSafeDereferncingWithOr() { assertThat(result).containsExactlyInAnyOrder("Bob", "Paul"); } - @Test - public void testNullSafeDereferncingWithInstanceof() { + @ParameterizedTest + @MethodSource("parameters") + public void testNullSafeDereferncingWithInstanceof(RUN_TYPE runType) { // instanceof has to be evaluated before null check String str = "import " + Person.class.getCanonicalName() + ";\n" + @@ -414,7 +424,7 @@ public void testNullSafeDereferncingWithInstanceof() { " result.add($p.getName());\n" + "end"; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); List result = new ArrayList<>(); ksession.setGlobal("result", result); diff --git a/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/NumberAndStringArithmeticOperationCoercionTest.java b/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/NumberAndStringArithmeticOperationCoercionTest.java index b92641ad932..10b5c36a39e 100644 --- a/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/NumberAndStringArithmeticOperationCoercionTest.java +++ b/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/NumberAndStringArithmeticOperationCoercionTest.java @@ -21,148 +21,162 @@ import java.math.BigDecimal; import org.drools.model.codegen.execmodel.domain.ValueHolder; -import org.junit.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; import org.kie.api.runtime.KieSession; import static org.assertj.core.api.Assertions.assertThat; public class NumberAndStringArithmeticOperationCoercionTest extends BaseModelTest { - public NumberAndStringArithmeticOperationCoercionTest(RUN_TYPE testRunType) { - super(testRunType); - } // NOTE: For BigDecimal specific issues, use BigDecimalTest - @Test - public void testMultiplyStringInt() { + @ParameterizedTest + @MethodSource("parameters") + public void testMultiplyStringInt(RUN_TYPE runType) { ValueHolder holder = new ValueHolder(); holder.setIntValue(100); holder.setStrValue("10"); - testValueHolder("ValueHolder( intValue == strValue * 10 )", holder); + testValueHolder(runType, "ValueHolder( intValue == strValue * 10 )", holder); } - @Test - public void testMultiplyStringIntWithBindVariable() { + @ParameterizedTest + @MethodSource("parameters") + public void testMultiplyStringIntWithBindVariable(RUN_TYPE runType) { ValueHolder holder = new ValueHolder(); holder.setIntValue(100); holder.setStrValue("10"); - testValueHolder("ValueHolder( $strValue : strValue, intValue == $strValue * 10 )", holder); + testValueHolder(runType, "ValueHolder( $strValue : strValue, intValue == $strValue * 10 )", holder); } - @Test - public void testMultiplyIntStringWithBindVariable() { + @ParameterizedTest + @MethodSource("parameters") + public void testMultiplyIntStringWithBindVariable(RUN_TYPE runType) { ValueHolder holder = new ValueHolder(); holder.setIntValue(100); holder.setStrValue("10"); - testValueHolder("ValueHolder( $strValue : strValue, intValue == 10 * $strValue)", holder); + testValueHolder(runType, "ValueHolder( $strValue : strValue, intValue == 10 * $strValue)", holder); } - @Test - public void testMultiplyStringIntWithBindVariableCompareToBigDecimal() { + @ParameterizedTest + @MethodSource("parameters") + public void testMultiplyStringIntWithBindVariableCompareToBigDecimal(RUN_TYPE runType) { ValueHolder holder = new ValueHolder(); holder.setStrValue("10"); holder.setBdValue(new BigDecimal("-10")); - testValueHolder("ValueHolder( $strValue : strValue, bdValue == $strValue * -1 )", holder); + testValueHolder(runType, "ValueHolder( $strValue : strValue, bdValue == $strValue * -1 )", holder); } - @Test - public void testMultiplyStringIntWithBindVariableCompareToObject() { + @ParameterizedTest + @MethodSource("parameters") + public void testMultiplyStringIntWithBindVariableCompareToObject(RUN_TYPE runType) { ValueHolder holder = new ValueHolder(); holder.setStrValue("20"); holder.setObjValue("200"); - testValueHolder("ValueHolder( $strValue : strValue, objValue == $strValue * 10 )", holder); + testValueHolder(runType, "ValueHolder( $strValue : strValue, objValue == $strValue * 10 )", holder); } - @Test - public void testMultiplyStringBigDecimal() { + @ParameterizedTest + @MethodSource("parameters") + public void testMultiplyStringBigDecimal(RUN_TYPE runType) { ValueHolder holder = new ValueHolder(); holder.setIntValue(10); holder.setStrValue("20"); - testValueHolder("ValueHolder( intValue == strValue * 0.5B )", holder); + testValueHolder(runType, "ValueHolder( intValue == strValue * 0.5B )", holder); } - @Test - public void testMultiplyDecimalStringInt() { + @ParameterizedTest + @MethodSource("parameters") + public void testMultiplyDecimalStringInt(RUN_TYPE runType) { ValueHolder holder = new ValueHolder(); holder.setIntValue(5); holder.setStrValue("0.5"); - testValueHolder("ValueHolder( intValue == strValue * 10 )", holder); + testValueHolder(runType, "ValueHolder( intValue == strValue * 10 )", holder); } - @Test - public void testMultiplyDecimalStringBigDecimal() { + @ParameterizedTest + @MethodSource("parameters") + public void testMultiplyDecimalStringBigDecimal(RUN_TYPE runType) { ValueHolder holder = new ValueHolder(); holder.setIntValue(5); holder.setStrValue("0.5"); - testValueHolder("ValueHolder( intValue == strValue * 10B )", holder); + testValueHolder(runType, "ValueHolder( intValue == strValue * 10B )", holder); } - @Test - public void testMultiplyIntDecimalString() { + @ParameterizedTest + @MethodSource("parameters") + public void testMultiplyIntDecimalString(RUN_TYPE runType) { ValueHolder holder = new ValueHolder(); holder.setIntValue(5); holder.setStrValue("0.5"); - testValueHolder("ValueHolder( intValue == 10 * strValue )", holder); + testValueHolder(runType, "ValueHolder( intValue == 10 * strValue )", holder); } - @Test - public void testMultiplyStringDouble() { + @ParameterizedTest + @MethodSource("parameters") + public void testMultiplyStringDouble(RUN_TYPE runType) { ValueHolder holder = new ValueHolder(); holder.setIntValue(101); holder.setStrValue("10"); - testValueHolder("ValueHolder( intValue == strValue * 10.1 )", holder); + testValueHolder(runType, "ValueHolder( intValue == strValue * 10.1 )", holder); } - @Test - public void testAddStringIntWithBindVariableCompareToObject() { + @ParameterizedTest + @MethodSource("parameters") + public void testAddStringIntWithBindVariableCompareToObject(RUN_TYPE runType) { ValueHolder holder = new ValueHolder(); holder.setStrValue("20"); holder.setObjValue("2010"); // String concat - testValueHolder("ValueHolder( $strValue : strValue, objValue == $strValue + 10 )", holder); + testValueHolder(runType, "ValueHolder( $strValue : strValue, objValue == $strValue + 10 )", holder); } - @Test - public void testAddIntStringWithBindVariableCompareToObject() { + @ParameterizedTest + @MethodSource("parameters") + public void testAddIntStringWithBindVariableCompareToObject(RUN_TYPE runType) { ValueHolder holder = new ValueHolder(); holder.setStrValue("20"); holder.setObjValue("1020"); // String concat - testValueHolder("ValueHolder( $strValue : strValue, objValue == 10 + $strValue )", holder); + testValueHolder(runType, "ValueHolder( $strValue : strValue, objValue == 10 + $strValue )", holder); } - @Test - public void testAddStringIntWithBindVariableCompareToObjectNonNumeric() { + @ParameterizedTest + @MethodSource("parameters") + public void testAddStringIntWithBindVariableCompareToObjectNonNumeric(RUN_TYPE runType) { ValueHolder holder = new ValueHolder(); holder.setStrValue("ABC"); holder.setObjValue("ABC10"); // String concat - testValueHolder("ValueHolder( $strValue : strValue, objValue == $strValue + 10 )", holder); + testValueHolder(runType, "ValueHolder( $strValue : strValue, objValue == $strValue + 10 )", holder); } - @Test - public void testSubtractStringInt() { + @ParameterizedTest + @MethodSource("parameters") + public void testSubtractStringInt(RUN_TYPE runType) { ValueHolder holder = new ValueHolder(); holder.setIntValue(40); holder.setStrValue("50"); - testValueHolder("ValueHolder( intValue == strValue - 10 )", holder); + testValueHolder(runType, "ValueHolder( intValue == strValue - 10 )", holder); } - @Test - public void testModStringInt() { + @ParameterizedTest + @MethodSource("parameters") + public void testModStringInt(RUN_TYPE runType) { ValueHolder holder = new ValueHolder(); holder.setIntValue(2); holder.setStrValue("12"); - testValueHolder("ValueHolder( intValue == strValue % 10 )", holder); + testValueHolder(runType, "ValueHolder( intValue == strValue % 10 )", holder); } - @Test - public void testDivideStringInt() { + @ParameterizedTest + @MethodSource("parameters") + public void testDivideStringInt(RUN_TYPE runType) { ValueHolder holder = new ValueHolder(); holder.setIntValue(5); holder.setStrValue("50"); - testValueHolder("ValueHolder( intValue == strValue / 10 )", holder); + testValueHolder(runType, "ValueHolder( intValue == strValue / 10 )", holder); } - private void testValueHolder(String pattern, ValueHolder holder) { + private void testValueHolder(RUN_TYPE runType, String pattern, ValueHolder holder) { String str = "import " + ValueHolder.class.getCanonicalName() + "\n" + "rule R dialect \"mvel\" when\n" + @@ -170,7 +184,7 @@ private void testValueHolder(String pattern, ValueHolder holder) { "then\n" + "end"; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); ksession.insert(holder); int fired = ksession.fireAllRules(); diff --git a/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/OOPathTest.java b/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/OOPathTest.java index edba0258d31..037397677ad 100644 --- a/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/OOPathTest.java +++ b/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/OOPathTest.java @@ -28,19 +28,17 @@ import org.drools.model.codegen.execmodel.domain.Man; import org.drools.model.codegen.execmodel.domain.Toy; import org.drools.model.codegen.execmodel.domain.Woman; -import org.junit.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; import org.kie.api.runtime.KieSession; import static org.assertj.core.api.Assertions.assertThat; public class OOPathTest extends BaseModelTest { - public OOPathTest( RUN_TYPE testRunType ) { - super( testRunType ); - } - - @Test - public void testOOPath() { + @ParameterizedTest + @MethodSource("parameters") + public void testOOPath(RUN_TYPE runType) { final String str = "import org.drools.model.codegen.execmodel.domain.*;\n" + "global java.util.List list\n" + @@ -51,7 +49,7 @@ public void testOOPath() { " list.add( $man.getName() );\n" + "end\n"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); final List list = new ArrayList<>(); ksession.setGlobal( "list", list ); @@ -73,8 +71,9 @@ public void testOOPath() { assertThat(list).containsExactlyInAnyOrder("Bob"); } - @Test - public void testOOPathBinding() { + @ParameterizedTest + @MethodSource("parameters") + public void testOOPathBinding(RUN_TYPE runType) { final String str = "import org.drools.model.codegen.execmodel.domain.*;\n" + "global java.util.List list\n" + @@ -85,7 +84,7 @@ public void testOOPathBinding() { " list.add( $age );\n" + "end\n"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); final List list = new ArrayList<>(); ksession.setGlobal( "list", list ); @@ -102,8 +101,9 @@ public void testOOPathBinding() { assertThat(list).containsExactlyInAnyOrder(38); } - @Test - public void testReactiveOOPath() { + @ParameterizedTest + @MethodSource("parameters") + public void testReactiveOOPath(RUN_TYPE runType) { final String str = "import org.drools.model.codegen.execmodel.domain.*;\n" + "global java.util.List list\n" + @@ -114,7 +114,7 @@ public void testReactiveOOPath() { " list.add( $toy.getName() );\n" + "end\n"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); final List list = new ArrayList<>(); ksession.setGlobal( "list", list ); @@ -145,8 +145,9 @@ public void testReactiveOOPath() { } - @Test - public void testBackReferenceConstraint() { + @ParameterizedTest + @MethodSource("parameters") + public void testBackReferenceConstraint(RUN_TYPE runType) { final String str = "import org.drools.model.codegen.execmodel.domain.*;\n" + "global java.util.List list\n" + @@ -157,7 +158,7 @@ public void testBackReferenceConstraint() { " list.add( $toy.getName() );\n" + "end\n"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); final List list = new ArrayList<>(); ksession.setGlobal( "list", list ); @@ -182,8 +183,9 @@ public void testBackReferenceConstraint() { assertThat(list).containsExactlyInAnyOrder("ball", "guitar"); } - @Test - public void testSimpleOOPathCast1() { + @ParameterizedTest + @MethodSource("parameters") + public void testSimpleOOPathCast1(RUN_TYPE runType) { final String str = "import org.drools.model.codegen.execmodel.domain.*;\n" + "global java.util.List list\n" + "\n" + @@ -193,7 +195,7 @@ public void testSimpleOOPathCast1() { " list.add( $man.getName() );\n" + "end\n"; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); final List list = new ArrayList<>(); ksession.setGlobal("list", list); @@ -206,8 +208,9 @@ public void testSimpleOOPathCast1() { assertThat(list).containsExactlyInAnyOrder("Bob"); } - @Test - public void testSimpleOOPathCast2() { + @ParameterizedTest + @MethodSource("parameters") + public void testSimpleOOPathCast2(RUN_TYPE runType) { final String str = "import org.drools.model.codegen.execmodel.domain.*;\n" + "global java.util.List list\n" + "\n" + @@ -217,7 +220,7 @@ public void testSimpleOOPathCast2() { " list.add( $name );\n" + "end\n"; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); final List list = new ArrayList<>(); ksession.setGlobal("list", list); @@ -230,8 +233,9 @@ public void testSimpleOOPathCast2() { assertThat(list).containsExactlyInAnyOrder("Bob"); } - @Test - public void testSimpleOOPathCast3() { + @ParameterizedTest + @MethodSource("parameters") + public void testSimpleOOPathCast3(RUN_TYPE runType) { final String str = "import org.drools.model.codegen.execmodel.domain.*;\n" + "global java.util.List list\n" + "\n" + @@ -241,7 +245,7 @@ public void testSimpleOOPathCast3() { " list.add( $name );\n" + "end\n"; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); final List list = new ArrayList<>(); ksession.setGlobal("list", list); @@ -254,8 +258,9 @@ public void testSimpleOOPathCast3() { assertThat(list).containsExactlyInAnyOrder("Bob"); } - @Test - public void testOOPathMultipleConditions() { + @ParameterizedTest + @MethodSource("parameters") + public void testOOPathMultipleConditions(RUN_TYPE runType) { final String drl = "import " + Employee.class.getCanonicalName() + ";" + "import " + Address.class.getCanonicalName() + ";" + @@ -267,7 +272,7 @@ public void testOOPathMultipleConditions() { " list.add( $address.getCity() );\n" + "end\n"; - KieSession kieSession = getKieSession(drl); + KieSession kieSession = getKieSession(runType, drl); List results = new ArrayList<>(); kieSession.setGlobal("list", results); @@ -283,8 +288,9 @@ public void testOOPathMultipleConditions() { assertThat(results).containsExactlyInAnyOrder("Big City"); } - @Test - public void testOOPathMultipleConditionsWithBinding() { + @ParameterizedTest + @MethodSource("parameters") + public void testOOPathMultipleConditionsWithBinding(RUN_TYPE runType) { final String drl = "import " + Employee.class.getCanonicalName() + ";" + "import " + Address.class.getCanonicalName() + ";" + @@ -298,7 +304,7 @@ public void testOOPathMultipleConditionsWithBinding() { " list.add( $employee.getName() );\n" + "end\n"; - KieSession kieSession = getKieSession(drl); + KieSession kieSession = getKieSession(runType, drl); List results = new ArrayList<>(); kieSession.setGlobal("list", results); @@ -314,8 +320,9 @@ public void testOOPathMultipleConditionsWithBinding() { assertThat(results).containsExactlyInAnyOrder("Alice"); } - @Test - public void testOrConditionalElementNoBinding() { + @ParameterizedTest + @MethodSource("parameters") + public void testOrConditionalElementNoBinding(RUN_TYPE runType) { final String drl = "import " + Employee.class.getCanonicalName() + ";" + "import " + Address.class.getCanonicalName() + ";" + @@ -331,7 +338,7 @@ public void testOrConditionalElementNoBinding() { " list.add( $employee.getName() );\n" + "end\n"; - KieSession kieSession = getKieSession(drl); + KieSession kieSession = getKieSession(runType, drl); List results = new ArrayList<>(); kieSession.setGlobal("list", results); @@ -347,8 +354,9 @@ public void testOrConditionalElementNoBinding() { assertThat(results).containsExactlyInAnyOrder("Bruno", "Alice"); } - @Test - public void testOrConditionalElement() { + @ParameterizedTest + @MethodSource("parameters") + public void testOrConditionalElement(RUN_TYPE runType) { final String drl = "import " + Employee.class.getCanonicalName() + ";" + "import " + Address.class.getCanonicalName() + ";" + @@ -362,7 +370,7 @@ public void testOrConditionalElement() { " list.add( $address.getCity() );\n" + "end\n"; - KieSession kieSession = getKieSession(drl); + KieSession kieSession = getKieSession(runType, drl); List results = new ArrayList<>(); kieSession.setGlobal("list", results); @@ -378,8 +386,9 @@ public void testOrConditionalElement() { assertThat(results).containsExactlyInAnyOrder("Big City", "Small City"); } - @Test - public void testOrConstraintNoBinding() { + @ParameterizedTest + @MethodSource("parameters") + public void testOrConstraintNoBinding(RUN_TYPE runType) { final String drl = "import " + Employee.class.getCanonicalName() + ";" + "import " + Address.class.getCanonicalName() + ";" + @@ -392,7 +401,7 @@ public void testOrConstraintNoBinding() { " list.add( $emp.getName() );\n" + "end\n"; - KieSession kieSession = getKieSession(drl); + KieSession kieSession = getKieSession(runType, drl); List results = new ArrayList<>(); kieSession.setGlobal("list", results); @@ -408,8 +417,9 @@ public void testOrConstraintNoBinding() { assertThat(results).containsExactlyInAnyOrder("Bruno", "Alice"); } - @Test - public void testOrConstraintWithJoin() { + @ParameterizedTest + @MethodSource("parameters") + public void testOrConstraintWithJoin(RUN_TYPE runType) { final String drl = "import " + Employee.class.getCanonicalName() + ";" + "import " + Address.class.getCanonicalName() + ";" + @@ -422,7 +432,7 @@ public void testOrConstraintWithJoin() { " list.add( $address.getCity() );\n" + "end\n"; - KieSession kieSession = getKieSession(drl); + KieSession kieSession = getKieSession(runType, drl); List results = new ArrayList<>(); kieSession.setGlobal("list", results); @@ -438,8 +448,9 @@ public void testOrConstraintWithJoin() { assertThat(results).containsExactlyInAnyOrder("Big City", "Small City"); } - @Test - public void testOrConstraint() { + @ParameterizedTest + @MethodSource("parameters") + public void testOrConstraint(RUN_TYPE runType) { final String drl = "import " + Employee.class.getCanonicalName() + ";" + "import " + Address.class.getCanonicalName() + ";" + @@ -452,7 +463,7 @@ public void testOrConstraint() { " list.add( $address.getCity() );\n" + "end\n"; - KieSession kieSession = getKieSession(drl); + KieSession kieSession = getKieSession(runType, drl); List results = new ArrayList<>(); kieSession.setGlobal("list", results); diff --git a/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/OnlyExecModelTest.java b/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/OnlyExecModelTest.java index 8c36c433a9e..99193325f11 100644 --- a/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/OnlyExecModelTest.java +++ b/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/OnlyExecModelTest.java @@ -18,24 +18,14 @@ */ package org.drools.model.codegen.execmodel; -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; +import java.util.stream.Stream; + import static org.drools.model.codegen.execmodel.BaseModelTest.RUN_TYPE.PATTERN_DSL; -@RunWith(Parameterized.class) public abstract class OnlyExecModelTest extends BaseModelTest { - public OnlyExecModelTest(RUN_TYPE testRunType) { - super(testRunType); - } - - final static Object[] ONLY_EXEC_MODEL = { - PATTERN_DSL, - }; - - @Parameterized.Parameters(name = "{0}") - public static Object[] params() { - return ONLY_EXEC_MODEL; + public static Stream parameters() { + return Stream.of(PATTERN_DSL); } } diff --git a/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/OnlyPatternTest.java b/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/OnlyPatternTest.java index 3c89f4d35ca..0f5e553b1ac 100644 --- a/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/OnlyPatternTest.java +++ b/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/OnlyPatternTest.java @@ -18,25 +18,13 @@ */ package org.drools.model.codegen.execmodel; -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; - import static org.drools.model.codegen.execmodel.BaseModelTest.RUN_TYPE.PATTERN_DSL; -@RunWith(Parameterized.class) -public abstract class OnlyPatternTest extends BaseModelTest { +import java.util.stream.Stream; - public OnlyPatternTest(RUN_TYPE testRunType) { - super(testRunType); - } - - final static Object[] EXCLUDE_FLOW = { - RUN_TYPE.STANDARD_FROM_DRL, - PATTERN_DSL, - }; +public abstract class OnlyPatternTest extends BaseModelTest { - @Parameterized.Parameters(name = "{0}") - public static Object[] params() { - return EXCLUDE_FLOW; + public static Stream parameters() { + return Stream.of(RUN_TYPE.STANDARD_FROM_DRL, PATTERN_DSL); } } diff --git a/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/OrTest.java b/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/OrTest.java index 242e13f7ab8..c041a4f5f42 100644 --- a/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/OrTest.java +++ b/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/OrTest.java @@ -21,7 +21,8 @@ import org.drools.model.codegen.execmodel.domain.Address; import org.drools.model.codegen.execmodel.domain.Employee; import org.drools.model.codegen.execmodel.domain.Person; -import org.junit.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; import org.kie.api.builder.Results; import org.kie.api.runtime.KieSession; @@ -32,12 +33,9 @@ public class OrTest extends BaseModelTest { - public OrTest( RUN_TYPE testRunType ) { - super( testRunType ); - } - - @Test - public void testOr() { + @ParameterizedTest + @MethodSource("parameters") + public void testOr(RUN_TYPE runType) { String str = "import " + Person.class.getCanonicalName() + ";" + "rule R when\n" + @@ -50,7 +48,7 @@ public void testOr() { " System.out.println(\"Found: \" + $s);\n" + "end"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); ksession.insert( "Mario" ); ksession.insert( new Person( "Mark", 37 ) ); @@ -59,8 +57,9 @@ public void testOr() { assertThat(ksession.fireAllRules()).isEqualTo(1); } - @Test - public void testOrWhenStringFirst() { + @ParameterizedTest + @MethodSource("parameters") + public void testOrWhenStringFirst(RUN_TYPE runType) { String str = "import " + Person.class.getCanonicalName() + ";" + "import " + Address.class.getCanonicalName() + ";" + @@ -74,7 +73,7 @@ public void testOrWhenStringFirst() { " System.out.println(\"Found: \" + $s.getClass());\n" + "end"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); ksession.insert( "Go" ); ksession.insert( new Person( "Mark", 37 ) ); @@ -84,8 +83,9 @@ public void testOrWhenStringFirst() { } - @Test - public void testOrWithBetaIndex() { + @ParameterizedTest + @MethodSource("parameters") + public void testOrWithBetaIndex(RUN_TYPE runType) { String str = "import " + Person.class.getCanonicalName() + ";" + "rule R when\n" + @@ -98,7 +98,7 @@ public void testOrWithBetaIndex() { " System.out.println(\"Found: \" + $s);\n" + "end"; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); ksession.insert("Mario"); ksession.insert(new Person("Mark", 37)); @@ -107,8 +107,9 @@ public void testOrWithBetaIndex() { assertThat(ksession.fireAllRules()).isEqualTo(1); } - @Test - public void testOrWithBetaIndexOffset() { + @ParameterizedTest + @MethodSource("parameters") + public void testOrWithBetaIndexOffset(RUN_TYPE runType) { String str = "import " + Person.class.getCanonicalName() + ";" + "rule R when\n" + @@ -122,7 +123,7 @@ public void testOrWithBetaIndexOffset() { " System.out.println(\"Found: \" + $s);\n" + "end"; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); ksession.insert("Mario"); ksession.insert(new Person("Mark", 37)); @@ -131,8 +132,9 @@ public void testOrWithBetaIndexOffset() { assertThat(ksession.fireAllRules()).isEqualTo(1); } - @Test - public void testOrConditional() { + @ParameterizedTest + @MethodSource("parameters") + public void testOrConditional(RUN_TYPE runType) { final String drl = "import " + Employee.class.getCanonicalName() + ";" + "import " + Address.class.getCanonicalName() + ";" + @@ -146,7 +148,7 @@ public void testOrConditional() { " list.add( $address.getCity() );\n" + "end\n"; - KieSession kieSession = getKieSession(drl); + KieSession kieSession = getKieSession(runType, drl); List results = new ArrayList<>(); kieSession.setGlobal("list", results); @@ -162,8 +164,9 @@ public void testOrConditional() { assertThat(results).containsExactlyInAnyOrder("Big City", "Small City"); } - @Test - public void testOrConstraint() { + @ParameterizedTest + @MethodSource("parameters") + public void testOrConstraint(RUN_TYPE runType) { final String drl = "import " + Employee.class.getCanonicalName() + ";" + "import " + Address.class.getCanonicalName() + ";" + @@ -175,7 +178,7 @@ public void testOrConstraint() { " list.add( $address.getCity() );\n" + "end\n"; - KieSession kieSession = getKieSession(drl); + KieSession kieSession = getKieSession(runType, drl); List results = new ArrayList<>(); kieSession.setGlobal("list", results); @@ -191,8 +194,9 @@ public void testOrConstraint() { assertThat(results).containsExactlyInAnyOrder("Big City", "Small City"); } - @Test - public void testOrWithDuplicatedVariables() { + @ParameterizedTest + @MethodSource("parameters") + public void testOrWithDuplicatedVariables(RUN_TYPE runType) { String str = "import " + Person.class.getCanonicalName() + ";" + "global java.util.List list\n" + @@ -210,7 +214,7 @@ public void testOrWithDuplicatedVariables() { " list.add( $p + \" has \" + $age + \" years\");\n" + "end\n"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); List results = new ArrayList<>(); ksession.setGlobal("list", results); @@ -227,8 +231,9 @@ public void testOrWithDuplicatedVariables() { assertThat(results.contains("Mario has 40 years")).isTrue(); } - @Test - public void generateErrorForEveryFieldInRHSNotDefinedInLHS() { + @ParameterizedTest + @MethodSource("parameters") + public void generateErrorForEveryFieldInRHSNotDefinedInLHS(RUN_TYPE runType) { // JBRULES-3390 final String drl1 = "package org.drools.compiler.integrationtests.operators; \n" + "declare B\n" + @@ -245,16 +250,17 @@ public void generateErrorForEveryFieldInRHSNotDefinedInLHS() { " System.out.println($bField);\n" + "end\n"; - Results results = getCompilationResults(drl1); + Results results = getCompilationResults(runType, drl1); assertThat(results.getMessages().isEmpty()).isFalse(); } - private Results getCompilationResults( String drl ) { - return createKieBuilder( drl ).getResults(); + private Results getCompilationResults( RUN_TYPE runType, String drl ) { + return createKieBuilder(runType, drl ).getResults(); } - @Test - public void testMultipleFiringWithOr() { + @ParameterizedTest + @MethodSource("parameters") + public void testMultipleFiringWithOr(RUN_TYPE runType) { // DROOLS-7466 final String str = "rule R when\n" + @@ -264,7 +270,7 @@ public void testMultipleFiringWithOr() { "then\n" + "end \n"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); assertThat(ksession.fireAllRules()).isEqualTo(2); } } diff --git a/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/PackagesIsolationTest.java b/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/PackagesIsolationTest.java index 41c912e99a1..e1d99b0e546 100644 --- a/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/PackagesIsolationTest.java +++ b/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/PackagesIsolationTest.java @@ -20,21 +20,19 @@ import java.util.Arrays; -import org.junit.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; import org.kie.api.runtime.KieSession; import static org.assertj.core.api.Assertions.assertThat; public class PackagesIsolationTest extends BaseModelTest { - public PackagesIsolationTest( RUN_TYPE testRunType ) { - super( testRunType ); - } - public static class HashSet { } - @Test - public void testDoNotMixImports() { + @ParameterizedTest + @MethodSource("parameters") + public void testDoNotMixImports(RUN_TYPE runType) { // DROOLS-5390 String str2 = "package mypkg2\n" + @@ -47,11 +45,12 @@ public void testDoNotMixImports() { " list.add(\"R2\");\n" + "end"; - check( str2 ); + check( runType, str2 ); } - @Test - public void testImportWildcard() { + @ParameterizedTest + @MethodSource("parameters") + public void testImportWildcard(RUN_TYPE runType) { String str2 = "package mypkg2\n" + "import mypkg1.*;\n" + @@ -62,11 +61,12 @@ public void testImportWildcard() { " list.add(\"R2\");\n" + "end"; - check( str2 ); + check( runType, str2 ); } - @Test - public void testImportType() { + @ParameterizedTest + @MethodSource("parameters") + public void testImportType(RUN_TYPE runType) { String str2 = "package mypkg2\n" + "import mypkg1.MyPojo;\n" + @@ -77,10 +77,10 @@ public void testImportType() { " list.add(\"R2\");\n" + "end"; - check( str2 ); + check( runType, str2 ); } - private void check( String str2 ) { + private void check( RUN_TYPE runType, String str2 ) { String str1 = "package mypkg1\n" + "global java.util.List list\n" + @@ -92,7 +92,7 @@ private void check( String str2 ) { " list.add(\"R1\");\n" + "end"; - KieSession ksession = getKieSession( str1, str2 ); + KieSession ksession = getKieSession(runType, str1, str2); java.util.List list = new java.util.ArrayList<>(); ksession.setGlobal( "list", list ); diff --git a/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/PrimitiveConversionErrorsTest.java b/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/PrimitiveConversionErrorsTest.java index 0b335efb372..52dacae6c6b 100644 --- a/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/PrimitiveConversionErrorsTest.java +++ b/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/PrimitiveConversionErrorsTest.java @@ -20,14 +20,13 @@ import java.io.IOException; import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collection; import java.util.List; +import java.util.stream.Stream; import org.drools.model.codegen.ExecutableModelProject; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.Arguments; +import org.junit.jupiter.params.provider.MethodSource; import org.kie.api.KieBase; import org.kie.api.KieServices; import org.kie.api.builder.KieBuilder; @@ -39,9 +38,9 @@ import org.kie.api.runtime.KieSession; import static org.assertj.core.api.Assertions.assertThat; +import static org.junit.jupiter.params.provider.Arguments.arguments; // DROOLS-6506 -@RunWith(Parameterized.class) public class PrimitiveConversionErrorsTest { private static final String RULE_TEMPLATE = "" + @@ -66,63 +65,49 @@ public class PrimitiveConversionErrorsTest { " $values.add($value);\n" + "end"; - @Parameterized.Parameters(name = "value{0} != {2}: Method Returns {0}, test against {1}") - public static Collection data() { - Object[][] data = new Object[][]{ - {Float.class, Float.class, 4f, 5f, 6f}, - {Float.class, Double.class, 4d, 5f, 6f}, - {Float.class, Integer.class, 4, 5f, 6f}, - {Float.class, Short.class, (short) 4, 5f, 6f}, - {Float.class, Byte.class, (byte) 4, 5f, 6f}, - - {Double.class, Float.class, 4f, 5d, 6d}, - {Double.class, Double.class, 4d, 5d, 6d}, - {Double.class, Integer.class, 4, 5d, 6d}, - {Double.class, Short.class, (short) 4, 5d, 6d}, - {Double.class, Byte.class, (byte) 4, 5d, 6d}, - - {Integer.class, Float.class, 4f, 5, 6}, - {Integer.class, Double.class, 4d, 5, 6}, - {Integer.class, Integer.class, 4, 5, 6}, - {Integer.class, Short.class, (short) 4, 5, 6}, - {Integer.class, Byte.class, (byte) 4, 5, 6}, - - {Short.class, Float.class, 4f, (short) 5, (short) 6}, - {Short.class, Double.class, 4d, (short) 5, (short) 6}, - {Short.class, Integer.class, 4, (short) 5, (short) 6}, - {Short.class, Short.class, (short) 4, (short) 5, (short) 6}, - {Short.class, Byte.class, (byte) 4, (short) 5, (short) 6}, - - {Byte.class, Float.class, 4f, (byte) 5, (byte) 6}, - {Byte.class, Double.class, 4d, (byte) 5, (byte) 6}, - {Byte.class, Integer.class, 4, (byte) 5, (byte) 6}, - {Byte.class, Short.class, (short) 4, (byte) 5, (byte) 6}, - {Byte.class, Byte.class, (byte) 4, (byte) 5, (byte) 6}, - }; - return Arrays.asList(data); + public static Stream data() { + return Stream.of( + arguments(Float.class, Float.class, 4f, 5f, 6f), + arguments(Float.class, Double.class, 4d, 5f, 6f), + arguments(Float.class, Integer.class, 4, 5f, 6f), + arguments(Float.class, Short.class, (short) 4, 5f, 6f), + arguments(Float.class, Byte.class, (byte) 4, 5f, 6f), + + arguments(Double.class, Float.class, 4f, 5d, 6d), + arguments(Double.class, Double.class, 4d, 5d, 6d), + arguments(Double.class, Integer.class, 4, 5d, 6d), + arguments(Double.class, Short.class, (short) 4, 5d, 6d), + arguments(Double.class, Byte.class, (byte) 4, 5d, 6d), + + arguments(Integer.class, Float.class, 4f, 5, 6), + arguments(Integer.class, Double.class, 4d, 5, 6), + arguments(Integer.class, Integer.class, 4, 5, 6), + arguments(Integer.class, Short.class, (short) 4, 5, 6), + arguments(Integer.class, Byte.class, (byte) 4, 5, 6), + + arguments(Short.class, Float.class, 4f, (short) 5, (short) 6), + arguments(Short.class, Double.class, 4d, (short) 5, (short) 6), + arguments(Short.class, Integer.class, 4, (short) 5, (short) 6), + arguments(Short.class, Short.class, (short) 4, (short) 5, (short) 6), + arguments(Short.class, Byte.class, (byte) 4, (short) 5, (short) 6), + + arguments(Byte.class, Float.class, 4f, (byte) 5, (byte) 6), + arguments(Byte.class, Double.class, 4d, (byte) 5, (byte) 6), + arguments(Byte.class, Integer.class, 4, (byte) 5, (byte) 6), + arguments(Byte.class, Short.class, (short) 4, (byte) 5, (byte) 6), + arguments(Byte.class, Byte.class, (byte) 4, (byte) 5, (byte) 6)); } - private final Object valueCheck; - private final Class valueType; - private final Object valueA; - private final Object valueB; + @ParameterizedTest(name="value{0} != {2}: Method Returns {0}, test against {1}") + @MethodSource("data") + public void withExecutableModel(Class valueType, Class valueCheckType, Object valueCheck, Object valueA, Object valueB) throws IOException { - public PrimitiveConversionErrorsTest(Class valueType, Class valueCheckType, Object valueCheck, Object valueA, Object valueB) { - this.valueCheck = valueCheck; - this.valueType = valueType; - this.valueA = valueA; - this.valueB = valueB; - } - - @Test - public void withExecutableModel() throws IOException { - - KieBase kbase = loadRules(this.valueType, this.valueCheck, true); + KieBase kbase = loadRules(valueType, valueCheck, true); KieSession session = kbase.newKieSession(); List values = new ArrayList<>(); - ClassWithValue ca = makeClassWithValue(this.valueA); - ClassWithValue cb = makeClassWithValue(this.valueB); + ClassWithValue ca = makeClassWithValue(valueA); + ClassWithValue cb = makeClassWithValue(valueB); session.insert(values); session.insert(ca); @@ -131,19 +116,20 @@ public void withExecutableModel() throws IOException { session.fireAllRules(); assertThat(values.size()).isEqualTo(2); - assertThat(values.contains(this.valueA)).isTrue(); - assertThat(values.contains(this.valueB)).isTrue(); + assertThat(values.contains(valueA)).isTrue(); + assertThat(values.contains(valueB)).isTrue(); } - @Test - public void withoutExecutableModel() throws IOException { + @ParameterizedTest(name="value{0} != {2}: Method Returns {0}, test against {1}") + @MethodSource("data") + public void withoutExecutableModel(Class valueType, Class valueCheckType, Object valueCheck, Object valueA, Object valueB) throws IOException { - KieBase kbase = loadRules(this.valueType, this.valueCheck, false); + KieBase kbase = loadRules(valueType, valueCheck, false); KieSession session = kbase.newKieSession(); List values = new ArrayList<>(); - ClassWithValue ca = makeClassWithValue(this.valueA); - ClassWithValue cb = makeClassWithValue(this.valueB); + ClassWithValue ca = makeClassWithValue(valueA); + ClassWithValue cb = makeClassWithValue(valueB); session.insert(values); session.insert(ca); @@ -152,8 +138,8 @@ public void withoutExecutableModel() throws IOException { session.fireAllRules(); assertThat(values.size()).isEqualTo(2); - assertThat(values.contains(this.valueA)).isTrue(); - assertThat(values.contains(this.valueB)).isTrue(); + assertThat(values.contains(valueA)).isTrue(); + assertThat(values.contains(valueB)).isTrue(); } private static KieBase loadRules(Class valueType, Object value, boolean useExecutable) throws IOException { diff --git a/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/PropertyReactivityMatrixTest.java b/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/PropertyReactivityMatrixTest.java index d4742f74e93..070b929db58 100644 --- a/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/PropertyReactivityMatrixTest.java +++ b/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/PropertyReactivityMatrixTest.java @@ -19,15 +19,19 @@ package org.drools.model.codegen.execmodel; import java.util.ArrayList; -import java.util.Collection; import java.util.List; +import java.util.stream.Stream; +import org.drools.model.codegen.execmodel.BaseModelTest.RUN_TYPE; import org.drools.util.StringUtils; -import org.junit.Test; -import org.junit.runners.Parameterized.Parameters; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.Arguments; +import org.junit.jupiter.params.provider.MethodSource; import org.kie.api.runtime.KieSession; import static org.assertj.core.api.Assertions.assertThat; +import static org.drools.model.codegen.execmodel.BaseModelTest.RUN_TYPE.PATTERN_DSL; +import static org.junit.jupiter.params.provider.Arguments.arguments; public class PropertyReactivityMatrixTest extends BaseModelTest { @@ -36,23 +40,23 @@ enum Dialect { MVEL } - private Dialect dialect; - @Parameters(name = "{0} {1}") - public static Collection parameters() { - List parameterData = new ArrayList(); + final static Object[] PLAIN = { + RUN_TYPE.STANDARD_FROM_DRL, + PATTERN_DSL, + }; + + + public static Stream parametersData() { + List parameterData = new ArrayList(); for (Object runType : PLAIN) { for (Dialect dialect : Dialect.values()) { - parameterData.add(new Object[]{runType, dialect}); + parameterData.add(arguments(runType, dialect)); } } - return parameterData; + return Stream.of(parameterData.toArray(new Arguments[0])); } - public PropertyReactivityMatrixTest(RUN_TYPE testRunType, Dialect testDialect) { - super(testRunType); - this.dialect = testDialect; - } public static class Fact { @@ -85,7 +89,7 @@ public void setValue2(int value2) { } } - private String setValueStatement(String property, int value) { + private String setValueStatement(Dialect dialect, String property, int value) { if (dialect == Dialect.JAVA) { return "set" + StringUtils.ucFirst(property) + "(" + value + ");"; } else { @@ -93,123 +97,136 @@ private String setValueStatement(String property, int value) { } } - @Test - public void modifyInsideIfTrueBlock_shouldTriggerReactivity() { - statementInsideBlock_shouldTriggerReactivity(" if (true) {\n" + + @ParameterizedTest + @MethodSource("parametersData") + public void modifyInsideIfTrueBlock_shouldTriggerReactivity(RUN_TYPE runType, Dialect dialect) { + statementInsideBlock_shouldTriggerReactivity(runType, dialect, " if (true) {\n" + " modify($fact) {\n" + - " " + setValueStatement("value1", 2) + "\n" + + " " + setValueStatement(dialect, "value1", 2) + "\n" + " }\n" + " }\n"); } - @Test - public void modifyInsideForBlock_shouldTriggerReactivity() { - statementInsideBlock_shouldTriggerReactivity(" for (int i = 0; i < 1; i++) {\n" + + @ParameterizedTest + @MethodSource("parametersData") + public void modifyInsideForBlock_shouldTriggerReactivity(RUN_TYPE runType, Dialect dialect) { + statementInsideBlock_shouldTriggerReactivity(runType, dialect, " for (int i = 0; i < 1; i++) {\n" + " modify($fact) {\n" + - " " + setValueStatement("value1", 2) + "\n" + + " " + setValueStatement(dialect, "value1", 2) + "\n" + " }\n" + " }\n"); } - @Test - public void modifyInsideCommentedIfTrueBlock_shouldTriggerReactivity() { - statementInsideBlock_shouldTriggerReactivity(" // if (true) {\n" + + @ParameterizedTest + @MethodSource("parametersData") + public void modifyInsideCommentedIfTrueBlock_shouldTriggerReactivity(RUN_TYPE runType, Dialect dialect) { + statementInsideBlock_shouldTriggerReactivity(runType, dialect, " // if (true) {\n" + " modify($fact) {\n" + - " " + setValueStatement("value1", 2) + "\n" + + " " + setValueStatement(dialect, "value1", 2) + "\n" + " }\n" + " // }\n"); } - @Test - public void modifyInsideIfBlockInsideAndOutsideAssignment_shouldTriggerReactivity() { - statementInsideBlock_shouldTriggerReactivity(" $fact." + setValueStatement("value1", 2) + "\n" + + @ParameterizedTest + @MethodSource("parametersData") + public void modifyInsideIfBlockInsideAndOutsideAssignment_shouldTriggerReactivity(RUN_TYPE runType, Dialect dialect) { + statementInsideBlock_shouldTriggerReactivity(runType, dialect, " $fact." + setValueStatement(dialect, "value1", 2) + "\n" + " if (true) {\n" + " modify($fact) {\n" + - " " + setValueStatement("value2", 2) + "\n" + + " " + setValueStatement(dialect, "value2", 2) + "\n" + " }\n" + " }"); } - @Test - public void updateInsideIfTrueBlock_shouldTriggerReactivity() { - statementInsideBlock_shouldTriggerReactivity(" if (true) {\n" + - " $fact." + setValueStatement("value1", 2) + ";\n" + + @ParameterizedTest + @MethodSource("parametersData") + public void updateInsideIfTrueBlock_shouldTriggerReactivity(RUN_TYPE runType, Dialect dialect) { + statementInsideBlock_shouldTriggerReactivity(runType, dialect, " if (true) {\n" + + " $fact." + setValueStatement(dialect, "value1", 2) + ";\n" + " update($fact);\n" + " }\n"); } - @Test - public void updateInsideForBlock_shouldTriggerReactivity() { - statementInsideBlock_shouldTriggerReactivity(" for (int i = 0; i < 1; i++) {\n" + - " $fact." + setValueStatement("value1", 2) + "\n" + + @ParameterizedTest + @MethodSource("parametersData") + public void updateInsideForBlock_shouldTriggerReactivity(RUN_TYPE runType, Dialect dialect) { + statementInsideBlock_shouldTriggerReactivity(runType, dialect, " for (int i = 0; i < 1; i++) {\n" + + " $fact." + setValueStatement(dialect, "value1", 2) + "\n" + " update($fact);\n" + " }\n"); } - @Test - public void updateInsideCommentedIfTrueBlock_shouldTriggerReactivity() { - statementInsideBlock_shouldTriggerReactivity(" // if (true) {\n" + - " $fact." + setValueStatement("value1", 2) + "\n" + + @ParameterizedTest + @MethodSource("parametersData") + public void updateInsideCommentedIfTrueBlock_shouldTriggerReactivity(RUN_TYPE runType, Dialect dialect) { + statementInsideBlock_shouldTriggerReactivity(runType, dialect, " // if (true) {\n" + + " $fact." + setValueStatement(dialect, "value1", 2) + "\n" + " update($fact);\n" + " // }\n"); } - @Test - public void updateInsideIfBlockInsideAndOutsideAssignment_shouldTriggerReactivity() { - statementInsideBlock_shouldTriggerReactivity(" $fact." + setValueStatement("value1", 2) + "\n" + + @ParameterizedTest + @MethodSource("parametersData") + public void updateInsideIfBlockInsideAndOutsideAssignment_shouldTriggerReactivity(RUN_TYPE runType, Dialect dialect) { + statementInsideBlock_shouldTriggerReactivity(runType, dialect, " $fact." + setValueStatement(dialect, "value1", 2) + "\n" + " if (true) {\n" + - " $fact." + setValueStatement("value2", 2) + "\n" + + " $fact." + setValueStatement(dialect, "value2", 2) + "\n" + " update($fact);\n" + " }"); } - @Test - public void assignmentAfterModify_shouldTriggerReactivity() { + @ParameterizedTest + @MethodSource("parametersData") + public void assignmentAfterModify_shouldTriggerReactivity(RUN_TYPE runType, Dialect dialect) { // DROOLS-7497 - statementInsideBlock_shouldTriggerReactivity(" modify($fact) {\n" + - " " + setValueStatement("value2", 2) + "\n" + + statementInsideBlock_shouldTriggerReactivity(runType, dialect, " modify($fact) {\n" + + " " + setValueStatement(dialect, "value2", 2) + "\n" + " }\n" + - " $fact." + setValueStatement("value1", 2) + "\n"); + " $fact." + setValueStatement(dialect, "value1", 2) + "\n"); } - @Test - public void assignmentBeforeAndAfterModify_shouldTriggerReactivity() { + @ParameterizedTest + @MethodSource("parametersData") + public void assignmentBeforeAndAfterModify_shouldTriggerReactivity(RUN_TYPE runType, Dialect dialect) { // DROOLS-7497 - statementInsideBlock_shouldTriggerReactivity(" $fact." + setValueStatement("value2", 2) + "\n" + + statementInsideBlock_shouldTriggerReactivity(runType, dialect, " $fact." + setValueStatement(dialect, "value2", 2) + "\n" + " modify($fact) {\n" + " }\n" + - " $fact." + setValueStatement("value1", 2) + "\n"); + " $fact." + setValueStatement(dialect, "value1", 2) + "\n"); } - @Test - public void assignmentAfterIfBlockModify_shouldTriggerReactivity() { + @ParameterizedTest + @MethodSource("parametersData") + public void assignmentAfterIfBlockModify_shouldTriggerReactivity(RUN_TYPE runType, Dialect dialect) { // DROOLS-7497 - statementInsideBlock_shouldTriggerReactivity(" if (true) {\n" + + statementInsideBlock_shouldTriggerReactivity(runType, dialect, " if (true) {\n" + " modify($fact) {\n" + - " " + setValueStatement("value2", 2) + "\n" + + " " + setValueStatement(dialect, "value2", 2) + "\n" + " }\n" + " }\n" + - " $fact." + setValueStatement("value1", 2) + "\n"); + " $fact." + setValueStatement(dialect, "value1", 2) + "\n"); } - @Test - public void assignmentBeforeAndAfterUpdate_shouldTriggerReactivity() { + @ParameterizedTest + @MethodSource("parametersData") + public void assignmentBeforeAndAfterUpdate_shouldTriggerReactivity(RUN_TYPE runType, Dialect dialect) { // DROOLS-7497 - statementInsideBlock_shouldTriggerReactivity(" $fact." + setValueStatement("value2", 2) + "\n" + + statementInsideBlock_shouldTriggerReactivity(runType, dialect, " $fact." + setValueStatement(dialect, "value2", 2) + "\n" + " update($fact);\n" + - " $fact." + setValueStatement("value1", 2) + "\n"); + " $fact." + setValueStatement(dialect, "value1", 2) + "\n"); } - @Test - public void assignmentAfterIfBlockUpdate_shouldTriggerReactivity() { + @ParameterizedTest + @MethodSource("parametersData") + public void assignmentAfterIfBlockUpdate_shouldTriggerReactivity(RUN_TYPE runType, Dialect dialect) { // DROOLS-7497 - statementInsideBlock_shouldTriggerReactivity(" if (true) {\n" + + statementInsideBlock_shouldTriggerReactivity(runType, dialect, " if (true) {\n" + " update($fact);\n" + " }\n" + - " $fact." + setValueStatement("value1", 2) + "\n"); + " $fact." + setValueStatement(dialect, "value1", 2) + "\n"); } - private void statementInsideBlock_shouldTriggerReactivity(String rhs) { + private void statementInsideBlock_shouldTriggerReactivity(RUN_TYPE runType, Dialect dialect, String rhs) { final String str = "import " + Fact.class.getCanonicalName() + ";\n" + "dialect \"" + dialect.name().toLowerCase() + "\"\n" + @@ -227,7 +244,7 @@ private void statementInsideBlock_shouldTriggerReactivity(String rhs) { " results.add(\"R2 fired\");\n" + "end\n"; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); List results = new ArrayList<>(); ksession.setGlobal("results", results); @@ -239,11 +256,12 @@ private void statementInsideBlock_shouldTriggerReactivity(String rhs) { .containsExactly("R2 fired"); } - @Test - public void modifyInsideIfFalseAndTrueBlock_shouldTriggerReactivity() { + @ParameterizedTest + @MethodSource("parametersData") + public void modifyInsideIfFalseAndTrueBlock_shouldTriggerReactivity(RUN_TYPE runType, Dialect dialect) { // DROOLS-7493 - statementInsideBlock_shouldTriggerReactivityWithLoop(" if (false) {\n" + - " $fact." + setValueStatement("value1", 2) + "\n" + // this line is not executed, but analyzed as a property reactivity + statementInsideBlock_shouldTriggerReactivityWithLoop(runType, dialect, " if (false) {\n" + + " $fact." + setValueStatement(dialect, "value1", 2) + "\n" + // this line is not executed, but analyzed as a property reactivity " }\n" + " if (true) {\n" + " modify($fact) {\n" + @@ -251,17 +269,18 @@ public void modifyInsideIfFalseAndTrueBlock_shouldTriggerReactivity() { " }\n"); } - @Test - public void updateInsideIfFalseAndTrueBlock_shouldTriggerReactivity() { - statementInsideBlock_shouldTriggerReactivityWithLoop(" if (false) {\n" + - " $fact." + setValueStatement("value1", 2) + "\n" + // this line is not executed, but analyzed as a property reactivity + @ParameterizedTest + @MethodSource("parametersData") + public void updateInsideIfFalseAndTrueBlock_shouldTriggerReactivity(RUN_TYPE runType, Dialect dialect) { + statementInsideBlock_shouldTriggerReactivityWithLoop(runType, dialect, " if (false) {\n" + + " $fact." + setValueStatement(dialect, "value1", 2) + "\n" + // this line is not executed, but analyzed as a property reactivity " }\n" + " if (true) {\n" + " update($fact);\n" + " }\n"); } - private void statementInsideBlock_shouldTriggerReactivityWithLoop(String rhs) { + private void statementInsideBlock_shouldTriggerReactivityWithLoop(RUN_TYPE runType, Dialect dialect, String rhs) { final String str = "import " + Fact.class.getCanonicalName() + ";\n" + "dialect \"" + dialect.name().toLowerCase() + "\"\n" + @@ -273,7 +292,7 @@ private void statementInsideBlock_shouldTriggerReactivityWithLoop(String rhs) { rhs + "end\n"; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); List results = new ArrayList<>(); ksession.setGlobal("results", results); @@ -285,25 +304,27 @@ private void statementInsideBlock_shouldTriggerReactivityWithLoop(String rhs) { .isEqualTo(10); } - @Test - public void modifyInsideIfFalseBlock_shouldNotTriggerReactivity() { + @ParameterizedTest + @MethodSource("parametersData") + public void modifyInsideIfFalseBlock_shouldNotTriggerReactivity(RUN_TYPE runType, Dialect dialect) { // DROOLS-7493 - statementInsideIfFalseBlock_shouldNotTriggerReactivityNorSelfLoop(" if (false) {\n" + + statementInsideIfFalseBlock_shouldNotTriggerReactivityNorSelfLoop(runType, dialect, " if (false) {\n" + " modify($fact) {\n" + - " " + setValueStatement("value1", 2) + "\n" + + " " + setValueStatement(dialect, "value1", 2) + "\n" + " }\n" + " }\n"); } - @Test - public void updateInsideIfFalseBlock_shouldNotTriggerReactivity() { - statementInsideIfFalseBlock_shouldNotTriggerReactivityNorSelfLoop(" if (false) {\n" + - " $fact." + setValueStatement("value1", 2) + "\n" + + @ParameterizedTest + @MethodSource("parametersData") + public void updateInsideIfFalseBlock_shouldNotTriggerReactivity(RUN_TYPE runType, Dialect dialect) { + statementInsideIfFalseBlock_shouldNotTriggerReactivityNorSelfLoop(runType, dialect, " if (false) {\n" + + " $fact." + setValueStatement(dialect, "value1", 2) + "\n" + " update($fact);\n" + " }\n"); } - private void statementInsideIfFalseBlock_shouldNotTriggerReactivityNorSelfLoop(String rhs) { + private void statementInsideIfFalseBlock_shouldNotTriggerReactivityNorSelfLoop(RUN_TYPE runType, Dialect dialect, String rhs) { final String str = "import " + Fact.class.getCanonicalName() + ";\n" + "dialect \"" + dialect.name().toLowerCase() + "\"\n" + @@ -321,7 +342,7 @@ private void statementInsideIfFalseBlock_shouldNotTriggerReactivityNorSelfLoop(S " results.add(\"R2 fired\");\n" + "end\n"; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); List results = new ArrayList<>(); ksession.setGlobal("results", results); diff --git a/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/PropertyReactivityTest.java b/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/PropertyReactivityTest.java index 66b9b8549c4..8c16a9c5a51 100644 --- a/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/PropertyReactivityTest.java +++ b/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/PropertyReactivityTest.java @@ -30,8 +30,9 @@ import org.drools.model.codegen.execmodel.domain.Pet; import org.drools.model.codegen.execmodel.domain.Result; import org.drools.model.codegen.execmodel.domain.VariousCasePropFact; - -import org.junit.Test; +import org.junit.jupiter.api.Timeout; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; import org.kie.api.builder.KieBuilder; import org.kie.api.builder.Message.Level; import org.kie.api.definition.type.Modifies; @@ -42,12 +43,9 @@ public class PropertyReactivityTest extends BaseModelTest { - public PropertyReactivityTest( RUN_TYPE testRunType ) { - super( testRunType ); - } - - @Test - public void testPropertyReactivity() { + @ParameterizedTest + @MethodSource("parameters") + public void testPropertyReactivity(RUN_TYPE runType) { final String str = "import " + Person.class.getCanonicalName() + ";\n" + "\n" + @@ -57,7 +55,7 @@ public void testPropertyReactivity() { " modify($p) { setAge( $p.getAge()+1 ) };\n" + "end\n"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); Person p = new Person("Mario", 40); ksession.insert( p ); @@ -66,8 +64,9 @@ public void testPropertyReactivity() { assertThat(p.getAge()).isEqualTo(41); } - @Test - public void testPropertyReactivityWithUpdate() { + @ParameterizedTest + @MethodSource("parameters") + public void testPropertyReactivityWithUpdate(RUN_TYPE runType) { final String str = "import " + Person.class.getCanonicalName() + ";\n" + "\n" + @@ -78,7 +77,7 @@ public void testPropertyReactivityWithUpdate() { " update($p);\n" + "end\n"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); Person p = new Person("Mario", 40); ksession.insert( p ); @@ -87,8 +86,9 @@ public void testPropertyReactivityWithUpdate() { assertThat(p.getAge()).isEqualTo(41); } - @Test - public void testPropertyReactivityMvel() { + @ParameterizedTest + @MethodSource("parameters") + public void testPropertyReactivityMvel(RUN_TYPE runType) { final String str = "import " + Person.class.getCanonicalName() + ";\n" + "\n" + @@ -98,7 +98,7 @@ public void testPropertyReactivityMvel() { " modify($p) { age = $p.age+1 };\n" + "end\n"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); Person p = new Person("Mario", 40); ksession.insert( p ); @@ -107,8 +107,9 @@ public void testPropertyReactivityMvel() { assertThat(p.getAge()).isEqualTo(41); } - @Test - public void testPropertyReactivityMvelWithUpdate() { + @ParameterizedTest + @MethodSource("parameters") + public void testPropertyReactivityMvelWithUpdate(RUN_TYPE runType) { final String str = "import " + Person.class.getCanonicalName() + ";\n" + "\n" + @@ -119,7 +120,7 @@ public void testPropertyReactivityMvelWithUpdate() { " update($p);\n" + "end\n"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); Person p = new Person("Mario", 40); ksession.insert( p ); @@ -128,8 +129,9 @@ public void testPropertyReactivityMvelWithUpdate() { assertThat(p.getAge()).isEqualTo(41); } - @Test - public void testWatch() { + @ParameterizedTest + @MethodSource("parameters") + public void testWatch(RUN_TYPE runType) { final String str = "import " + Person.class.getCanonicalName() + ";\n" + "\n" + @@ -139,7 +141,7 @@ public void testWatch() { " modify($p) { setAge( $p.getAge()+1 ) };\n" + "end\n"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); Person p = new Person("Mario", 40); ksession.insert( p ); @@ -148,8 +150,9 @@ public void testWatch() { assertThat(p.getAge()).isEqualTo(41); } - @Test - public void testWatchAll() { + @ParameterizedTest + @MethodSource("parameters") + public void testWatchAll(RUN_TYPE runType) { // DROOLS-4509 final String str = @@ -161,7 +164,7 @@ public void testWatchAll() { " modify($p) { setAge( $p.getAge()+1 ) };\n" + "end\n"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); Person p = new Person("Mario", 40); ksession.insert( p ); @@ -170,8 +173,9 @@ public void testWatchAll() { assertThat(p.getAge()).isEqualTo(50); } - @Test - public void testWatchAllBeforeBeta() { + @ParameterizedTest + @MethodSource("parameters") + public void testWatchAllBeforeBeta(RUN_TYPE runType) { // DROOLS-4509 final String str = @@ -185,7 +189,7 @@ public void testWatchAllBeforeBeta() { " modify($p) { setAge( $p.getAge()+1 ) };\n" + "end\n"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); Person p = new Person("Mario", 40); ksession.insert( p ); @@ -195,8 +199,9 @@ public void testWatchAllBeforeBeta() { assertThat(p.getAge()).isEqualTo(50); } - @Test - public void testWatchAllBeforeFrom() { + @ParameterizedTest + @MethodSource("parameters") + public void testWatchAllBeforeFrom(RUN_TYPE runType) { // DROOLS-4509 final String str = @@ -210,7 +215,7 @@ public void testWatchAllBeforeFrom() { " modify($p) { setAge( $p.getAge()+1 ) };\n" + "end\n"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); Person p = new Person("Mario", 40); p.addAddress( new Address( "Milan" ) ); @@ -221,8 +226,9 @@ public void testWatchAllBeforeFrom() { assertThat(p.getAge()).isEqualTo(50); } - @Test - public void testImplicitWatch() { + @ParameterizedTest + @MethodSource("parameters") + public void testImplicitWatch(RUN_TYPE runType) { String str = "import " + Result.class.getCanonicalName() + ";" + "import " + Person.class.getCanonicalName() + ";" + @@ -234,7 +240,7 @@ public void testImplicitWatch() { " $r.setValue($p2.getName() + \" is older than \" + $p1.getName());\n" + "end"; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); Result result = new Result(); ksession.insert(result); @@ -262,8 +268,9 @@ public void testImplicitWatch() { assertThat(result.getValue()).isEqualTo("Edson is older than Mark"); } - @Test - public void testImplicitWatchWithDeclaration() { + @ParameterizedTest + @MethodSource("parameters") + public void testImplicitWatchWithDeclaration(RUN_TYPE runType) { String str = "import " + Result.class.getCanonicalName() + ";" + "import " + Person.class.getCanonicalName() + ";" + @@ -275,7 +282,7 @@ public void testImplicitWatchWithDeclaration() { " $r.setValue($p2.getName() + \" is older than \" + $p1.getName());\n" + "end"; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); Result result = new Result(); ksession.insert(result); @@ -303,8 +310,9 @@ public void testImplicitWatchWithDeclaration() { assertThat(result.getValue()).isEqualTo("Edson is older than Mark"); } - @Test - public void testImmutableField() { + @ParameterizedTest + @MethodSource("parameters") + public void testImmutableField(RUN_TYPE runType) { final String str = "declare Integer @propertyReactive end\n" + "declare Long @propertyReactive end\n" + @@ -314,16 +322,17 @@ public void testImmutableField() { "then\n" + "end\n"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); ksession.insert( 42 ); ksession.insert( 42L ); assertThat(ksession.fireAllRules()).isEqualTo(1); } - - @Test(timeout = 5000L) - public void testPRAfterAccumulate() { + @ParameterizedTest + @MethodSource("parameters") + @Timeout(5000) + public void testPRAfterAccumulate(RUN_TYPE runType) { // DROOLS-2427 final String str = "import " + Order.class.getCanonicalName() + "\n" + @@ -338,7 +347,7 @@ public void testPRAfterAccumulate() { " modify($o) { setPrice(10) }\n" + "end\n"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); Order order = new Order( Arrays.asList(new OrderLine( 9 ), new OrderLine( 8 )), 12 ); ksession.insert( order ); @@ -396,8 +405,10 @@ public String getValue() { public void setValue(String value) {} } - @Test(timeout = 5000L) - public void testPRWithAddOnList() { + @ParameterizedTest + @MethodSource("parameters") + @Timeout(5000) + public void testPRWithAddOnList(RUN_TYPE runType) { final String str = "import " + Bean.class.getCanonicalName() + "\n" + "rule R when\n" + @@ -407,14 +418,15 @@ public void testPRWithAddOnList() { " update($b);\n" + "end\n"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); ksession.insert( new Bean() ); assertThat(ksession.fireAllRules()).isEqualTo(1); } - @Test - public void testPRWithUpdateOnList() { + @ParameterizedTest + @MethodSource("parameters") + public void testPRWithUpdateOnList(RUN_TYPE runType) { final String str = "import " + List.class.getCanonicalName() + "\n" + "rule R1 when\n" + @@ -428,14 +440,15 @@ public void testPRWithUpdateOnList() { "then\n" + "end\n"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); ksession.insert( new ArrayList() ); assertThat(ksession.fireAllRules()).isEqualTo(1); } - @Test - public void testPROnAtomic() { + @ParameterizedTest + @MethodSource("parameters") + public void testPROnAtomic(RUN_TYPE runType) { final String str = "import " + AtomicInteger.class.getCanonicalName() + "\n" + "rule R2 when\n" + @@ -446,33 +459,41 @@ public void testPROnAtomic() { " update($i);" + "end\n"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); ksession.insert(new AtomicInteger(0)); assertThat(ksession.fireAllRules()).isEqualTo(3); } - @Test(timeout = 10000L) - public void testPropertyReactivityWith2Rules() { - checkPropertyReactivityWith2Rules( "age == 41\n" ); + @ParameterizedTest + @MethodSource("parameters") + @Timeout(10000) + public void testPropertyReactivityWith2Rules(RUN_TYPE runType) { + checkPropertyReactivityWith2Rules(runType, "age == 41\n"); } - @Test(timeout = 10000L) - public void testPropertyReactivityWith2RulesUsingAccessor() { - checkPropertyReactivityWith2Rules( "getAge() == 41\n" ); + @ParameterizedTest + @MethodSource("parameters") + @Timeout(10000) + public void testPropertyReactivityWith2RulesUsingAccessor(RUN_TYPE runType) { + checkPropertyReactivityWith2Rules(runType, "getAge() == 41\n"); } - @Test(timeout = 10000L) - public void testPropertyReactivityWith2RulesLiteralFirst() { - checkPropertyReactivityWith2Rules( "41 == age\n" ); + @ParameterizedTest + @MethodSource("parameters") + @Timeout(10000) + public void testPropertyReactivityWith2RulesLiteralFirst(RUN_TYPE runType) { + checkPropertyReactivityWith2Rules(runType, "41 == age\n"); } - @Test(timeout = 10000L) - public void testPropertyReactivityWith2RulesLiteralFirstUsingAccessor() { - checkPropertyReactivityWith2Rules( "41 == getAge()\n" ); + @ParameterizedTest + @MethodSource("parameters") + @Timeout(10000) + public void testPropertyReactivityWith2RulesLiteralFirstUsingAccessor(RUN_TYPE runType) { + checkPropertyReactivityWith2Rules(runType, "41 == getAge()\n"); } - private void checkPropertyReactivityWith2Rules( String constraint ) { + private void checkPropertyReactivityWith2Rules(RUN_TYPE runType, String constraint) { final String str = "import " + Person.class.getCanonicalName() + ";\n" + "\n" + @@ -487,7 +508,7 @@ private void checkPropertyReactivityWith2Rules( String constraint ) { " modify($p) { setEmployed( true ) };\n" + "end\n"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); Person p = new Person( "Mario", 40 ); ksession.insert( p ); @@ -497,8 +518,9 @@ private void checkPropertyReactivityWith2Rules( String constraint ) { assertThat(p.getEmployed()).isTrue(); } - @Test - public void testReassignment() { + @ParameterizedTest + @MethodSource("parameters") + public void testReassignment(RUN_TYPE runType) { // DROOLS-4884 final String str = "package com.example\n" + @@ -523,13 +545,14 @@ public void testReassignment() { " update($c);\n" + "end\n\n"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); assertThat(ksession.fireAllRules(5)).isEqualTo(5); } - @Test - public void testReassignment2() { + @ParameterizedTest + @MethodSource("parameters") + public void testReassignment2(RUN_TYPE runType) { // DROOLS-4884 final String str = "package com.example\n" + @@ -554,13 +577,14 @@ public void testReassignment2() { " update($c);\n" + "end\n\n"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); assertThat(ksession.fireAllRules(5)).isEqualTo(2); } - @Test - public void testMultipleFieldUpdate() { + @ParameterizedTest + @MethodSource("parameters") + public void testMultipleFieldUpdate(RUN_TYPE runType) { final String str = "import " + Person.class.getCanonicalName() + ";\n" + "\n" + @@ -575,7 +599,7 @@ public void testMultipleFieldUpdate() { " modify($p) { setAge( $p.getAge()+1 ) };\n" + "end\n"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); Person p = new Person("Mario", 40); p.setLikes("Beer"); @@ -585,8 +609,9 @@ public void testMultipleFieldUpdate() { assertThat(p.getAge()).isEqualTo(42); } - @Test - public void testComplexSetterArgument() { + @ParameterizedTest + @MethodSource("parameters") + public void testComplexSetterArgument(RUN_TYPE runType) { String str = "import " + Person.class.getCanonicalName() + ";" + "rule R \n" + @@ -596,7 +621,7 @@ public void testComplexSetterArgument() { " modify($p) { setLikes( String.valueOf(($p.getAddress().getStreet() + $p.getAddress().getCity()))) };\n" + "end"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); Person me = new Person( "Mario", 40 ); me.setAddress(new Address("street1", 2, "city1")); @@ -607,8 +632,9 @@ public void testComplexSetterArgument() { assertThat(me.getLikes()).isEqualTo("street1city1"); } - @Test - public void thisWithGetter() { + @ParameterizedTest + @MethodSource("parameters") + public void thisWithGetter(RUN_TYPE runType) { String str = "import " + Person.class.getCanonicalName() + ";" + "rule R \n" + @@ -618,7 +644,7 @@ public void thisWithGetter() { " modify($p) { setLikes(\"Cheese\") };\n" + "end"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); Person me = new Person( "Mario", 40 ); me.setAddress(new Address("street1", 2, "city1")); @@ -627,8 +653,9 @@ public void thisWithGetter() { assertThat(ksession.fireAllRules(10)).as("should not loop").isEqualTo(1); } - @Test - public void nullSafeDereferencing() { + @ParameterizedTest + @MethodSource("parameters") + public void nullSafeDereferencing(RUN_TYPE runType) { String str = "import " + Person.class.getCanonicalName() + ";" + "rule R \n" + @@ -638,7 +665,7 @@ public void nullSafeDereferencing() { " modify($p) { setLikes(\"Cheese\") };\n" + "end"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); Person me = new Person( "Mario", 40 ); me.setAddress(new Address("street1", 2, "city1")); @@ -647,8 +674,9 @@ public void nullSafeDereferencing() { assertThat(ksession.fireAllRules(10)).as("should not loop").isEqualTo(1); } - @Test - public void testNestedPropInRHS() throws Exception { + @ParameterizedTest + @MethodSource("parameters") + public void testNestedPropInRHS(RUN_TYPE runType) throws Exception { // Property Reactivity for "owner" final String str = "package org.drools.test;\n" + @@ -665,7 +693,7 @@ public void testNestedPropInRHS() throws Exception { "then\n" + "end"; - final KieSession ksession = getKieSession(str); + final KieSession ksession = getKieSession(runType, str); Pet pet = new Pet(Pet.PetType.cat); Person person = new Person("John"); @@ -677,8 +705,9 @@ public void testNestedPropInRHS() throws Exception { assertThat(ksession.fireAllRules()).isEqualTo(2); } - @Test - public void testDeeplyNestedPropInRHS() throws Exception { + @ParameterizedTest + @MethodSource("parameters") + public void testDeeplyNestedPropInRHS(RUN_TYPE runType) throws Exception { // Property Reactivity for "owner" final String str = "package org.drools.test;\n" + @@ -695,7 +724,7 @@ public void testDeeplyNestedPropInRHS() throws Exception { "then\n" + "end"; - final KieSession ksession = getKieSession(str); + final KieSession ksession = getKieSession(runType, str); Pet pet = new Pet(Pet.PetType.cat); Person person = new Person("John"); @@ -707,8 +736,9 @@ public void testDeeplyNestedPropInRHS() throws Exception { assertThat(ksession.fireAllRules()).isEqualTo(2); } - @Test - public void testOutsideModifyBlockWithGetterAsArgument() { + @ParameterizedTest + @MethodSource("parameters") + public void testOutsideModifyBlockWithGetterAsArgument(RUN_TYPE runType) { final String str = "import " + Person.class.getCanonicalName() + ";\n" + "\n" + @@ -719,7 +749,7 @@ public void testOutsideModifyBlockWithGetterAsArgument() { " modify($p) { setAge(41) };\n" + "end\n"; - final KieSession ksession = getKieSession(str); + final KieSession ksession = getKieSession(runType, str); Person p = new Person("Mario", 40); ksession.insert(p); @@ -729,8 +759,9 @@ public void testOutsideModifyBlockWithGetterAsArgument() { assertThat(p.getAge()).isEqualTo(41); } - @Test - public void testOutsideModifyBlockWithNonGetterAsArgument() { + @ParameterizedTest + @MethodSource("parameters") + public void testOutsideModifyBlockWithNonGetterAsArgument(RUN_TYPE runType) { final String str = "import " + Person.class.getCanonicalName() + ";\n" + "\n" + @@ -741,7 +772,7 @@ public void testOutsideModifyBlockWithNonGetterAsArgument() { " modify($p) { setAge(41) };\n" + "end\n"; - final KieSession ksession = getKieSession(str); + final KieSession ksession = getKieSession(runType, str); Person p = new Person("Mario", 40); ksession.insert(p); @@ -751,8 +782,9 @@ public void testOutsideModifyBlockWithNonGetterAsArgument() { assertThat(p.getAge()).isEqualTo(41); } - @Test - public void testMultipleModifyBlocksWithNonGetterAsArgument() { + @ParameterizedTest + @MethodSource("parameters") + public void testMultipleModifyBlocksWithNonGetterAsArgument(RUN_TYPE runType) { final String str = "import " + Person.class.getCanonicalName() + ";\n" + "import " + Address.class.getCanonicalName() + ";\n" + @@ -768,7 +800,7 @@ public void testMultipleModifyBlocksWithNonGetterAsArgument() { " modify($a) { setNumber(20) };\n" + "end\n"; - final KieSession ksession = getKieSession(str); + final KieSession ksession = getKieSession(runType, str); Person p = new Person("Mario", 40); ksession.insert(p); @@ -783,8 +815,9 @@ public void testMultipleModifyBlocksWithNonGetterAsArgument() { assertThat(a.getNumber()).isEqualTo(20); } - @Test - public void testUpdateWithGetterAsArgument() { + @ParameterizedTest + @MethodSource("parameters") + public void testUpdateWithGetterAsArgument(RUN_TYPE runType) { final String str = "import " + Person.class.getCanonicalName() + ";\n" + "\n" + @@ -796,7 +829,7 @@ public void testUpdateWithGetterAsArgument() { " update($p);\n" + "end\n"; - final KieSession ksession = getKieSession(str); + final KieSession ksession = getKieSession(runType, str); Person p = new Person("Mario", 40); ksession.insert(p); @@ -806,8 +839,9 @@ public void testUpdateWithGetterAsArgument() { assertThat(p.getAge()).isEqualTo(41); } - @Test - public void testUpdateWithNonGetterAsArgument() { + @ParameterizedTest + @MethodSource("parameters") + public void testUpdateWithNonGetterAsArgument(RUN_TYPE runType) { final String str = "import " + Person.class.getCanonicalName() + ";\n" + "\n" + @@ -819,7 +853,7 @@ public void testUpdateWithNonGetterAsArgument() { " update($p);\n" + "end\n"; - final KieSession ksession = getKieSession(str); + final KieSession ksession = getKieSession(runType, str); Person p = new Person("Mario", 40); ksession.insert(p); @@ -829,8 +863,9 @@ public void testUpdateWithNonGetterAsArgument() { assertThat(p.getAge()).isEqualTo(41); } - @Test - public void testUpdateWithNonGetterAsDeclaration() { + @ParameterizedTest + @MethodSource("parameters") + public void testUpdateWithNonGetterAsDeclaration(RUN_TYPE runType) { final String str = "import " + Person.class.getCanonicalName() + ";\n" + "\n" + @@ -843,7 +878,7 @@ public void testUpdateWithNonGetterAsDeclaration() { " update($p);\n" + "end\n"; - final KieSession ksession = getKieSession(str); + final KieSession ksession = getKieSession(runType, str); Person p = new Person("Mario", 40); ksession.insert(p); @@ -853,8 +888,9 @@ public void testUpdateWithNonGetterAsDeclaration() { assertThat(p.getAge()).isEqualTo(41); } - @Test - public void testUpdateWithNonGetterIntentinalLoop() { + @ParameterizedTest + @MethodSource("parameters") + public void testUpdateWithNonGetterIntentinalLoop(RUN_TYPE runType) { final String str = "import " + Person.class.getCanonicalName() + ";\n" + "\n" + @@ -866,7 +902,7 @@ public void testUpdateWithNonGetterIntentinalLoop() { " update($p);\n" + "end\n"; - final KieSession ksession = getKieSession(str); + final KieSession ksession = getKieSession(runType, str); Person p = new Person("Mario", 40); ksession.insert(p); @@ -879,8 +915,9 @@ public void testUpdateWithNonGetterIntentinalLoop() { assertThat(p.getAge()).isEqualTo(41); } - @Test - public void testPropertyReactivityOnBoundVariable() { + @ParameterizedTest + @MethodSource("parameters") + public void testPropertyReactivityOnBoundVariable(RUN_TYPE runType) { // RHDM-1387 final String str = "import " + Person.class.getCanonicalName() + ";\n" + @@ -891,7 +928,7 @@ public void testPropertyReactivityOnBoundVariable() { " modify($p) { setAge( $p.getAge()+1 ) };\n" + "end\n"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); Person p = new Person("Mario", 40); ksession.insert( p ); @@ -904,8 +941,9 @@ public static int dummy(int i) { return i; } - @Test - public void testWatchCallingExternalMethod() { + @ParameterizedTest + @MethodSource("parameters") + public void testWatchCallingExternalMethod(RUN_TYPE runType) { // DROOLS-5514 final String str = "import static " + this.getClass().getCanonicalName() + ".dummy;\n" + @@ -917,7 +955,7 @@ public void testWatchCallingExternalMethod() { " modify($p) { setAge( $p.getAge()+1 ) };\n" + "end\n"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); Person p = new Person("Mario", 40); ksession.insert( p ); @@ -926,8 +964,9 @@ public void testWatchCallingExternalMethod() { assertThat(p.getAge()).isEqualTo(50); } - @Test - public void testWatchCallingExternalMethod2() { + @ParameterizedTest + @MethodSource("parameters") + public void testWatchCallingExternalMethod2(RUN_TYPE runType) { // DROOLS-5514 final String str = "import static " + this.getClass().getCanonicalName() + ".dummy;\n" + @@ -939,7 +978,7 @@ public void testWatchCallingExternalMethod2() { " modify($p) { setName( $p.getName()+\"1\" ) };\n" + "end\n"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); Person p = new Person("Mario", 40); ksession.insert( p ); @@ -948,8 +987,9 @@ public void testWatchCallingExternalMethod2() { assertThat(p.getName()).isEqualTo("Mario111"); } - @Test - public void testWatchCallingExternalMethod3() { + @ParameterizedTest + @MethodSource("parameters") + public void testWatchCallingExternalMethod3(RUN_TYPE runType) { // DROOLS-5514 final String str = "import static " + this.getClass().getCanonicalName() + ".dummy;\n" + @@ -961,7 +1001,7 @@ public void testWatchCallingExternalMethod3() { " modify($p) { setName( $p.getName()+\"1\" ) };\n" + "end\n"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); Person p = new Person("Mario", 40); ksession.insert( p ); @@ -970,8 +1010,9 @@ public void testWatchCallingExternalMethod3() { assertThat(p.getName()).isEqualTo("Mario1"); } - @Test - public void test2PropertiesInOneExpression() { + @ParameterizedTest + @MethodSource("parameters") + public void test2PropertiesInOneExpression(RUN_TYPE runType) { // DROOLS-5677 final String str = "import " + Person.class.getCanonicalName() + ";\n" + @@ -998,7 +1039,7 @@ public void test2PropertiesInOneExpression() { " modify($p) { setSalary( 100 ) };\n" + "end\n"; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); Person p = new Person("John", 0); p.setSalary(0); @@ -1011,8 +1052,9 @@ public void test2PropertiesInOneExpression() { assertThat(p.getSalary().intValue()).isEqualTo(20); // R2 should be cancelled } - @Test - public void test3PropertiesInOneExpression() { + @ParameterizedTest + @MethodSource("parameters") + public void test3PropertiesInOneExpression(RUN_TYPE runType) { // DROOLS-5677 final String str = "import " + Person.class.getCanonicalName() + ";\n" + @@ -1046,7 +1088,7 @@ public void test3PropertiesInOneExpression() { " modify($p) { setSalary( 100 ) };\n" + "end\n"; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); Person p = new Person("John", 0); p.setSalary(0); @@ -1109,8 +1151,9 @@ public static String convertToString(int num) { return "BIG"; } - @Test - public void testExternalFunction() { + @ParameterizedTest + @MethodSource("parameters") + public void testExternalFunction(RUN_TYPE runType) { // BAPL-1773 final String str = "import " + Fact.class.getCanonicalName() + ";\n" + @@ -1122,7 +1165,7 @@ public void testExternalFunction() { " modify($fact) { setResult(\"OK\") };\n" + "end\n"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); Fact fact = new Fact(); fact.setA(99999); @@ -1133,8 +1176,9 @@ public void testExternalFunction() { assertThat(fact.getResult()).isEqualTo("OK"); } - @Test - public void testExternalFunction2() { + @ParameterizedTest + @MethodSource("parameters") + public void testExternalFunction2(RUN_TYPE runType) { // BAPL-1773 final String str = "import " + Fact.class.getCanonicalName() + ";\n" + @@ -1146,7 +1190,7 @@ public void testExternalFunction2() { " modify($fact) { setA(99999) };\n" + "end\n"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); Fact fact = new Fact(); fact.setA(99999); @@ -1156,8 +1200,9 @@ public void testExternalFunction2() { assertThat(ksession.fireAllRules(3)).isEqualTo(3); } - @Test - public void externalFunctionWithBindVariable_shouldNotCauseInfiniteLoop() { + @ParameterizedTest + @MethodSource("parameters") + public void externalFunctionWithBindVariable_shouldNotCauseInfiniteLoop(RUN_TYPE runType) { // DROOLS-7372 final String str = "import " + Fact.class.getCanonicalName() + ";\n" + "import static " + PropertyReactivityTest.class.getCanonicalName() + ".*;\n" + @@ -1168,7 +1213,7 @@ public void externalFunctionWithBindVariable_shouldNotCauseInfiniteLoop() { " modify($fact) { setResult(\"OK\") };\n" + "end\n"; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); Fact bigString = new Fact(); bigString.setA(99999); @@ -1181,8 +1226,9 @@ public void externalFunctionWithBindVariable_shouldNotCauseInfiniteLoop() { assertThat(bigString.getResult()).isEqualTo("OK"); } - @Test - public void externalFunctionWithBindVariableFromAnotherPatternOfSameType_shouldTriggerClassReactive() { + @ParameterizedTest + @MethodSource("parameters") + public void externalFunctionWithBindVariableFromAnotherPatternOfSameType_shouldTriggerClassReactive(RUN_TYPE runType) { // DROOLS-7398 final String str = "import " + Fact.class.getCanonicalName() + ";\n" + @@ -1194,7 +1240,7 @@ public void externalFunctionWithBindVariableFromAnotherPatternOfSameType_shouldT " modify($fact2) { setResult(\"OK\") };\n" + "end\n"; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); Fact bigStringFact = new Fact(); bigStringFact.setA(99999); @@ -1206,8 +1252,9 @@ public void externalFunctionWithBindVariableFromAnotherPatternOfSameType_shouldT .isEqualTo(10); } - @Test - public void multipleExternalFunctionsWithBindVariablesFromAnotherPatternOfSameType_shouldTriggerClassReactive() { + @ParameterizedTest + @MethodSource("parameters") + public void multipleExternalFunctionsWithBindVariablesFromAnotherPatternOfSameType_shouldTriggerClassReactive(RUN_TYPE runType) { // DROOLS-7398 final String str = "import " + Fact.class.getCanonicalName() + ";\n" + @@ -1219,7 +1266,7 @@ public void multipleExternalFunctionsWithBindVariablesFromAnotherPatternOfSameTy " modify($fact2) { setResult(\"OK\") };\n" + "end\n"; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); Fact bigStringFact = new Fact(); bigStringFact.setA(99999); @@ -1232,8 +1279,9 @@ public void multipleExternalFunctionsWithBindVariablesFromAnotherPatternOfSameTy .isEqualTo(10); } - @Test - public void externalFunctionWithBindVariableFromAnotherPatternOfDifferentType_shouldTriggerClassReactive() { + @ParameterizedTest + @MethodSource("parameters") + public void externalFunctionWithBindVariableFromAnotherPatternOfDifferentType_shouldTriggerClassReactive(RUN_TYPE runType) { // DROOLS-7390 final String str = "import " + Fact.class.getCanonicalName() + ";\n" + @@ -1246,7 +1294,7 @@ public void externalFunctionWithBindVariableFromAnotherPatternOfDifferentType_sh " modify($fact2) { setResult(\"OK\") };\n" + "end\n"; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); AnotherFact bigStringAnotherFact = new AnotherFact(); bigStringAnotherFact.setA(99999); @@ -1262,8 +1310,9 @@ public void externalFunctionWithBindVariableFromAnotherPatternOfDifferentType_sh .isEqualTo(10); } - @Test - public void testUnwatch() { + @ParameterizedTest + @MethodSource("parameters") + public void testUnwatch(RUN_TYPE runType) { // RHDM-1553 final String str = "import " + Person.class.getCanonicalName() + ";\n" + @@ -1274,7 +1323,7 @@ public void testUnwatch() { " modify($p) { setAge( $p.getAge() + 1 ) };\n" + "end\n"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); Person p = new Person("Mario", 40); ksession.insert( p ); @@ -1283,8 +1332,9 @@ public void testUnwatch() { assertThat(p.getAge()).isEqualTo(41); } - @Test - public void testUnwatchWithFieldBinding() { + @ParameterizedTest + @MethodSource("parameters") + public void testUnwatchWithFieldBinding(RUN_TYPE runType) { // RHDM-1553 final String str = "import " + Person.class.getCanonicalName() + ";\n" + @@ -1295,7 +1345,7 @@ public void testUnwatchWithFieldBinding() { " modify($p) { setAge( $age + 1 ) };\n" + "end\n"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); Person p = new Person("Mario", 40); ksession.insert( p ); @@ -1304,8 +1354,9 @@ public void testUnwatchWithFieldBinding() { assertThat(p.getAge()).isEqualTo(41); } - @Test - public void testUnwatchWithFieldBindingAndMvel() { + @ParameterizedTest + @MethodSource("parameters") + public void testUnwatchWithFieldBindingAndMvel(RUN_TYPE runType) { // RHDM-1553 final String str = "import " + Person.class.getCanonicalName() + ";\n" + @@ -1316,7 +1367,7 @@ public void testUnwatchWithFieldBindingAndMvel() { " modify($p) { age = $age + 1 };\n" + "end\n"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); Person p = new Person("Mario", 40); ksession.insert( p ); @@ -1325,8 +1376,9 @@ public void testUnwatchWithFieldBindingAndMvel() { assertThat(p.getAge()).isEqualTo(41); } - @Test - public void testUnwatchWithWatchedField() { + @ParameterizedTest + @MethodSource("parameters") + public void testUnwatchWithWatchedField(RUN_TYPE runType) { // RHDM-1553 final String str = "import " + Person.class.getCanonicalName() + ";\n" + @@ -1337,7 +1389,7 @@ public void testUnwatchWithWatchedField() { " modify($p) { setAge( $p.getAge() + 1 ) };\n" + "end\n"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); Person p = new Person("Mario", 40); ksession.insert( p ); @@ -1346,8 +1398,9 @@ public void testUnwatchWithWatchedField() { assertThat(p.getAge()).isEqualTo(43); } - @Test - public void testNoConstraint() { + @ParameterizedTest + @MethodSource("parameters") + public void testNoConstraint(RUN_TYPE runType) { final String str = "import " + Person.class.getCanonicalName() + ";\n" + "\n" + @@ -1357,7 +1410,7 @@ public void testNoConstraint() { " modify($p) { setAge( $p.getAge()+1 ) };\n" + "end\n"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); Person p = new Person("Mario", 40); ksession.insert( p ); @@ -1366,8 +1419,9 @@ public void testNoConstraint() { assertThat(p.getAge()).isEqualTo(41); } - @Test - public void testNoConstraintWithUpdate() { + @ParameterizedTest + @MethodSource("parameters") + public void testNoConstraintWithUpdate(RUN_TYPE runType) { final String str = "import " + Person.class.getCanonicalName() + ";\n" + "\n" + @@ -1378,7 +1432,7 @@ public void testNoConstraintWithUpdate() { " update($p);\n" + "end\n"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); Person p = new Person("Mario", 40); ksession.insert( p ); @@ -1387,8 +1441,9 @@ public void testNoConstraintWithUpdate() { assertThat(p.getAge()).isEqualTo(41); } - @Test - public void testModifiesAnnotation() { + @ParameterizedTest + @MethodSource("parameters") + public void testModifiesAnnotation(RUN_TYPE runType) { final String str = "import " + Light.class.getCanonicalName() + ";\n" + "\n" + @@ -1398,7 +1453,7 @@ public void testModifiesAnnotation() { " modify($l) { turnOn() };\n" + "end\n"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); Light l = new Light("Alert"); ksession.insert( l ); @@ -1437,8 +1492,9 @@ public void setName(String name) { } } - @Test - public void testSettersInAndOutModifyBlock() { + @ParameterizedTest + @MethodSource("parameters") + public void testSettersInAndOutModifyBlock(RUN_TYPE runType) { // RHDM-1552 final String str = "import " + Person.class.getCanonicalName() + ";\n" + @@ -1450,7 +1506,7 @@ public void testSettersInAndOutModifyBlock() { " modify($p) { setName( \"Mario\" ) };\n" + "end\n"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); Person p = new Person("Mario", 40); ksession.insert( p ); @@ -1459,8 +1515,9 @@ public void testSettersInAndOutModifyBlock() { assertThat(p.getAge()).isEqualTo(43); } - @Test - public void testSettersInAndOutModifyBlockMvel() { + @ParameterizedTest + @MethodSource("parameters") + public void testSettersInAndOutModifyBlockMvel(RUN_TYPE runType) { // RHDM-1552 final String str = "import " + Person.class.getCanonicalName() + ";\n" + @@ -1472,7 +1529,7 @@ public void testSettersInAndOutModifyBlockMvel() { " modify($p) { name = \"Mario\" };\n" + "end\n"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); Person p = new Person("Mario", 40); ksession.insert( p ); @@ -1481,8 +1538,9 @@ public void testSettersInAndOutModifyBlockMvel() { assertThat(p.getAge()).isEqualTo(43); } - @Test - public void testMvelModifyBlockWithComma() { + @ParameterizedTest + @MethodSource("parameters") + public void testMvelModifyBlockWithComma(RUN_TYPE runType) { // RHDM-1552 final String str = "import " + Person.class.getCanonicalName() + ";\n" + @@ -1493,7 +1551,7 @@ public void testMvelModifyBlockWithComma() { " modify($p) { setName(\"Mario\"), age = $p.age + 1 };\n" + "end\n"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); Person p = new Person("Mario", 40); ksession.insert( p ); @@ -1542,8 +1600,9 @@ private static class StackFrame { } } - @Test - public void testUpdateNonPropertyInMvel() { + @ParameterizedTest + @MethodSource("parameters") + public void testUpdateNonPropertyInMvel(RUN_TYPE runType) { // DROOLS-6096 final String str = "import " + AssessmentContext.class.getCanonicalName() + ";\n" + @@ -1567,7 +1626,7 @@ public void testUpdateNonPropertyInMvel() { " update($ac);\n" + "end\n"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); AssessmentContext ac1 = new AssessmentContext(); ac1.pushStackFrame(null); @@ -1578,8 +1637,9 @@ public void testUpdateNonPropertyInMvel() { assertThat(ksession.fireAllRules(2)).isEqualTo(2); } - @Test - public void testPropertyReactivityWithPublicField() { + @ParameterizedTest + @MethodSource("parameters") + public void testPropertyReactivityWithPublicField(RUN_TYPE runType) { final String str = "import " + Person.class.getCanonicalName() + ";\n" + "rule R1 when\n" + @@ -1596,7 +1656,7 @@ public void testPropertyReactivityWithPublicField() { "then\n" + "end\n"; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); Person p = new Person("John"); p.publicAge = 40; @@ -1607,8 +1667,9 @@ public void testPropertyReactivityWithPublicField() { assertThat(p.publicAge).isEqualTo(41); } - @Test - public void testUnknownPropertyNameInWatch() throws Exception { + @ParameterizedTest + @MethodSource("parameters") + public void testUnknownPropertyNameInWatch(RUN_TYPE runType) throws Exception { final String str = "import " + Person.class.getCanonicalName() + ";\n" + "global java.util.List result;\n" + @@ -1624,12 +1685,13 @@ public void testUnknownPropertyNameInWatch() throws Exception { " modify($p) { setAge(20) }\n" + "end\n"; - KieBuilder kbuilder = createKieBuilder(str); + KieBuilder kbuilder = createKieBuilder(runType, str); assertThat(kbuilder.getResults().hasMessages(Level.ERROR)).isTrue(); } - @Test - public void testSetterWithoutGetter() { + @ParameterizedTest + @MethodSource("parameters") + public void testSetterWithoutGetter(RUN_TYPE runType) { // DROOLS-6523 final String str = "import " + ClassWithValue.class.getCanonicalName() + ";\n" + @@ -1640,7 +1702,7 @@ public void testSetterWithoutGetter() { " update($cwv);\n" + "end\n"; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); ClassWithValue cwv = new ClassWithValue(); ksession.insert(cwv); @@ -1671,8 +1733,9 @@ public void addDoubleValue(double doubleValue) { } } - @Test - public void testPropertyReactivityOn2Properties() { + @ParameterizedTest + @MethodSource("parameters") + public void testPropertyReactivityOn2Properties(RUN_TYPE runType) { final String str = "import " + Person.class.getCanonicalName() + ";\n" + "\n" + @@ -1685,7 +1748,7 @@ public void testPropertyReactivityOn2Properties() { " };\n" + "end\n"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); Person p = new Person("Mario", 40); ksession.insert( p ); @@ -1695,8 +1758,9 @@ public void testPropertyReactivityOn2Properties() { assertThat(p.getId()).isEqualTo(1); } - @Test - public void testPropertyReactivityOn2PropertiesWithWrongSeparator() { + @ParameterizedTest + @MethodSource("parameters") + public void testPropertyReactivityOn2PropertiesWithWrongSeparator(RUN_TYPE runType) { // DROOLS-6480 final String str = "import " + Person.class.getCanonicalName() + ";\n" + @@ -1710,12 +1774,13 @@ public void testPropertyReactivityOn2PropertiesWithWrongSeparator() { " };\n" + "end\n"; - KieBuilder kbuilder = createKieBuilder(str); + KieBuilder kbuilder = createKieBuilder(runType, str); assertThat(kbuilder.getResults().hasMessages(Level.ERROR)).isTrue(); } - @Test - public void testMvelModifyAfterSingleQuote() { + @ParameterizedTest + @MethodSource("parameters") + public void testMvelModifyAfterSingleQuote(RUN_TYPE runType) { // DROOLS-6542 final String str = "import " + Person.class.getCanonicalName() + ";\n" + @@ -1733,7 +1798,7 @@ public void testMvelModifyAfterSingleQuote() { " insert(\"ok\");\n" + "end\n"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); Person p = new Person("Mario", 40); ksession.insert( p ); @@ -1743,38 +1808,43 @@ public void testMvelModifyAfterSingleQuote() { assertThat(ksession.getObjects((Object object) -> object.equals("ok")).size()).isEqualTo(1); } - @Test - public void testOnlyFirstLetterIsUpperCaseProperty() { + @ParameterizedTest + @MethodSource("parameters") + public void testOnlyFirstLetterIsUpperCaseProperty(RUN_TYPE runType) { // See JavaBeans 1.01 spec : 8.8 Capitalization of inferred names // “FooBah” becomes “fooBah” - testVariousCasePropFact("modify($f) { MyTarget = \"123\" };", "R1", "R2"); // Actually, this modifies "myTarget" property (backed by private "MyTarget" field). This shouldn't react R1 + testVariousCasePropFact(runType, "modify($f) { MyTarget = \"123\" };", "R1", "R2"); // Actually, this modifies "myTarget" property (backed by private "MyTarget" field). This shouldn't react R1 } - @Test - public void testTwoFirstLettersAreUpperCaseProperty() { + @ParameterizedTest + @MethodSource("parameters") + public void testTwoFirstLettersAreUpperCaseProperty(RUN_TYPE runType) { // See JavaBeans 1.01 spec : 8.8 Capitalization of inferred names // “URL” becomes “URL” - testVariousCasePropFact("modify($f) { URL = \"123\" };", "R1", "R2"); // This shouldn't react R1 + testVariousCasePropFact(runType, "modify($f) { URL = \"123\" };", "R1", "R2"); // This shouldn't react R1 } - @Test - public void testFirstLetterIsMultibyteProperty() { + @ParameterizedTest + @MethodSource("parameters") + public void testFirstLetterIsMultibyteProperty(RUN_TYPE runType) { // Multibyte is not mentioned in JavaBeans spec - testVariousCasePropFact("modify($f) { 名前 = \"123\" };", "R1", "R2"); // This shouldn't react R1 + testVariousCasePropFact(runType, "modify($f) { 名前 = \"123\" };", "R1", "R2"); // This shouldn't react R1 } - @Test - public void testOnlyFirstLetterIsUpperCaseAndMultibyteProperty() { + @ParameterizedTest + @MethodSource("parameters") + public void testOnlyFirstLetterIsUpperCaseAndMultibyteProperty(RUN_TYPE runType) { // Multibyte is not mentioned in JavaBeans spec - testVariousCasePropFact("modify($f) { My名前 = \"123\" };", "R1", "R2"); // Actually, this modifies "my名前" property (backed by private "My名前" field). This shouldn't react R1 + testVariousCasePropFact(runType, "modify($f) { My名前 = \"123\" };", "R1", "R2"); // Actually, this modifies "my名前" property (backed by private "My名前" field). This shouldn't react R1 } - @Test - public void testOnlyFirstLetterIsUpperCasePublicFieldProperty() { - testVariousCasePropFact("modify($f) { MyPublicTarget = \"123\" };", "R1", "R2"); // this modifies "MyPublicTarget" public field directly. This shouldn't react R1 + @ParameterizedTest + @MethodSource("parameters") + public void testOnlyFirstLetterIsUpperCasePublicFieldProperty(RUN_TYPE runType) { + testVariousCasePropFact(runType, "modify($f) { MyPublicTarget = \"123\" };", "R1", "R2"); // this modifies "MyPublicTarget" public field directly. This shouldn't react R1 } - private void testVariousCasePropFact(String modifyStatement, String... expectedResults) { + private void testVariousCasePropFact(RUN_TYPE runType, String modifyStatement, String... expectedResults) { final String str = "import " + VariousCasePropFact.class.getCanonicalName() + ";\n" + "dialect \"mvel\"\n" + @@ -1795,7 +1865,7 @@ private void testVariousCasePropFact(String modifyStatement, String... expectedR modifyStatement + "\n" + "end\n"; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); List results = new ArrayList<>(); ksession.setGlobal("results", results); @@ -1807,8 +1877,9 @@ private void testVariousCasePropFact(String modifyStatement, String... expectedR assertThat(results).containsExactly(expectedResults); } - @Test - public void bindOnlyPropertyReacts() { + @ParameterizedTest + @MethodSource("parameters") + public void bindOnlyPropertyReacts(RUN_TYPE runType) { // DROOLS-7214 final String str = "import " + Person.class.getCanonicalName() + ";\n" + @@ -1819,7 +1890,7 @@ public void bindOnlyPropertyReacts() { " modify($p) { age = $age + 1 };\n" + "end\n"; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); Person p = new Person("Mario", 40); ksession.insert(p); @@ -1828,8 +1899,9 @@ public void bindOnlyPropertyReacts() { assertThat(fired).isEqualTo(10); } - @Test - public void bindOnlyMapPropertyReacts() { + @ParameterizedTest + @MethodSource("parameters") + public void bindOnlyMapPropertyReacts(RUN_TYPE runType) { // DROOLS-7214 final String str = "import " + Person.class.getCanonicalName() + ";\n" + @@ -1841,7 +1913,7 @@ public void bindOnlyMapPropertyReacts() { " modify($p) { itemsString = $p.itemsString };\n" + "end\n"; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); Person p = new Person("Mario", 40); p.getItemsString().put("A", "itemA"); @@ -1851,8 +1923,9 @@ public void bindOnlyMapPropertyReacts() { assertThat(fired).isEqualTo(10); } - @Test - public void bindOnlyMapPropertyWithAccessOperatorReacts() { + @ParameterizedTest + @MethodSource("parameters") + public void bindOnlyMapPropertyWithAccessOperatorReacts(RUN_TYPE runType) { // DROOLS-7214 final String str = "import " + Person.class.getCanonicalName() + ";\n" + @@ -1864,7 +1937,7 @@ public void bindOnlyMapPropertyWithAccessOperatorReacts() { " modify($p) { itemsString = $p.itemsString };\n" + "end\n"; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); Person p = new Person("Mario", 40); p.getItemsString().put("A", "itemA"); @@ -1874,8 +1947,9 @@ public void bindOnlyMapPropertyWithAccessOperatorReacts() { assertThat(fired).isEqualTo(10); } - @Test - public void bindOnlyListPropertyWithAccessOperatorReacts() { + @ParameterizedTest + @MethodSource("parameters") + public void bindOnlyListPropertyWithAccessOperatorReacts(RUN_TYPE runType) { // DROOLS-7214 final String str = "import " + Person.class.getCanonicalName() + ";\n" + @@ -1888,7 +1962,7 @@ public void bindOnlyListPropertyWithAccessOperatorReacts() { " modify($p) { addresses = $p.addresses };\n" + "end\n"; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); Person p = new Person("Mario", 40); p.getAddresses().add(new Address("A")); @@ -1899,8 +1973,9 @@ public void bindOnlyListPropertyWithAccessOperatorReacts() { assertThat(fired).isEqualTo(10); } - @Test - public void testPropertyReactivityWithRedundantVariableDeclaration() { + @ParameterizedTest + @MethodSource("parameters") + public void testPropertyReactivityWithRedundantVariableDeclaration(RUN_TYPE runType) { // KIE-DROOLS-5943 final String str = "import " + Person.class.getCanonicalName() + ";\n" + @@ -1912,7 +1987,7 @@ public void testPropertyReactivityWithRedundantVariableDeclaration() { " update($p);\n" + "end\n"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); Person p = new Person("Mario", 40); ksession.insert( p ); diff --git a/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/PrototypeTest.java b/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/PrototypeTest.java index 7e3ccd1154d..05a4202a55a 100644 --- a/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/PrototypeTest.java +++ b/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/PrototypeTest.java @@ -49,7 +49,7 @@ import org.drools.model.prototype.PrototypeExpression; import org.drools.model.prototype.PrototypeVariable; import org.drools.modelcompiler.KieBaseBuilder; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.kie.api.KieBase; import org.kie.api.KieServices; import org.kie.api.conf.EventProcessingOption; diff --git a/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/PrototypesAllowedTest.java b/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/PrototypesAllowedTest.java index 28c257ea97e..1eb18501903 100644 --- a/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/PrototypesAllowedTest.java +++ b/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/PrototypesAllowedTest.java @@ -30,7 +30,7 @@ import org.drools.model.impl.ModelImpl; import org.drools.model.prototype.PrototypeVariable; import org.drools.modelcompiler.KieBaseBuilder; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.kie.api.KieBase; import org.kie.api.conf.PrototypesOption; import org.kie.api.io.ResourceType; diff --git a/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/QueryTest.java b/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/QueryTest.java index 65f5cc039af..e06419bf327 100644 --- a/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/QueryTest.java +++ b/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/QueryTest.java @@ -31,7 +31,8 @@ import org.drools.model.codegen.execmodel.domain.Result; import org.drools.model.codegen.execmodel.oopathdtables.InternationalAddress; import org.drools.model.codegen.execmodel.util.TrackingAgendaEventListener; -import org.junit.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; import org.kie.api.KieServices; import org.kie.api.command.Command; import org.kie.api.definition.type.FactType; @@ -46,12 +47,9 @@ public class QueryTest extends BaseModelTest { - public QueryTest( RUN_TYPE testRunType ) { - super( testRunType ); - } - - @Test - public void testQueryZeroArgs() { + @ParameterizedTest + @MethodSource("parameters") + public void testQueryZeroArgs(RUN_TYPE runType) { String str = "import " + Person.class.getCanonicalName() + ";" + "global java.lang.Integer ageG;" + @@ -59,7 +57,7 @@ public void testQueryZeroArgs() { " $p : Person(age > ageG)\n" + "end "; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); ksession.setGlobal("ageG", 40); @@ -75,15 +73,16 @@ public void testQueryZeroArgs() { } - @Test - public void testQueryOneArgument() { + @ParameterizedTest + @MethodSource("parameters") + public void testQueryOneArgument(RUN_TYPE runType) { String str = "import " + Person.class.getCanonicalName() + ";" + "query olderThan( int $age )\n" + " $p : Person(age > $age)\n" + "end "; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); ksession.insert( new Person( "Mark", 39 ) ); ksession.insert( new Person( "Mario", 41 ) ); @@ -95,15 +94,16 @@ public void testQueryOneArgument() { assertThat(p.getName()).isEqualTo("Mario"); } - @Test - public void testQueryOneArgumentWithoutType() { + @ParameterizedTest + @MethodSource("parameters") + public void testQueryOneArgumentWithoutType(RUN_TYPE runType) { String str = "import " + Person.class.getCanonicalName() + ";" + "query olderThan( $age )\n" + " $p : Person(age > (Integer)$age)\n" + "end "; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); ksession.insert( new Person( "Mark", 39 ) ); ksession.insert( new Person( "Mario", 41 ) ); @@ -115,8 +115,9 @@ public void testQueryOneArgumentWithoutType() { assertThat(p.getName()).isEqualTo("Mario"); } - @Test - public void testQueryInRule() { + @ParameterizedTest + @MethodSource("parameters") + public void testQueryInRule(RUN_TYPE runType) { String str = "import " + Result.class.getCanonicalName() + ";" + "import " + Person.class.getCanonicalName() + ";" + @@ -129,7 +130,7 @@ public void testQueryInRule() { " insert(new Result($p.getName()));\n" + "end"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); ksession.insert( new Person( "Mark", 39 ) ); ksession.insert( new Person( "Mario", 41 ) ); @@ -141,8 +142,9 @@ public void testQueryInRule() { assertThat(results.iterator().next().getValue()).isEqualTo("Mario"); } - @Test - public void testQueryInRuleWithDeclaration() { + @ParameterizedTest + @MethodSource("parameters") + public void testQueryInRuleWithDeclaration(RUN_TYPE runType) { String str = "import " + Result.class.getCanonicalName() + ";" + "import " + Person.class.getCanonicalName() + ";" + @@ -156,7 +158,7 @@ public void testQueryInRuleWithDeclaration() { " insert(new Result($p.getName()));\n" + "end"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); ksession.insert( new Person( "Mark", 39 ) ); ksession.insert( new Person( "Mario", 41 ) ); @@ -170,8 +172,9 @@ public void testQueryInRuleWithDeclaration() { } - @Test - public void testQueryInvokedWithGlobal() { + @ParameterizedTest + @MethodSource("parameters") + public void testQueryInvokedWithGlobal(RUN_TYPE runType) { String str = "import " + Result.class.getCanonicalName() + ";" + "import " + Person.class.getCanonicalName() + ";" + @@ -186,7 +189,7 @@ public void testQueryInvokedWithGlobal() { " insert(new Result($p.getName()));\n" + "end"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); ksession.setGlobal("ageG", 40); @@ -201,8 +204,9 @@ public void testQueryInvokedWithGlobal() { assertThat(results.iterator().next().getValue()).isEqualTo("Mario"); } - @Test - public void testNonPositionalQuery() { + @ParameterizedTest + @MethodSource("parameters") + public void testNonPositionalQuery(RUN_TYPE runType) { String str = "import " + Result.class.getCanonicalName() + ";" + "import " + Person.class.getCanonicalName() + ";" + @@ -210,7 +214,7 @@ public void testNonPositionalQuery() { " $p : Person(name == $n, age == $a)\n" + "end"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); ksession.insert( new Person( "Mark", 39 ) ); ksession.insert( new Person( "Mario", 41 ) ); @@ -222,15 +226,16 @@ public void testNonPositionalQuery() { assertThat(p.getName()).isEqualTo("Mario"); } - @Test - public void testPositionalQuery() { + @ParameterizedTest + @MethodSource("parameters") + public void testPositionalQuery(RUN_TYPE runType) { String str = "import " + Person.class.getCanonicalName() + ";" + "query findPerson( String $n, int $a )\n" + " $p : Person($n, $a;)\n" + "end"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); ksession.insert( new Person( "Mark", 39 ) ); ksession.insert( new Person( "Mario", 41 ) ); @@ -242,15 +247,16 @@ public void testPositionalQuery() { assertThat(p.getName()).isEqualTo("Mario"); } - @Test - public void testUnificationParameterInPattern() { + @ParameterizedTest + @MethodSource("parameters") + public void testUnificationParameterInPattern(RUN_TYPE runType) { String str = "import " + Person.class.getCanonicalName() + ";" + "query personsAges(int ages)\n" + "$p : Person(ages := age)\n" + "end\n"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); ksession.insert( new Person( "Mark", 39 ) ); ksession.insert( new Person( "Mario", 41 ) ); @@ -262,8 +268,9 @@ public void testUnificationParameterInPattern() { assertThat(p.getName()).isEqualTo("Mario"); } - @Test - public void testQueryCallingQuery() { + @ParameterizedTest + @MethodSource("parameters") + public void testQueryCallingQuery(RUN_TYPE runType) { String str = "import " + Relationship.class.getCanonicalName() + ";" + "query isRelatedTo(String x, String y)\n" + @@ -273,7 +280,7 @@ public void testQueryCallingQuery() { " Relationship(x, y;)\n" + "end"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); ksession.insert( new Relationship( "A", "B" ) ); ksession.insert( new Relationship( "B", "C" ) ); @@ -286,8 +293,9 @@ public void testQueryCallingQuery() { } - @Test - public void testQueryWithOOPath() { + @ParameterizedTest + @MethodSource("parameters") + public void testQueryWithOOPath(RUN_TYPE runType) { String str = "import " + java.util.List.class.getCanonicalName() + ";" + "import " + org.drools.model.codegen.execmodel.oopathdtables.Person.class.getCanonicalName() + ";" + @@ -297,7 +305,7 @@ public void testQueryWithOOPath() { "$cities : List() from accumulate (Person ( $city: /address#InternationalAddress[state == \"Safecountry\"]/city), collectList($city))\n" + "end"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); org.drools.model.codegen.execmodel.oopathdtables.Person person = new org.drools.model.codegen.execmodel.oopathdtables.Person(); person.setAddress(new InternationalAddress("", 1, "Milan", "Safecountry")); @@ -314,8 +322,9 @@ public void testQueryWithOOPath() { assertThat(cities.get(0)).isEqualTo("Milan"); } - @Test - public void testQueryWithOOPathTransformedToFrom() { + @ParameterizedTest + @MethodSource("parameters") + public void testQueryWithOOPathTransformedToFrom(RUN_TYPE runType) { String str = "import " + java.util.List.class.getCanonicalName() + ";" + "import " + org.drools.model.codegen.execmodel.oopathdtables.Person.class.getCanonicalName() + ";" + @@ -327,7 +336,7 @@ public void testQueryWithOOPathTransformedToFrom() { "$cities : List() from accumulate ($city : String() from $a.city, collectList($city))\n" + "end"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); org.drools.model.codegen.execmodel.oopathdtables.Person person = new org.drools.model.codegen.execmodel.oopathdtables.Person(); person.setAddress(new InternationalAddress("", 1, "Milan", "Safecountry")); @@ -344,8 +353,9 @@ public void testQueryWithOOPathTransformedToFrom() { assertThat(cities.get(0)).isEqualTo("Milan"); } - @Test - public void testQueryWithOOPathTransformedToFromInsideAcc() { + @ParameterizedTest + @MethodSource("parameters") + public void testQueryWithOOPathTransformedToFromInsideAcc(RUN_TYPE runType) { String str = "import " + java.util.List.class.getCanonicalName() + ";" + "import " + org.drools.model.codegen.execmodel.oopathdtables.Person.class.getCanonicalName() + ";" + @@ -358,7 +368,7 @@ public void testQueryWithOOPathTransformedToFromInsideAcc() { " $city : String() from $a.city, collectList($city))\n" + "end"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); org.drools.model.codegen.execmodel.oopathdtables.Person person2 = new org.drools.model.codegen.execmodel.oopathdtables.Person(); person2.setAddress(new InternationalAddress("", 1, "Rome", "Unsafecountry")); @@ -376,8 +386,9 @@ public void testQueryWithOOPathTransformedToFromInsideAcc() { assertThat(cities.get(0)).isEqualTo("Milan"); } - @Test - public void testPositionalRecursiveQueryWithUnification() { + @ParameterizedTest + @MethodSource("parameters") + public void testPositionalRecursiveQueryWithUnification(RUN_TYPE runType) { String str = "import " + Relationship.class.getCanonicalName() + ";" + "query isRelatedTo(String x, String y)\n" + @@ -386,7 +397,7 @@ public void testPositionalRecursiveQueryWithUnification() { " ( Relationship (z, y;) and ?isRelatedTo(x, z;))\n" + "end"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); ksession.insert( new Relationship( "A", "B" ) ); ksession.insert( new Relationship( "B", "C" ) ); @@ -400,8 +411,9 @@ public void testPositionalRecursiveQueryWithUnification() { assertThat("B".equals(resultDrlx)).isTrue(); } - @Test - public void testPositionalRecursiveQuery() throws Exception { + @ParameterizedTest + @MethodSource("parameters") + public void testPositionalRecursiveQuery(RUN_TYPE runType) throws Exception { String query = "query isContainedIn(String x, String y)\n" + " Location (x, y;)\n" + @@ -409,11 +421,12 @@ public void testPositionalRecursiveQuery() throws Exception { " ( Location (z, y;) and ?isContainedIn(x, z;))\n" + "end\n"; - checkRecursiveQuery( query ); + checkRecursiveQuery(runType, query); } - @Test - public void testUnificationRecursiveQuery() throws Exception { + @ParameterizedTest + @MethodSource("parameters") + public void testUnificationRecursiveQuery(RUN_TYPE runType) throws Exception { String query = "query isContainedIn(String x, String y)\n" + " Location( x := thing, y := location)\n" + @@ -421,10 +434,10 @@ public void testUnificationRecursiveQuery() throws Exception { " ( Location(z := thing, y := location) and ?isContainedIn( x := x, z := y ) )\n" + "end\n"; - checkRecursiveQuery( query ); + checkRecursiveQuery(runType, query); } - private void checkRecursiveQuery( String query ) throws InstantiationException, IllegalAccessException { + private void checkRecursiveQuery(RUN_TYPE runType , String query) throws InstantiationException, IllegalAccessException { String str = "package org.test;\n" + "import " + Person.class.getCanonicalName() + ";" + @@ -449,7 +462,7 @@ private void checkRecursiveQuery( String query ) throws InstantiationException, // "then\n" + // "end"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); FactType locationType = ksession.getKieBase().getFactType("org.test", "Location"); @@ -501,8 +514,9 @@ private void checkRecursiveQuery( String query ) throws InstantiationException, assertThat(listener.isRuleFired("testPushQueryRule")).isFalse(); } - @Test - public void testRecursiveQueryWithBatchCommand() throws Exception { + @ParameterizedTest + @MethodSource("parameters") + public void testRecursiveQueryWithBatchCommand(RUN_TYPE runType) throws Exception { String str = "package org.test;\n" + "import " + Person.class.getCanonicalName() + ";" + @@ -517,7 +531,7 @@ public void testRecursiveQueryWithBatchCommand() throws Exception { "end"; KieServices kieServices = KieServices.Factory.get(); - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); FactType locationType = ksession.getKieBase().getFactType("org.test", "Location"); @@ -576,8 +590,9 @@ public void testRecursiveQueryWithBatchCommand() throws Exception { assertThat(l.contains("key")).isTrue(); } - @Test - public void testQueryUnificationUnset() { + @ParameterizedTest + @MethodSource("parameters") + public void testQueryUnificationUnset(RUN_TYPE runType) { String str = "package drl;\n" + "declare Anon " + " cld : String @key " + @@ -618,12 +633,13 @@ public void testQueryUnificationUnset() { "then " + "end "; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); ksession.fireAllRules(); } - @Test - public void testQueryCalling2Queries() { + @ParameterizedTest + @MethodSource("parameters") + public void testQueryCalling2Queries(RUN_TYPE runType) { String str = "import " + Person.class.getCanonicalName() + ";" + "query isPersonOlderThan(Person p, int ageFrom)\n" + @@ -639,7 +655,7 @@ public void testQueryCalling2Queries() { "end\n" + "\n"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); ksession.insert( new Person( "Mark", 39 ) ); ksession.insert( new Person( "Mario", 41 ) ); @@ -651,15 +667,16 @@ public void testQueryCalling2Queries() { assertThat(p.getName()).isEqualTo("Mario"); } - @Test - public void testQueriesWithVariableUnification() throws Exception { + @ParameterizedTest + @MethodSource("parameters") + public void testQueriesWithVariableUnification(RUN_TYPE runType) throws Exception { String str = "import " + Person.class.getCanonicalName() + ";" + "query peeps( String $name, int $age ) \n" + " $p : Person( $name := name, $age := age ) \n" + "end\n"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); Person p1 = new Person( "darth", 100 ); Person p2 = new Person( "yoda", 300 ); @@ -704,8 +721,9 @@ public void testQueriesWithVariableUnification() throws Exception { assertThat(names.contains("darth")).isTrue(); } - @Test - public void testQueryWithUpdateOnFactHandle() throws Exception { + @ParameterizedTest + @MethodSource("parameters") + public void testQueryWithUpdateOnFactHandle(RUN_TYPE runType) throws Exception { String str = "global java.util.List list; " + "query foo( Integer $i ) " + @@ -727,7 +745,7 @@ public void testQueryWithUpdateOnFactHandle() throws Exception { "end\n" + "\n"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); final List list = new ArrayList<>(); ksession.setGlobal("list", list); @@ -742,8 +760,9 @@ public void testQueryWithUpdateOnFactHandle() throws Exception { assertThat((int) list.get(1)).isEqualTo(22); } - @Test - public void testQueryCallWithBindings() { + @ParameterizedTest + @MethodSource("parameters") + public void testQueryCallWithBindings(RUN_TYPE runType) { String str = "package org.drools.compiler.test \n" + "import " + Person.class.getCanonicalName() + "\n" + @@ -760,7 +779,7 @@ public void testQueryCallWithBindings() { " Person( $name := name, $age := age; ) \n" + "end\n"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); final List list = new ArrayList<>(); ksession.setGlobal("list", list); @@ -772,8 +791,9 @@ public void testQueryCallWithBindings() { assertThat(list.get(0)).isEqualTo("Mario : 44"); } - @Test - public void testQueryCallWithJoinInputAndOutput() { + @ParameterizedTest + @MethodSource("parameters") + public void testQueryCallWithJoinInputAndOutput(RUN_TYPE runType) { String str = "package org.drools.compiler.test \n" + "import " + Person.class.getCanonicalName() + "\n" + @@ -790,7 +810,7 @@ public void testQueryCallWithJoinInputAndOutput() { " list.add( $name1 + \" : \" + $age1 );\n" + "end \n"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); final List list = new ArrayList<>(); ksession.setGlobal("list", list); @@ -802,8 +822,9 @@ public void testQueryCallWithJoinInputAndOutput() { assertThat(list.get(0)).isEqualTo("Mario : 44"); } - @Test - public void testQueryWithDyanmicInsert() throws IOException, ClassNotFoundException { + @ParameterizedTest + @MethodSource("parameters") + public void testQueryWithDyanmicInsert(RUN_TYPE runType) throws IOException, ClassNotFoundException { String str = "package org.drools.compiler.test \n" + "import " + Person.class.getCanonicalName() + "\n" + @@ -820,7 +841,7 @@ public void testQueryWithDyanmicInsert() throws IOException, ClassNotFoundExcept " list.add( $p );\n" + "end \n"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); try { final List list = new ArrayList<>(); @@ -837,8 +858,9 @@ public void testQueryWithDyanmicInsert() throws IOException, ClassNotFoundExcept } } - @Test - public void testQuerySameNameBinding() throws IOException, ClassNotFoundException { + @ParameterizedTest + @MethodSource("parameters") + public void testQuerySameNameBinding(RUN_TYPE runType) throws IOException, ClassNotFoundException { String str = "package org.drools.compiler.test \n" + "import " + Person.class.getCanonicalName() + "\n" + @@ -847,7 +869,7 @@ public void testQuerySameNameBinding() throws IOException, ClassNotFoundExceptio " Person( name := name ) \n" + "end \n"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); ksession.insert( new Person("Mario", 44) ); ksession.insert( new Person("Mark", 40) ); @@ -870,8 +892,9 @@ public void testQuerySameNameBinding() throws IOException, ClassNotFoundExceptio assertThat(list.get(0)).isEqualTo("Mario"); } - @Test - public void testQuery10Args() throws IOException, ClassNotFoundException { + @ParameterizedTest + @MethodSource("parameters") + public void testQuery10Args(RUN_TYPE runType) throws IOException, ClassNotFoundException { String str = "package org.drools.compiler.test \n" + "import " + Person.class.getCanonicalName() + "\n" + @@ -880,7 +903,7 @@ public void testQuery10Args() throws IOException, ClassNotFoundException { " Person( name := name, age := age, ageLong := ageLong, id := id, likes := likes ) \n" + "end \n"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); Person mario = new Person("Mario", 44); mario.setAgeLong(44L); @@ -908,8 +931,9 @@ public void testQuery10Args() throws IOException, ClassNotFoundException { assertThat(list.get(0)).isEqualTo("Mario"); } - @Test - public void testPositionalQueryWithAccumulate() { + @ParameterizedTest + @MethodSource("parameters") + public void testPositionalQueryWithAccumulate(RUN_TYPE runType) { // DROOLS-6128 String str = "import " + Result.class.getCanonicalName() + ";" + @@ -930,7 +954,7 @@ public void testPositionalQueryWithAccumulate() { " ) \n" + "end"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); ksession.fireAllRules(); QueryResults results = ksession.getQueryResults( "accAge", "Mark" ); @@ -942,8 +966,9 @@ public void testPositionalQueryWithAccumulate() { assertThat(resultDrlx).isEqualTo(37); } - @Test - public void testPositionalQueryWithAmbigousName() { + @ParameterizedTest + @MethodSource("parameters") + public void testPositionalQueryWithAmbigousName(RUN_TYPE runType) { // DROOLS-6128 String str = "import " + Result.class.getCanonicalName() + ";" + @@ -964,7 +989,7 @@ public void testPositionalQueryWithAmbigousName() { " ) \n" + "end"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); ksession.fireAllRules(); QueryResults results = ksession.getQueryResults( "accAge", "Mark" ); @@ -976,8 +1001,9 @@ public void testPositionalQueryWithAmbigousName() { assertThat(resultDrlx).isEqualTo(37); } - @Test - public void testQueryWithAccumulateAndUnification() { + @ParameterizedTest + @MethodSource("parameters") + public void testQueryWithAccumulateAndUnification(RUN_TYPE runType) { // DROOLS-6105 String str = "import " + Result.class.getCanonicalName() + ";\n" + @@ -1005,7 +1031,7 @@ public void testQueryWithAccumulateAndUnification() { " result.add($sum);" + "end\n"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); List result = new ArrayList<>(); ksession.setGlobal( "result", result ); @@ -1017,8 +1043,9 @@ public void testQueryWithAccumulateAndUnification() { assertThat((int) result.get(0)).isEqualTo(37); } - @Test - public void testQueryWithAccumulateInvokingQuery() { + @ParameterizedTest + @MethodSource("parameters") + public void testQueryWithAccumulateInvokingQuery(RUN_TYPE runType) { // DROOLS-6105 String str = "import " + Result.class.getCanonicalName() + ";\n" + @@ -1049,7 +1076,7 @@ public void testQueryWithAccumulateInvokingQuery() { " result.add($sum);" + "end\n"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); List result = new ArrayList<>(); ksession.setGlobal( "result", result ); @@ -1061,8 +1088,9 @@ public void testQueryWithAccumulateInvokingQuery() { assertThat((int) result.get(0)).isEqualTo(37); } - @Test - public void testQueryDoubleUnification() { + @ParameterizedTest + @MethodSource("parameters") + public void testQueryDoubleUnification(RUN_TYPE runType) { // DROOLS-6105 final String str = "" + "package org.drools.compiler.test \n" + @@ -1087,7 +1115,7 @@ public void testQueryDoubleUnification() { "end\n" + ""; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); ksession.fireAllRules(); QueryResults results = ksession.getQueryResults("whereFood", Variable.v, "kitchen"); @@ -1096,8 +1124,9 @@ public void testQueryDoubleUnification() { assertThat(row.get("x")).isEqualTo("crackers"); } - @Test - public void testQueryWithInheritance() { + @ParameterizedTest + @MethodSource("parameters") + public void testQueryWithInheritance(RUN_TYPE runType) { // DROOLS-6105 final String str = "" + "global java.util.List list;\n" + @@ -1124,7 +1153,7 @@ public void testQueryWithInheritance() { " list.addAll( $food ); \n" + "end\n"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); List list = new ArrayList<>(); ksession.setGlobal( "list", list ); diff --git a/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/RuleAttributesTest.java b/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/RuleAttributesTest.java index 02c73e43f83..a553aafed21 100644 --- a/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/RuleAttributesTest.java +++ b/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/RuleAttributesTest.java @@ -27,7 +27,9 @@ import org.drools.model.codegen.execmodel.domain.Person; import org.drools.model.codegen.execmodel.domain.Result; -import org.junit.Test; +import org.junit.jupiter.api.Timeout; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; import org.kie.api.event.rule.AfterMatchFiredEvent; import org.kie.api.event.rule.DefaultAgendaEventListener; import org.kie.api.runtime.KieSession; @@ -37,12 +39,10 @@ public class RuleAttributesTest extends BaseModelTest { - public RuleAttributesTest( RUN_TYPE testRunType ) { - super( testRunType ); - } - - @Test(timeout = 5000) - public void testNoLoop() { + @ParameterizedTest + @MethodSource("parameters") + @Timeout(5000) + public void testNoLoop(RUN_TYPE runType) { String str = "import " + Person.class.getCanonicalName() + ";" + "rule R no-loop when\n" + @@ -51,7 +51,7 @@ public void testNoLoop() { " modify($p) { setAge($p.getAge()+1) };\n" + "end"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); Person me = new Person( "Mario", 40 ); ksession.insert( me ); @@ -60,8 +60,9 @@ public void testNoLoop() { assertThat(me.getAge()).isEqualTo(41); } - @Test - public void testSalience() throws Exception { + @ParameterizedTest + @MethodSource("parameters") + public void testSalience(RUN_TYPE runType) throws Exception { String str = "import " + Result.class.getCanonicalName() + ";" + "import " + Person.class.getCanonicalName() + ";" + @@ -79,7 +80,7 @@ public void testSalience() throws Exception { " delete($p);" + "end\n"; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); ksession.insert(new Person("Mario", 40)); ksession.fireAllRules(); @@ -89,8 +90,9 @@ public void testSalience() throws Exception { assertThat(results.contains("R2")).isTrue(); } - @Test - public void testSalienceExpressionAttribute() throws Exception { + @ParameterizedTest + @MethodSource("parameters") + public void testSalienceExpressionAttribute(RUN_TYPE runType) throws Exception { String str = "import " + Person.class.getCanonicalName() + ";" + "\n" + "rule R1 salience -$p.getAge() when\n" + @@ -106,7 +108,7 @@ public void testSalienceExpressionAttribute() throws Exception { " delete($p);" + "end\n"; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); ksession.insert(new Person("Mario", 40)); ksession.fireAllRules(); @@ -116,8 +118,9 @@ public void testSalienceExpressionAttribute() throws Exception { assertThat(results.contains("R2")).isTrue(); } - @Test - public void testExpressionEnabledAttribute() throws Exception { + @ParameterizedTest + @MethodSource("parameters") + public void testExpressionEnabledAttribute(RUN_TYPE runType) throws Exception { String str = "import " + Person.class.getCanonicalName() + ";\n" + "rule R1\n" + "enabled ($b)\n" + @@ -129,7 +132,7 @@ public void testExpressionEnabledAttribute() throws Exception { " delete($p);" + "end\n"; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); ksession.insert(Boolean.FALSE); Person mario = new Person("Mario", 40); @@ -142,8 +145,9 @@ public void testExpressionEnabledAttribute() throws Exception { assertThat(!results.contains("R1")).isTrue(); } - @Test - public void testCrossNoLoopWithNodeSharing() throws Exception { + @ParameterizedTest + @MethodSource("parameters") + public void testCrossNoLoopWithNodeSharing(RUN_TYPE runType) throws Exception { String str = "package org.drools.compiler.loop " + "rule 'Rule 1' " + @@ -168,7 +172,7 @@ public void testCrossNoLoopWithNodeSharing() throws Exception { " update( $thing2 ); " + "end"; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); ksession.insert( "hello" ); ksession.insert( new Integer( 42 ) ); @@ -181,8 +185,9 @@ public void testCrossNoLoopWithNodeSharing() throws Exception { assertThat(x).isEqualTo(2); } - @Test - public void testCalendars() { + @ParameterizedTest + @MethodSource("parameters") + public void testCalendars(RUN_TYPE runType) { String str = "package org.drools.compiler.integrationtests;\n" + "\n" + @@ -204,7 +209,7 @@ public void testCalendars() { " list.add(\"weekday\");\n" + "end"; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); ArrayList list = new ArrayList(); @@ -243,8 +248,9 @@ public boolean isTimeIncluded(long timestamp) { } }; - @Test - public void testAutoFocus() { + @ParameterizedTest + @MethodSource("parameters") + public void testAutoFocus(RUN_TYPE runType) { String str = "package org.drools.testcoverage.functional;\n" + "//generated from Decision Table\n" + @@ -335,7 +341,7 @@ public void testAutoFocus() { "end\n" + "\n"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); final OrderListener listener = new OrderListener(); ksession.addEventListener(listener); @@ -378,8 +384,9 @@ public String get(final int index) { } } - @Test - public void testMetadataBasics() { + @ParameterizedTest + @MethodSource("parameters") + public void testMetadataBasics(RUN_TYPE runType) { final String PACKAGE_NAME = "org.asd"; final String RULE_NAME = "hello world"; final String RULE_KEY = "output"; @@ -392,7 +399,7 @@ public void testMetadataBasics() { " System.out.println(\"Hello world!\");\n" + " end"; - KieSession ksession = getKieSession(rule); + KieSession ksession = getKieSession(runType, rule); final Map metadata = ksession.getKieBase().getRule(PACKAGE_NAME, RULE_NAME).getMetaData(); @@ -400,8 +407,9 @@ public void testMetadataBasics() { assertThat(metadata.get(RULE_KEY)).isEqualTo("\"" + RULE_VALUE + "\""); } - @Test - public void testMetadataValue() { + @ParameterizedTest + @MethodSource("parameters") + public void testMetadataValue(RUN_TYPE runType) { final String rule = " package org.test;\n" + " rule R1\n" + " @metaValueString(\"asd\")\n" + @@ -413,7 +421,7 @@ public void testMetadataValue() { " System.out.println(\"Hello world!\");\n" + " end"; - KieSession ksession = getKieSession(rule); + KieSession ksession = getKieSession(runType, rule); final Map metadata = ksession.getKieBase().getRule("org.test", "R1").getMetaData(); @@ -423,8 +431,9 @@ public void testMetadataValue() { assertThat(metadata.get("metaValueCheck3")).isSameAs(System.out); } - @Test - public void testDynamicSalience() { + @ParameterizedTest + @MethodSource("parameters") + public void testDynamicSalience(RUN_TYPE runType) { String str = "global java.util.List list;\n" + "rule R1 salience $s.length when\n" + @@ -438,7 +447,7 @@ public void testDynamicSalience() { " list.add($i);" + "end\n"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); List list = new ArrayList<>(); ksession.setGlobal( "list", list ); @@ -454,8 +463,9 @@ public void testDynamicSalience() { public static final int CONST_SALIENCE = 1; - @Test - public void testSalienceFromConstant() { + @ParameterizedTest + @MethodSource("parameters") + public void testSalienceFromConstant(RUN_TYPE runType) { // DROOLS-5550 String str = "import " + RuleAttributesTest.class.getCanonicalName() + "\n;" + @@ -471,7 +481,7 @@ public void testSalienceFromConstant() { " list.add($i);" + "end\n"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); List list = new ArrayList<>(); ksession.setGlobal( "list", list ); diff --git a/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/SegmentPrototypeExpressionTest.java b/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/SegmentPrototypeExpressionTest.java index 383a1a044f0..66ee1911396 100644 --- a/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/SegmentPrototypeExpressionTest.java +++ b/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/SegmentPrototypeExpressionTest.java @@ -19,7 +19,7 @@ package org.drools.model.codegen.execmodel; import org.drools.model.prototype.PrototypeExpression; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.kie.api.prototype.PrototypeFact; import org.kie.api.prototype.PrototypeFactInstance; diff --git a/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/TextBlockTest.java b/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/TextBlockTest.java index b0c237961d5..d3517a1124b 100644 --- a/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/TextBlockTest.java +++ b/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/TextBlockTest.java @@ -22,19 +22,17 @@ import java.util.List; import org.drools.model.codegen.execmodel.domain.Person; -import org.junit.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; import org.kie.api.runtime.KieSession; import static org.assertj.core.api.Assertions.assertThat; public class TextBlockTest extends OnlyExecModelTest { - public TextBlockTest(RUN_TYPE testRunType) { - super(testRunType); - } - - @Test - public void testMultiLineStrings() { + @ParameterizedTest(name = "{0}") + @MethodSource("parameters") + public void testMultiLineStrings(RUN_TYPE runType) { final String str = "package org.drools.mvel.compiler\n" + "global java.util.List list;\n" + @@ -53,7 +51,7 @@ public void testMultiLineStrings() { "end\n"; - KieSession ksession = getKieSession(str ); + KieSession ksession = getKieSession(runType, str); final List list = new ArrayList<>(); ksession.setGlobal("list", list); diff --git a/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/ToStringTest.java b/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/ToStringTest.java index db49afe2372..1400bf32346 100644 --- a/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/ToStringTest.java +++ b/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/ToStringTest.java @@ -31,7 +31,7 @@ import org.drools.model.functions.Predicate1; import org.drools.model.functions.Predicate2; import org.drools.model.view.ExprViewItem; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.kie.api.runtime.rule.AccumulateFunction; import static org.assertj.core.api.Assertions.assertThat; diff --git a/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/TypeCoercionTest.java b/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/TypeCoercionTest.java index 67cd73f3bd3..b83c11cc216 100644 --- a/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/TypeCoercionTest.java +++ b/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/TypeCoercionTest.java @@ -28,19 +28,17 @@ import org.drools.model.codegen.execmodel.domain.DateTimeHolder; import org.drools.model.codegen.execmodel.domain.Person; import org.drools.model.codegen.execmodel.domain.Result; -import org.junit.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; import org.kie.api.runtime.KieSession; import static org.assertj.core.api.Assertions.assertThat; public class TypeCoercionTest extends BaseModelTest { - public TypeCoercionTest( RUN_TYPE testRunType ) { - super( testRunType ); - } - - @Test - public void testEqualCoercion() { + @ParameterizedTest + @MethodSource("parameters") + public void testEqualCoercion(RUN_TYPE runType) { String str = "import " + Person.class.getCanonicalName() + "\n" + "global java.util.List list\n" + @@ -50,7 +48,7 @@ public void testEqualCoercion() { " list.add($name);" + "end "; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); List list = new ArrayList<>(); ksession.setGlobal( "list", list ); @@ -63,8 +61,9 @@ public void testEqualCoercion() { assertThat(list.get(0)).isEqualTo("40"); } - @Test - public void testComparisonCoercion() { + @ParameterizedTest + @MethodSource("parameters") + public void testComparisonCoercion(RUN_TYPE runType) { String str = "import " + Person.class.getCanonicalName() + "\n" + "global java.util.List list\n" + @@ -74,7 +73,7 @@ public void testComparisonCoercion() { " list.add($name);" + "end "; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); List list = new ArrayList<>(); ksession.setGlobal( "list", list ); @@ -87,8 +86,9 @@ public void testComparisonCoercion() { assertThat(list.get(0)).isEqualTo("40"); } - @Test - public void testComparisonCoercion2() { + @ParameterizedTest + @MethodSource("parameters") + public void testComparisonCoercion2(RUN_TYPE runType) { String str = "import " + Person.class.getCanonicalName() + "\n" + "global java.util.List list\n" + @@ -98,7 +98,7 @@ public void testComparisonCoercion2() { " list.add($name);" + "end "; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); List list = new ArrayList<>(); ksession.setGlobal( "list", list ); @@ -111,8 +111,9 @@ public void testComparisonCoercion2() { assertThat(list.get(0)).isEqualTo("Mario"); } - @Test - public void testPrimitiveCoercion() { + @ParameterizedTest + @MethodSource("parameters") + public void testPrimitiveCoercion(RUN_TYPE runType) { String str = "import " + Person.class.getCanonicalName() + "\n" + "global java.util.List list\n" + @@ -122,7 +123,7 @@ public void testPrimitiveCoercion() { " list.add(\"\" + $n);" + "end "; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); List list = new ArrayList<>(); ksession.setGlobal( "list", list ); @@ -147,8 +148,9 @@ public Long getValue() { } } - @Test - public void testDoubleToInt() { + @ParameterizedTest + @MethodSource("parameters") + public void testDoubleToInt(RUN_TYPE runType) { final String drl1 = "import " + DoubleHolder.class.getCanonicalName() + ";\n" + "rule R when\n" + @@ -156,14 +158,15 @@ public void testDoubleToInt() { "then\n" + "end\n"; - KieSession ksession = getKieSession( drl1 ); + KieSession ksession = getKieSession(runType, drl1); ksession.insert(new DoubleHolder()); assertThat(ksession.fireAllRules()).isEqualTo(1); } - @Test - public void testLongToInt() { + @ParameterizedTest + @MethodSource("parameters") + public void testLongToInt(RUN_TYPE runType) { final String drl1 = "import " + LongHolder.class.getCanonicalName() + ";\n" + "rule R when\n" + @@ -171,14 +174,15 @@ public void testLongToInt() { "then\n" + "end\n"; - KieSession ksession = getKieSession( drl1 ); + KieSession ksession = getKieSession(runType, drl1); ksession.insert(new LongHolder()); assertThat(ksession.fireAllRules()).isEqualTo(1); } - @Test - public void testJoinLongToDouble() { + @ParameterizedTest + @MethodSource("parameters") + public void testJoinLongToDouble(RUN_TYPE runType) { final String drl1 = "import " + DoubleHolder.class.getCanonicalName() + ";\n" + "import " + LongHolder.class.getCanonicalName() + ";\n" + @@ -188,15 +192,16 @@ public void testJoinLongToDouble() { "then\n" + "end\n"; - KieSession ksession = getKieSession( drl1 ); + KieSession ksession = getKieSession(runType, drl1); ksession.insert(new LongHolder()); ksession.insert(new DoubleHolder()); assertThat(ksession.fireAllRules()).isEqualTo(1); } - @Test - public void testJoinDoubleToLong() { + @ParameterizedTest + @MethodSource("parameters") + public void testJoinDoubleToLong(RUN_TYPE runType) { final String drl1 = "import " + DoubleHolder.class.getCanonicalName() + ";\n" + "import " + LongHolder.class.getCanonicalName() + ";\n" + @@ -206,15 +211,16 @@ public void testJoinDoubleToLong() { "then\n" + "end\n"; - KieSession ksession = getKieSession( drl1 ); + KieSession ksession = getKieSession(runType, drl1); ksession.insert(new LongHolder()); ksession.insert(new DoubleHolder()); assertThat(ksession.fireAllRules()).isEqualTo(1); } - @Test - public void testStringToDateComparison() { + @ParameterizedTest + @MethodSource("parameters") + public void testStringToDateComparison(RUN_TYPE runType) { String str = "import " + Date.class.getCanonicalName() + ";\n" + "declare Flight departuretime : java.util.Date end\n" + @@ -224,13 +230,14 @@ public void testStringToDateComparison() { "then\n" + "end\n"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); ksession.insert( new ChildFactWithObject(5, 1, new Object[0]) ); assertThat(ksession.fireAllRules()).isEqualTo(2); } - @Test - public void testBetaJoinShortInt() { + @ParameterizedTest + @MethodSource("parameters") + public void testBetaJoinShortInt(RUN_TYPE runType) { String str = "import " + Person.class.getCanonicalName() + ";" + "rule R when\n" + @@ -239,12 +246,13 @@ public void testBetaJoinShortInt() { "then\n" + "end\n"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); assertThat(ksession.fireAllRules()).isEqualTo(0); } - @Test - public void testBetaJoinShortIntBoxed() { + @ParameterizedTest + @MethodSource("parameters") + public void testBetaJoinShortIntBoxed(RUN_TYPE runType) { String str = "import " + Person.class.getCanonicalName() + ";" + "rule R when\n" + @@ -253,12 +261,13 @@ public void testBetaJoinShortIntBoxed() { "then\n" + "end\n"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); assertThat(ksession.fireAllRules()).isEqualTo(0); } - @Test - public void testPrimitivePromotionInLHS() { + @ParameterizedTest + @MethodSource("parameters") + public void testPrimitivePromotionInLHS(RUN_TYPE runType) { // DROOLS-4717 String str = "import " + Person.class.getCanonicalName() + ";" + @@ -269,7 +278,7 @@ public void testPrimitivePromotionInLHS() { " insert(new Result($p));\n" + "end"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); final Person luca = new Person("Luca", 35); ksession.insert(luca); @@ -281,8 +290,9 @@ public void testPrimitivePromotionInLHS() { assertThat(results.stream().map(Result::getValue)).containsExactlyInAnyOrder(luca); } - @Test - public void testIntToObjectCoercion() { + @ParameterizedTest + @MethodSource("parameters") + public void testIntToObjectCoercion(RUN_TYPE runType) { // DROOLS-5320 String str = "rule R when\n" + @@ -291,14 +301,15 @@ public void testIntToObjectCoercion() { "then\n" + "end "; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); ksession.insert( 3 ); assertThat(ksession.fireAllRules()).isEqualTo(1); } - @Test - public void testDoubleNaN() { + @ParameterizedTest + @MethodSource("parameters") + public void testDoubleNaN(RUN_TYPE runType) { // DROOLS-5692 String str = "import " + DoubleNaNPojo.class.getCanonicalName() + ";\n" + @@ -312,7 +323,7 @@ public void testDoubleNaN() { " update($nanTest);\n" + "end"; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); DoubleNaNPojo nan = new DoubleNaNPojo(); nan.setTestBoolean(false); @@ -386,8 +397,9 @@ public Short getTestShort() { } } - @Test - public void testStringToIntCoercion() { + @ParameterizedTest + @MethodSource("parameters") + public void testStringToIntCoercion(RUN_TYPE runType) { // DROOLS-5939 String str = "import " + ClassWithIntProperty.class.getCanonicalName() + ";\n" + @@ -399,7 +411,7 @@ public void testStringToIntCoercion() { "then\n" + "end"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); ksession.insert( new ClassWithIntProperty( 10 ) ); ksession.insert( new ClassWithStringProperty( "10" ) ); @@ -407,8 +419,9 @@ public void testStringToIntCoercion() { assertThat(ksession.fireAllRules()).isEqualTo(1); } - @Test - public void testIntToStringCoercion() { + @ParameterizedTest + @MethodSource("parameters") + public void testIntToStringCoercion(RUN_TYPE runType) { // DROOLS-5939 String str = "import " + ClassWithIntProperty.class.getCanonicalName() + ";\n" + @@ -420,7 +433,7 @@ public void testIntToStringCoercion() { "then\n" + "end"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); ksession.insert( new ClassWithIntProperty( 10 ) ); ksession.insert( new ClassWithStringProperty( "10" ) ); @@ -428,8 +441,9 @@ public void testIntToStringCoercion() { assertThat(ksession.fireAllRules()).isEqualTo(1); } - @Test - public void testShortToIntCoercion() { + @ParameterizedTest + @MethodSource("parameters") + public void testShortToIntCoercion(RUN_TYPE runType) { // DROOLS-5939 String str = "import " + ClassWithShortProperty.class.getCanonicalName() + ";\n" + @@ -441,7 +455,7 @@ public void testShortToIntCoercion() { "then\n" + "end"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); ksession.insert( new ClassWithShortProperty( (short)10 ) ); ksession.insert( new ClassWithIntProperty( 10 ) ); @@ -449,8 +463,9 @@ public void testShortToIntCoercion() { assertThat(ksession.fireAllRules()).isEqualTo(1); } - @Test - public void testIntToShortCoercion() { + @ParameterizedTest + @MethodSource("parameters") + public void testIntToShortCoercion(RUN_TYPE runType) { // DROOLS-5939 String str = "import " + ClassWithShortProperty.class.getCanonicalName() + ";\n" + @@ -462,7 +477,7 @@ public void testIntToShortCoercion() { "then\n" + "end"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); ksession.insert( new ClassWithShortProperty( (short)10 ) ); ksession.insert( new ClassWithIntProperty( 10 ) ); @@ -470,8 +485,9 @@ public void testIntToShortCoercion() { assertThat(ksession.fireAllRules()).isEqualTo(1); } - @Test - public void testCoercionOnBoundVariable() { + @ParameterizedTest + @MethodSource("parameters") + public void testCoercionOnBoundVariable(RUN_TYPE runType) { // DROOLS-5945 String str = "import " + ClassWithIntProperty.class.getCanonicalName() + ";\n" + @@ -481,15 +497,16 @@ public void testCoercionOnBoundVariable() { "then\n" + "end"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); ksession.insert( new ClassWithIntProperty( 3 ) ); assertThat(ksession.fireAllRules()).isEqualTo(0); } - @Test - public void testCompareDateLiteral() throws Exception { + @ParameterizedTest + @MethodSource("parameters") + public void testCompareDateLiteral(RUN_TYPE runType) throws Exception { String str = "import " + DateTimeHolder.class.getCanonicalName() + ";" + "rule R when\n" + @@ -497,15 +514,16 @@ public void testCompareDateLiteral() throws Exception { "then\n" + "end\n"; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); ksession.insert(new DateTimeHolder(ZonedDateTime.now())); assertThat(ksession.fireAllRules()).isEqualTo(1); } - @Test - public void testCompareLocalDateLiteral() throws Exception { + @ParameterizedTest + @MethodSource("parameters") + public void testCompareLocalDateLiteral(RUN_TYPE runType) throws Exception { String str = "import " + DateTimeHolder.class.getCanonicalName() + ";" + "rule R when\n" + @@ -513,15 +531,16 @@ public void testCompareLocalDateLiteral() throws Exception { "then\n" + "end\n"; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); ksession.insert(new DateTimeHolder(ZonedDateTime.now())); assertThat(ksession.fireAllRules()).isEqualTo(1); } - @Test - public void testCompareLocalDateTimeLiteral() throws Exception { + @ParameterizedTest + @MethodSource("parameters") + public void testCompareLocalDateTimeLiteral(RUN_TYPE runType) throws Exception { String str = "import " + DateTimeHolder.class.getCanonicalName() + ";" + "rule R when\n" + @@ -529,15 +548,16 @@ public void testCompareLocalDateTimeLiteral() throws Exception { "then\n" + "end\n"; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); ksession.insert(new DateTimeHolder(ZonedDateTime.now())); assertThat(ksession.fireAllRules()).isEqualTo(1); } - @Test - public void testCompareLocalDateTimeLiteral2() throws Exception { + @ParameterizedTest + @MethodSource("parameters") + public void testCompareLocalDateTimeLiteral2(RUN_TYPE runType) throws Exception { String str = "import " + DateTimeHolder.class.getCanonicalName() + ";" + "rule R when\n" + @@ -545,21 +565,22 @@ public void testCompareLocalDateTimeLiteral2() throws Exception { "then\n" + "end\n"; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); ksession.insert(new DateTimeHolder(ZonedDateTime.now())); assertThat(ksession.fireAllRules()).isEqualTo(0); } - @Test - public void testPrimitiveDoubleToIntCoercion() { + @ParameterizedTest + @MethodSource("parameters") + public void testPrimitiveDoubleToIntCoercion(RUN_TYPE runType) { // DROOLS-6491 - checkDoubleToIntCoercion(true); - checkDoubleToIntCoercion(false); + checkDoubleToIntCoercion(runType, true); + checkDoubleToIntCoercion(runType, false); } - private void checkDoubleToIntCoercion(boolean boxed) { + private void checkDoubleToIntCoercion(RUN_TYPE runType, boolean boxed) { String str = "import " + Person.class.getCanonicalName() + "\n" + "global java.util.List list\n" + @@ -569,7 +590,7 @@ private void checkDoubleToIntCoercion(boolean boxed) { " list.add($name);" + "end "; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); List list = new ArrayList<>(); ksession.setGlobal( "list", list ); @@ -582,8 +603,9 @@ private void checkDoubleToIntCoercion(boolean boxed) { assertThat(list.get(0)).isEqualTo("Mario"); } - @Test - public void testFloatOperation() { + @ParameterizedTest + @MethodSource("parameters") + public void testFloatOperation(RUN_TYPE runType) { // DROOLS-7334 String str = "import " + Person.class.getCanonicalName() + "\n" + @@ -594,7 +616,7 @@ public void testFloatOperation() { " list.add($name);" + "end "; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); List list = new ArrayList<>(); ksession.setGlobal( "list", list ); @@ -613,8 +635,9 @@ public void testFloatOperation() { assertThat(list.get(0)).isEqualTo("Mario"); } - @Test - public void testCoerceObjectToString() { + @ParameterizedTest + @MethodSource("parameters") + public void testCoerceObjectToString(RUN_TYPE runType) { String str = "package constraintexpression\n" + "\n" + "import " + Person.class.getCanonicalName() + "\n" + @@ -627,7 +650,7 @@ public void testCoerceObjectToString() { " System.out.println($p); \n" + "end \n"; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); try { Person person = new Person("someName"); ksession.insert(person); diff --git a/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/TypeDeclarationTest.java b/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/TypeDeclarationTest.java index e34aeb6ffed..a985ac0c156 100644 --- a/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/TypeDeclarationTest.java +++ b/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/TypeDeclarationTest.java @@ -18,14 +18,14 @@ */ package org.drools.model.codegen.execmodel; -import java.util.Arrays; import java.util.Collection; import java.util.HashMap; import java.util.List; import java.util.Map; import org.drools.model.codegen.execmodel.domain.Result; -import org.junit.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; import org.kie.api.KieBase; import org.kie.api.definition.type.FactType; import org.kie.api.runtime.KieSession; @@ -34,12 +34,9 @@ public class TypeDeclarationTest extends BaseModelTest { - public TypeDeclarationTest( RUN_TYPE testRunType ) { - super( testRunType ); - } - - @Test - public void testRecursiveDeclaration() throws Exception { + @ParameterizedTest + @MethodSource("parameters") + public void testRecursiveDeclaration(RUN_TYPE runType) throws Exception { String str = "package org.drools.compiler\n" + "declare Node\n" + @@ -53,7 +50,7 @@ public void testRecursiveDeclaration() throws Exception { " System.out.println( $value );\n" + "end"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); KieBase kbase = ksession.getKieBase(); FactType nodeType = kbase.getFactType( "org.drools.compiler", "Node" ); @@ -70,8 +67,9 @@ public void testRecursiveDeclaration() throws Exception { assertThat(rules).isEqualTo(1); } - @Test - public void testGenerics() throws Exception { + @ParameterizedTest + @MethodSource("parameters") + public void testGenerics(RUN_TYPE runType) throws Exception { // DROOLS-4939 String str = "package org.drools.compiler\n" + @@ -85,7 +83,7 @@ public void testGenerics() throws Exception { " System.out.println( $node );\n" + "end"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); KieBase kbase = ksession.getKieBase(); FactType nodeType = kbase.getFactType( "org.drools.compiler", "Node" ); @@ -101,8 +99,9 @@ public interface ValuesProvider { Map getValues(); } - @Test - public void testGenericsMap() throws Exception { + @ParameterizedTest + @MethodSource("parameters") + public void testGenericsMap(RUN_TYPE runType) throws Exception { // DROOLS-4939 String str = "package org.drools.compiler\n" + @@ -117,7 +116,7 @@ public void testGenericsMap() throws Exception { " System.out.println( $node );\n" + "end"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); KieBase kbase = ksession.getKieBase(); FactType nodeType = kbase.getFactType( "org.drools.compiler", "Node" ); @@ -131,8 +130,9 @@ public void testGenericsMap() throws Exception { assertThat(rules).isEqualTo(1); } - @Test - public void testSerialVersionUID() throws Exception { + @ParameterizedTest + @MethodSource("parameters") + public void testSerialVersionUID(RUN_TYPE runType) throws Exception { // DROOLS-5340 String str = "package org.drools.compiler\n" + @@ -150,13 +150,14 @@ public void testSerialVersionUID() throws Exception { " insert( new ServiceInformation(\"123456\", \"ServiceTest\", new ArrayList()) );\n" + "end"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); int rules = ksession.fireAllRules(); assertThat(rules).isEqualTo(1); } - @Test - public void testSerialVersionUIDWithAllkeys() throws Exception { + @ParameterizedTest + @MethodSource("parameters") + public void testSerialVersionUIDWithAllkeys(RUN_TYPE runType) throws Exception { // DROOLS-5400 String str = "package org.drools.compiler\n" + @@ -174,13 +175,14 @@ public void testSerialVersionUIDWithAllkeys() throws Exception { " insert( new ServiceInformation(\"123456\", \"ServiceTest\", new ArrayList()) );\n" + "end"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); int rules = ksession.fireAllRules(); assertThat(rules).isEqualTo(1); } - @Test - public void testPositionalWithLiteral() { + @ParameterizedTest + @MethodSource("parameters") + public void testPositionalWithLiteral(RUN_TYPE runType) { // DROOLS-6128 String str = "import " + Result.class.getCanonicalName() + ";" + @@ -200,7 +202,7 @@ public void testPositionalWithLiteral() { " insert(new Result($age));\n" + "end"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); ksession.fireAllRules(); @@ -209,8 +211,9 @@ public void testPositionalWithLiteral() { assertThat(results.iterator().next().getValue()).isEqualTo(37); } - @Test - public void testPositionalWithJoin() { + @ParameterizedTest + @MethodSource("parameters") + public void testPositionalWithJoin(RUN_TYPE runType) { // DROOLS-6128 String str = "import " + Result.class.getCanonicalName() + ";" + @@ -231,7 +234,7 @@ public void testPositionalWithJoin() { " insert(new Result($age));\n" + "end"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); ksession.insert( "Mark" ); ksession.fireAllRules(); diff --git a/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/TypeObjectCoercionTest.java b/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/TypeObjectCoercionTest.java index fdf022aa260..a70c563e22b 100644 --- a/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/TypeObjectCoercionTest.java +++ b/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/TypeObjectCoercionTest.java @@ -23,7 +23,8 @@ import java.util.List; import java.util.Map; -import org.junit.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; import org.kie.api.runtime.KieSession; import static org.assertj.core.api.Assertions.assertThat; @@ -31,11 +32,7 @@ public class TypeObjectCoercionTest extends BaseModelTest { - public TypeObjectCoercionTest(RUN_TYPE testRunType) { - super(testRunType); - } - - private KieSession getKieSessionForJoinObjectToString() { + private KieSession getKieSessionForJoinObjectToString(RUN_TYPE runType) { // NOTE: If we write a test with IntegerHolder instead of ObjectHolder, standard-drl fails with a compilation error // text=Unable to Analyse Expression value >= $i: @@ -51,13 +48,14 @@ private KieSession getKieSessionForJoinObjectToString() { "then\n" + "end\n"; - return getKieSession(drl1); + return getKieSession(runType, drl1); } - @Test - public void testJoinObjectToString1() { + @ParameterizedTest + @MethodSource("parameters") + public void testJoinObjectToString1(RUN_TYPE runType) { - KieSession ksession = getKieSessionForJoinObjectToString(); + KieSession ksession = getKieSessionForJoinObjectToString(runType); // String "10" > Integer 5 ksession.insert(new ObjectHolder(Integer.valueOf(5))); @@ -65,10 +63,11 @@ public void testJoinObjectToString1() { assertThat(ksession.fireAllRules()).isEqualTo(1); // standard-drl : 10 > 5 (Number comparison) } - @Test - public void testJoinObjectToString2() { + @ParameterizedTest + @MethodSource("parameters") + public void testJoinObjectToString2(RUN_TYPE runType) { - KieSession ksession = getKieSessionForJoinObjectToString(); + KieSession ksession = getKieSessionForJoinObjectToString(runType); // String "10" > String "5" ksession.insert(new ObjectHolder("5")); @@ -76,10 +75,11 @@ public void testJoinObjectToString2() { assertThat(ksession.fireAllRules()).isEqualTo(0); // standard-drl : "10" < "5" (String comparison) } - @Test - public void testJoinObjectToString3() { + @ParameterizedTest + @MethodSource("parameters") + public void testJoinObjectToString3(RUN_TYPE runType) { - KieSession ksession = getKieSessionForJoinObjectToString(); + KieSession ksession = getKieSessionForJoinObjectToString(runType); // String "ABC" > Integer 5 ksession.insert(new ObjectHolder(Integer.valueOf(5))); @@ -88,10 +88,11 @@ public void testJoinObjectToString3() { assertThatThrownBy(()->ksession.fireAllRules()).isInstanceOf(RuntimeException.class); // standard-drl : ClassCastException: java.lang.Integer cannot be cast to java.lang.String } - @Test - public void testJoinObjectToString4() { + @ParameterizedTest + @MethodSource("parameters") + public void testJoinObjectToString4(RUN_TYPE runType) { - KieSession ksession = getKieSessionForJoinObjectToString(); + KieSession ksession = getKieSessionForJoinObjectToString(runType); // String "10" > String "ABC" ksession.insert(new ObjectHolder("ABC")); @@ -100,10 +101,11 @@ public void testJoinObjectToString4() { ksession.dispose(); } - @Test - public void testJoinObjectToString5() { + @ParameterizedTest + @MethodSource("parameters") + public void testJoinObjectToString5(RUN_TYPE runType) { - KieSession ksession = getKieSessionForJoinObjectToString(); + KieSession ksession = getKieSessionForJoinObjectToString(runType); // String "ABC" > String "DEF" ksession.insert(new ObjectHolder("DEF")); @@ -112,10 +114,11 @@ public void testJoinObjectToString5() { ksession.dispose(); } - @Test - public void testJoinObjectToStringNonComparable() { + @ParameterizedTest + @MethodSource("parameters") + public void testJoinObjectToStringNonComparable(RUN_TYPE runType) { - KieSession ksession = getKieSessionForJoinObjectToString(); + KieSession ksession = getKieSessionForJoinObjectToString(runType); // String "10" > Object ksession.insert(new ObjectHolder(new Object())); // not Comparable @@ -126,7 +129,7 @@ public void testJoinObjectToStringNonComparable() { } - private KieSession getKieSessionForJoinStringToObject() { + private KieSession getKieSessionForJoinStringToObject(RUN_TYPE runType) { final String drl1 = "import " + ObjectHolder.class.getCanonicalName() + ";\n" + @@ -137,13 +140,14 @@ private KieSession getKieSessionForJoinStringToObject() { "then\n" + "end\n"; - return getKieSession(drl1); + return getKieSession(runType, drl1); } - @Test - public void testJoinStringToObject1() { + @ParameterizedTest + @MethodSource("parameters") + public void testJoinStringToObject1(RUN_TYPE runType) { - KieSession ksession = getKieSessionForJoinStringToObject(); + KieSession ksession = getKieSessionForJoinStringToObject(runType); // Integer 5 > String "10" ksession.insert(new StringHolder("10")); @@ -151,10 +155,11 @@ public void testJoinStringToObject1() { assertThat(ksession.fireAllRules()).isEqualTo(0); // standard-drl : 5 < 10 (Number comparison) } - @Test - public void testJoinStringToObject2() { + @ParameterizedTest + @MethodSource("parameters") + public void testJoinStringToObject2(RUN_TYPE runType) { - KieSession ksession = getKieSessionForJoinStringToObject(); + KieSession ksession = getKieSessionForJoinStringToObject(runType); // String "5" > String "10" ksession.insert(new StringHolder("10")); @@ -162,10 +167,11 @@ public void testJoinStringToObject2() { assertThat(ksession.fireAllRules()).isEqualTo(1); // standard-drl : "5" > "10" (String comparison) } - @Test - public void testJoinStringToObject3() { + @ParameterizedTest + @MethodSource("parameters") + public void testJoinStringToObject3(RUN_TYPE runType) { - KieSession ksession = getKieSessionForJoinStringToObject(); + KieSession ksession = getKieSessionForJoinStringToObject(runType); // Integer 5 > String "ABC" ksession.insert(new StringHolder("ABC")); @@ -176,10 +182,11 @@ public void testJoinStringToObject3() { } - @Test - public void testJoinStringToObject4() { + @ParameterizedTest + @MethodSource("parameters") + public void testJoinStringToObject4(RUN_TYPE runType) { - KieSession ksession = getKieSessionForJoinStringToObject(); + KieSession ksession = getKieSessionForJoinStringToObject(runType); // String "ABC" > String "10" ksession.insert(new StringHolder("10")); @@ -188,10 +195,11 @@ public void testJoinStringToObject4() { ksession.dispose(); } - @Test - public void testJoinStringToObject5() { + @ParameterizedTest + @MethodSource("parameters") + public void testJoinStringToObject5(RUN_TYPE runType) { - KieSession ksession = getKieSessionForJoinStringToObject(); + KieSession ksession = getKieSessionForJoinStringToObject(runType); // String "DEF" > String "ABC" ksession.insert(new StringHolder("ABC")); @@ -200,7 +208,7 @@ public void testJoinStringToObject5() { ksession.dispose(); } - private KieSession getKieSessionForJoinIntegerToObject() { + private KieSession getKieSessionForJoinIntegerToObject(RUN_TYPE runType) { final String drl1 = "import " + ObjectHolder.class.getCanonicalName() + ";\n" + @@ -211,13 +219,14 @@ private KieSession getKieSessionForJoinIntegerToObject() { "then\n" + "end\n"; - return getKieSession(drl1); + return getKieSession(runType, drl1); } - @Test - public void testJoinIntegerToObject1() { + @ParameterizedTest + @MethodSource("parameters") + public void testJoinIntegerToObject1(RUN_TYPE runType) { - KieSession ksession = getKieSessionForJoinIntegerToObject(); + KieSession ksession = getKieSessionForJoinIntegerToObject(runType); // Integer 10 > Integer 5 ksession.insert(new IntegerHolder(Integer.valueOf(5))); @@ -225,10 +234,11 @@ public void testJoinIntegerToObject1() { assertThat(ksession.fireAllRules()).isEqualTo(1); } - @Test - public void testJoinIntegerToObject2() { + @ParameterizedTest + @MethodSource("parameters") + public void testJoinIntegerToObject2(RUN_TYPE runType) { - KieSession ksession = getKieSessionForJoinIntegerToObject(); + KieSession ksession = getKieSessionForJoinIntegerToObject(runType); // String "10" > Integer 5 ksession.insert(new IntegerHolder(Integer.valueOf(5))); @@ -236,10 +246,11 @@ public void testJoinIntegerToObject2() { assertThat(ksession.fireAllRules()).isEqualTo(1); } - @Test - public void testJoinIntegerToObject3() { + @ParameterizedTest + @MethodSource("parameters") + public void testJoinIntegerToObject3(RUN_TYPE runType) { - KieSession ksession = getKieSessionForJoinIntegerToObject(); + KieSession ksession = getKieSessionForJoinIntegerToObject(runType); // String "ABC" > Integer 5 ksession.insert(new IntegerHolder(Integer.valueOf(5))); @@ -248,10 +259,11 @@ public void testJoinIntegerToObject3() { assertThatThrownBy(()->ksession.fireAllRules()).isInstanceOf(RuntimeException.class); // standard-drl : Caused by ClassCastException: java.lang.String cannot be cast to java.lang.Integer } - @Test - public void testJoinIntegerToObjectNonComparable() { + @ParameterizedTest + @MethodSource("parameters") + public void testJoinIntegerToObjectNonComparable(RUN_TYPE runType) { - KieSession ksession = getKieSessionForJoinIntegerToObject(); + KieSession ksession = getKieSessionForJoinIntegerToObject(runType); // Object > Integer 5 ksession.insert(new IntegerHolder(Integer.valueOf(5))); @@ -259,7 +271,7 @@ public void testJoinIntegerToObjectNonComparable() { assertThat(ksession.fireAllRules()).isEqualTo(0); // in case of standard-drl, MathProcessor.doOperationNonNumeric() returns false when the left operand is not Comparable } - private KieSession getKieSessionForJoinObjectToInteger() { + private KieSession getKieSessionForJoinObjectToInteger(RUN_TYPE runType) { final String drl1 = "import " + ObjectHolder.class.getCanonicalName() + ";\n" + @@ -270,13 +282,14 @@ private KieSession getKieSessionForJoinObjectToInteger() { "then\n" + "end\n"; - return getKieSession(drl1); + return getKieSession(runType, drl1); } - @Test - public void testJoinObjectToInteger1() { + @ParameterizedTest + @MethodSource("parameters") + public void testJoinObjectToInteger1(RUN_TYPE runType) { - KieSession ksession = getKieSessionForJoinObjectToInteger(); + KieSession ksession = getKieSessionForJoinObjectToInteger(runType); // Integer 10 > Integer 5 ksession.insert(new ObjectHolder(Integer.valueOf(5))); @@ -284,10 +297,11 @@ public void testJoinObjectToInteger1() { assertThat(ksession.fireAllRules()).isEqualTo(1); } - @Test - public void testJoinObjectToInteger2() { + @ParameterizedTest + @MethodSource("parameters") + public void testJoinObjectToInteger2(RUN_TYPE runType) { - KieSession ksession = getKieSessionForJoinObjectToInteger(); + KieSession ksession = getKieSessionForJoinObjectToInteger(runType); // Integer 10 > String "5" ksession.insert(new ObjectHolder(new String("5"))); @@ -295,10 +309,11 @@ public void testJoinObjectToInteger2() { assertThat(ksession.fireAllRules()).isEqualTo(1); } - @Test - public void testJoinObjectToInteger3() { + @ParameterizedTest + @MethodSource("parameters") + public void testJoinObjectToInteger3(RUN_TYPE runType) { - KieSession ksession = getKieSessionForJoinObjectToInteger(); + KieSession ksession = getKieSessionForJoinObjectToInteger(runType); // Integer 10 > String "ABC" ksession.insert(new ObjectHolder(new String("ABC"))); @@ -307,10 +322,11 @@ public void testJoinObjectToInteger3() { assertThatThrownBy(()->ksession.fireAllRules()).isInstanceOf(RuntimeException.class); // standard-drl : Caused by ClassCastException: java.lang.String cannot be cast to java.lang.Integer } - @Test - public void testJoinObjectToIntegerNonComparable() { + @ParameterizedTest + @MethodSource("parameters") + public void testJoinObjectToIntegerNonComparable(RUN_TYPE runType) { - KieSession ksession = getKieSessionForJoinObjectToInteger(); + KieSession ksession = getKieSessionForJoinObjectToInteger(runType); // Integer 10 > Object ksession.insert(new ObjectHolder(new Object())); // not Comparable @@ -359,8 +375,9 @@ public Integer getValue() { } } - @Test - public void testJoinObjectToStringWithMap() { + @ParameterizedTest + @MethodSource("parameters") + public void testJoinObjectToStringWithMap(RUN_TYPE runType) { // This rule mimics JittingTest#testJitMapCoercion() @@ -373,7 +390,7 @@ public void testJoinObjectToStringWithMap() { "then\n" + "end\n"; - KieSession ksession = getKieSession(drl1); + KieSession ksession = getKieSession(runType, drl1); Map map = new HashMap<>(); map.put("key", 5); @@ -382,8 +399,9 @@ public void testJoinObjectToStringWithMap() { assertThat(ksession.fireAllRules()).isEqualTo(1); } - @Test - public void testCoercionStringVsObjectIntegerWithMap() { + @ParameterizedTest + @MethodSource("parameters") + public void testCoercionStringVsObjectIntegerWithMap(RUN_TYPE runType) { final String drl = "package org.drools.compiler.integrationtests;\n" + "import " + Map.class.getCanonicalName() + ";\n" + "import " + StringHolder.class.getCanonicalName() + ";\n" + @@ -398,7 +416,7 @@ public void testCoercionStringVsObjectIntegerWithMap() { // String is coerced to Integer (thus, Number comparison) - KieSession ksession = getKieSession(drl); + KieSession ksession =getKieSession(runType, drl); try { final List list = new ArrayList<>(); ksession.setGlobal("list", list); @@ -424,8 +442,9 @@ public void testCoercionStringVsObjectIntegerWithMap() { } } - @Test - public void testCoercionStringVsExplicitIntegerWithMap() { + @ParameterizedTest + @MethodSource("parameters") + public void testCoercionStringVsExplicitIntegerWithMap(RUN_TYPE runType) { final String drl = "package org.drools.compiler.integrationtests;\n" + "import " + Map.class.getCanonicalName() + ";\n" + "import " + StringHolder.class.getCanonicalName() + ";\n" + @@ -440,7 +459,7 @@ public void testCoercionStringVsExplicitIntegerWithMap() { // String is coerced to Integer (thus, Number comparison) - KieSession ksession = getKieSession(drl); + KieSession ksession =getKieSession(runType, drl); try { final List list = new ArrayList<>(); ksession.setGlobal("list", list); diff --git a/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/UseClassFieldsInRulesTest.java b/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/UseClassFieldsInRulesTest.java index beec7efc349..3e1a920ea99 100644 --- a/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/UseClassFieldsInRulesTest.java +++ b/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/UseClassFieldsInRulesTest.java @@ -18,16 +18,14 @@ */ package org.drools.model.codegen.execmodel; -import org.junit.Test; import org.kie.api.runtime.KieSession; import static org.assertj.core.api.Assertions.assertThat; -public class UseClassFieldsInRulesTest extends BaseModelTest { +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; - public UseClassFieldsInRulesTest( BaseModelTest.RUN_TYPE testRunType ) { - super( testRunType ); - } +public class UseClassFieldsInRulesTest extends BaseModelTest { public static class ClassWithFields { public final int field = 3; @@ -38,54 +36,63 @@ public int getValue() { } } - @Test - public void testUseAccessor() { - doCheck(true, "value > 2"); + @ParameterizedTest + @MethodSource("parameters") + public void testUseAccessor(RUN_TYPE runType) { + doCheck(runType, true, "value > 2"); } - @Test - public void testUseField() { - doCheck(true, "field > 2"); + @ParameterizedTest + @MethodSource("parameters") + public void testUseField(RUN_TYPE runType) { + doCheck(runType, true, "field > 2"); } - @Test - public void testUseStaticField() { - doCheck(true, "STATIC_FIELD > 2"); + @ParameterizedTest + @MethodSource("parameters") + public void testUseStaticField(RUN_TYPE runType) { + doCheck(runType, true, "STATIC_FIELD > 2"); } - @Test - public void testUseAccessorInFunction() { - doCheck(true, "greaterThan( value, 2 )"); + @ParameterizedTest + @MethodSource("parameters") + public void testUseAccessorInFunction(RUN_TYPE runType) { + doCheck(runType, true, "greaterThan( value, 2 )"); } - @Test - public void testUseFieldInFunction() { - doCheck(true, "greaterThan( field, 2 )"); + @ParameterizedTest + @MethodSource("parameters") + public void testUseFieldInFunction(RUN_TYPE runType) { + doCheck(runType, true, "greaterThan( field, 2 )"); } - @Test - public void testUseStaticFieldInFunction() { - doCheck(true, "greaterThan( STATIC_FIELD, 2 )"); + @ParameterizedTest + @MethodSource("parameters") + public void testUseStaticFieldInFunction(RUN_TYPE runType) { + doCheck(runType, true, "greaterThan( STATIC_FIELD, 2 )"); } public static boolean greaterThanMethod(int i1, int i2) { return i1 > i2; } - @Test - public void testUseAccessorInMethod() { - doCheck(false, "greaterThanMethod( value, 2 )"); + @ParameterizedTest + @MethodSource("parameters") + public void testUseAccessorInMethod(RUN_TYPE runType) { + doCheck(runType, false, "greaterThanMethod( value, 2 )"); } - @Test - public void testUseFieldInMethod() { - doCheck(false, "greaterThanMethod( field, 2 )"); + @ParameterizedTest + @MethodSource("parameters") + public void testUseFieldInMethod(RUN_TYPE runType) { + doCheck(runType, false, "greaterThanMethod( field, 2 )"); } - @Test - public void testUseStaticFieldInMethod() { - doCheck(false, "greaterThanMethod( STATIC_FIELD, 2 )"); + @ParameterizedTest + @MethodSource("parameters") + public void testUseStaticFieldInMethod(RUN_TYPE runType) { + doCheck(runType, false, "greaterThanMethod( STATIC_FIELD, 2 )"); } - private void doCheck(boolean useFunction, String pattern) { + private void doCheck(RUN_TYPE runType, boolean useFunction, String pattern) { String str = "import " + ClassWithFields.class.getCanonicalName() + "\n" + (useFunction ? @@ -96,14 +103,15 @@ private void doCheck(boolean useFunction, String pattern) { "then\n" + "end "; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); ksession.insert(new ClassWithFields()); assertThat(ksession.fireAllRules()).isEqualTo(1); } - @Test - public void testMethodInFrom() { + @ParameterizedTest + @MethodSource("parameters") + public void testMethodInFrom(RUN_TYPE runType) { String str = "import " + ClassWithFields.class.getCanonicalName() + "\n" + "import static " + UseClassFieldsInRulesTest.class.getCanonicalName() + ".*\n" + @@ -112,12 +120,13 @@ public void testMethodInFrom() { "then\n" + "end "; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); assertThat(ksession.fireAllRules()).isEqualTo(1); } - @Test - public void testMethodInEval() { + @ParameterizedTest + @MethodSource("parameters") + public void testMethodInEval(RUN_TYPE runType) { String str = "import " + ClassWithFields.class.getCanonicalName() + "\n" + "import static " + UseClassFieldsInRulesTest.class.getCanonicalName() + ".*\n" + @@ -126,12 +135,13 @@ public void testMethodInEval() { "then\n" + "end "; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); assertThat(ksession.fireAllRules()).isEqualTo(1); } - @Test - public void testFunctionInFrom() { + @ParameterizedTest + @MethodSource("parameters") + public void testFunctionInFrom(RUN_TYPE runType) { String str = "import " + ClassWithFields.class.getCanonicalName() + "\n" + "function boolean greaterThan(int i1, int i2) { return i1 > i2; }\n" + @@ -140,12 +150,13 @@ public void testFunctionInFrom() { "then\n" + "end "; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); assertThat(ksession.fireAllRules()).isEqualTo(1); } - @Test - public void testFunctionWithEval() { + @ParameterizedTest + @MethodSource("parameters") + public void testFunctionWithEval(RUN_TYPE runType) { String str = "import " + ClassWithFields.class.getCanonicalName() + "\n" + "function boolean greaterThan(int i1, int i2) { return i1 > i2; }\n" + @@ -154,7 +165,7 @@ public void testFunctionWithEval() { "then\n" + "end "; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); assertThat(ksession.fireAllRules()).isEqualTo(1); } } diff --git a/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/alphaNetworkCompiler/ObjectTypeNodeCompilerTest.java b/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/alphaNetworkCompiler/ObjectTypeNodeCompilerTest.java index 682c060394c..8c4a9610d73 100644 --- a/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/alphaNetworkCompiler/ObjectTypeNodeCompilerTest.java +++ b/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/alphaNetworkCompiler/ObjectTypeNodeCompilerTest.java @@ -25,19 +25,17 @@ import org.drools.model.codegen.execmodel.domain.EnumFact1; import org.drools.model.codegen.execmodel.domain.Person; import org.drools.model.codegen.execmodel.domain.Result; -import org.junit.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; import org.kie.api.runtime.KieSession; import static org.assertj.core.api.Assertions.assertThat; public class ObjectTypeNodeCompilerTest extends BaseModelTest { - public ObjectTypeNodeCompilerTest(RUN_TYPE testRunType) { - super(testRunType); - } - - @Test - public void testAlphaConstraint() { + @ParameterizedTest + @MethodSource("parameters") + public void testAlphaConstraint(RUN_TYPE runType) { String str = "rule \"Bind\"\n" + "when\n" + @@ -45,7 +43,7 @@ public void testAlphaConstraint() { "then\n" + "end"; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); ksession.insert("Luca"); ksession.insert("Asdrubale"); @@ -53,8 +51,9 @@ public void testAlphaConstraint() { assertThat(ksession.fireAllRules()).isEqualTo(1); } - @Test - public void testAlphaConstraintsSwitchString() { + @ParameterizedTest + @MethodSource("parameters") + public void testAlphaConstraintsSwitchString(RUN_TYPE runType) { String str = "import " + Person.class.getCanonicalName() + ";" + "rule \"Bind1\"\n" + @@ -73,7 +72,7 @@ public void testAlphaConstraintsSwitchString() { "then\n" + "end\n"; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); ksession.insert(new Person("Luca")); ksession.insert(new Person("Asdrubale")); @@ -84,8 +83,9 @@ public void testAlphaConstraintsSwitchString() { /* This generates the switch but not the inlining */ - @Test - public void testAlphaConstraintsSwitchBigDecimal() { + @ParameterizedTest + @MethodSource("parameters") + public void testAlphaConstraintsSwitchBigDecimal(RUN_TYPE runType) { String str = "import " + Person.class.getCanonicalName() + ";" + "import " + BigDecimal.class.getCanonicalName() + ";" + @@ -105,7 +105,7 @@ public void testAlphaConstraintsSwitchBigDecimal() { "then\n" + "end\n"; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); ksession.insert(new Person("Luca", new BigDecimal(0))); ksession.insert(new Person("Asdrubale", new BigDecimal(10))); @@ -113,8 +113,9 @@ public void testAlphaConstraintsSwitchBigDecimal() { assertThat(ksession.fireAllRules()).isEqualTo(1); } - @Test - public void testAlphaConstraintsSwitchPerson() { + @ParameterizedTest + @MethodSource("parameters") + public void testAlphaConstraintsSwitchPerson(RUN_TYPE runType) { String str = "import " + Person.class.getCanonicalName() + ";" + "rule \"Bind1\"\n" + @@ -133,7 +134,7 @@ public void testAlphaConstraintsSwitchPerson() { "then\n" + "end\n"; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); ksession.insert(new Person("Luca")); ksession.insert(new Person("Asdrubale")); @@ -141,8 +142,9 @@ public void testAlphaConstraintsSwitchPerson() { assertThat(ksession.fireAllRules()).isEqualTo(1); } - @Test - public void testAlphaConstraintsSwitchIntegers() { + @ParameterizedTest + @MethodSource("parameters") + public void testAlphaConstraintsSwitchIntegers(RUN_TYPE runType) { String str = "rule \"Bind1\"\n" + "when\n" + @@ -160,7 +162,7 @@ public void testAlphaConstraintsSwitchIntegers() { "then\n" + "end\n"; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); ksession.insert("Luca"); ksession.insert("Asdrubale"); @@ -168,8 +170,9 @@ public void testAlphaConstraintsSwitchIntegers() { assertThat(ksession.fireAllRules()).isEqualTo(1); } - @Test - public void testEnum() { + @ParameterizedTest + @MethodSource("parameters") + public void testEnum(RUN_TYPE runType) { String str = "import " + EnumFact1.class.getCanonicalName() + ";\n" + "import " + ChildFactWithEnum1.class.getCanonicalName() + ";\n" + @@ -186,14 +189,15 @@ public void testEnum() { "then\n" + "end\n"; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); ksession.insert(new ChildFactWithEnum1(1, 3, EnumFact1.FIRST)); ksession.insert(new ChildFactWithEnum1(1, 3, EnumFact1.SECOND)); assertThat(ksession.fireAllRules()).isEqualTo(2); } - @Test - public void testAlphaConstraintWithModification() { + @ParameterizedTest + @MethodSource("parameters") + public void testAlphaConstraintWithModification(RUN_TYPE runType) { String str = "import " + Result.class.getCanonicalName() + ";" + "rule \"Bind\"\n" + @@ -204,7 +208,7 @@ public void testAlphaConstraintWithModification() { " $r.setValue($s + \" is greater than 4 and smaller than 10\");\n" + "end"; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); ksession.insert("Luca"); ksession.insert("Asdrubale"); @@ -218,8 +222,9 @@ public void testAlphaConstraintWithModification() { assertThat(result.getValue()).isEqualTo("Asdrubale is greater than 4 and smaller than 10"); } - @Test - public void testModify() { + @ParameterizedTest + @MethodSource("parameters") + public void testModify(RUN_TYPE runType) { String str = "import " + Person.class.getCanonicalName() + ";" + "rule \"Modify\"\n" + @@ -229,7 +234,7 @@ public void testModify() { " modify($p) { setName($p.getName() + \"30\"); }" + "end"; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); final Person luca = new Person("Luca", 30); ksession.insert(luca); @@ -240,8 +245,9 @@ public void testModify() { assertThat(luca.getName()).isEqualTo("Luca30"); } - @Test - public void testModify2() { + @ParameterizedTest + @MethodSource("parameters") + public void testModify2(RUN_TYPE runType) { String str = "import " + Person.class.getCanonicalName() + ";" + "rule \"Modify\"\n" + @@ -251,7 +257,7 @@ public void testModify2() { " modify($p) { setAge($p.getAge() + 1); }" + "end"; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); final Person luca = new Person("Luca", 30); ksession.insert(luca); @@ -265,8 +271,9 @@ public void testModify2() { assertThat(luca.getAge() == 40).isTrue(); } - @Test - public void testAlphaConstraintNagate() { + @ParameterizedTest + @MethodSource("parameters") + public void testAlphaConstraintNagate(RUN_TYPE runType) { final String str = "import " + Person.class.getCanonicalName() + ";\n" + "rule R1 when\n" + @@ -274,7 +281,7 @@ public void testAlphaConstraintNagate() { "then\n" + "end"; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); try { ksession.insert(new Person("Mario", 45)); assertThat(ksession.fireAllRules()).isEqualTo(0); diff --git a/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/assembler/AssemblerTest.java b/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/assembler/AssemblerTest.java index 244c35e90eb..5b29de0af4e 100644 --- a/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/assembler/AssemblerTest.java +++ b/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/assembler/AssemblerTest.java @@ -21,7 +21,7 @@ import java.util.List; import org.drools.model.codegen.ExecutableModelProject; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.kie.api.KieBase; import org.kie.api.KieServices; import org.kie.api.builder.KieBuilder; diff --git a/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/bigdecimaltest/BigDecimalTest.java b/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/bigdecimaltest/BigDecimalTest.java index 885b27cb026..038b4950442 100644 --- a/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/bigdecimaltest/BigDecimalTest.java +++ b/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/bigdecimaltest/BigDecimalTest.java @@ -23,19 +23,17 @@ import java.util.List; import org.drools.model.codegen.execmodel.BaseModelTest; -import org.junit.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; import org.kie.api.runtime.KieSession; import static org.assertj.core.api.Assertions.assertThat; public class BigDecimalTest extends BaseModelTest { - public BigDecimalTest(RUN_TYPE testRunType) { - super(testRunType); - } - - @Test - public void testBigDecimalGreaterThan() { + @ParameterizedTest + @MethodSource("parameters") + public void testBigDecimalGreaterThan(RUN_TYPE runType) { String str = "package org.drools.modelcompiler.bigdecimals\n" + "import " + Customer.class.getCanonicalName() + ";\n" + @@ -50,7 +48,7 @@ public void testBigDecimalGreaterThan() { "update($policy);\n" + "end"; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); Customer customer = new Customer(); customer.setCode("code1"); @@ -67,8 +65,9 @@ public void testBigDecimalGreaterThan() { } - @Test - public void testBigDecimalCompare() { + @ParameterizedTest + @MethodSource("parameters") + public void testBigDecimalCompare(RUN_TYPE runType) { String str = "package org.drools.modelcompiler.bigdecimals\n" + "import " + Customer.class.getCanonicalName() + ";\n" + @@ -83,7 +82,7 @@ public void testBigDecimalCompare() { "update($policy);\n" + "end"; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); Customer customer = new Customer(); customer.setCode("code1"); @@ -100,8 +99,9 @@ public void testBigDecimalCompare() { } - @Test - public void testBigDecimalEqualsToNull() { + @ParameterizedTest + @MethodSource("parameters") + public void testBigDecimalEqualsToNull(RUN_TYPE runType) { String str = "package org.drools.modelcompiler.bigdecimals\n" + "import " + Customer.class.getCanonicalName() + ";\n" + @@ -112,7 +112,7 @@ public void testBigDecimalEqualsToNull() { "then\n" + "end"; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); Customer customer = new Customer(); @@ -120,8 +120,9 @@ public void testBigDecimalEqualsToNull() { assertThat(ksession.fireAllRules()).isEqualTo(1); } - @Test - public void testBigDecimalNotEqualsToNull() { + @ParameterizedTest + @MethodSource("parameters") + public void testBigDecimalNotEqualsToNull(RUN_TYPE runType) { String str = "package org.drools.modelcompiler.bigdecimals\n" + "import " + Customer.class.getCanonicalName() + ";\n" + @@ -132,7 +133,7 @@ public void testBigDecimalNotEqualsToNull() { "then\n" + "end"; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); Customer customer = new Customer(); customer.setCode("code1"); @@ -142,8 +143,9 @@ public void testBigDecimalNotEqualsToNull() { assertThat(ksession.fireAllRules()).isEqualTo(1); } - @Test - public void testBigDecimalNotEqualsToLiteralNull() { + @ParameterizedTest + @MethodSource("parameters") + public void testBigDecimalNotEqualsToLiteralNull(RUN_TYPE runType) { String str = "package org.drools.modelcompiler.bigdecimals\n" + "import " + Customer.class.getCanonicalName() + ";\n" + @@ -154,7 +156,7 @@ public void testBigDecimalNotEqualsToLiteralNull() { "then\n" + "end"; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); Customer customer = new Customer(); customer.setCode("code1"); @@ -164,8 +166,9 @@ public void testBigDecimalNotEqualsToLiteralNull() { assertThat(ksession.fireAllRules()).isEqualTo(1); } - @Test - public void testBigDecimalNotEqualsToLiteralValue() { + @ParameterizedTest + @MethodSource("parameters") + public void testBigDecimalNotEqualsToLiteralValue(RUN_TYPE runType) { String str = "package org.drools.modelcompiler.bigdecimals\n" + "import " + Customer.class.getCanonicalName() + ";\n" + @@ -176,7 +179,7 @@ public void testBigDecimalNotEqualsToLiteralValue() { "then\n" + "end"; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); Customer customer = new Customer(); customer.setCode("code1"); @@ -186,8 +189,9 @@ public void testBigDecimalNotEqualsToLiteralValue() { assertThat(ksession.fireAllRules()).isEqualTo(1); } - @Test - public void testBigDecimalGreaterThanNull() { + @ParameterizedTest + @MethodSource("parameters") + public void testBigDecimalGreaterThanNull(RUN_TYPE runType) { String str = "package org.drools.modelcompiler.bigdecimals\n" + "import " + Customer.class.getCanonicalName() + ";\n" + @@ -198,7 +202,7 @@ public void testBigDecimalGreaterThanNull() { "then\n" + "end"; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); Customer customer = new Customer(); customer.setCode("code1"); @@ -208,8 +212,9 @@ public void testBigDecimalGreaterThanNull() { assertThat(ksession.fireAllRules()).isEqualTo(0); } - @Test - public void testBigDecimalEquals() { + @ParameterizedTest + @MethodSource("parameters") + public void testBigDecimalEquals(RUN_TYPE runType) { // DROOLS-3527 String str = "package org.drools.modelcompiler.bigdecimals\n" + @@ -220,7 +225,7 @@ public void testBigDecimalEquals() { "then\n" + "end"; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); Customer customer = new Customer(); customer.setRate(new BigDecimal("12.111")); @@ -231,8 +236,9 @@ public void testBigDecimalEquals() { } - @Test - public void testBigDecimalAdd() { + @ParameterizedTest + @MethodSource("parameters") + public void testBigDecimalAdd(RUN_TYPE runType) { // RHDM-1635 String str = "package org.drools.modelcompiler.bigdecimals\n" + @@ -243,7 +249,7 @@ public void testBigDecimalAdd() { "then\n" + "end"; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); Customer c1 = new Customer(); c1.setRate(new BigDecimal("10")); @@ -256,8 +262,9 @@ public void testBigDecimalAdd() { assertThat(ksession.fireAllRules()).isEqualTo(1); } - @Test - public void testBigDecimalRemainder() { + @ParameterizedTest + @MethodSource("parameters") + public void testBigDecimalRemainder(RUN_TYPE runType) { // RHDM-1635 String str = "package org.drools.modelcompiler.bigdecimals\n" + @@ -268,7 +275,7 @@ public void testBigDecimalRemainder() { "then\n" + "end"; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); Customer c1 = new Customer(); c1.setRate(new BigDecimal("20")); @@ -313,8 +320,9 @@ public String toString() { } } - @Test - public void testNonTerminatingDecimalExpansion() { + @ParameterizedTest + @MethodSource("parameters") + public void testNonTerminatingDecimalExpansion(RUN_TYPE runType) { // DROOLS-6804 String str = "package org.drools.modelcompiler.bigdecimals\n" + @@ -325,7 +333,7 @@ public void testNonTerminatingDecimalExpansion() { " $o.setTax($price - ($price / ($taxRate + 1)));\n" + "end"; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); Order order = new Order(); order.setPrice(new BigDecimal("100000000")); @@ -336,8 +344,9 @@ public void testNonTerminatingDecimalExpansion() { assertThat(order.getTax()).isEqualTo(new BigDecimal("9090909.09090909090909090909090909")); } - @Test - public void testBigDecimalAndStringComparison() { + @ParameterizedTest + @MethodSource("parameters") + public void testBigDecimalAndStringComparison(RUN_TYPE runType) { // DROOLS-6823 String str = "package org.drools.modelcompiler.bigdecimals\n" + @@ -348,7 +357,7 @@ public void testBigDecimalAndStringComparison() { "then\n" + "end"; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); Order order = new Order(); order.setPrice(new BigDecimal(300)); @@ -358,8 +367,9 @@ public void testBigDecimalAndStringComparison() { assertThat(ksession.fireAllRules()).isEqualTo(1); } - @Test - public void testStringAndBigDecimalComparison() { + @ParameterizedTest + @MethodSource("parameters") + public void testStringAndBigDecimalComparison(RUN_TYPE runType) { // DROOLS-6823 String str = "package org.drools.modelcompiler.bigdecimals\n" + @@ -370,7 +380,7 @@ public void testStringAndBigDecimalComparison() { "then\n" + "end"; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); Order order = new Order(); order.setPrice(new BigDecimal(300)); @@ -412,62 +422,73 @@ public void setBd2(BigDecimal bd2) { } } - @Test - public void testMultiply() { - testBigDecimalArithmeticOperation("BdHolder(bd2 == bd1 * 10)", "10", "100"); + @ParameterizedTest + @MethodSource("parameters") + public void testMultiply(RUN_TYPE runType) { + testBigDecimalArithmeticOperation(runType, "BdHolder(bd2 == bd1 * 10)", "10", "100"); } - @Test - public void testMultiplyWithNegativeValue() { - testBigDecimalArithmeticOperation("BdHolder(bd2 == bd1 * -1)", "10", "-10"); + @ParameterizedTest + @MethodSource("parameters") + public void testMultiplyWithNegativeValue(RUN_TYPE runType) { + testBigDecimalArithmeticOperation(runType, "BdHolder(bd2 == bd1 * -1)", "10", "-10"); } - @Test - public void testMultiplyWithBindVariable() { - testBigDecimalArithmeticOperation("BdHolder($bd1 : bd1, bd2 == $bd1 * 10)", "10", "100"); + @ParameterizedTest + @MethodSource("parameters") + public void testMultiplyWithBindVariable(RUN_TYPE runType) { + testBigDecimalArithmeticOperation(runType, "BdHolder($bd1 : bd1, bd2 == $bd1 * 10)", "10", "100"); } - @Test - public void testMultiplyWithBindVariableWithNegativeValue() { - testBigDecimalArithmeticOperation("BdHolder($bd1 : bd1, bd2 == $bd1 * -1)", "10", "-10"); + @ParameterizedTest + @MethodSource("parameters") + public void testMultiplyWithBindVariableWithNegativeValue(RUN_TYPE runType) { + testBigDecimalArithmeticOperation(runType, "BdHolder($bd1 : bd1, bd2 == $bd1 * -1)", "10", "-10"); } - @Test - public void testMultiplyWithBindVariableWithNegativeValueEnclosed() { - testBigDecimalArithmeticOperation("BdHolder($bd1 : bd1, bd2 == $bd1 * (-1))", "10", "-10"); + @ParameterizedTest + @MethodSource("parameters") + public void testMultiplyWithBindVariableWithNegativeValueEnclosed(RUN_TYPE runType) { + testBigDecimalArithmeticOperation(runType, "BdHolder($bd1 : bd1, bd2 == $bd1 * (-1))", "10", "-10"); } - @Test - public void testMultiplyWithBindVariableWithNegativeValueEnclosedBoth() { - testBigDecimalArithmeticOperation("BdHolder($bd1 : bd1, bd2 == ($bd1 * -1))", "10", "-10"); + @ParameterizedTest + @MethodSource("parameters") + public void testMultiplyWithBindVariableWithNegativeValueEnclosedBoth(RUN_TYPE runType) { + testBigDecimalArithmeticOperation(runType, "BdHolder($bd1 : bd1, bd2 == ($bd1 * -1))", "10", "-10"); } - @Test - public void testMultiplyWithBindVariableWithNegativeValueEnclosedNest() { - testBigDecimalArithmeticOperation("BdHolder($bd1 : bd1, bd2 == ($bd1 * (-1)))", "10", "-10"); + @ParameterizedTest + @MethodSource("parameters") + public void testMultiplyWithBindVariableWithNegativeValueEnclosedNest(RUN_TYPE runType) { + testBigDecimalArithmeticOperation(runType, "BdHolder($bd1 : bd1, bd2 == ($bd1 * (-1)))", "10", "-10"); } - @Test - public void testAddWithBindVariable() { - testBigDecimalArithmeticOperation("BdHolder($bd1 : bd1, bd2 == $bd1 + 10)", "10", "20"); + @ParameterizedTest + @MethodSource("parameters") + public void testAddWithBindVariable(RUN_TYPE runType) { + testBigDecimalArithmeticOperation(runType, "BdHolder($bd1 : bd1, bd2 == $bd1 + 10)", "10", "20"); } - @Test - public void testSubtractWithBindVariable() { - testBigDecimalArithmeticOperation("BdHolder($bd1 : bd1, bd2 == $bd1 - 10)", "10", "0"); + @ParameterizedTest + @MethodSource("parameters") + public void testSubtractWithBindVariable(RUN_TYPE runType) { + testBigDecimalArithmeticOperation(runType, "BdHolder($bd1 : bd1, bd2 == $bd1 - 10)", "10", "0"); } - @Test - public void testDivideWithBindVariable() { - testBigDecimalArithmeticOperation("BdHolder($bd1 : bd1, bd2 == $bd1 / 10)", "10", "1"); + @ParameterizedTest + @MethodSource("parameters") + public void testDivideWithBindVariable(RUN_TYPE runType) { + testBigDecimalArithmeticOperation(runType, "BdHolder($bd1 : bd1, bd2 == $bd1 / 10)", "10", "1"); } - @Test - public void testModWithBindVariable() { - testBigDecimalArithmeticOperation("BdHolder($bd1 : bd1, bd2 == $bd1 % 10)", "10", "0"); + @ParameterizedTest + @MethodSource("parameters") + public void testModWithBindVariable(RUN_TYPE runType) { + testBigDecimalArithmeticOperation(runType, "BdHolder($bd1 : bd1, bd2 == $bd1 % 10)", "10", "0"); } - private void testBigDecimalArithmeticOperation(String pattern, String bd1, String bd2) { + private void testBigDecimalArithmeticOperation(RUN_TYPE runType, String pattern, String bd1, String bd2) { String str = "package org.drools.modelcompiler.bigdecimals\n" + "import " + BdHolder.class.getCanonicalName() + ";\n" + @@ -476,7 +497,7 @@ private void testBigDecimalArithmeticOperation(String pattern, String bd1, Strin "then\n" + "end"; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); BdHolder holder = new BdHolder(new BigDecimal(bd1), new BigDecimal(bd2)); ksession.insert(holder); @@ -484,8 +505,9 @@ private void testBigDecimalArithmeticOperation(String pattern, String bd1, Strin assertThat(ksession.fireAllRules()).isEqualTo(1); } - @Test - public void testBigDecimalLiteralLhsNegative() { + @ParameterizedTest + @MethodSource("parameters") + public void testBigDecimalLiteralLhsNegative(RUN_TYPE runType) { // DROOLS-6596 String str = "package org.drools.modelcompiler.bigdecimals\n" + @@ -495,7 +517,7 @@ public void testBigDecimalLiteralLhsNegative() { "then\n" + "end"; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); BdHolder holder = new BdHolder(); holder.setBd1(new BigDecimal("10")); @@ -505,8 +527,9 @@ public void testBigDecimalLiteralLhsNegative() { assertThat(fired).isEqualTo(1); } - @Test - public void testBigDecimalLiteralRhsNegative() { + @ParameterizedTest + @MethodSource("parameters") + public void testBigDecimalLiteralRhsNegative(RUN_TYPE runType) { // DROOLS-6596 String str = "package org.drools.modelcompiler.bigdecimals\n" + @@ -517,7 +540,7 @@ public void testBigDecimalLiteralRhsNegative() { " $holder.bd1 = -10.5B;\n" + "end"; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); BdHolder holder = new BdHolder(); ksession.insert(holder); @@ -526,8 +549,9 @@ public void testBigDecimalLiteralRhsNegative() { assertThat(holder.getBd1()).isEqualTo(new BigDecimal("-10.5")); } - @Test - public void testBigDecimalLiteralWithBinding() { + @ParameterizedTest + @MethodSource("parameters") + public void testBigDecimalLiteralWithBinding(RUN_TYPE runType) { // DROOLS-6936 String str = "package org.drools.modelcompiler.bigdecimals\n" + @@ -540,7 +564,7 @@ public void testBigDecimalLiteralWithBinding() { " result.add($zero);\n" + "end"; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); List result = new ArrayList<>(); ksession.setGlobal("result", result); @@ -552,8 +576,9 @@ public void testBigDecimalLiteralWithBinding() { assertThat(result).containsExactly(new BigDecimal("0")); } - @Test - public void testModifyWithNegativeBigDecimal() { + @ParameterizedTest + @MethodSource("parameters") + public void testModifyWithNegativeBigDecimal(RUN_TYPE runType) { // DROOLS-7324 String str = "package org.drools.modelcompiler.bigdecimals\n" + @@ -565,7 +590,7 @@ public void testModifyWithNegativeBigDecimal() { " modify($bd) { bd1 = -1 }\n" + "end"; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); List result = new ArrayList<>(); ksession.setGlobal("result", result); @@ -577,8 +602,9 @@ public void testModifyWithNegativeBigDecimal() { assertThat(fires).isEqualTo(1); } - @Test - public void bigDecimalArithmeticInMethodCallScope() { + @ParameterizedTest + @MethodSource("parameters") + public void bigDecimalArithmeticInMethodCallScope(RUN_TYPE runType) { // DROOLS-7364 String str = "package org.drools.modelcompiler.bigdecimals\n" + @@ -592,7 +618,7 @@ public void bigDecimalArithmeticInMethodCallScope() { " result.add($ans);\n" + "end"; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); List result = new ArrayList<>(); ksession.setGlobal("result", result); @@ -604,8 +630,9 @@ public void bigDecimalArithmeticInMethodCallScope() { assertThat(result).contains(2000L); } - @Test - public void bigDecimalArithmeticInMethodCallScopeInMethodCallArgument() { + @ParameterizedTest + @MethodSource("parameters") + public void bigDecimalArithmeticInMethodCallScopeInMethodCallArgument(RUN_TYPE runType) { // DROOLS-7364 String str = "package org.drools.modelcompiler.bigdecimals\n" + @@ -619,7 +646,7 @@ public void bigDecimalArithmeticInMethodCallScopeInMethodCallArgument() { " result.add($ans);\n" + "end"; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); List result = new ArrayList<>(); ksession.setGlobal("result", result); @@ -631,8 +658,9 @@ public void bigDecimalArithmeticInMethodCallScopeInMethodCallArgument() { assertThat(result).contains("2,000"); } - @Test - public void nonBigDecimalArithmeticInMethodCallScopeInMethodCallArgument() { + @ParameterizedTest + @MethodSource("parameters") + public void nonBigDecimalArithmeticInMethodCallScopeInMethodCallArgument(RUN_TYPE runType) { // DROOLS-7364 String str = "package org.drools.modelcompiler.bigdecimals\n" + @@ -646,7 +674,7 @@ public void nonBigDecimalArithmeticInMethodCallScopeInMethodCallArgument() { " result.add($ans);\n" + "end"; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); List result = new ArrayList<>(); ksession.setGlobal("result", result); @@ -658,8 +686,9 @@ public void nonBigDecimalArithmeticInMethodCallScopeInMethodCallArgument() { assertThat(result).contains("2,000"); } - @Test - public void bigDecimalArithmeticInMethodCallArgumentWithoutEnclosedExpr() { + @ParameterizedTest + @MethodSource("parameters") + public void bigDecimalArithmeticInMethodCallArgumentWithoutEnclosedExpr(RUN_TYPE runType) { // DROOLS-7364 String str = "package org.drools.modelcompiler.bigdecimals\n" + @@ -674,7 +703,7 @@ public void bigDecimalArithmeticInMethodCallArgumentWithoutEnclosedExpr() { " result.add($ans);\n" + "end"; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); List result = new ArrayList<>(); ksession.setGlobal("result", result); @@ -693,8 +722,9 @@ public static String getString(String format, BigDecimal bd) { } } - @Test - public void bigDecimalEqualityWithDifferentScale_shouldBeEqual() { + @ParameterizedTest + @MethodSource("parameters") + public void bigDecimalEqualityWithDifferentScale_shouldBeEqual(RUN_TYPE runType) { // DROOLS-7414 String str = "package org.drools.modelcompiler.bigdecimals\n" + @@ -708,7 +738,7 @@ public void bigDecimalEqualityWithDifferentScale_shouldBeEqual() { " result.add($rate);\n" + "end"; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); List result = new ArrayList<>(); ksession.setGlobal("result", result); @@ -722,8 +752,9 @@ public void bigDecimalEqualityWithDifferentScale_shouldBeEqual() { assertThat(result).contains(new BigDecimal("1.00")); } - @Test - public void bigDecimalCoercionInMethodArgument_shouldNotFailToBuild() { + @ParameterizedTest + @MethodSource("parameters") + public void bigDecimalCoercionInMethodArgument_shouldNotFailToBuild(RUN_TYPE runType) { // KIE-748 String str = "package org.drools.modelcompiler.bigdecimals\n" + @@ -735,7 +766,7 @@ public void bigDecimalCoercionInMethodArgument_shouldNotFailToBuild() { " then\n" + "end"; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); BDFact bdFact = new BDFact(); bdFact.setValue2(new BigDecimal("3")); @@ -745,8 +776,9 @@ public void bigDecimalCoercionInMethodArgument_shouldNotFailToBuild() { assertThat(ksession.fireAllRules()).isEqualTo(1); } - @Test - public void bigDecimalCoercionInNestedMethodArgument_shouldNotFailToBuild() { + @ParameterizedTest + @MethodSource("parameters") + public void bigDecimalCoercionInNestedMethodArgument_shouldNotFailToBuild(RUN_TYPE runType) { // KIE-748 String str = "package org.drools.modelcompiler.bigdecimals\n" + @@ -758,7 +790,7 @@ public void bigDecimalCoercionInNestedMethodArgument_shouldNotFailToBuild() { " then\n" + "end"; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); BDFact bdFact = new BDFact(); bdFact.setValue1(new BigDecimal("10")); @@ -773,22 +805,25 @@ public static String intToString(int value) { return Integer.toString(value); } - @Test - public void bindVariableToBigDecimalCoercion2Operands_shouldBindCorrectResult() { - bindVariableToBigDecimalCoercion("$var : (1000 * value1)"); + @ParameterizedTest + @MethodSource("parameters") + public void bindVariableToBigDecimalCoercion2Operands_shouldBindCorrectResult(RUN_TYPE runType) { + bindVariableToBigDecimalCoercion(runType, "$var : (1000 * value1)"); } - @Test - public void bindVariableToBigDecimalCoercion3Operands_shouldBindCorrectResult() { - bindVariableToBigDecimalCoercion("$var : (100000 * value1 / 100)"); + @ParameterizedTest + @MethodSource("parameters") + public void bindVariableToBigDecimalCoercion3Operands_shouldBindCorrectResult(RUN_TYPE runType) { + bindVariableToBigDecimalCoercion(runType, "$var : (100000 * value1 / 100)"); } - @Test - public void bindVariableToBigDecimalCoercion3OperandsWithParentheses_shouldBindCorrectResult() { - bindVariableToBigDecimalCoercion("$var : ((100000 * value1) / 100)"); + @ParameterizedTest + @MethodSource("parameters") + public void bindVariableToBigDecimalCoercion3OperandsWithParentheses_shouldBindCorrectResult(RUN_TYPE runType) { + bindVariableToBigDecimalCoercion(runType, "$var : ((100000 * value1) / 100)"); } - private void bindVariableToBigDecimalCoercion(String binding) { + private void bindVariableToBigDecimalCoercion(RUN_TYPE runType, String binding) { // KIE-775 String str = "package org.drools.modelcompiler.bigdecimals\n" + @@ -801,7 +836,7 @@ private void bindVariableToBigDecimalCoercion(String binding) { " result.add($var);\n" + "end"; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); List result = new ArrayList<>(); ksession.setGlobal("result", result); @@ -814,8 +849,9 @@ private void bindVariableToBigDecimalCoercion(String binding) { assertThat(result).contains(new BigDecimal("80000")); } - @Test - public void bigDecimalInWithInt_shouldNotFailToBuild() { + @ParameterizedTest + @MethodSource("parameters") + public void bigDecimalInWithInt_shouldNotFailToBuild(RUN_TYPE runType) { String str = "package org.drools.modelcompiler.bigdecimals\n" + "import " + BDFact.class.getCanonicalName() + ";\n" + @@ -825,7 +861,7 @@ public void bigDecimalInWithInt_shouldNotFailToBuild() { " then\n" + "end"; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); BDFact bdFact = new BDFact(); bdFact.setValue1(new BigDecimal("100")); @@ -835,8 +871,9 @@ public void bigDecimalInWithInt_shouldNotFailToBuild() { assertThat(ksession.fireAllRules()).isEqualTo(1); } - @Test - public void bigDecimalInWithBD_shouldNotFailToBuild() { + @ParameterizedTest + @MethodSource("parameters") + public void bigDecimalInWithBD_shouldNotFailToBuild(RUN_TYPE runType) { String str = "package org.drools.modelcompiler.bigdecimals\n" + "import " + BDFact.class.getCanonicalName() + ";\n" + @@ -846,7 +883,7 @@ public void bigDecimalInWithBD_shouldNotFailToBuild() { " then\n" + "end"; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); BDFact bdFact = new BDFact(); bdFact.setValue1(new BigDecimal("100")); diff --git a/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/bigintegertest/BigIntegerTest.java b/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/bigintegertest/BigIntegerTest.java index abaf1ea4ab4..d1703048680 100644 --- a/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/bigintegertest/BigIntegerTest.java +++ b/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/bigintegertest/BigIntegerTest.java @@ -21,17 +21,14 @@ import java.math.BigInteger; import org.drools.model.codegen.execmodel.BaseModelTest; -import org.junit.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; import org.kie.api.runtime.KieSession; import static org.assertj.core.api.Assertions.assertThat; public class BigIntegerTest extends BaseModelTest { - public BigIntegerTest(RUN_TYPE testRunType) { - super(testRunType); - } - public static class BiHolder { private BigInteger bi1; @@ -64,8 +61,9 @@ public void setBi2(BigInteger bi2) { } } - @Test - public void testBigIntegerLiteralLhsNegative() { + @ParameterizedTest + @MethodSource("parameters") + public void testBigIntegerLiteralLhsNegative(RUN_TYPE runType) { // DROOLS-6596 String str = "package org.drools.modelcompiler.bigintegerss\n" + @@ -75,7 +73,7 @@ public void testBigIntegerLiteralLhsNegative() { "then\n" + "end"; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); BiHolder holder = new BiHolder(); holder.setBi1(new BigInteger("10")); @@ -85,8 +83,9 @@ public void testBigIntegerLiteralLhsNegative() { assertThat(fired).isEqualTo(1); } - @Test - public void testBigIntegerLiteralRhsNegative() { + @ParameterizedTest + @MethodSource("parameters") + public void testBigIntegerLiteralRhsNegative(RUN_TYPE runType) { // DROOLS-6596 String str = "package org.drools.modelcompiler.bigdecimals\n" + @@ -97,7 +96,7 @@ public void testBigIntegerLiteralRhsNegative() { " $holder.bi1 = -10I;\n" + "end"; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); BiHolder holder = new BiHolder(); ksession.insert(holder); diff --git a/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/constraints/ConstraintEvaluationExceptionTest.java b/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/constraints/ConstraintEvaluationExceptionTest.java index 896985761cd..07699c328ab 100644 --- a/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/constraints/ConstraintEvaluationExceptionTest.java +++ b/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/constraints/ConstraintEvaluationExceptionTest.java @@ -27,7 +27,8 @@ import org.drools.model.functions.PredicateInformation; import org.drools.modelcompiler.constraints.ConstraintEvaluationException; import org.drools.mvel.MVELConstraint; -import org.junit.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; import org.kie.api.io.Resource; import java.util.Collections; @@ -40,58 +41,58 @@ public class ConstraintEvaluationExceptionTest extends BaseModelTest { private MVELConstraint mvelConstraint; // non-exec-model - public ConstraintEvaluationExceptionTest(RUN_TYPE testRunType) { - super(testRunType); - } - - @Test - public void testMultipleRules() { - initConstraintTestField("age > 20", "R1", "sample.drl"); - addRuleToConstraintTestField("R2", "sample.drl"); - addRuleToConstraintTestField("R3", "sample.drl"); + @ParameterizedTest + @MethodSource("parameters") + public void testMultipleRules(RUN_TYPE runType) { + initConstraintTestField(runType, "age > 20", "R1", "sample.drl"); + addRuleToConstraintTestField(runType, "R2", "sample.drl"); + addRuleToConstraintTestField(runType, "R3", "sample.drl"); - assertMessage("Error evaluating constraint 'age > 20' in [Rule \"R1\", \"R2\", \"R3\" in sample.drl]"); + assertMessage(runType, "Error evaluating constraint 'age > 20' in [Rule \"R1\", \"R2\", \"R3\" in sample.drl]"); } - @Test - public void testMultipleRuleFiles() { - initConstraintTestField("age > 20", "R1", "sample1.drl"); - addRuleToConstraintTestField("R2", "sample1.drl"); - addRuleToConstraintTestField("R3", "sample2.drl"); + @ParameterizedTest + @MethodSource("parameters") + public void testMultipleRuleFiles(RUN_TYPE runType) { + initConstraintTestField(runType, "age > 20", "R1", "sample1.drl"); + addRuleToConstraintTestField(runType, "R2", "sample1.drl"); + addRuleToConstraintTestField(runType, "R3", "sample2.drl"); - assertMessage("Error evaluating constraint 'age > 20' in [Rule \"R1\", \"R2\" in sample1.drl] [Rule \"R3\" in sample2.drl]"); + assertMessage(runType, "Error evaluating constraint 'age > 20' in [Rule \"R1\", \"R2\" in sample1.drl] [Rule \"R3\" in sample2.drl]"); } - @Test - public void testNull() { - initConstraintTestField("age > 20", null, "sample1.drl"); - addRuleToConstraintTestField("R2", null); - addRuleToConstraintTestField(null, null); + @ParameterizedTest + @MethodSource("parameters") + public void testNull(RUN_TYPE runType) { + initConstraintTestField(runType, "age > 20", null, "sample1.drl"); + addRuleToConstraintTestField(runType, "R2", null); + addRuleToConstraintTestField(runType, null, null); // Irregular case. Not much useful info but doesn't throw NPE - assertMessage("Error evaluating constraint 'age > 20' in [Rule \"\", \"R2\" in ] [Rule \"\" in sample1.drl]"); + assertMessage(runType, "Error evaluating constraint 'age > 20' in [Rule \"\", \"R2\" in ] [Rule \"\" in sample1.drl]"); } - @Test - public void testExceedMaxRuleDefs() { - initConstraintTestField("age > 20", "R1", "sample1.drl"); - addRuleToConstraintTestField("R2", "sample1.drl"); - addRuleToConstraintTestField("R3", "sample1.drl"); - addRuleToConstraintTestField("R4", "sample1.drl"); - addRuleToConstraintTestField("R5", "sample1.drl"); - addRuleToConstraintTestField("R6", "sample1.drl"); - addRuleToConstraintTestField("R7", "sample2.drl"); - addRuleToConstraintTestField("R8", "sample2.drl"); - addRuleToConstraintTestField("R9", "sample2.drl"); - addRuleToConstraintTestField("R10", "sample3.drl"); - addRuleToConstraintTestField("R11", "sample3.drl"); - - assertMessage("Error evaluating constraint 'age > 20' in [Rule \"R1\", \"R2\", \"R3\", \"R4\", \"R5\", \"R6\" in sample1.drl] [Rule \"R7\", \"R8\", \"R9\" in sample2.drl] [Rule \"R10\" in sample3.drl]" + + @ParameterizedTest + @MethodSource("parameters") + public void testExceedMaxRuleDefs(RUN_TYPE runType) { + initConstraintTestField(runType, "age > 20", "R1", "sample1.drl"); + addRuleToConstraintTestField(runType, "R2", "sample1.drl"); + addRuleToConstraintTestField(runType, "R3", "sample1.drl"); + addRuleToConstraintTestField(runType, "R4", "sample1.drl"); + addRuleToConstraintTestField(runType, "R5", "sample1.drl"); + addRuleToConstraintTestField(runType, "R6", "sample1.drl"); + addRuleToConstraintTestField(runType, "R7", "sample2.drl"); + addRuleToConstraintTestField(runType, "R8", "sample2.drl"); + addRuleToConstraintTestField(runType, "R9", "sample2.drl"); + addRuleToConstraintTestField(runType, "R10", "sample3.drl"); + addRuleToConstraintTestField(runType, "R11", "sample3.drl"); + + assertMessage(runType, "Error evaluating constraint 'age > 20' in [Rule \"R1\", \"R2\", \"R3\", \"R4\", \"R5\", \"R6\" in sample1.drl] [Rule \"R7\", \"R8\", \"R9\" in sample2.drl] [Rule \"R10\" in sample3.drl]" + " and in more rules"); } - private void initConstraintTestField(String constraint, String ruleName, String ruleFileName) { - if (testRunType.isExecutableModel()) { + private void initConstraintTestField(RUN_TYPE runType, String constraint, String ruleName, String ruleFileName) { + if (runType.isExecutableModel()) { predicateInformation = new PredicateInformation(constraint, ruleName, ruleFileName); } else { mvelConstraint = new MVELConstraint("com.example", constraint, null, null, null, null, null); @@ -108,8 +109,8 @@ private void initConstraintTestField(String constraint, String ruleName, String } } - private void addRuleToConstraintTestField(String ruleName, String ruleFileName) { - if (testRunType.isExecutableModel()) { + private void addRuleToConstraintTestField(RUN_TYPE runType, String ruleName, String ruleFileName) { + if (runType.isExecutableModel()) { predicateInformation.addRuleNames(ruleName, ruleFileName); } else { // in non-exec-model, node sharing triggers merging @@ -128,9 +129,9 @@ private void addRuleToConstraintTestField(String ruleName, String ruleFileName) } } - private void assertMessage(String expected) { + private void assertMessage(RUN_TYPE runType, String expected) { Exception ex; - if (testRunType.isExecutableModel()) { + if (runType.isExecutableModel()) { ex = new ConstraintEvaluationException(predicateInformation, new RuntimeException("OriginalException")); } else { ex = new org.drools.mvel.ConstraintEvaluationException(mvelConstraint.getExpression(), mvelConstraint.getEvaluationContext(), new RuntimeException("OriginalException")); diff --git a/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/drlx/DrlxCompilerTest.java b/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/drlx/DrlxCompilerTest.java index 83687215e6d..12d250a8dd9 100644 --- a/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/drlx/DrlxCompilerTest.java +++ b/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/drlx/DrlxCompilerTest.java @@ -39,9 +39,9 @@ import org.drools.mvel.DrlDumper; import org.drools.mvel.parser.MvelParser; import org.drools.mvel.parser.ParseStart; +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.Test; import org.drools.io.InputStreamResource; -import org.junit.Ignore; -import org.junit.Test; import org.kie.api.KieServices; import org.kie.api.builder.KieBuilder; import org.kie.api.builder.KieFileSystem; @@ -81,7 +81,7 @@ public void testSingleFileUnit() throws Exception { } @Test - @Ignore("Rule Unit compiler is not available in Drools 8 yet") + @Disabled("Rule Unit compiler is not available in Drools 8 yet") public void testCompileUnit() throws IOException { InputStream p = getClass().getClassLoader().getResourceAsStream("drlx1/Example.drlx"); InputStreamResource r = new InputStreamResource(p); @@ -114,7 +114,7 @@ public void testCompileUnit() throws IOException { } @Test - @Ignore("Rule Unit Executor is not available in Drools 8 yet") + @Disabled("Rule Unit Executor is not available in Drools 8 yet") public void testCompileUnitFull() throws IOException { String path = "drlx1/Example.drlx"; InputStream p = getClass().getClassLoader().getResourceAsStream(path); diff --git a/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/exchange/SendReceiveTest.java b/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/exchange/SendReceiveTest.java index 93a63835411..a278ff378d1 100644 --- a/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/exchange/SendReceiveTest.java +++ b/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/exchange/SendReceiveTest.java @@ -29,7 +29,7 @@ import org.drools.model.impl.Exchange; import org.drools.model.impl.ModelImpl; import org.drools.modelcompiler.KieBaseBuilder; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.kie.api.KieBase; import org.kie.api.runtime.KieSession; diff --git a/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/fireandalarm/CompilerTest.java b/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/fireandalarm/CompilerTest.java index 977d7ef186a..71a699e8268 100644 --- a/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/fireandalarm/CompilerTest.java +++ b/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/fireandalarm/CompilerTest.java @@ -22,21 +22,19 @@ import org.drools.model.codegen.execmodel.fireandalarm.model.Alarm; import org.drools.model.codegen.execmodel.fireandalarm.model.Fire; import org.drools.model.codegen.execmodel.fireandalarm.model.Room; -import org.drools.model.codegen.execmodel.fireandalarm.model.Sprinkler; -import org.junit.Test; +import org.drools.model.codegen.execmodel.fireandalarm.model.Sprinkler; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; import org.kie.api.runtime.KieSession; -import org.kie.api.runtime.rule.FactHandle; +import org.kie.api.runtime.rule.FactHandle; import static org.assertj.core.api.Assertions.assertThat; public class CompilerTest extends BaseModelTest { - public CompilerTest( RUN_TYPE testRunType ) { - super( testRunType ); - } - - @Test - public void testFireAndAlarm() { + @ParameterizedTest + @MethodSource("parameters") + public void testFireAndAlarm(RUN_TYPE runType) { String str = "import " + StringBuilder.class.getCanonicalName() + ";\n" + "import " + Alarm.class.getCanonicalName() + ";\n" + @@ -87,7 +85,7 @@ public void testFireAndAlarm() { " sb.append( \"Everything is ok\\n\" );\n" + "end\n"; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); StringBuilder sb = new StringBuilder(); ksession.setGlobal( "sb", sb ); diff --git a/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/fireandalarm/FireAndAlarmTest.java b/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/fireandalarm/FireAndAlarmTest.java index 1c07380ae2d..7161da15f7e 100644 --- a/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/fireandalarm/FireAndAlarmTest.java +++ b/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/fireandalarm/FireAndAlarmTest.java @@ -27,7 +27,7 @@ import org.drools.model.codegen.execmodel.fireandalarm.model.Sprinkler; import org.drools.model.impl.ModelImpl; import org.drools.modelcompiler.KieBaseBuilder; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.kie.api.KieBase; import org.kie.api.runtime.KieSession; import org.kie.api.runtime.rule.FactHandle; diff --git a/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/fireandalarm/FireAndAlarmUsingDroolsTest.java b/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/fireandalarm/FireAndAlarmUsingDroolsTest.java index 24de303265d..04cbc8cfaca 100644 --- a/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/fireandalarm/FireAndAlarmUsingDroolsTest.java +++ b/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/fireandalarm/FireAndAlarmUsingDroolsTest.java @@ -27,7 +27,7 @@ import org.drools.model.codegen.execmodel.fireandalarm.model.Sprinkler; import org.drools.model.impl.ModelImpl; import org.drools.modelcompiler.KieBaseBuilder; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.kie.api.KieBase; import org.kie.api.runtime.KieSession; import org.kie.api.runtime.rule.FactHandle; diff --git a/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/generator/ConsequenceTest.java b/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/generator/ConsequenceTest.java index e2c7c131dfc..56d31bd34a2 100644 --- a/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/generator/ConsequenceTest.java +++ b/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/generator/ConsequenceTest.java @@ -18,7 +18,7 @@ */ package org.drools.model.codegen.execmodel.generator; -import org.junit.Test; +import org.junit.jupiter.api.Test; import static org.assertj.core.api.Assertions.assertThat; import static org.drools.model.codegen.execmodel.generator.Consequence.containsWord; diff --git a/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/generator/ConstraintTestUtil.java b/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/generator/ConstraintTestUtil.java index 15819559b52..d09a5308380 100644 --- a/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/generator/ConstraintTestUtil.java +++ b/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/generator/ConstraintTestUtil.java @@ -1,5 +1,5 @@ /** - * Licensed to the Apache Software Foundation (ASF) under one +e * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file diff --git a/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/generator/DrlxParseUtilTest.java b/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/generator/DrlxParseUtilTest.java index d6c52b92838..0f2e568b92a 100644 --- a/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/generator/DrlxParseUtilTest.java +++ b/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/generator/DrlxParseUtilTest.java @@ -40,7 +40,7 @@ import org.drools.util.ClassTypeResolver; import org.drools.util.MethodUtils; import org.drools.util.TypeResolver; -import org.junit.Test; +import org.junit.jupiter.api.Test; import static java.util.Optional.of; import static org.assertj.core.api.Assertions.assertThat; diff --git a/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/generator/ExpressionTyperTest.java b/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/generator/ExpressionTyperTest.java index 619214eeec6..40c3e3885f8 100644 --- a/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/generator/ExpressionTyperTest.java +++ b/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/generator/ExpressionTyperTest.java @@ -50,10 +50,11 @@ import org.drools.mvel.parser.printer.PrintUtil; import org.drools.util.ClassTypeResolver; import org.drools.util.TypeResolver; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.drools.model.codegen.execmodel.generator.DrlxParseUtil.THIS_PLACEHOLDER; public class ExpressionTyperTest { @@ -65,7 +66,7 @@ public class ExpressionTyperTest { private KnowledgeBuilderImpl knowledgeBuilder = new KnowledgeBuilderImpl(); private RuleDescr ruleDescr = new RuleDescr("testRule"); - @Before + @BeforeEach public void setUp() throws Exception { imports = new HashSet<>(); packageModel = new PackageModel("", "", null, null, new DRLIdGenerator()); @@ -242,9 +243,9 @@ public void halfBinaryOrAndAmpersand() { assertThat(toTypedExpression("age < 15 || > 20 && < 30", Person.class).getExpression().toString()).isEqualTo(expected); } - @Test(expected = CannotTypeExpressionException.class) + @Test public void invalidHalfBinary() { - toTypedExpression("> 20 && < 30", Person.class).getExpression(); + assertThatExceptionOfType(CannotTypeExpressionException.class).isThrownBy(() ->toTypedExpression("> 20 && < 30", Person.class).getExpression()); } @Test @@ -253,9 +254,9 @@ public void halfPointFreeOrAndAmpersand() { assertThat(toTypedExpression("name str[startsWith] \"M\" || str[endsWith] \"a\" && str[length] 4", Person.class).getExpression().toString()).isEqualTo(expected); } - @Test(expected = CannotTypeExpressionException.class) + @Test public void invalidHalfPointFree() { - toTypedExpression("str[endsWith] \"a\" && str[length] 4", Person.class).getExpression(); + assertThatExceptionOfType(CannotTypeExpressionException.class).isThrownBy(() -> toTypedExpression("str[endsWith] \"a\" && str[length] 4", Person.class).getExpression()); } @Test diff --git a/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/generator/FlattenScopeTest.java b/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/generator/FlattenScopeTest.java index e34e2ecd4db..3dcdd3b77c0 100644 --- a/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/generator/FlattenScopeTest.java +++ b/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/generator/FlattenScopeTest.java @@ -33,7 +33,7 @@ import com.github.javaparser.ast.expr.SimpleName; import com.github.javaparser.ast.expr.StringLiteralExpr; import org.drools.util.TypeResolver; -import org.junit.Test; +import org.junit.jupiter.api.Test; import static com.github.javaparser.ast.NodeList.nodeList; import static java.util.Arrays.asList; diff --git a/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/generator/GeneratedClassDeclarationTest.java b/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/generator/GeneratedClassDeclarationTest.java index 84a50b8d325..1b8a3537c1c 100644 --- a/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/generator/GeneratedClassDeclarationTest.java +++ b/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/generator/GeneratedClassDeclarationTest.java @@ -26,7 +26,7 @@ import org.drools.model.codegen.execmodel.generator.declaredtype.api.MethodDefinition; import org.drools.model.codegen.execmodel.generator.declaredtype.api.TypeDefinition; import org.drools.model.codegen.execmodel.generator.declaredtype.generator.GeneratedClassDeclaration; -import org.junit.Test; +import org.junit.jupiter.api.Test; import static org.assertj.core.api.Assertions.assertThat; diff --git a/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/generator/StringUtilTest.java b/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/generator/StringUtilTest.java index 3d136d6baa1..8566f953ed2 100644 --- a/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/generator/StringUtilTest.java +++ b/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/generator/StringUtilTest.java @@ -18,7 +18,7 @@ */ package org.drools.model.codegen.execmodel.generator; -import org.junit.Test; +import org.junit.jupiter.api.Test; import static org.assertj.core.api.Assertions.assertThat; import static org.drools.modelcompiler.util.StringUtil.toId; diff --git a/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/generator/drlxparse/CoercedExpressionTest.java b/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/generator/drlxparse/CoercedExpressionTest.java index 83e1a2c3a6d..0f2232b39e6 100644 --- a/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/generator/drlxparse/CoercedExpressionTest.java +++ b/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/generator/drlxparse/CoercedExpressionTest.java @@ -18,14 +18,12 @@ */ package org.drools.model.codegen.execmodel.generator.drlxparse; -import java.util.Map; - import com.github.javaparser.ast.expr.StringLiteralExpr; import org.drools.util.MethodUtils; +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.Test; import org.drools.model.codegen.execmodel.generator.DrlxParseUtil; import org.drools.model.codegen.execmodel.generator.TypedExpression; -import org.junit.Ignore; -import org.junit.Test; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; @@ -193,7 +191,7 @@ private TypedExpression expr(String exprString, Class exprClass) { } @Test - @Ignore("should support bigDecimal coercion also?") + @Disabled("should support bigDecimal coercion also?") public void coerceBigDecimal() { final TypedExpression left = expr(THIS_PLACEHOLDER + ".getRate()", java.math.BigDecimal.class); final TypedExpression right = expr("0.0d", Double.class); diff --git a/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/generator/drlxparse/ConstraintParserTest.java b/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/generator/drlxparse/ConstraintParserTest.java index cc62dedfdc3..6dd9391edae 100644 --- a/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/generator/drlxparse/ConstraintParserTest.java +++ b/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/generator/drlxparse/ConstraintParserTest.java @@ -31,8 +31,8 @@ import org.drools.modelcompiler.util.EvaluationUtil; import org.drools.util.ClassTypeResolver; import org.drools.util.TypeResolver; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import static org.assertj.core.api.Assertions.assertThat; @@ -40,7 +40,7 @@ public class ConstraintParserTest { private ConstraintParser parser; - @Before + @BeforeEach public void setup() { PackageModel packageModel = new PackageModel("org.kie.test:constraint-parser-test:1.0.0", "org.kie.test", null, null, new DRLIdGenerator()); Set imports = new HashSet<>(); diff --git a/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/inlinecast/InlineCastTest.java b/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/inlinecast/InlineCastTest.java index 1d7eb90b6c8..3c60fc5f311 100644 --- a/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/inlinecast/InlineCastTest.java +++ b/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/inlinecast/InlineCastTest.java @@ -25,20 +25,18 @@ import org.drools.model.codegen.execmodel.domain.InternationalAddress; import org.drools.model.codegen.execmodel.domain.Person; import org.drools.model.codegen.execmodel.domain.Result; -import org.junit.Ignore; -import org.junit.Test; +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; import org.kie.api.runtime.KieSession; import static org.assertj.core.api.Assertions.assertThat; public class InlineCastTest extends BaseModelTest { - public InlineCastTest(RUN_TYPE testRunType ) { - super( testRunType ); - } - - @Test - public void testInlineCastThis() { + @ParameterizedTest + @MethodSource("parameters") + public void testInlineCastThis(RUN_TYPE runType) { String str = "import " + Result.class.getCanonicalName() + ";" + "import " + Person.class.getCanonicalName() + ";" + @@ -49,7 +47,7 @@ public void testInlineCastThis() { " $r.setValue(\"Found: \" + $o);\n" + "end"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); Result result = new Result(); ksession.insert( result ); @@ -62,8 +60,9 @@ public void testInlineCastThis() { assertThat(result.getValue()).isEqualTo("Found: Mark"); } - @Test - public void testInlineCastProjectionThis() { + @ParameterizedTest + @MethodSource("parameters") + public void testInlineCastProjectionThis(RUN_TYPE runType) { String str = "import " + Result.class.getCanonicalName() + ";" + "import " + Person.class.getCanonicalName() + ";" + @@ -74,7 +73,7 @@ public void testInlineCastProjectionThis() { " $r.setValue(\"Found: \" + $name + \" $p class: \" + $p.getClass().getCanonicalName());\n" + "end"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); Result result = new Result(); ksession.insert( result ); @@ -86,8 +85,9 @@ public void testInlineCastProjectionThis() { assertThat(result.getValue()).isEqualTo("Found: Mark $p class: " + Person.class.getCanonicalName()); } - @Test - public void testInlineCastProjectionThisExplicit() { + @ParameterizedTest + @MethodSource("parameters") + public void testInlineCastProjectionThisExplicit(RUN_TYPE runType) { String str = "import " + Result.class.getCanonicalName() + ";" + "import " + Person.class.getCanonicalName() + ";" + @@ -98,7 +98,7 @@ public void testInlineCastProjectionThisExplicit() { " $r.setValue(\"Found: \" + $name + \" $p class: \" + $p.getClass().getCanonicalName());\n" + "end"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); Result result = new Result(); ksession.insert( result ); @@ -131,9 +131,10 @@ public interface DMNModelInstrumentedBase { DMNModelInstrumentedBase getParent(); } - @Ignore("This test is not testing anything") - @Test - public void testExplicitCast() { + @Disabled("This test is not testing anything") + @ParameterizedTest + @MethodSource("parameters") + public void testExplicitCast(RUN_TYPE runType) { String str = "import " + OutputClause.class.getCanonicalName() + "\n;" + "import " + DecisionTable.class.getCanonicalName() + "\n;" + @@ -143,13 +144,14 @@ public void testExplicitCast() { "then\n" + "end\n"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); ksession.fireAllRules(); } - @Ignore("This test is not testing anything") - @Test - public void testInlineCastParent() { + @Disabled("This test is not testing anything") + @ParameterizedTest + @MethodSource("parameters") + public void testInlineCastParent(RUN_TYPE runType) { String str = "import " + OutputClause.class.getCanonicalName() + "\n;" + "import " + DecisionTable.class.getCanonicalName() + "\n;" + @@ -159,12 +161,13 @@ public void testInlineCastParent() { "then\n" + "end\n"; - KieSession ksession = getKieSession( str ); + KieSession ksession = getKieSession(runType, str); ksession.fireAllRules(); } - @Test - public void testInlineCastProjection() { + @ParameterizedTest + @MethodSource("parameters") + public void testInlineCastProjection(RUN_TYPE runType) { String str = "import " + Person.class.getCanonicalName() + ";" + "import " + InternationalAddress.class.getCanonicalName() + ";" + "rule R when\n" + @@ -173,7 +176,7 @@ public void testInlineCastProjection() { " insert($a);\n" + "end"; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); Person john = new Person("John", 47); InternationalAddress a = new InternationalAddress("address", "Italy"); @@ -186,8 +189,9 @@ public void testInlineCastProjection() { assertThat(results.iterator().next()).isEqualTo("Italy"); } - @Test - public void testInlineCastProjectionOnMethod() { + @ParameterizedTest + @MethodSource("parameters") + public void testInlineCastProjectionOnMethod(RUN_TYPE runType) { String str = "import " + Person.class.getCanonicalName() + ";" + "import " + InternationalAddress.class.getCanonicalName() + ";" + "rule R when\n" + @@ -196,7 +200,7 @@ public void testInlineCastProjectionOnMethod() { " insert($a);\n" + "end"; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); Person john = new Person("John", 47); InternationalAddress a = new InternationalAddress("address", "Italy"); @@ -210,8 +214,9 @@ public void testInlineCastProjectionOnMethod() { } - @Test - public void testInlineCastForAField() { + @ParameterizedTest + @MethodSource("parameters") + public void testInlineCastForAField(RUN_TYPE runType) { String str = "import " + Person.class.getCanonicalName() + ";" + "import " + InternationalAddress.class.getCanonicalName() + ";" + "rule R when\n" + @@ -220,7 +225,7 @@ public void testInlineCastForAField() { " insert(\"matched\");\n" + "end"; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); Person john = new Person("John", 47); InternationalAddress a = new InternationalAddress("address", "Italy"); @@ -233,8 +238,9 @@ public void testInlineCastForAField() { assertThat(results.size()).isEqualTo(1); } - @Test - public void testInlineCastForAFieldWithFQN() { + @ParameterizedTest + @MethodSource("parameters") + public void testInlineCastForAFieldWithFQN(RUN_TYPE runType) { String str = "import " + Person.class.getCanonicalName() + ";" + "rule R when\n" + " $p : Person( address#" + InternationalAddress.class.getCanonicalName() + ".state.length == 5 )\n" + @@ -242,7 +248,7 @@ public void testInlineCastForAFieldWithFQN() { " insert(\"matched\");\n" + "end"; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); Person john = new Person("John", 47); InternationalAddress a = new InternationalAddress("address", "Italy"); @@ -255,8 +261,9 @@ public void testInlineCastForAFieldWithFQN() { assertThat(results.size()).isEqualTo(1); } - @Test - public void testInlineCastForAFieldAndMixMethodCall() { + @ParameterizedTest + @MethodSource("parameters") + public void testInlineCastForAFieldAndMixMethodCall(RUN_TYPE runType) { String str = "import " + Person.class.getCanonicalName() + ";" + "import " + InternationalAddress.class.getCanonicalName() + ";" + "rule R when\n" + @@ -265,7 +272,7 @@ public void testInlineCastForAFieldAndMixMethodCall() { " insert(\"matched\");\n" + "end"; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); Person john = new Person("John", 47); InternationalAddress a = new InternationalAddress("address", "Italy"); @@ -278,8 +285,9 @@ public void testInlineCastForAFieldAndMixMethodCall() { assertThat(results.size()).isEqualTo(1); } - @Test - public void testInlineCastSingle() { + @ParameterizedTest + @MethodSource("parameters") + public void testInlineCastSingle(RUN_TYPE runType) { String str = "import " + ICAbstractA.class.getCanonicalName() + ";" + "import " + ICAbstractB.class.getCanonicalName() + ";" + "import " + ICAbstractC.class.getCanonicalName() + ";" + @@ -292,7 +300,7 @@ public void testInlineCastSingle() { " insert(\"matched\");\n" + "end"; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); ICA a = new ICA(); ICB b = new ICB(); @@ -307,8 +315,9 @@ public void testInlineCastSingle() { assertThat(results.size()).isEqualTo(1); } - @Test - public void testInlineCastMultiple() { + @ParameterizedTest + @MethodSource("parameters") + public void testInlineCastMultiple(RUN_TYPE runType) { String str = "import " + ICAbstractA.class.getCanonicalName() + ";" + "import " + ICAbstractB.class.getCanonicalName() + ";" + "import " + ICAbstractC.class.getCanonicalName() + ";" + @@ -321,7 +330,7 @@ public void testInlineCastMultiple() { " insert(\"matched\");\n" + "end"; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); ICA a = new ICA(); ICB b = new ICB(); diff --git a/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/operators/BaseOperatorsTest.java b/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/operators/BaseOperatorsTest.java index e378e6f0a55..98e0fb4f970 100644 --- a/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/operators/BaseOperatorsTest.java +++ b/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/operators/BaseOperatorsTest.java @@ -26,7 +26,6 @@ import org.drools.compiler.kie.builder.impl.DrlProject; import org.drools.model.codegen.ExecutableModelProject; -import org.drools.model.codegen.execmodel.BaseModelTest; import org.drools.model.codegen.execmodel.BaseModelTest.RUN_TYPE; import org.drools.model.codegen.execmodel.KJARUtils; import org.kie.api.KieServices; @@ -38,16 +37,16 @@ import org.kie.api.runtime.KieContainer; import org.kie.api.runtime.KieSession; -import static org.junit.Assert.fail; +import static org.assertj.core.api.Assertions.fail; public abstract class BaseOperatorsTest { - protected static final RUN_TYPE[] RUN_TYPES = new BaseModelTest.RUN_TYPE[]{RUN_TYPE.STANDARD_FROM_DRL, RUN_TYPE.PATTERN_DSL}; - protected static final Class[] TYPES = new Class[]{Integer.class, Long.class, Byte.class, Character.class, Short.class, Float.class, Double.class, BigInteger.class, BigDecimal.class}; - protected static final String[] EQUALITY_COMPARISON_OPERATORS = new String[]{"==", "!="}; - protected static final boolean[] NULL_PROPERTY_ON_LEFT = new boolean[]{true, false}; + protected static final RUN_TYPE[] RUN_TYPES = {RUN_TYPE.STANDARD_FROM_DRL, RUN_TYPE.PATTERN_DSL}; + protected static final Class[] TYPES = {Integer.class, Long.class, Byte.class, Character.class, Short.class, Float.class, Double.class, BigInteger.class, BigDecimal.class}; + protected static final String[] EQUALITY_COMPARISON_OPERATORS = {"==", "!="}; + protected static final boolean[] NULL_PROPERTY_ON_LEFT = {true, false}; - protected KieSession getKieSession(String drl, RUN_TYPE testRunType) { + protected KieSession getKieSession(String drl, RUN_TYPE runType) { KieServices ks = KieServices.get(); ReleaseId releaseId = ks.newReleaseId("org.kie", "kjar-test-" + UUID.randomUUID(), "1.0"); @@ -60,12 +59,12 @@ protected KieSession getKieSession(String drl, RUN_TYPE testRunType) { kfs.write("src/main/resources/com/sample/Sample1.drl", drl); KieBuilder kieBuilder; - if (testRunType.equals(RUN_TYPE.STANDARD_FROM_DRL)) { + if (runType.equals(RUN_TYPE.STANDARD_FROM_DRL)) { kieBuilder = ks.newKieBuilder(kfs).buildAll(DrlProject.class); - } else if (testRunType.equals(RUN_TYPE.PATTERN_DSL)) { + } else if (runType.equals(RUN_TYPE.PATTERN_DSL)) { kieBuilder = ks.newKieBuilder(kfs).buildAll(ExecutableModelProject.class); } else { - throw new UnsupportedOperationException(testRunType + " is not supported"); + throw new UnsupportedOperationException(runType + " is not supported"); } List messages = kieBuilder.getResults().getMessages(); diff --git a/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/operators/DateOperatorTest.java b/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/operators/DateOperatorTest.java index 482bf005670..588bbcef0ed 100644 --- a/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/operators/DateOperatorTest.java +++ b/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/operators/DateOperatorTest.java @@ -22,22 +22,18 @@ import java.text.SimpleDateFormat; import org.drools.model.codegen.execmodel.BaseModelTest; -import org.drools.model.codegen.execmodel.domain.Person; import org.drools.model.codegen.execmodel.domain.SimpleDateHolder; -import org.junit.Ignore; -import org.junit.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; import org.kie.api.runtime.KieSession; import static org.assertj.core.api.Assertions.assertThat; public class DateOperatorTest extends BaseModelTest { - public DateOperatorTest(RUN_TYPE testRunType) { - super(testRunType); - } - - @Test - public void dateBetweenGlobals() throws ParseException { + @ParameterizedTest + @MethodSource("parameters") + public void dateBetweenGlobals(RUN_TYPE runType) throws ParseException { String str = "import " + SimpleDateHolder.class.getCanonicalName() + ";" + "global java.util.Date $startDate;\n" + @@ -47,7 +43,7 @@ public void dateBetweenGlobals() throws ParseException { "then\n" + "end"; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy"); ksession.setGlobal("$startDate", sdf.parse("04/01/2019")); ksession.setGlobal("$endDate", sdf.parse("05/01/2019")); @@ -59,8 +55,9 @@ public void dateBetweenGlobals() throws ParseException { assertThat(fired).isEqualTo(1); } - @Test - public void dateBetweenVariables() throws ParseException { + @ParameterizedTest + @MethodSource("parameters") + public void dateBetweenVariables(RUN_TYPE runType) throws ParseException { String str = "import " + SimpleDateHolder.class.getCanonicalName() + ";" + "rule R when\n" + @@ -70,7 +67,7 @@ public void dateBetweenVariables() throws ParseException { "then\n" + "end"; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(runType, str); SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy"); SimpleDateHolder holderA = new SimpleDateHolder("A", sdf.parse("04/01/2019")); diff --git a/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/operators/EqualityComparisonTest.java b/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/operators/EqualityComparisonTest.java index 60c5b548361..824bce2c014 100644 --- a/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/operators/EqualityComparisonTest.java +++ b/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/operators/EqualityComparisonTest.java @@ -19,64 +19,52 @@ package org.drools.model.codegen.execmodel.operators; import java.util.ArrayList; -import java.util.Collection; import java.util.List; +import java.util.stream.Stream; import org.drools.model.codegen.execmodel.BaseModelTest.RUN_TYPE; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; -import org.junit.runners.Parameterized.Parameters; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.Arguments; +import org.junit.jupiter.params.provider.MethodSource; import org.kie.api.runtime.KieSession; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; +import static org.junit.jupiter.params.provider.Arguments.arguments; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.fail; -@RunWith(Parameterized.class) public class EqualityComparisonTest extends BaseOperatorsTest { - @Parameters(name = "{0} {1} {2} {3}") - public static Collection ruleParams() { - List parameterData = new ArrayList(); + public static Stream ruleParams() { + List parameterData = new ArrayList(); for (RUN_TYPE runType : RUN_TYPES) { for (Class type : TYPES) { for (String operator : EQUALITY_COMPARISON_OPERATORS) { for (boolean nullPropertyOnLeft : NULL_PROPERTY_ON_LEFT) - parameterData.add(new Object[]{runType, type, operator, nullPropertyOnLeft}); + parameterData.add(arguments(runType, type, operator, nullPropertyOnLeft)); } } } - return parameterData; + + return Stream.of(parameterData.toArray(new Arguments[0])); } - @Parameterized.Parameter(0) - public RUN_TYPE testRunType; - - @Parameterized.Parameter(1) - public Class type; - - @Parameterized.Parameter(2) - public String operator; - - @Parameterized.Parameter(3) - public boolean nullPropertyOnLeft; - - @Before + @BeforeEach public void setUp() { org.drools.compiler.rule.builder.util.ConstraintTestUtil.disableNormalizeConstraint(); org.drools.model.codegen.execmodel.generator.ConstraintTestUtil.disableNormalizeConstraint(); } - @After + @AfterEach public void tearDown() { org.drools.compiler.rule.builder.util.ConstraintTestUtil.enableNormalizeConstraint(); org.drools.model.codegen.execmodel.generator.ConstraintTestUtil.enableNormalizeConstraint(); } - @Test - public void compareWithNullProperty() throws Exception { + @ParameterizedTest(name = "{0} {1} {2} {3}") + @MethodSource("ruleParams") + public void compareWithNullProperty(RUN_TYPE testRunType, Class type, String operator, boolean nullPropertyOnLeft) throws Exception { String propertyName = BaseOperatorsTest.getPropertyName(type); String instanceValueString = BaseOperatorsTest.getInstanceValueString(type); String drl = "import " + type.getCanonicalName() + ";\n" + @@ -95,11 +83,7 @@ public void compareWithNullProperty() throws Exception { ksession.insert(new ValueHolder()); try { int fired = ksession.fireAllRules(); - if (operator.equals("==") && fired == 0 || operator.equals("!=") && fired == 1) { - assertTrue(true); - } else { - fail("Wrong result"); - } + assertThat(operator.equals("==") && fired == 0 || operator.equals("!=") && fired == 1).withFailMessage("Wrong result").isTrue(); } catch (org.drools.mvel.ConstraintEvaluationException | org.drools.modelcompiler.constraints.ConstraintEvaluationException e) { throw new RuntimeException("Unexpected Exception", e); } diff --git a/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/operators/EqualityComparisonWith2PropertiesTest.java b/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/operators/EqualityComparisonWith2PropertiesTest.java index 67439d0513f..93c5dc7e34f 100644 --- a/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/operators/EqualityComparisonWith2PropertiesTest.java +++ b/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/operators/EqualityComparisonWith2PropertiesTest.java @@ -19,64 +19,54 @@ package org.drools.model.codegen.execmodel.operators; import java.util.ArrayList; -import java.util.Collection; import java.util.List; +import java.util.stream.Stream; import org.drools.model.codegen.execmodel.BaseModelTest.RUN_TYPE; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; -import org.junit.runners.Parameterized.Parameters; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.Arguments; +import org.junit.jupiter.params.provider.MethodSource; import org.kie.api.runtime.KieSession; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; +import static org.assertj.core.api.Assertions.assertThat; +import static org.junit.jupiter.params.provider.Arguments.arguments; -@RunWith(Parameterized.class) public class EqualityComparisonWith2PropertiesTest extends BaseOperatorsTest { - @Parameters(name = "{0} {1} {2} {3}") - public static Collection ruleParams() { - List parameterData = new ArrayList(); + + + public static Stream ruleParams() { + List parameterData = new ArrayList(); for (RUN_TYPE runType : RUN_TYPES) { for (Class type : TYPES) { for (String operator : EQUALITY_COMPARISON_OPERATORS) { for (boolean nullPropertyOnLeft : NULL_PROPERTY_ON_LEFT) - parameterData.add(new Object[]{runType, type, operator, nullPropertyOnLeft}); + parameterData.add(arguments(runType, type, operator, nullPropertyOnLeft)); } } } - return parameterData; + + return Stream.of(parameterData.toArray(new Arguments[0])); } + - @Parameterized.Parameter(0) - public RUN_TYPE testRunType; - - @Parameterized.Parameter(1) - public Class type; - - @Parameterized.Parameter(2) - public String operator; - - @Parameterized.Parameter(3) - public boolean nullPropertyOnLeft; - - @Before + @BeforeEach public void setUp() { org.drools.compiler.rule.builder.util.ConstraintTestUtil.disableNormalizeConstraint(); org.drools.model.codegen.execmodel.generator.ConstraintTestUtil.disableNormalizeConstraint(); } - @After + @AfterEach public void tearDown() { org.drools.compiler.rule.builder.util.ConstraintTestUtil.enableNormalizeConstraint(); org.drools.model.codegen.execmodel.generator.ConstraintTestUtil.enableNormalizeConstraint(); } - @Test - public void compareWithNullProperty() throws Exception { + @ParameterizedTest(name = "{0} {1} {2} {3}") + @MethodSource("ruleParams") + public void compareWithNullProperty(RUN_TYPE testRunType, Class type, String operator, boolean nullPropertyOnLeft) throws Exception { String firstPropertyName = BaseOperatorsTest.getPropertyNameWithPrefix(type, "first"); String secondPropertyName = BaseOperatorsTest.getPropertyNameWithPrefix(type, "second"); String drl = "import " + type.getCanonicalName() + ";\n" + @@ -95,11 +85,7 @@ public void compareWithNullProperty() throws Exception { ksession.insert(new ValueHolderWith2Properties()); try { int fired = ksession.fireAllRules(); - if (operator.equals("==") && fired == 0 || operator.equals("!=") && fired == 1) { - assertTrue(true); - } else { - fail("Wrong result"); - } + assertThat(operator.equals("==") && fired == 0 || operator.equals("!=") && fired == 1).withFailMessage("Wrong result").isTrue(); } catch (org.drools.mvel.ConstraintEvaluationException | org.drools.modelcompiler.constraints.ConstraintEvaluationException e) { throw new RuntimeException("Unexpected Exception", e); } diff --git a/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/util/LambdaUtilTest.java b/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/util/LambdaUtilTest.java index 115868333e5..63e3698eb08 100644 --- a/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/util/LambdaUtilTest.java +++ b/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/util/LambdaUtilTest.java @@ -20,7 +20,8 @@ import com.github.javaparser.ast.expr.Expression; import com.github.javaparser.ast.expr.LambdaExpr; -import org.junit.Test; + +import org.junit.jupiter.api.Test; import static com.github.javaparser.StaticJavaParser.parseExpression; import static org.assertj.core.api.Assertions.assertThat; diff --git a/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/util/lambdareplace/ExecModelLambdaPostProcessorTest.java b/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/util/lambdareplace/ExecModelLambdaPostProcessorTest.java index 877ce72394c..8551686e008 100644 --- a/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/util/lambdareplace/ExecModelLambdaPostProcessorTest.java +++ b/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/util/lambdareplace/ExecModelLambdaPostProcessorTest.java @@ -22,18 +22,19 @@ import java.util.ArrayList; import java.util.HashMap; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + import com.github.javaparser.StaticJavaParser; import com.github.javaparser.ast.CompilationUnit; import com.github.javaparser.ast.body.MethodDeclaration; -import org.junit.Before; -import org.junit.Test; import static com.github.javaparser.StaticJavaParser.parseResource; import static org.drools.model.codegen.execmodel.util.lambdareplace.MaterializedLambdaTestUtils.verifyCreatedClass; public class ExecModelLambdaPostProcessorTest { - @Before + @BeforeEach public void configJP() { StaticJavaParser.getConfiguration().setCharacterEncoding(Charset.defaultCharset()); } diff --git a/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/util/lambdareplace/MaterializedLambdaConsequenceTest.java b/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/util/lambdareplace/MaterializedLambdaConsequenceTest.java index 0505fb10a40..747aa5b188f 100644 --- a/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/util/lambdareplace/MaterializedLambdaConsequenceTest.java +++ b/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/util/lambdareplace/MaterializedLambdaConsequenceTest.java @@ -23,7 +23,7 @@ import java.util.Collections; import java.util.List; -import org.junit.Test; +import org.junit.jupiter.api.Test; import static org.drools.model.codegen.execmodel.util.lambdareplace.MaterializedLambdaTestUtils.verifyCreatedClass; diff --git a/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/util/lambdareplace/MaterializedLambdaExtractorTest.java b/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/util/lambdareplace/MaterializedLambdaExtractorTest.java index a238d833c71..bff83366078 100644 --- a/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/util/lambdareplace/MaterializedLambdaExtractorTest.java +++ b/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/util/lambdareplace/MaterializedLambdaExtractorTest.java @@ -20,7 +20,7 @@ import java.util.ArrayList; -import org.junit.Test; +import org.junit.jupiter.api.Test; import static org.drools.model.codegen.execmodel.generator.DrlxParseUtil.toClassOrInterfaceType; import static org.drools.model.codegen.execmodel.util.lambdareplace.MaterializedLambdaTestUtils.verifyCreatedClass; diff --git a/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/util/lambdareplace/MaterializedLambdaPredicateTest.java b/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/util/lambdareplace/MaterializedLambdaPredicateTest.java index 643d4b976f6..678e63daa73 100644 --- a/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/util/lambdareplace/MaterializedLambdaPredicateTest.java +++ b/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/util/lambdareplace/MaterializedLambdaPredicateTest.java @@ -21,7 +21,7 @@ import java.util.ArrayList; import org.drools.model.functions.PredicateInformation; -import org.junit.Test; +import org.junit.jupiter.api.Test; import static org.drools.model.codegen.execmodel.util.lambdareplace.MaterializedLambdaTestUtils.verifyCreatedClass; diff --git a/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/variables/VariablesTest.java b/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/variables/VariablesTest.java index ea8744845ef..a9f229d0ce0 100644 --- a/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/variables/VariablesTest.java +++ b/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/variables/VariablesTest.java @@ -21,19 +21,17 @@ import java.util.Collection; import org.drools.model.codegen.execmodel.BaseModelTest; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; import static org.assertj.core.api.Assertions.assertThat; -import org.junit.Test; import org.kie.api.runtime.KieSession; public class VariablesTest extends BaseModelTest { - - public VariablesTest(RUN_TYPE testRunType) { - super(testRunType); - } - - @Test - public void testThreeVariables() { + + @ParameterizedTest + @MethodSource("parameters") + public void testThreeVariables(BaseModelTest.RUN_TYPE testRunType) { String str = "import " + SimpleObject.class.getCanonicalName() + ";\n" + "import " + Result.class.getCanonicalName() + ";\n" + @@ -46,7 +44,7 @@ public void testThreeVariables() { "insert (new Result($id, $v1 + $v2));\n" + "end"; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(testRunType, str); SimpleObject m1 = new SimpleObject("id", 1); SimpleObject m2 = new SimpleObject("id", 2); @@ -60,8 +58,9 @@ public void testThreeVariables() { assertThat(results.iterator().next().getValue()).isEqualTo(3); } - @Test - public void testFourVariables() { + @ParameterizedTest + @MethodSource("parameters") + public void testFourVariables(BaseModelTest.RUN_TYPE testRunType) { String str = "import " + SimpleObject.class.getCanonicalName() + ";\n" + "import " + Result.class.getCanonicalName() + ";\n" + @@ -75,7 +74,7 @@ public void testFourVariables() { "insert (new Result($id, $v1 + $v2 + $v3));\n" + "end"; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(testRunType, str); SimpleObject m1 = new SimpleObject("id", 1); SimpleObject m2 = new SimpleObject("id", 2); @@ -91,8 +90,9 @@ public void testFourVariables() { assertThat(results.iterator().next().getValue()).isEqualTo(6); } - @Test - public void testFiveVariables() { + @ParameterizedTest + @MethodSource("parameters") + public void testFiveVariables(BaseModelTest.RUN_TYPE testRunType) { String str = "import " + SimpleObject.class.getCanonicalName() + ";\n" + "import " + Result.class.getCanonicalName() + ";\n" + @@ -107,7 +107,7 @@ public void testFiveVariables() { "insert (new Result($id, $v1 + $v2 + $v3 + $v4));\n" + "end"; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(testRunType, str); SimpleObject m1 = new SimpleObject("id", 1); SimpleObject m2 = new SimpleObject("id", 2); @@ -125,8 +125,9 @@ public void testFiveVariables() { assertThat(results.iterator().next().getValue()).isEqualTo(10); } - @Test - public void testSixVariables() { + @ParameterizedTest + @MethodSource("parameters") + public void testSixVariables(BaseModelTest.RUN_TYPE testRunType) { String str = "import " + SimpleObject.class.getCanonicalName() + ";\n" + "import " + Result.class.getCanonicalName() + ";\n" + @@ -142,7 +143,7 @@ public void testSixVariables() { "insert (new Result($id, $v1 + $v2 + $v3 + $v4 + $v5));\n" + "end"; - KieSession ksession = getKieSession(str); + KieSession ksession = getKieSession(testRunType, str); SimpleObject m1 = new SimpleObject("id", 1); SimpleObject m2 = new SimpleObject("id", 2); diff --git a/drools-model/drools-model-codegen/src/test/resources/logback-test.xml b/drools-model/drools-model-codegen/src/test/resources/logback-test.xml index dbee14ec590..25b6a1f4918 100644 --- a/drools-model/drools-model-codegen/src/test/resources/logback-test.xml +++ b/drools-model/drools-model-codegen/src/test/resources/logback-test.xml @@ -36,6 +36,7 @@ + diff --git a/drools-model/drools-model-compiler/pom.xml b/drools-model/drools-model-compiler/pom.xml index c7128d54f13..99d7f28ba6a 100644 --- a/drools-model/drools-model-compiler/pom.xml +++ b/drools-model/drools-model-compiler/pom.xml @@ -68,9 +68,9 @@ - junit - junit - test + org.junit.jupiter + junit-jupiter + test org.assertj diff --git a/drools-model/drools-model-compiler/src/test/java/org/drools/modelcompiler/PatternDSLTest.java b/drools-model/drools-model-compiler/src/test/java/org/drools/modelcompiler/PatternDSLTest.java index bb7f803825f..a9692d970b9 100644 --- a/drools-model/drools-model-compiler/src/test/java/org/drools/modelcompiler/PatternDSLTest.java +++ b/drools-model/drools-model-compiler/src/test/java/org/drools/modelcompiler/PatternDSLTest.java @@ -59,11 +59,10 @@ import org.drools.modelcompiler.domain.Woman; import org.drools.modelcompiler.dsl.pattern.D; import org.drools.modelcompiler.util.EvaluationUtil; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.kie.api.KieBase; import org.kie.api.KieServices; import org.kie.api.conf.EventProcessingOption; -import org.kie.api.runtime.ClassObjectFilter; import org.kie.api.runtime.KieSession; import org.kie.api.runtime.KieSessionConfiguration; import org.kie.api.runtime.conf.ClockTypeOption; diff --git a/drools-model/drools-model-prototype/pom.xml b/drools-model/drools-model-prototype/pom.xml index 55892638c63..7d035e24bdd 100644 --- a/drools-model/drools-model-prototype/pom.xml +++ b/drools-model/drools-model-prototype/pom.xml @@ -56,9 +56,9 @@ - junit - junit - test + org.junit.jupiter + junit-jupiter + test org.assertj diff --git a/drools-model/drools-model-prototype/src/test/java/org/drools/model/prototype/PrototypeFieldExtractorTest.java b/drools-model/drools-model-prototype/src/test/java/org/drools/model/prototype/PrototypeFieldExtractorTest.java index 0b081f3c43c..9f9e0c5c1cd 100644 --- a/drools-model/drools-model-prototype/src/test/java/org/drools/model/prototype/PrototypeFieldExtractorTest.java +++ b/drools-model/drools-model-prototype/src/test/java/org/drools/model/prototype/PrototypeFieldExtractorTest.java @@ -23,7 +23,7 @@ import org.drools.base.rule.Declaration; import org.drools.base.rule.Pattern; import org.drools.base.rule.accessor.ReadAccessor; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.kie.api.prototype.PrototypeFact; import org.kie.api.prototype.PrototypeFactInstance; diff --git a/drools-model/drools-mvel-compiler/pom.xml b/drools-model/drools-mvel-compiler/pom.xml index 7bb56461fac..68e8e37d9a7 100644 --- a/drools-model/drools-mvel-compiler/pom.xml +++ b/drools-model/drools-mvel-compiler/pom.xml @@ -38,11 +38,6 @@ - - junit - junit - test - com.github.javaparser @@ -57,6 +52,11 @@ drools-core + + org.junit.jupiter + junit-jupiter + test + org.assertj assertj-core diff --git a/drools-model/drools-mvel-compiler/src/test/java/org/drools/mvel/ArithmeticTest.java b/drools-model/drools-mvel-compiler/src/test/java/org/drools/mvel/ArithmeticTest.java index d8b43dfb040..c4aa468b007 100644 --- a/drools-model/drools-mvel-compiler/src/test/java/org/drools/mvel/ArithmeticTest.java +++ b/drools-model/drools-mvel-compiler/src/test/java/org/drools/mvel/ArithmeticTest.java @@ -24,8 +24,8 @@ import java.util.LinkedHashMap; import java.util.Map; -import org.junit.Ignore; -import org.junit.Test; +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.Test; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.within; @@ -43,7 +43,7 @@ public class ArithmeticTest { - @Ignore("DROOLS-6572 - Generates wrong code for promotion") + @Disabled("DROOLS-6572 - Generates wrong code for promotion") @Test public void testMath() { String expression = "pi * hour"; @@ -57,7 +57,7 @@ public void testMath2() { assertThat(executeExpressionWithDefaultVariables("foo.number-1")).isEqualTo(3); } - @Ignore("DROOLS-6572 - Rounding error") + @Disabled("DROOLS-6572 - Rounding error") @Test public void testMath3() { String expression = "(10 * 5) * 2 / 3"; @@ -66,7 +66,7 @@ public void testMath3() { assertThat(executeExpressionWithDefaultVariables(expression)).isEqualTo(result); } - @Ignore("DROOLS-6572 - Rounding error") + @Disabled("DROOLS-6572 - Rounding error") @Test public void testMath4() { String expression = "(100 % 3) * 2 - 1 / 1 + 8 + (5 * 2)"; @@ -75,7 +75,7 @@ public void testMath4() { assertThat(executeExpressionWithDefaultVariables(expression)).isEqualTo(result); } - @Ignore("DROOLS-6572 - Rounding error") + @Disabled("DROOLS-6572 - Rounding error") @Test public void testMath4a() { String expression = "(100 % 90) * 20 - 15 / 16 + 80 + (50 * 21)"; @@ -100,7 +100,7 @@ public void testMath5a() { assertThat(executeExpressionWithDefaultVariables(expression)).isEqualTo(result); } - @Ignore("DROOLS-6572 - Rounding error") + @Disabled("DROOLS-6572 - Rounding error") @Test public void testMath6() { String expression = "(300 * five + 1) + (100 / 2 * 2)"; @@ -109,7 +109,7 @@ public void testMath6() { assertThat(executeExpressionWithDefaultVariables(expression)).isEqualTo(result); } - @Ignore("DROOLS-6572 - Rounding error") + @Disabled("DROOLS-6572 - Rounding error") @Test public void testMath7() { String expression = "(100 % 3) * 2 - 1 / 1 + 8 + (5 * 2)"; @@ -126,13 +126,13 @@ public void testMath8() { assertThat(executeExpressionWithDefaultVariables(expression)).isEqualTo(result); } - @Ignore("DROOLS-6572 - Unable to parse **") + @Disabled("DROOLS-6572 - Unable to parse **") @Test public void testPowerOf() { assertThat(executeExpressionWithDefaultVariables("5 ** 2")).isEqualTo(25); } - @Ignore("DROOLS-6572 - Unable to parse") + @Disabled("DROOLS-6572 - Unable to parse") @Test public void testSignOperator() { String expr = "int x = 15; -x"; @@ -173,7 +173,7 @@ public void testMath17() { assertThat(executeExpressionWithDefaultVariables(expression)).isEqualTo(result); } - @Ignore("DROOLS-6572 - Unable to parse multiple assignements") + @Disabled("DROOLS-6572 - Unable to parse multiple assignements") @Test public void testMath18() { String expression = "a = 100d; b = 50d; c = 20d; d = 30d; e = 2d; (a * b) * c / d * e"; @@ -182,7 +182,7 @@ public void testMath18() { assertThat(executeExpression(expression, Collections.emptyMap())).isEqualTo(result); } - @Ignore("DROOLS-6572 - Unable to parse multiple assignments") + @Disabled("DROOLS-6572 - Unable to parse multiple assignments") @Test public void testMath19() { String expression = "a = 100; b = 500; c = 200; d = 150; e = 500; f = 800; g = 400; a-b*c*d + e*f-g"; @@ -190,7 +190,7 @@ public void testMath19() { assertThat(executeExpression(expression, Collections.emptyMap())).isEqualTo(result); } - @Ignore("DROOLS-6572 - Unable to parse") + @Disabled("DROOLS-6572 - Unable to parse") @Test public void testMath32() { String expression = "x = 20; y = 10; z = 5; x-y-z"; @@ -199,7 +199,7 @@ public void testMath32() { assertThat(executeExpression(expression, Collections.emptyMap())).isEqualTo(result); } - @Ignore("DROOLS-6572 - Unable to parse") + @Disabled("DROOLS-6572 - Unable to parse") @Test public void testMath33() { String expression = "x = 20; y = 2; z = 2; x/y/z"; @@ -224,7 +224,7 @@ public void testMath21() { assertThat(executeExpressionWithDefaultVariables(expression)).isEqualTo(expected); } - @Ignore("DROOLS-6572 - Unable to parse **") + @Disabled("DROOLS-6572 - Unable to parse **") @Test public void testMath22() { String expression = "(100-50)*70-30*(20-9)**3"; @@ -233,7 +233,7 @@ public void testMath22() { assertThat(executeExpressionWithDefaultVariables(expression)).isEqualTo(result); } - @Ignore("DROOLS-6572 - Unable to parse **") + @Disabled("DROOLS-6572 - Unable to parse **") @Test public void testMath22b() { String expression = "a = 100; b = 50; c = 70; d = 30; e = 20; f = 9; g = 3; (a-b)*c-d*(e-f)**g"; @@ -242,7 +242,7 @@ public void testMath22b() { assertThat(executeExpression(expression, Collections.emptyMap())).isEqualTo(result); } - @Ignore("DROOLS-6572 - Unable to parse **") + @Disabled("DROOLS-6572 - Unable to parse **") @Test public void testMath23() { String expression = "10 ** (3)*10**3"; @@ -251,7 +251,7 @@ public void testMath23() { assertThat(executeExpressionWithDefaultVariables(expression)).isEqualTo(result); } - @Ignore("DROOLS-6572 - Rounding error") + @Disabled("DROOLS-6572 - Rounding error") @Test public void testMath24() { String expression = "51 * 52 * 33 / 24 / 15 + 45 * 66 * 47 * 28 + 19"; @@ -260,7 +260,7 @@ public void testMath24() { assertThat(executeExpressionWithDefaultVariables(expression)).isEqualTo(result); } - @Ignore("DROOLS-6572 - Calculation error") + @Disabled("DROOLS-6572 - Calculation error") @Test public void testMath25() { String expression = "51 * (40 - 1000 * 50) + 100 + 50 * 20 / 10 + 11 + 12 - 80"; @@ -269,7 +269,7 @@ public void testMath25() { assertThat(executeExpressionWithDefaultVariables(expression)).isEqualTo(result); } - @Ignore("DROOLS-6572 - Unable to parse **") + @Disabled("DROOLS-6572 - Unable to parse **") @Test public void testMath26() { String expression = "5 + 3 * 8 * 2 ** 2"; @@ -278,7 +278,7 @@ public void testMath26() { assertThat(executeExpressionWithDefaultVariables(expression)).isEqualTo(result); } - @Ignore("DROOLS-6572 - Unable to parse **") + @Disabled("DROOLS-6572 - Unable to parse **") @Test public void testMath27() { String expression = "50 + 30 * 80 * 20 ** 3 * 51"; @@ -287,7 +287,7 @@ public void testMath27() { assertThat(executeExpressionWithDefaultVariables(expression)).isEqualTo((int) result); } - @Ignore("DROOLS-6572 - Unable to parse **") + @Disabled("DROOLS-6572 - Unable to parse **") @Test public void testMath28() { String expression = "50 + 30 + 80 + 11 ** 2 ** 2 * 51"; @@ -296,7 +296,7 @@ public void testMath28() { assertThat(executeExpressionWithDefaultVariables(expression)).isEqualTo((int) result); } - @Ignore("DROOLS-6572 - Rounding error") + @Disabled("DROOLS-6572 - Rounding error") @Test public void testMath29() { String expression = "10 + 20 / 4 / 4"; @@ -305,7 +305,7 @@ public void testMath29() { assertThat(executeExpressionWithDefaultVariables(expression)).isEqualTo(result); } - @Ignore("DROOLS-6572 - Rounding error") + @Disabled("DROOLS-6572 - Rounding error") @Test public void testMath30() { String expression = "40 / 20 + 10 + 60 / 21"; @@ -314,7 +314,7 @@ public void testMath30() { assertThat(executeExpressionWithDefaultVariables(expression)).isEqualTo(result); } - @Ignore("DROOLS-6572 - Unable to parse **") + @Disabled("DROOLS-6572 - Unable to parse **") @Test public void testMath31() { String expression = "40 / 20 + 5 - 4 + 8 / 2 * 2 * 6 ** 2 + 6 - 8"; @@ -323,7 +323,7 @@ public void testMath31() { assertThat(executeExpressionWithDefaultVariables(expression)).isEqualTo(result); } - @Ignore("DROOLS-6572 - Rounding error") + @Disabled("DROOLS-6572 - Rounding error") @Test public void testMath34() { String expression = "a+b-c*d*x/y-z+10"; @@ -341,7 +341,7 @@ public void testMath34() { assertThat(executeExpression(expression, map)).isEqualTo(result); } - @Ignore("DROOLS-6572 - Rounding error") + @Disabled("DROOLS-6572 - Rounding error") @Test public void testMath34_Interpreted() { String expression = "a+b-c*x/y-z"; @@ -358,7 +358,7 @@ public void testMath34_Interpreted() { assertThat(executeExpression(expression, map)).isEqualTo(result); } - @Ignore("DROOLS-6572 - Rounding error") + @Disabled("DROOLS-6572 - Rounding error") @Test public void testMath35() { String expression = "b/x/b/b*y+a"; @@ -376,7 +376,7 @@ public void testMath35() { } - @Ignore("DROOLS-6572 - Rounding error") + @Disabled("DROOLS-6572 - Rounding error") @Test public void testMath35_Interpreted() { String expression = "b/x/b/b*y+a"; @@ -393,7 +393,7 @@ public void testMath35_Interpreted() { assertThat(executeExpression(expression, map)).isEqualTo(result); } - @Ignore("DROOLS-6572 - Rounding error") + @Disabled("DROOLS-6572 - Rounding error") @Test public void testMath36() { String expression = "b/x*z/a+x-b+x-b/z+y"; @@ -410,7 +410,7 @@ public void testMath36() { assertThat(executeExpression(expression, map)).isEqualTo(result); } - @Ignore("DROOLS-6572 - Rounding error") + @Disabled("DROOLS-6572 - Rounding error") @Test public void testMath37() { String expression = "x+a*a*c/x*b*z+x/y-b"; @@ -427,7 +427,7 @@ public void testMath37() { assertThat(executeExpression(expression, map)).isEqualTo(result); } - @Ignore("DROOLS-6572 - Rounding error") + @Disabled("DROOLS-6572 - Rounding error") @Test public void testMath38() { String expression = "100 + 200 - 300 + 400 - 500 + 105 / 205 - 405 + 305 * 206"; @@ -436,7 +436,7 @@ public void testMath38() { assertThat(executeExpressionWithDefaultVariables(expression)).isEqualTo(result); } - @Ignore("DROOLS-6572 - Rounding error") + @Disabled("DROOLS-6572 - Rounding error") @Test public void testMath39() { String expression = "147 + 60 / 167 % 448 + 36 * 23 / 166"; @@ -445,7 +445,7 @@ public void testMath39() { assertThat(executeExpressionWithDefaultVariables(expression)).isEqualTo(result); } - @Ignore("DROOLS-6572 - Rounding error") + @Disabled("DROOLS-6572 - Rounding error") @Test public void testMath40() { String expression = "228 - 338 % 375 - 103 + 260 + 412 * 177 + 121"; @@ -507,21 +507,21 @@ public void testMath44b() { assertThat(executeExpression(expression, vars)).isEqualTo(result); } - @Ignore("DROOLS-6572 - Unable to parse") + @Disabled("DROOLS-6572 - Unable to parse") @Test public void testOperatorPrecedence() { String expression = "_x_001 = 500.2; _x_002 = 200.8; _r_001 = 701; _r_001 == _x_001 + _x_002 || _x_001 == 500 + 0.1"; assertThat(executeExpressionWithDefaultVariables(expression)).isEqualTo(true); } - @Ignore("DROOLS-6572 - Unable to parse") + @Disabled("DROOLS-6572 - Unable to parse") @Test public void testOperatorPrecedence2() { String expression = "_x_001 = 500.2; _x_002 = 200.8; _r_001 = 701; _r_001 == _x_001 + _x_002 && _x_001 == 500 + 0.2"; assertThat(executeExpressionWithDefaultVariables(expression)).isEqualTo(true); } - @Ignore("DROOLS-6572 - Unable to parse") + @Disabled("DROOLS-6572 - Unable to parse") @Test public void testOperatorPrecedence3() { String expression = "_x_001 = 500.2; _x_002 = 200.9; _r_001 = 701; _r_001 == _x_001 + _x_002 && _x_001 == 500 + 0.2"; @@ -529,7 +529,7 @@ public void testOperatorPrecedence3() { assertThat(executeExpressionWithDefaultVariables(expression)).isEqualTo(false); } - @Ignore("DROOLS-6572 - Unable to parse") + @Disabled("DROOLS-6572 - Unable to parse") @Test public void testOperatorPrecedence4() { String expression = "_x_001 = 500.2; _x_002 = 200.9; _r_001 = 701; _r_001 == _x_001 + _x_002 || _x_001 == 500 + 0.2"; @@ -558,13 +558,13 @@ public void testBitwiseOr1() { assertThat(executeExpressionWithDefaultVariables("2|4")).isEqualTo(6); } - @Ignore("DROOLS-6572 - Considers second element a boolean") + @Disabled("DROOLS-6572 - Considers second element a boolean") @Test public void testBitwiseOr2() { assertThat(executeExpressionWithDefaultVariables("(2 | 1) > 0")).isEqualTo(true); } - @Ignore("DROOLS-6572 - Considers second element a boolean") + @Disabled("DROOLS-6572 - Considers second element a boolean") @Test public void testBitwiseOr3() { assertThat(executeExpressionWithDefaultVariables("(2|1) == 3")).isEqualTo(true); @@ -595,7 +595,7 @@ public void testShiftLeft2() { assertThat(executeExpressionWithDefaultVariables("five << 1")).isEqualTo(5 << 1); } - @Ignore("DROOLS-6572 - Generates wrong code - unable to parse <<<") + @Disabled("DROOLS-6572 - Generates wrong code - unable to parse <<<") @Test public void testUnsignedShiftLeft() { assertThat(executeExpressionWithDefaultVariables("-2 <<< 0")).isEqualTo(2); @@ -631,7 +631,7 @@ public void testShiftLeftAssign() { assertThat(executeExpressionWithDefaultVariables("_yYy = 10; _yYy <<= 2")).isEqualTo(10 << 2); } - @Ignore("DROOLS-6572 - Unable to parse") + @Disabled("DROOLS-6572 - Unable to parse") @Test public void testUnsignedShiftRightAssign() { String expression = "_xXx = -5; _xXx >>>= 2"; @@ -669,7 +669,7 @@ public void testDeepPropertyAdd() { assertThat(executeExpressionWithDefaultVariables("foo.countTest+ 10")).isEqualTo(10); } - @Ignore("DROOLS-6572 - Generates wrong code") + @Disabled("DROOLS-6572 - Generates wrong code") @Test public void testDeepAssignmentIncrement() { String expression = "foo.countTest += 5; if (foo.countTest == 5) { foo.countTest = 0; return true; }" + @@ -681,7 +681,7 @@ public void testDeepAssignmentIncrement() { " else { foo.countTest = 0; return false; }")).isEqualTo(true); } - @Ignore("DROOLS-6572 - Generates wrong code - check for statements") + @Disabled("DROOLS-6572 - Generates wrong code - check for statements") @Test public void testDeepAssignmentWithBlock() { String expression = "with (foo) { countTest += 5 }; if (foo.countTest == 5) { foo.countTest = 0; return true; }" + @@ -723,19 +723,19 @@ public void testOperativeAssignShift3() { assertThat(executeExpressionWithDefaultVariables("int val = -5; val >>>= 2; val")).isEqualTo(val >>>= 2); } - @Ignore("DROOLS-6572 - Unable to parse") + @Disabled("DROOLS-6572 - Unable to parse") @Test public void testAssignPlus() { assertThat(executeExpressionWithDefaultVariables("xx0 = 5; xx0 += 4; xx0 + 1")).isEqualTo(10); } - @Ignore("DROOLS-6572 - Unable to parse") + @Disabled("DROOLS-6572 - Unable to parse") @Test public void testAssignPlus2() { assertThat(executeExpressionWithDefaultVariables("xx0 = 5; xx0 =+ 4; xx0 + 1")).isEqualTo(10); } - @Ignore("DROOLS-6572 - Rounding error") + @Disabled("DROOLS-6572 - Rounding error") @Test public void testAssignDiv() { assertThat(executeExpressionWithDefaultVariables("xx0 = 20; xx0 /= 10; xx0")).isEqualTo(2.0); @@ -750,7 +750,7 @@ public void testAssignSub() { assertThat(executeExpressionWithDefaultVariables("xx0 = 15; xx0 -= 4; xx0")).isEqualTo(11); } - @Ignore("DROOLS-6572 - Calculation error") + @Disabled("DROOLS-6572 - Calculation error") @Test public void testAssignSub2() { assertThat(executeExpressionWithDefaultVariables("xx0 = 5; xx0 =- 100")).isEqualTo(-95); @@ -762,7 +762,7 @@ public void testBooleanStrAppend() { } - @Ignore("DROOLS-6572 - Unable to parse") + @Disabled("DROOLS-6572 - Unable to parse") @Test public void testStringAppend() { String expression = "c + 'bar'"; @@ -784,7 +784,7 @@ public void testStrongTypingModeComparison() { } - @Ignore("DROOLS-6572 - Rounding error") + @Disabled("DROOLS-6572 - Rounding error") @Test public void testJIRA158() { String expression = "(float) (4/2 + Math.sin(1))"; @@ -822,7 +822,7 @@ public void testJIRA163() { assertThat(executeExpression(expression, vars)).isEqualTo(result); } - @Ignore("DROOLS-6572 - Wrong value calculated") + @Disabled("DROOLS-6572 - Wrong value calculated") @Test public void testJIRA164() { String expression = "1 / (var1 + var1) * var1"; @@ -837,7 +837,7 @@ public void testJIRA164() { } - @Ignore("DROOLS-6572 - Wrong value calculated") + @Disabled("DROOLS-6572 - Wrong value calculated") @Test public void testJIRA164b() { String expression = "1 + 1 / (var1 + var1) * var1"; @@ -850,7 +850,7 @@ public void testJIRA164b() { assertThat(executeExpression(expression, vars)).isEqualTo(result); } - @Ignore("DROOLS-6572 - Wrong value calculated") + @Disabled("DROOLS-6572 - Wrong value calculated") @Test public void testJIRA164c() { double var1 = 1d; @@ -864,7 +864,7 @@ public void testJIRA164c() { assertThat(executeExpression(expression, vars)).isEqualTo(result); } - @Ignore("DROOLS-6572 - Wrong value calculated") + @Disabled("DROOLS-6572 - Wrong value calculated") @Test public void testJIRA164d() { double var1 = 1d; @@ -877,7 +877,7 @@ public void testJIRA164d() { assertThat(executeExpression(expression, vars)).isEqualTo(result); } - @Ignore("DROOLS-6572 - Wrong value calculated") + @Disabled("DROOLS-6572 - Wrong value calculated") @Test public void testJIRA164e() { String expression = "10 + 11 + 12 / (var1 + var1 + 51 + 71) * var1 + 13 + 14"; @@ -889,7 +889,7 @@ public void testJIRA164e() { assertThat(((Double) executeExpression(expression, vars)).floatValue()).isCloseTo((float) (10 + 11 + 12 / (var1 + var1 + 51 + 71) * var1 + 13 + 14), within(0.01f)); } - @Ignore("DROOLS-6572 - Wrong value calculated") + @Disabled("DROOLS-6572 - Wrong value calculated") @Test public void testJIRA164f() { String expression = "10 + 11 + 12 / (var1 + 1 + var1 + 51 + 71) * var1 + 13 + 14"; @@ -995,7 +995,7 @@ public void testJIRA210() { } } - @Ignore("DROOLS-6572 - Generates wrong code - missing symbol") + @Disabled("DROOLS-6572 - Generates wrong code - missing symbol") @Test public void testMathDec30() { Map params = new HashMap<>(); @@ -1027,7 +1027,7 @@ public void testJIRA99_Compiled() { assertThat(executeExpression("x - y - z", map)).isEqualTo(20 - 10 - 5); } - @Ignore("DROOLS-6572 - Too many iterations - why") + @Disabled("DROOLS-6572 - Too many iterations - why") @Test public void testModExpr() { String str = "$y % 4 == 0 && $y % 100 != 0 || $y % 400 == 0 "; @@ -1054,7 +1054,7 @@ public void testIntsWithDivision() { assertThat(result).isTrue(); } - @Ignore("DROOLS-6572 - Wrong result") + @Disabled("DROOLS-6572 - Wrong result") @Test public void testMathCeil() { String expression = "Math.ceil( x/3 ) == 2"; @@ -1065,7 +1065,7 @@ public void testMathCeil() { assertThat(result).isTrue(); } - @Ignore("DROOLS-6572 - Generates wrong code") + @Disabled("DROOLS-6572 - Generates wrong code") @Test public void testStaticMathCeil() { int x = 4; @@ -1078,7 +1078,7 @@ public void testStaticMathCeil() { assertThat(executeExpression(expression, vars)).isEqualTo(Integer.valueOf(2)); } - @Ignore("DROOLS-6572 - Calculates wrong result") + @Disabled("DROOLS-6572 - Calculates wrong result") @Test public void testStaticMathCeilWithJavaClassStyleLiterals() { String expression = "java.lang.Math.ceil( x/3 )"; diff --git a/drools-model/drools-mvel-compiler/src/test/java/org/drools/mvelcompiler/ConstraintCompilerTest.java b/drools-model/drools-mvel-compiler/src/test/java/org/drools/mvelcompiler/ConstraintCompilerTest.java index a84d73bd9f0..0f6401d3710 100644 --- a/drools-model/drools-mvel-compiler/src/test/java/org/drools/mvelcompiler/ConstraintCompilerTest.java +++ b/drools-model/drools-mvel-compiler/src/test/java/org/drools/mvelcompiler/ConstraintCompilerTest.java @@ -27,8 +27,8 @@ import org.drools.Person; import org.drools.util.ClassTypeResolver; import org.drools.util.TypeResolver; +import org.junit.jupiter.api.Test; import org.drools.mvelcompiler.context.MvelCompilerContext; -import org.junit.Test; public class ConstraintCompilerTest implements CompilerTest { diff --git a/drools-model/drools-mvel-compiler/src/test/java/org/drools/mvelcompiler/MvelCompilerTest.java b/drools-model/drools-mvel-compiler/src/test/java/org/drools/mvelcompiler/MvelCompilerTest.java index 9604a497243..74bdd45d5b6 100644 --- a/drools-model/drools-mvel-compiler/src/test/java/org/drools/mvelcompiler/MvelCompilerTest.java +++ b/drools-model/drools-mvel-compiler/src/test/java/org/drools/mvelcompiler/MvelCompilerTest.java @@ -24,7 +24,7 @@ import org.drools.Person; import org.drools.util.MethodUtils; -import org.junit.Test; +import org.junit.jupiter.api.Test; import static org.assertj.core.api.Assertions.assertThat; diff --git a/drools-model/drools-mvel-compiler/src/test/java/org/drools/mvelcompiler/PreprocessCompilerTest.java b/drools-model/drools-mvel-compiler/src/test/java/org/drools/mvelcompiler/PreprocessCompilerTest.java index c02fc88b30b..1296cee6214 100644 --- a/drools-model/drools-mvel-compiler/src/test/java/org/drools/mvelcompiler/PreprocessCompilerTest.java +++ b/drools-model/drools-mvel-compiler/src/test/java/org/drools/mvelcompiler/PreprocessCompilerTest.java @@ -23,7 +23,7 @@ import org.drools.Person; import org.drools.mvelcompiler.context.MvelCompilerContext; -import org.junit.Test; +import org.junit.jupiter.api.Test; import static org.assertj.core.api.Assertions.assertThat; diff --git a/drools-model/drools-mvel-compiler/src/test/java/org/drools/mvelcompiler/util/MethodResolutionUtilsTest.java b/drools-model/drools-mvel-compiler/src/test/java/org/drools/mvelcompiler/util/MethodResolutionUtilsTest.java index 7bef361efae..1d561331f0a 100644 --- a/drools-model/drools-mvel-compiler/src/test/java/org/drools/mvelcompiler/util/MethodResolutionUtilsTest.java +++ b/drools-model/drools-mvel-compiler/src/test/java/org/drools/mvelcompiler/util/MethodResolutionUtilsTest.java @@ -35,7 +35,7 @@ import org.drools.mvelcompiler.ast.StringLiteralExpressionT; import org.drools.mvelcompiler.ast.TypedExpression; import org.drools.mvelcompiler.context.MvelCompilerContext; -import org.junit.Test; +import org.junit.jupiter.api.Test; import java.lang.reflect.Method; import java.util.ArrayList; diff --git a/drools-model/drools-mvel-parser/pom.xml b/drools-model/drools-mvel-parser/pom.xml index 00c721b6eca..5d0bf9a42cc 100644 --- a/drools-model/drools-mvel-parser/pom.xml +++ b/drools-model/drools-mvel-parser/pom.xml @@ -48,9 +48,9 @@ test - junit - junit - test + org.junit.jupiter + junit-jupiter + test org.assertj diff --git a/drools-model/drools-mvel-parser/src/test/java/org/drools/mvel/parser/DrlxParserTest.java b/drools-model/drools-mvel-parser/src/test/java/org/drools/mvel/parser/DrlxParserTest.java index 6bb61df814a..9c505d358f5 100644 --- a/drools-model/drools-mvel-parser/src/test/java/org/drools/mvel/parser/DrlxParserTest.java +++ b/drools-model/drools-mvel-parser/src/test/java/org/drools/mvel/parser/DrlxParserTest.java @@ -21,10 +21,11 @@ import java.io.IOException; import java.nio.file.Paths; +import org.junit.jupiter.api.Test; + import com.github.javaparser.ParseResult; import com.github.javaparser.ParserConfiguration; import com.github.javaparser.ast.CompilationUnit; -import org.junit.Test; import static org.assertj.core.api.Assertions.fail; import static org.drools.mvel.parser.Providers.provider; diff --git a/drools-model/drools-mvel-parser/src/test/java/org/drools/mvel/parser/DroolsMvelParserTest.java b/drools-model/drools-mvel-parser/src/test/java/org/drools/mvel/parser/DroolsMvelParserTest.java index 49910e35269..2092885874c 100644 --- a/drools-model/drools-mvel-parser/src/test/java/org/drools/mvel/parser/DroolsMvelParserTest.java +++ b/drools-model/drools-mvel-parser/src/test/java/org/drools/mvel/parser/DroolsMvelParserTest.java @@ -47,11 +47,12 @@ import org.drools.mvel.parser.ast.expr.TemporalLiteralChunkExpr; import org.drools.mvel.parser.ast.expr.TemporalLiteralExpr; import org.drools.mvel.parser.printer.PrintUtil; -import org.junit.Test; +import org.junit.jupiter.api.Test; import static org.drools.mvel.parser.DrlxParser.parseExpression; import static org.drools.mvel.parser.printer.PrintUtil.printNode; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; public class DroolsMvelParserTest { @@ -293,10 +294,10 @@ public void testHalfDotFreeExprWithFourTemporalArgs() { assertThat(printNode(expression)).isEqualTo(expr); } - @Test(expected = ParseProblemException.class) + @Test public void testInvalidTemporalArgs() { String expr = "this after[5ms,8f] $a"; - Expression expression = parseExpression( parser, expr ).getExpr(); + assertThatExceptionOfType(ParseProblemException.class).isThrownBy(() -> parseExpression( parser, expr ).getExpr()); } @Test @@ -797,10 +798,10 @@ public void testModifyStatement() { "}"); } - @Test(expected = ParseProblemException.class) + @Test public void testModifyFailing() { String expr = "{ modify { name = \"Luca\", age = \"35\" }; }"; - MvelParser.parseBlock(expr); + assertThatExceptionOfType(ParseProblemException.class).isThrownBy(() -> MvelParser.parseBlock(expr)); } @Test @@ -875,10 +876,10 @@ public void testWithStatement() { "}"); } - @Test(expected = ParseProblemException.class) + @Test public void testWithFailing() { String expr = "{ with { name = \"Luca\", age = \"35\" }; }"; - MvelParser.parseBlock(expr); + assertThatExceptionOfType(ParseProblemException.class).isThrownBy(() -> MvelParser.parseBlock(expr)); } @Test diff --git a/drools-test-coverage/test-compiler-integration/pom.xml b/drools-test-coverage/test-compiler-integration/pom.xml index 6ccf1cbdc67..f470744b644 100644 --- a/drools-test-coverage/test-compiler-integration/pom.xml +++ b/drools-test-coverage/test-compiler-integration/pom.xml @@ -101,7 +101,26 @@ xstream test - + + org.junit.vintage + junit-vintage-engine + test + + + org.junit.jupiter + junit-jupiter-api + test + + + org.junit.jupiter + junit-jupiter-engine + test + + + org.junit.jupiter + junit-jupiter-params + test + org.assertj assertj-core diff --git a/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/compiler/integrationtests/AccumulateCepTest.java b/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/compiler/integrationtests/AccumulateCepTest.java index 60569200768..00f7fa2f8cc 100644 --- a/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/compiler/integrationtests/AccumulateCepTest.java +++ b/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/compiler/integrationtests/AccumulateCepTest.java @@ -19,19 +19,18 @@ package org.drools.compiler.integrationtests; import java.util.ArrayList; -import java.util.Collection; import java.util.List; import java.util.concurrent.TimeUnit; +import java.util.stream.Stream; import org.drools.compiler.integrationtests.incrementalcompilation.TestUtil; import org.drools.kiesession.rulebase.InternalKnowledgeBase; import org.drools.core.impl.RuleBaseFactory; import org.drools.testcoverage.common.util.KieBaseTestConfiguration; import org.drools.testcoverage.common.util.KieBaseUtil; -import org.drools.testcoverage.common.util.TestParametersUtil; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; +import org.drools.testcoverage.common.util.TestParametersUtil2; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; import org.kie.api.KieBase; import org.kie.api.definition.type.FactType; import org.kie.api.runtime.KieSession; @@ -42,7 +41,6 @@ import static java.util.Arrays.asList; import static org.assertj.core.api.Assertions.assertThat; -@RunWith(Parameterized.class) public class AccumulateCepTest { public static final String TEST_MANY_SLIDING_WINDOWS_DRL = "package com.sample;\n" + @@ -72,19 +70,13 @@ public class AccumulateCepTest { "end\n" + "\n"; - private final KieBaseTestConfiguration kieBaseTestConfiguration; - - public AccumulateCepTest(final KieBaseTestConfiguration kieBaseTestConfiguration) { - this.kieBaseTestConfiguration = kieBaseTestConfiguration; - } - - @Parameterized.Parameters(name = "KieBase type={0}") - public static Collection getParameters() { - return TestParametersUtil.getKieBaseStreamConfigurations(true); + public static Stream parameters() { + return TestParametersUtil2.getKieBaseStreamConfigurations(true).stream(); } - @Test - public void testAccumulatesExpireVsCancel() throws Exception { + @ParameterizedTest + @MethodSource("parameters") + public void testAccumulatesExpireVsCancel(KieBaseTestConfiguration kieBaseTestConfiguration) throws Exception { // JBRULES-3201 final String drl = "package com.sample;\n" + "\n" + @@ -134,8 +126,9 @@ public void testAccumulatesExpireVsCancel() throws Exception { } } - @Test - public void testManySlidingWindows() { + @ParameterizedTest + @MethodSource("parameters") + public void testManySlidingWindows(KieBaseTestConfiguration kieBaseTestConfiguration) { final KieBase kbase = KieBaseUtil.getKieBaseFromKieModuleFromDrl("accumulate-test", kieBaseTestConfiguration, TEST_MANY_SLIDING_WINDOWS_DRL); diff --git a/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/compiler/integrationtests/AccumulateConsistencyTest.java b/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/compiler/integrationtests/AccumulateConsistencyTest.java index 41eb61e5d42..ee6caa2c2e0 100644 --- a/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/compiler/integrationtests/AccumulateConsistencyTest.java +++ b/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/compiler/integrationtests/AccumulateConsistencyTest.java @@ -23,14 +23,15 @@ import java.util.HashMap; import java.util.List; import java.util.Map; +import java.util.stream.Stream; import org.drools.testcoverage.common.model.MyFact; import org.drools.testcoverage.common.model.Person; import org.drools.testcoverage.common.util.KieBaseTestConfiguration; import org.drools.testcoverage.common.util.KieBaseUtil; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.Arguments; +import org.junit.jupiter.params.provider.MethodSource; import org.kie.api.KieBase; import org.kie.api.KieServices; import org.kie.api.runtime.KieSession; @@ -40,31 +41,25 @@ import org.kie.api.runtime.rule.Variable; import static org.assertj.core.api.Assertions.assertThat; +import static org.junit.jupiter.params.provider.Arguments.arguments; -@RunWith(Parameterized.class) public class AccumulateConsistencyTest { - private final KieBaseTestConfiguration kieBaseTestConfiguration; - private final boolean accumulateNullPropagation; - public AccumulateConsistencyTest(final KieBaseTestConfiguration kieBaseTestConfiguration, boolean accumulateNullPropagation) { - this.kieBaseTestConfiguration = kieBaseTestConfiguration; - this.accumulateNullPropagation = accumulateNullPropagation; - } // accumulateNullPropagation is false by default in drools 7.x - @Parameterized.Parameters(name = "KieBase type={0}, accumulateNullPropagation= {1}") - public static Collection getParameters() { - Collection parameters = new ArrayList<>(); - parameters.add(new Object[]{KieBaseTestConfiguration.CLOUD_IDENTITY, false}); - parameters.add(new Object[]{KieBaseTestConfiguration.CLOUD_IDENTITY_MODEL_PATTERN, false}); - parameters.add(new Object[]{KieBaseTestConfiguration.CLOUD_IDENTITY, true}); - parameters.add(new Object[]{KieBaseTestConfiguration.CLOUD_IDENTITY_MODEL_PATTERN, true}); - return parameters; + public static Stream parameters() { + Collection parameters = new ArrayList<>(); + parameters.add(arguments(KieBaseTestConfiguration.CLOUD_IDENTITY, false)); + parameters.add(arguments(KieBaseTestConfiguration.CLOUD_IDENTITY_MODEL_PATTERN, false)); + parameters.add(arguments(KieBaseTestConfiguration.CLOUD_IDENTITY, true)); + parameters.add(arguments(KieBaseTestConfiguration.CLOUD_IDENTITY_MODEL_PATTERN, true)); + return parameters.stream(); } - @Test - public void testMinNoMatch() { + @ParameterizedTest(name = "KieBase type={0}, accumulateNullPropagation= {1}") + @MethodSource("parameters") + public void testMinNoMatch(KieBaseTestConfiguration kieBaseTestConfiguration, boolean accumulateNullPropagation) { final String drl = "package org.drools.compiler.integrationtests;\n" + "import " + Person.class.getCanonicalName() + ";\n" + @@ -93,8 +88,9 @@ public void testMinNoMatch() { } } - @Test - public void testMaxNoMatch() { + @ParameterizedTest(name = "KieBase type={0}, accumulateNullPropagation= {1}") + @MethodSource("parameters") + public void testMaxNoMatch(KieBaseTestConfiguration kieBaseTestConfiguration, boolean accumulateNullPropagation) { final String drl = "package org.drools.compiler.integrationtests;\n" + "import " + Person.class.getCanonicalName() + ";\n" + @@ -123,8 +119,9 @@ public void testMaxNoMatch() { } } - @Test - public void testAveNoMatch() { + @ParameterizedTest(name = "KieBase type={0}, accumulateNullPropagation= {1}") + @MethodSource("parameters") + public void testAveNoMatch(KieBaseTestConfiguration kieBaseTestConfiguration, boolean accumulateNullPropagation) { final String drl = "package org.drools.compiler.integrationtests;\n" + "import " + Person.class.getCanonicalName() + ";\n" + @@ -153,8 +150,9 @@ public void testAveNoMatch() { } } - @Test - public void testSumNoMatch() { + @ParameterizedTest(name = "KieBase type={0}, accumulateNullPropagation= {1}") + @MethodSource("parameters") + public void testSumNoMatch(KieBaseTestConfiguration kieBaseTestConfiguration, boolean accumulateNullPropagation) { final String drl = "package org.drools.compiler.integrationtests;\n" + "import " + Person.class.getCanonicalName() + ";\n" + @@ -179,8 +177,9 @@ public void testSumNoMatch() { } } - @Test - public void testCountNoMatch() { + @ParameterizedTest(name = "KieBase type={0}, accumulateNullPropagation= {1}") + @MethodSource("parameters") + public void testCountNoMatch(KieBaseTestConfiguration kieBaseTestConfiguration, boolean accumulateNullPropagation) { final String drl = "package org.drools.compiler.integrationtests;\n" + "import " + Person.class.getCanonicalName() + ";\n" + @@ -205,8 +204,9 @@ public void testCountNoMatch() { } } - @Test - public void testMinMaxNoMatch() { + @ParameterizedTest(name = "KieBase type={0}, accumulateNullPropagation= {1}") + @MethodSource("parameters") + public void testMinMaxNoMatch(KieBaseTestConfiguration kieBaseTestConfiguration, boolean accumulateNullPropagation) { final String drl = "package org.drools.compiler.integrationtests;\n" + "import " + Person.class.getCanonicalName() + ";\n" + @@ -232,8 +232,9 @@ public void testMinMaxNoMatch() { } } - @Test - public void testMinMaxMatch() { + @ParameterizedTest(name = "KieBase type={0}, accumulateNullPropagation= {1}") + @MethodSource("parameters") + public void testMinMaxMatch(KieBaseTestConfiguration kieBaseTestConfiguration, boolean accumulateNullPropagation) { final String drl = "package org.drools.compiler.integrationtests;\n" + "import " + Person.class.getCanonicalName() + ";\n" + @@ -269,8 +270,9 @@ public void testMinMaxMatch() { } } - @Test - public void testMinNoMatchAccFrom() { + @ParameterizedTest(name = "KieBase type={0}, accumulateNullPropagation= {1}") + @MethodSource("parameters") + public void testMinNoMatchAccFrom(KieBaseTestConfiguration kieBaseTestConfiguration, boolean accumulateNullPropagation) { final String drl = "package org.drools.compiler.integrationtests;\n" + @@ -300,8 +302,9 @@ public void testMinNoMatchAccFrom() { } } - @Test - public void testMinMatchUnification() { + @ParameterizedTest(name = "KieBase type={0}, accumulateNullPropagation= {1}") + @MethodSource("parameters") + public void testMinMatchUnification(KieBaseTestConfiguration kieBaseTestConfiguration, boolean accumulateNullPropagation) { final String drl = "package org.drools.compiler.integrationtests;\n" + @@ -330,8 +333,9 @@ public void testMinMatchUnification() { } } - @Test - public void testMinNoMatchUnification() { + @ParameterizedTest(name = "KieBase type={0}, accumulateNullPropagation= {1}") + @MethodSource("parameters") + public void testMinNoMatchUnification(KieBaseTestConfiguration kieBaseTestConfiguration, boolean accumulateNullPropagation) { final String drl = "package org.drools.compiler.integrationtests;\n" + "import " + Person.class.getCanonicalName() + ";\n" + @@ -363,8 +367,9 @@ public void testMinNoMatchUnification() { } } - @Test - public void testMinMatchUnificationQuery() { + @ParameterizedTest(name = "KieBase type={0}, accumulateNullPropagation= {1}") + @MethodSource("parameters") + public void testMinMatchUnificationQuery(KieBaseTestConfiguration kieBaseTestConfiguration, boolean accumulateNullPropagation) { final String drl = "package org.drools.compiler.integrationtests;\n" + diff --git a/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/compiler/integrationtests/AnnotationsCepTest.java b/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/compiler/integrationtests/AnnotationsCepTest.java index 6f14418494f..b52d7fb25c1 100644 --- a/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/compiler/integrationtests/AnnotationsCepTest.java +++ b/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/compiler/integrationtests/AnnotationsCepTest.java @@ -18,37 +18,29 @@ */ package org.drools.compiler.integrationtests; -import java.util.Collection; +import java.util.stream.Stream; import org.drools.testcoverage.common.model.Person; import org.drools.testcoverage.common.util.KieBaseTestConfiguration; import org.drools.testcoverage.common.util.KieBaseUtil; -import org.drools.testcoverage.common.util.TestParametersUtil; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; +import org.drools.testcoverage.common.util.TestParametersUtil2; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; import org.kie.api.KieBase; import org.kie.api.conf.MBeansOption; import org.kie.api.definition.rule.Rule; import static org.assertj.core.api.Assertions.assertThat; -@RunWith(Parameterized.class) public class AnnotationsCepTest { - private final KieBaseTestConfiguration kieBaseTestConfiguration; - - public AnnotationsCepTest(final KieBaseTestConfiguration kieBaseTestConfiguration) { - this.kieBaseTestConfiguration = kieBaseTestConfiguration; - } - - @Parameterized.Parameters(name = "KieBase type={0}") - public static Collection getParameters() { - return TestParametersUtil.getKieBaseStreamConfigurations(true); + public static Stream parameters() { + return TestParametersUtil2.getKieBaseStreamConfigurations(true).stream(); } - @Test - public void testRuleAnnotation() { + @ParameterizedTest(name = "KieBase type={0}") + @MethodSource("parameters") + public void testRuleAnnotation(KieBaseTestConfiguration kieBaseTestConfiguration) { final String drl = "package org.drools.compiler.integrationtests\n" + "import " + Person.class.getCanonicalName() + "; \n" + "rule X\n" + @@ -74,8 +66,9 @@ public void testRuleAnnotation() { } - @Test - public void testRuleAnnotation2() { + @ParameterizedTest(name = "KieBase type={0}") + @MethodSource("parameters") + public void testRuleAnnotation2(KieBaseTestConfiguration kieBaseTestConfiguration) { final String drl = "package org.drools.compiler.integrationtests\n" + "import " + Person.class.getCanonicalName() + "; \n" + "rule X\n" + diff --git a/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/compiler/integrationtests/AnnotationsOnPatternTest.java b/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/compiler/integrationtests/AnnotationsOnPatternTest.java index af509a19d0d..691a692741b 100644 --- a/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/compiler/integrationtests/AnnotationsOnPatternTest.java +++ b/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/compiler/integrationtests/AnnotationsOnPatternTest.java @@ -19,9 +19,9 @@ package org.drools.compiler.integrationtests; import java.util.Arrays; -import java.util.Collection; import java.util.List; import java.util.Map; +import java.util.stream.Stream; import org.drools.base.definitions.rule.impl.RuleImpl; import org.drools.base.factmodel.AnnotationDefinition; @@ -30,32 +30,24 @@ import org.drools.testcoverage.common.util.KieBaseTestConfiguration; import org.drools.testcoverage.common.util.KieBaseUtil; import org.drools.testcoverage.common.util.KieUtil; -import org.drools.testcoverage.common.util.TestParametersUtil; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; +import org.drools.testcoverage.common.util.TestParametersUtil2; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; import org.kie.api.KieBase; import org.kie.api.builder.KieBuilder; import org.kie.api.definition.rule.Rule; import static org.assertj.core.api.Assertions.assertThat; -@RunWith(Parameterized.class) public class AnnotationsOnPatternTest { - private final KieBaseTestConfiguration kieBaseTestConfiguration; - - public AnnotationsOnPatternTest(final KieBaseTestConfiguration kieBaseTestConfiguration) { - this.kieBaseTestConfiguration = kieBaseTestConfiguration; - } - - @Parameterized.Parameters(name = "KieBase type={0}") - public static Collection getParameters() { - return TestParametersUtil.getKieBaseCloudConfigurations(false); + public static Stream parameters() { + return TestParametersUtil2.getKieBaseCloudConfigurations(false).stream(); } - @Test - public void testAnnotationWithUnknownProperty() { + @ParameterizedTest(name = "KieBase type={0}") + @MethodSource("parameters") + public void testAnnotationWithUnknownProperty(KieBaseTestConfiguration kieBaseTestConfiguration) { final String drl = "package org.drools.test; " + "import " + Outer.class.getName().replace("$", ".") + "; " + "import " + Inner.class.getName().replace("$", ".") + "; " + @@ -70,8 +62,9 @@ public void testAnnotationWithUnknownProperty() { assertThat(kieBuilder.getResults().getMessages()).hasSize(1); } - @Test - public void testAnnotationWithUnknownClass() { + @ParameterizedTest(name = "KieBase type={0}") + @MethodSource("parameters") + public void testAnnotationWithUnknownClass(KieBaseTestConfiguration kieBaseTestConfiguration) { final String drl = "package org.drools.test; " + "import " + Outer.class.getName().replace("$", ".") + "; " + @@ -85,8 +78,9 @@ public void testAnnotationWithUnknownClass() { assertThat(kieBuilder.getResults().getMessages()).hasSize(1); } - @Test - public void testAnnotationWithQualifiandClass() { + @ParameterizedTest(name = "KieBase type={0}") + @MethodSource("parameters") + public void testAnnotationWithQualifiandClass(KieBaseTestConfiguration kieBaseTestConfiguration) { final String drl = "package org.drools.test; " + "import " + Outer.class.getName().replace("$", ".") + "; " + @@ -107,8 +101,9 @@ public void testAnnotationWithQualifiandClass() { assertThat(adef).isNotNull(); } - @Test - public void testNestedAnnotations() { + @ParameterizedTest(name = "KieBase type={0}") + @MethodSource("parameters") + public void testNestedAnnotations(KieBaseTestConfiguration kieBaseTestConfiguration) { final String drl = "package org.drools.test; " + "import " + Outer.class.getName().replace("$", ".") + "; " + "import " + Inner.class.getName().replace("$", ".") + "; " + @@ -136,8 +131,9 @@ public void testNestedAnnotations() { assertThat(inner.getPropertyValue("text")).isEqualTo("world"); } - @Test - public void testNestedAnnotationsWithMultiplicity() { + @ParameterizedTest(name = "KieBase type={0}") + @MethodSource("parameters") + public void testNestedAnnotationsWithMultiplicity(KieBaseTestConfiguration kieBaseTestConfiguration) { final String drl = "package org.drools.test; " + "import " + Outer.class.getName().replace("$", ".") + "; " + "import " + Inner.class.getName().replace("$", ".") + "; " + @@ -162,8 +158,9 @@ public void testNestedAnnotationsWithMultiplicity() { assertThat(val instanceof AnnotationDefinition[]).isTrue(); } - @Test - public void testRuleAnnotations() { + @ParameterizedTest(name = "KieBase type={0}") + @MethodSource("parameters") + public void testRuleAnnotations(KieBaseTestConfiguration kieBaseTestConfiguration) { final String drl = "package org.drools.test; " + "import " + Inner.class.getName().replace("$", ".") + "; " + @@ -185,8 +182,9 @@ public void testRuleAnnotations() { assertThat(((Map) obj).get("text")).isEqualTo("a"); } - @Test - public void testTypedSimpleArrays() { + @ParameterizedTest(name = "KieBase type={0}") + @MethodSource("parameters") + public void testTypedSimpleArrays(KieBaseTestConfiguration kieBaseTestConfiguration) { final String drl = "package org.drools.test; " + "import " + AnnotationsTest.Simple.class.getName().replace("$", ".") + "; " + @@ -209,8 +207,9 @@ public void testTypedSimpleArrays() { assertThat(val instanceof int[]).isTrue(); } - @Test - public void testCollectAnnotationsParsingAndBuilding() { + @ParameterizedTest(name = "KieBase type={0}") + @MethodSource("parameters") + public void testCollectAnnotationsParsingAndBuilding(KieBaseTestConfiguration kieBaseTestConfiguration) { final String packageName = "org.drools.compiler.integrationtests"; diff --git a/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/compiler/integrationtests/AnnotationsTest.java b/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/compiler/integrationtests/AnnotationsTest.java index 0a737a950e1..267e636c286 100644 --- a/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/compiler/integrationtests/AnnotationsTest.java +++ b/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/compiler/integrationtests/AnnotationsTest.java @@ -24,15 +24,14 @@ import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; import java.lang.reflect.Field; -import java.util.Collection; +import java.util.stream.Stream; import org.drools.testcoverage.common.util.KieBaseTestConfiguration; import org.drools.testcoverage.common.util.KieBaseUtil; import org.drools.testcoverage.common.util.KieUtil; -import org.drools.testcoverage.common.util.TestParametersUtil; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; +import org.drools.testcoverage.common.util.TestParametersUtil2; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; import org.kie.api.KieBase; import org.kie.api.builder.KieBuilder; import org.kie.api.definition.type.FactType; @@ -43,18 +42,10 @@ import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.fail; -@RunWith(Parameterized.class) public class AnnotationsTest { - private final KieBaseTestConfiguration kieBaseTestConfiguration; - - public AnnotationsTest(final KieBaseTestConfiguration kieBaseTestConfiguration) { - this.kieBaseTestConfiguration = kieBaseTestConfiguration; - } - - @Parameterized.Parameters(name = "KieBase type={0}") - public static Collection getParameters() { - return TestParametersUtil.getKieBaseCloudConfigurations(true); + public static Stream parameters() { + return TestParametersUtil2.getKieBaseCloudConfigurations(true).stream(); } public enum AnnPropEnum { @@ -97,8 +88,9 @@ public String getValue() { AnnPropEnum[] enumArrProp() default {AnnPropEnum.TWO, AnnPropEnum.THREE}; } - @Test - public void annotationTest() { + @ParameterizedTest(name = "KieBase type={0}") + @MethodSource("parameters") + public void annotationTest(KieBaseTestConfiguration kieBaseTestConfiguration) { final String drl = "package org.drools.compiler.test;\n " + "" + @@ -192,8 +184,9 @@ public void annotationTest() { assertThat(ann2.enumArrProp()).isEqualTo(new AnnPropEnum[]{AnnPropEnum.TWO, AnnPropEnum.THREE}); } - @Test - public void annotationErrorTest() { + @ParameterizedTest(name = "KieBase type={0}") + @MethodSource("parameters") + public void annotationErrorTest(KieBaseTestConfiguration kieBaseTestConfiguration) { final String drl = "package org.drools.compiler.test;\n " + "" + @@ -221,8 +214,9 @@ public void annotationErrorTest() { assertThat(kieBuilder2.getResults().getMessages()).hasSize(3); } - @Test - public void testAnnotationNameClash() { + @ParameterizedTest(name = "KieBase type={0}") + @MethodSource("parameters") + public void testAnnotationNameClash(KieBaseTestConfiguration kieBaseTestConfiguration) { final String drl = "package org.drools.test\n" + "" + "declare Annot\n" + @@ -256,8 +250,9 @@ public static class Duration { } - @Test - public void testAnnotationNameClashWithRegularClass() { + @ParameterizedTest(name = "KieBase type={0}") + @MethodSource("parameters") + public void testAnnotationNameClashWithRegularClass(KieBaseTestConfiguration kieBaseTestConfiguration) { final String drl = "package org.drools.test\n" + "import " + Duration.class.getCanonicalName() + "; " + @@ -278,8 +273,9 @@ public void testAnnotationNameClashWithRegularClass() { int[] numbers(); } - @Test - public void testAnnotationOnLHSAndMerging() { + @ParameterizedTest(name = "KieBase type={0}") + @MethodSource("parameters") + public void testAnnotationOnLHSAndMerging(KieBaseTestConfiguration kieBaseTestConfiguration) { final String drl = "package org.drools.compiler; " + " " + diff --git a/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/compiler/integrationtests/ArrayTest.java b/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/compiler/integrationtests/ArrayTest.java index ab781ef687c..63abe7b8cc7 100644 --- a/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/compiler/integrationtests/ArrayTest.java +++ b/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/compiler/integrationtests/ArrayTest.java @@ -19,39 +19,31 @@ package org.drools.compiler.integrationtests; import java.util.ArrayList; -import java.util.Collection; import java.util.List; +import java.util.stream.Stream; import org.drools.testcoverage.common.model.Primitives; import org.drools.testcoverage.common.model.TestParam; import org.drools.testcoverage.common.util.KieBaseTestConfiguration; import org.drools.testcoverage.common.util.KieBaseUtil; -import org.drools.testcoverage.common.util.TestParametersUtil; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; +import org.drools.testcoverage.common.util.TestParametersUtil2; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; import org.kie.api.KieBase; import org.kie.api.runtime.KieSession; import org.kie.api.runtime.rule.FactHandle; import static org.assertj.core.api.Assertions.assertThat; -@RunWith(Parameterized.class) public class ArrayTest { - private final KieBaseTestConfiguration kieBaseTestConfiguration; - - public ArrayTest(final KieBaseTestConfiguration kieBaseTestConfiguration) { - this.kieBaseTestConfiguration = kieBaseTestConfiguration; - } - - @Parameterized.Parameters(name = "KieBase type={0}") - public static Collection getParameters() { - return TestParametersUtil.getKieBaseCloudConfigurations(true); + public static Stream parameters() { + return TestParametersUtil2.getKieBaseCloudConfigurations(true).stream(); } - @Test - public void testEqualsOnIntArray() { + @ParameterizedTest(name = "KieBase type={0}") + @MethodSource("parameters") + public void testEqualsOnIntArray(KieBaseTestConfiguration kieBaseTestConfiguration) { final String drl = "package org.drools.compiler;\n" + @@ -82,8 +74,9 @@ public void testEqualsOnIntArray() { } } - @Test - public void testContainsBooleanArray() { + @ParameterizedTest(name = "KieBase type={0}") + @MethodSource("parameters") + public void testContainsBooleanArray(KieBaseTestConfiguration kieBaseTestConfiguration) { final KieBase kbase = KieBaseUtil.getKieBaseFromKieModuleFromDrl("array-test", kieBaseTestConfiguration, getDrl("Boolean", false, "true")); @@ -106,8 +99,9 @@ public void testContainsBooleanArray() { } } - @Test - public void testNotContainsBooleanArray() { + @ParameterizedTest(name = "KieBase type={0}") + @MethodSource("parameters") + public void testNotContainsBooleanArray(KieBaseTestConfiguration kieBaseTestConfiguration) { final String drl = "package org.drools.compiler;\n" + "import " + Primitives.class.getCanonicalName() + ";\n" + @@ -145,8 +139,9 @@ public void testNotContainsBooleanArray() { } } - @Test - public void testContainsByteArray() { + @ParameterizedTest(name = "KieBase type={0}") + @MethodSource("parameters") + public void testContainsByteArray(KieBaseTestConfiguration kieBaseTestConfiguration) { final KieBase kbase = KieBaseUtil.getKieBaseFromKieModuleFromDrl("array-test", kieBaseTestConfiguration, getDrl("Byte", false, "1")); final KieSession kieSession = kbase.newKieSession(); @@ -168,8 +163,9 @@ public void testContainsByteArray() { } } - @Test - public void testNotContainsByteArray() { + @ParameterizedTest(name = "KieBase type={0}") + @MethodSource("parameters") + public void testNotContainsByteArray(KieBaseTestConfiguration kieBaseTestConfiguration) { final KieBase kbase = KieBaseUtil.getKieBaseFromKieModuleFromDrl("array-test", kieBaseTestConfiguration, getDrl("Byte", true, "1")); final KieSession kieSession = kbase.newKieSession(); @@ -191,8 +187,9 @@ public void testNotContainsByteArray() { } } - @Test - public void testContainsShortArray() { + @ParameterizedTest(name = "KieBase type={0}") + @MethodSource("parameters") + public void testContainsShortArray(KieBaseTestConfiguration kieBaseTestConfiguration) { final KieBase kbase = KieBaseUtil.getKieBaseFromKieModuleFromDrl("array-test", kieBaseTestConfiguration, getDrl("Short", false, "1")); final KieSession kieSession = kbase.newKieSession(); @@ -214,8 +211,9 @@ public void testContainsShortArray() { } } - @Test - public void testNotContainsShortArray() { + @ParameterizedTest(name = "KieBase type={0}") + @MethodSource("parameters") + public void testNotContainsShortArray(KieBaseTestConfiguration kieBaseTestConfiguration) { final KieBase kbase = KieBaseUtil.getKieBaseFromKieModuleFromDrl("array-test", kieBaseTestConfiguration, getDrl("Short", true, "1")); final KieSession kieSession = kbase.newKieSession(); @@ -237,8 +235,9 @@ public void testNotContainsShortArray() { } } - @Test - public void testContainsCharArray() { + @ParameterizedTest(name = "KieBase type={0}") + @MethodSource("parameters") + public void testContainsCharArray(KieBaseTestConfiguration kieBaseTestConfiguration) { final KieBase kbase = KieBaseUtil.getKieBaseFromKieModuleFromDrl("array-test", kieBaseTestConfiguration, getDrl("Character", false, "'c'")); final KieSession kieSession = kbase.newKieSession(); @@ -260,8 +259,9 @@ public void testContainsCharArray() { } } - @Test - public void testNotContainsCharArray() { + @ParameterizedTest(name = "KieBase type={0}") + @MethodSource("parameters") + public void testNotContainsCharArray(KieBaseTestConfiguration kieBaseTestConfiguration) { final KieBase kbase = KieBaseUtil.getKieBaseFromKieModuleFromDrl("array-test", kieBaseTestConfiguration, getDrl("Character", true, "'c'")); final KieSession kieSession = kbase.newKieSession(); @@ -283,8 +283,9 @@ public void testNotContainsCharArray() { } } - @Test - public void testContainsIntArray() { + @ParameterizedTest(name = "KieBase type={0}") + @MethodSource("parameters") + public void testContainsIntArray(KieBaseTestConfiguration kieBaseTestConfiguration) { final KieBase kbase = KieBaseUtil.getKieBaseFromKieModuleFromDrl("array-test", kieBaseTestConfiguration, getDrl("Integer", false, "10")); final KieSession kieSession = kbase.newKieSession(); @@ -306,8 +307,9 @@ public void testContainsIntArray() { } } - @Test - public void testNotContainsIntArray() { + @ParameterizedTest(name = "KieBase type={0}") + @MethodSource("parameters") + public void testNotContainsIntArray(KieBaseTestConfiguration kieBaseTestConfiguration) { final KieBase kbase = KieBaseUtil.getKieBaseFromKieModuleFromDrl("array-test", kieBaseTestConfiguration, getDrl("Integer", true, "10")); final KieSession kieSession = kbase.newKieSession(); @@ -329,8 +331,9 @@ public void testNotContainsIntArray() { } } - @Test - public void testContainsLongArray() { + @ParameterizedTest(name = "KieBase type={0}") + @MethodSource("parameters") + public void testContainsLongArray(KieBaseTestConfiguration kieBaseTestConfiguration) { final KieBase kbase = KieBaseUtil.getKieBaseFromKieModuleFromDrl("array-test", kieBaseTestConfiguration, getDrl("Long", false, "10")); final KieSession kieSession = kbase.newKieSession(); @@ -352,8 +355,9 @@ public void testContainsLongArray() { } } - @Test - public void testNotContainsLongArray() { + @ParameterizedTest(name = "KieBase type={0}") + @MethodSource("parameters") + public void testNotContainsLongArray(KieBaseTestConfiguration kieBaseTestConfiguration) { final KieBase kbase = KieBaseUtil.getKieBaseFromKieModuleFromDrl("array-test", kieBaseTestConfiguration, getDrl("Long", true, "10")); final KieSession kieSession = kbase.newKieSession(); @@ -375,8 +379,9 @@ public void testNotContainsLongArray() { } } - @Test - public void testContainsFloatArray() { + @ParameterizedTest(name = "KieBase type={0}") + @MethodSource("parameters") + public void testContainsFloatArray(KieBaseTestConfiguration kieBaseTestConfiguration) { final KieBase kbase = KieBaseUtil.getKieBaseFromKieModuleFromDrl("array-test", kieBaseTestConfiguration, getDrl("Float", false, "10f")); final KieSession kieSession = kbase.newKieSession(); @@ -398,8 +403,9 @@ public void testContainsFloatArray() { } } - @Test - public void testNotContainsFloatArray() { + @ParameterizedTest(name = "KieBase type={0}") + @MethodSource("parameters") + public void testNotContainsFloatArray(KieBaseTestConfiguration kieBaseTestConfiguration) { final KieBase kbase = KieBaseUtil.getKieBaseFromKieModuleFromDrl("array-test", kieBaseTestConfiguration, getDrl("Float", true, "10f")); final KieSession kieSession = kbase.newKieSession(); @@ -421,8 +427,9 @@ public void testNotContainsFloatArray() { } } - @Test - public void testContainsDoubleArray() { + @ParameterizedTest(name = "KieBase type={0}") + @MethodSource("parameters") + public void testContainsDoubleArray(KieBaseTestConfiguration kieBaseTestConfiguration) { final KieBase kbase = KieBaseUtil.getKieBaseFromKieModuleFromDrl("array-test", kieBaseTestConfiguration, getDrl("Double", false, "10")); final KieSession kieSession = kbase.newKieSession(); @@ -444,8 +451,9 @@ public void testContainsDoubleArray() { } } - @Test - public void testNotContainsDoubleArray() { + @ParameterizedTest(name = "KieBase type={0}") + @MethodSource("parameters") + public void testNotContainsDoubleArray(KieBaseTestConfiguration kieBaseTestConfiguration) { final KieBase kbase = KieBaseUtil.getKieBaseFromKieModuleFromDrl("array-test", kieBaseTestConfiguration, getDrl("Double", true, "10")); final KieSession kieSession = kbase.newKieSession(); @@ -528,8 +536,9 @@ private void testArrayContains(final KieSession kieSession, final Primitives p1, assertThat(resultsList.size()).isEqualTo(2); } - @Test - public void testPrimitiveArray() { + @ParameterizedTest(name = "KieBase type={0}") + @MethodSource("parameters") + public void testPrimitiveArray(KieBaseTestConfiguration kieBaseTestConfiguration) { final String drl = "package org.drools.compiler\n" + "import " + Primitives.class.getCanonicalName() + "\n" + "global java.util.List result;\n" + @@ -587,8 +596,9 @@ public void testPrimitiveArray() { } } - @Test - public void testArrayUsage() { + @ParameterizedTest(name = "KieBase type={0}") + @MethodSource("parameters") + public void testArrayUsage(KieBaseTestConfiguration kieBaseTestConfiguration) { final String drl = "import " + TestParam.class.getCanonicalName() + "\n" + "global java.util.List list;\n" + diff --git a/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/compiler/integrationtests/BetaTest.java b/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/compiler/integrationtests/BetaTest.java index a939bd41741..7e4f9cf1fc9 100644 --- a/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/compiler/integrationtests/BetaTest.java +++ b/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/compiler/integrationtests/BetaTest.java @@ -19,40 +19,33 @@ package org.drools.compiler.integrationtests; import java.util.ArrayList; -import java.util.Collection; import java.util.List; +import java.util.stream.Stream; import org.drools.testcoverage.common.model.FirstClass; import org.drools.testcoverage.common.model.SecondClass; import org.drools.testcoverage.common.util.KieBaseTestConfiguration; import org.drools.testcoverage.common.util.KieBaseUtil; import org.drools.testcoverage.common.util.KieUtil; -import org.drools.testcoverage.common.util.TestParametersUtil; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; +import org.drools.testcoverage.common.util.TestParametersUtil2; +import org.junit.jupiter.api.Timeout; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; import org.kie.api.KieBase; import org.kie.api.runtime.KieSession; import org.kie.api.runtime.rule.FactHandle; import static org.assertj.core.api.Assertions.assertThat; -@RunWith(Parameterized.class) public class BetaTest { - private final KieBaseTestConfiguration kieBaseTestConfiguration; - - public BetaTest(final KieBaseTestConfiguration kieBaseTestConfiguration) { - this.kieBaseTestConfiguration = kieBaseTestConfiguration; - } - - @Parameterized.Parameters(name = "KieBase type={0}") - public static Collection getParameters() { - return TestParametersUtil.getKieBaseCloudConfigurations(true); + public static Stream parameters() { + return TestParametersUtil2.getKieBaseCloudConfigurations(true).stream(); } - @Test - public void testDefaultBetaConstrains() { + @ParameterizedTest(name = "KieBase type={0}") + @MethodSource("parameters") + public void testDefaultBetaConstrains(KieBaseTestConfiguration kieBaseTestConfiguration) { final String drl = "package org.drools.compiler\n" + "import " + FirstClass.class.getCanonicalName() + "\n" + @@ -132,8 +125,10 @@ public void testDefaultBetaConstrains() { } } - @Test(timeout = 5000) - public void testEfficientBetaNodeNetworkUpdate() { + @ParameterizedTest(name = "KieBase type={0}") + @MethodSource("parameters") + @Timeout(5000) + public void testEfficientBetaNodeNetworkUpdate(KieBaseTestConfiguration kieBaseTestConfiguration) { // [JBRULES-3372] final String drl = "declare SimpleMembership\n" + diff --git a/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/compiler/integrationtests/BigRuleSetCompilationTest.java b/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/compiler/integrationtests/BigRuleSetCompilationTest.java index 21266b156cd..ff64d1a2320 100644 --- a/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/compiler/integrationtests/BigRuleSetCompilationTest.java +++ b/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/compiler/integrationtests/BigRuleSetCompilationTest.java @@ -23,7 +23,7 @@ import org.drools.io.ByteArrayResource; import org.drools.model.codegen.ExecutableModelProject; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.kie.api.KieServices; import org.kie.api.builder.KieBuilder; import org.kie.api.builder.KieFileSystem; diff --git a/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/compiler/integrationtests/CalendarTest.java b/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/compiler/integrationtests/CalendarTest.java index 3130b72d5a7..c5f6d37f746 100644 --- a/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/compiler/integrationtests/CalendarTest.java +++ b/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/compiler/integrationtests/CalendarTest.java @@ -20,35 +20,27 @@ import java.util.ArrayList; import java.util.Calendar; -import java.util.Collection; +import java.util.stream.Stream; import org.drools.testcoverage.common.util.KieBaseTestConfiguration; import org.drools.testcoverage.common.util.KieBaseUtil; -import org.drools.testcoverage.common.util.TestParametersUtil; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; +import org.drools.testcoverage.common.util.TestParametersUtil2; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; import org.kie.api.KieBase; import org.kie.api.runtime.KieSession; import static org.assertj.core.api.Assertions.assertThat; -@RunWith(Parameterized.class) public class CalendarTest { - private final KieBaseTestConfiguration kieBaseTestConfiguration; - - public CalendarTest(final KieBaseTestConfiguration kieBaseTestConfiguration) { - this.kieBaseTestConfiguration = kieBaseTestConfiguration; - } - - @Parameterized.Parameters(name = "KieBase type={0}") - public static Collection getParameters() { - return TestParametersUtil.getKieBaseCloudConfigurations(true); + public static Stream parameters() { + return TestParametersUtil2.getKieBaseCloudConfigurations(true).stream(); } - @Test - public void test() { + @ParameterizedTest(name = "KieBase type={0}") + @MethodSource("parameters") + public void test(KieBaseTestConfiguration kieBaseTestConfiguration) { // BZ-1007385 final String drl = "package org.drools.compiler.integrationtests;\n" + "\n" + diff --git a/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/compiler/integrationtests/CepEspNegativeCloudTest.java b/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/compiler/integrationtests/CepEspNegativeCloudTest.java index 17f87ca5159..e5d497cebc4 100644 --- a/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/compiler/integrationtests/CepEspNegativeCloudTest.java +++ b/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/compiler/integrationtests/CepEspNegativeCloudTest.java @@ -18,17 +18,17 @@ */ package org.drools.compiler.integrationtests; -import java.util.Collection; import java.util.concurrent.TimeUnit; +import java.util.stream.Stream; import org.drools.testcoverage.common.model.StockTick; import org.drools.testcoverage.common.util.KieBaseTestConfiguration; import org.drools.testcoverage.common.util.KieBaseUtil; import org.drools.testcoverage.common.util.KieSessionTestConfiguration; -import org.drools.testcoverage.common.util.TestParametersUtil; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; +import org.drools.testcoverage.common.util.TestParametersUtil2; +import org.junit.jupiter.api.Timeout; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; import org.kie.api.KieBase; import org.kie.api.definition.type.FactType; import org.kie.api.runtime.KieSession; @@ -39,22 +39,16 @@ import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.fail; -@RunWith(Parameterized.class) public class CepEspNegativeCloudTest { - private final KieBaseTestConfiguration kieBaseTestConfiguration; - - public CepEspNegativeCloudTest(final KieBaseTestConfiguration kieBaseTestConfiguration) { - this.kieBaseTestConfiguration = kieBaseTestConfiguration; - } - - @Parameterized.Parameters(name = "KieBase type={0}") - public static Collection getParameters() { - return TestParametersUtil.getKieBaseCloudConfigurations(true); + public static Stream parameters() { + return TestParametersUtil2.getKieBaseCloudConfigurations(true).stream(); } - @Test(timeout=10000) - public void testCloudModeExpiration() throws InstantiationException, IllegalAccessException, InterruptedException { + @ParameterizedTest + @MethodSource("parameters") + @Timeout(10000) + public void testCloudModeExpiration(KieBaseTestConfiguration kieBaseTestConfiguration) throws InstantiationException, IllegalAccessException, InterruptedException { final String drl = "package org.drools.cloud\n" + "import " + StockTick.class.getCanonicalName() + "\n" + "declare Event\n" + @@ -105,8 +99,9 @@ public void testCloudModeExpiration() throws InstantiationException, IllegalAcce } } - @Test - public void testThrowsWhenCreatingKieBaseUsingWindowsInCloudMode() { + @ParameterizedTest + @MethodSource("parameters") + public void testThrowsWhenCreatingKieBaseUsingWindowsInCloudMode(KieBaseTestConfiguration kieBaseTestConfiguration) { final String drl = "declare TestEvent\n" + " @role( event )\n" + @@ -126,8 +121,9 @@ public void testThrowsWhenCreatingKieBaseUsingWindowsInCloudMode() { } } - @Test - public void testTemporalQuery() { + @ParameterizedTest + @MethodSource("parameters") + public void testTemporalQuery(KieBaseTestConfiguration kieBaseTestConfiguration) { // BZ-967441 final String drl = "package org.drools.compiler.integrationtests;\n" + diff --git a/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/compiler/integrationtests/CepJavaTypeTest.java b/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/compiler/integrationtests/CepJavaTypeTest.java index 451c5a28c19..8213c074f0a 100644 --- a/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/compiler/integrationtests/CepJavaTypeTest.java +++ b/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/compiler/integrationtests/CepJavaTypeTest.java @@ -19,15 +19,16 @@ package org.drools.compiler.integrationtests; import java.util.Collection; +import java.util.stream.Stream; import org.drools.testcoverage.common.util.KieBaseTestConfiguration; import org.drools.testcoverage.common.util.KieBaseUtil; import org.drools.testcoverage.common.util.KieUtil; -import org.drools.testcoverage.common.util.TestParametersUtil; +import org.drools.testcoverage.common.util.TestParametersUtil2; import org.drools.testcoverage.common.util.TimeUtil; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; +import org.junit.jupiter.api.Timeout; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; import org.kie.api.KieBase; import org.kie.api.builder.KieBuilder; import org.kie.api.definition.type.Expires; @@ -37,25 +38,18 @@ import static org.assertj.core.api.Assertions.assertThat; -@RunWith(Parameterized.class) public class CepJavaTypeTest { - private final KieBaseTestConfiguration kieBaseTestConfiguration; - - public CepJavaTypeTest(final KieBaseTestConfiguration kieBaseTestConfiguration) { - this.kieBaseTestConfiguration = kieBaseTestConfiguration; - } - - @Parameterized.Parameters(name = "KieBase type={0}") - public static Collection getParameters() { - return TestParametersUtil.getKieBaseStreamConfigurations(true); + public static Stream parameters() { + return TestParametersUtil2.getKieBaseStreamConfigurations(true).stream(); } @Role(value = Role.Type.EVENT) public static class Event { } - @Test - public void testJavaTypeAnnotatedWithRole_WindowTime() { + @ParameterizedTest(name = "KieBase type={0}") + @MethodSource("parameters") + public void testJavaTypeAnnotatedWithRole_WindowTime(KieBaseTestConfiguration kieBaseTestConfiguration) { final String drl = "package org.drools.compiler.integrationtests\n" + "\n" + "import " + CepJavaTypeTest.Event.class.getCanonicalName() + ";\n" @@ -70,8 +64,9 @@ public void testJavaTypeAnnotatedWithRole_WindowTime() { assertThat(kieBuilder.getResults().getMessages()).isEmpty(); } - @Test - public void testJavaTypeAnnotatedWithRole_WindowLength() { + @ParameterizedTest(name = "KieBase type={0}") + @MethodSource("parameters") + public void testJavaTypeAnnotatedWithRole_WindowLength(KieBaseTestConfiguration kieBaseTestConfiguration) { final String drl = "package org.drools.compiler.integrationtests\n" + "\n" + "import " + CepJavaTypeTest.Event.class.getCanonicalName() + ";\n" @@ -104,8 +99,10 @@ public MyMessage(final String n) { public long getTs() { return ts; } } - @Test(timeout = 5000) - public void testEventWithShortExpiration() throws InterruptedException { + @ParameterizedTest(name = "KieBase type={0}") + @MethodSource("parameters") + @Timeout(5000) + public void testEventWithShortExpiration(KieBaseTestConfiguration kieBaseTestConfiguration) throws InterruptedException { // BZ-1265773 final String drl = "import " + MyMessage.class.getCanonicalName() +"\n" + "rule \"Rule A Start\"\n" + diff --git a/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/compiler/integrationtests/ClassLoaderTest.java b/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/compiler/integrationtests/ClassLoaderTest.java index cd44b685e1e..54ec8480c47 100644 --- a/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/compiler/integrationtests/ClassLoaderTest.java +++ b/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/compiler/integrationtests/ClassLoaderTest.java @@ -26,7 +26,7 @@ import org.drools.testcoverage.common.util.KieBaseTestConfiguration; import org.drools.testcoverage.common.util.KieSessionTestConfiguration; import org.drools.testcoverage.common.util.KieUtil; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.kie.api.KieServices; import org.kie.api.builder.KieBuilder; import org.kie.api.builder.KieFileSystem; diff --git a/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/compiler/integrationtests/CommandsTest.java b/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/compiler/integrationtests/CommandsTest.java index ad42a905458..e9c314aefc8 100644 --- a/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/compiler/integrationtests/CommandsTest.java +++ b/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/compiler/integrationtests/CommandsTest.java @@ -18,17 +18,16 @@ */ package org.drools.compiler.integrationtests; -import java.util.Collection; import java.util.concurrent.TimeUnit; +import java.util.stream.Stream; import org.drools.testcoverage.common.model.Cheese; import org.drools.testcoverage.common.util.KieBaseTestConfiguration; import org.drools.testcoverage.common.util.KieBaseUtil; import org.drools.testcoverage.common.util.KieSessionTestConfiguration; -import org.drools.testcoverage.common.util.TestParametersUtil; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; +import org.drools.testcoverage.common.util.TestParametersUtil2; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; import org.kie.api.KieBase; import org.kie.api.KieServices; import org.kie.api.command.KieCommands; @@ -36,22 +35,15 @@ import static org.assertj.core.api.Assertions.assertThat; -@RunWith(Parameterized.class) public class CommandsTest { - private final KieBaseTestConfiguration kieBaseTestConfiguration; - - public CommandsTest(final KieBaseTestConfiguration kieBaseTestConfiguration) { - this.kieBaseTestConfiguration = kieBaseTestConfiguration; - } - - @Parameterized.Parameters(name = "KieBase type={0}") - public static Collection getParameters() { - return TestParametersUtil.getKieBaseCloudConfigurations(true); + public static Stream parameters() { + return TestParametersUtil2.getKieBaseCloudConfigurations(true).stream(); } - @Test - public void testSessionTimeCommands() { + @ParameterizedTest(name = "KieBase type={0}") + @MethodSource("parameters") + public void testSessionTimeCommands(KieBaseTestConfiguration kieBaseTestConfiguration) { final String drl = "package org.drools.compiler.integrationtests \n" + "import " + Cheese.class.getCanonicalName() + " \n" + diff --git a/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/compiler/integrationtests/ConditionLimitTest.java b/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/compiler/integrationtests/ConditionLimitTest.java index ed6455944e2..7fba9629c95 100644 --- a/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/compiler/integrationtests/ConditionLimitTest.java +++ b/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/compiler/integrationtests/ConditionLimitTest.java @@ -18,32 +18,23 @@ */ package org.drools.compiler.integrationtests; -import java.util.Collection; +import java.util.stream.Stream; import org.drools.testcoverage.common.util.KieBaseTestConfiguration; import org.drools.testcoverage.common.util.KieBaseUtil; -import org.drools.testcoverage.common.util.TestParametersUtil; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; +import org.drools.testcoverage.common.util.TestParametersUtil2; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; import org.kie.api.KieBase; import org.kie.api.runtime.KieSession; import org.kie.api.runtime.rule.FactHandle; import static org.assertj.core.api.Assertions.assertThat; -@RunWith(Parameterized.class) public class ConditionLimitTest { - private final KieBaseTestConfiguration kieBaseTestConfiguration; - - public ConditionLimitTest(final KieBaseTestConfiguration kieBaseTestConfiguration) { - this.kieBaseTestConfiguration = kieBaseTestConfiguration; - } - - @Parameterized.Parameters(name = "KieBase type={0}") - public static Collection getParameters() { - return TestParametersUtil.getKieBaseStreamConfigurations(true); + public static Stream parameters() { + return TestParametersUtil2.getKieBaseStreamConfigurations(true).stream(); } public static class FieldObject { @@ -69,8 +60,9 @@ public void setValue(String value) { } } - @Test - public void testEvalErrorHandling() { + @ParameterizedTest(name = "KieBase type={0}") + @MethodSource("parameters") + public void testEvalErrorHandling(KieBaseTestConfiguration kieBaseTestConfiguration) { // DROOLS-6856 final int INPUT_COUNT = 65; diff --git a/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/compiler/integrationtests/ConsequenceOffsetTest.java b/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/compiler/integrationtests/ConsequenceOffsetTest.java index 3df7f6dd35b..0da5e296b9a 100644 --- a/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/compiler/integrationtests/ConsequenceOffsetTest.java +++ b/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/compiler/integrationtests/ConsequenceOffsetTest.java @@ -20,7 +20,7 @@ import org.drools.compiler.builder.impl.KnowledgeBuilderImpl; import org.drools.drl.ast.descr.RuleDescr; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.kie.api.io.ResourceType; import org.kie.internal.builder.KnowledgeBuilder; import org.kie.internal.builder.KnowledgeBuilderFactory; diff --git a/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/compiler/integrationtests/ConsequenceTypeTest.java b/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/compiler/integrationtests/ConsequenceTypeTest.java index 8129a57ac28..07f0f48d1d8 100644 --- a/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/compiler/integrationtests/ConsequenceTypeTest.java +++ b/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/compiler/integrationtests/ConsequenceTypeTest.java @@ -19,35 +19,27 @@ package org.drools.compiler.integrationtests; -import java.util.Collection; +import java.util.stream.Stream; import org.drools.testcoverage.common.util.KieBaseTestConfiguration; import org.drools.testcoverage.common.util.KieBaseUtil; -import org.drools.testcoverage.common.util.TestParametersUtil; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; +import org.drools.testcoverage.common.util.TestParametersUtil2; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; import org.kie.api.KieBase; import org.kie.api.runtime.KieSession; import static org.assertj.core.api.Assertions.assertThat; -@RunWith(Parameterized.class) public class ConsequenceTypeTest { - private final KieBaseTestConfiguration kieBaseTestConfiguration; - - public ConsequenceTypeTest(final KieBaseTestConfiguration kieBaseTestConfiguration) { - this.kieBaseTestConfiguration = kieBaseTestConfiguration; - } - - @Parameterized.Parameters(name = "KieBase type={0}") - public static Collection getParameters() { - return TestParametersUtil.getKieBaseCloudConfigurations(true); + public static Stream parameters() { + return TestParametersUtil2.getKieBaseCloudConfigurations(true).stream(); } - @Test - public void test() { + @ParameterizedTest(name = "KieBase type={0}") + @MethodSource("parameters") + public void test(KieBaseTestConfiguration kieBaseTestConfiguration) { // KIE-1133 int ruleNr = 100; diff --git a/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/compiler/integrationtests/ConstraintsTest.java b/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/compiler/integrationtests/ConstraintsTest.java index a67fc39c7be..ca9a368903e 100644 --- a/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/compiler/integrationtests/ConstraintsTest.java +++ b/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/compiler/integrationtests/ConstraintsTest.java @@ -19,11 +19,11 @@ package org.drools.compiler.integrationtests; import java.util.ArrayList; -import java.util.Collection; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; +import java.util.stream.Stream; import org.drools.testcoverage.common.model.Cheese; import org.drools.testcoverage.common.model.Message; @@ -32,32 +32,24 @@ import org.drools.testcoverage.common.util.KieBaseTestConfiguration; import org.drools.testcoverage.common.util.KieBaseUtil; import org.drools.testcoverage.common.util.KieUtil; -import org.drools.testcoverage.common.util.TestParametersUtil; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; +import org.drools.testcoverage.common.util.TestParametersUtil2; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; import org.kie.api.KieBase; import org.kie.api.builder.KieBuilder; import org.kie.api.runtime.KieSession; import static org.assertj.core.api.Assertions.assertThat; -@RunWith(Parameterized.class) public class ConstraintsTest { - - private final KieBaseTestConfiguration kieBaseTestConfiguration; - - public ConstraintsTest(final KieBaseTestConfiguration kieBaseTestConfiguration) { - this.kieBaseTestConfiguration = kieBaseTestConfiguration; - } - - @Parameterized.Parameters(name = "KieBase type={0}") - public static Collection getParameters() { - return TestParametersUtil.getKieBaseCloudConfigurations(true); + + public static Stream parameters() { + return TestParametersUtil2.getKieBaseCloudConfigurations(true).stream(); } - @Test - public void testExpressionConstraints1() { + @ParameterizedTest(name = "KieBase type={0}") + @MethodSource("parameters") + public void testExpressionConstraints1(KieBaseTestConfiguration kieBaseTestConfiguration) { final String drl = "package org.drools.compiler.integrationtests\n" + "import " + Mailbox.FolderType.class.getCanonicalName() + ";\n" + "import " + Mailbox.class.getCanonicalName() + ";\n" + @@ -77,11 +69,12 @@ public void testExpressionConstraints1() { " then\n" + "end\n"; - testExpressionConstraints(drl); + testExpressionConstraints(kieBaseTestConfiguration, drl); } - @Test - public void testExpressionConstraints2() { + @ParameterizedTest(name = "KieBase type={0}") + @MethodSource("parameters") + public void testExpressionConstraints2(KieBaseTestConfiguration kieBaseTestConfiguration) { final String drl = "package org.drools.compiler.integrationtests\n" + "import " + Mailbox.FolderType.class.getCanonicalName() + ";\n" + "import " + Mailbox.class.getCanonicalName() + ";\n" + @@ -106,11 +99,12 @@ public void testExpressionConstraints2() { " then\n" + "end\n"; - testExpressionConstraints(drl); + testExpressionConstraints(kieBaseTestConfiguration, drl); } - @Test - public void testExpressionConstraints3() { + @ParameterizedTest(name = "KieBase type={0}") + @MethodSource("parameters") + public void testExpressionConstraints3(KieBaseTestConfiguration kieBaseTestConfiguration) { final String drl = "package org.drools.compiler.integrationtests\n" + "import " + Mailbox.FolderType.class.getCanonicalName() + ";\n" + "import " + Mailbox.class.getCanonicalName() + ";\n" + @@ -144,10 +138,10 @@ public void testExpressionConstraints3() { " then\n" + "end"; - testExpressionConstraints(drl); + testExpressionConstraints(kieBaseTestConfiguration, drl); } - private void testExpressionConstraints(final String drl) { + private void testExpressionConstraints(KieBaseTestConfiguration kieBaseTestConfiguration, final String drl) { final KieBase kbase = KieBaseUtil.getKieBaseFromKieModuleFromDrl("constraints-test", kieBaseTestConfiguration, drl); final KieSession ksession = kbase.newKieSession(); try { @@ -165,8 +159,9 @@ private void testExpressionConstraints(final String drl) { } } - @Test - public void testExpressionConstraints4() { + @ParameterizedTest(name = "KieBase type={0}") + @MethodSource("parameters") + public void testExpressionConstraints4(KieBaseTestConfiguration kieBaseTestConfiguration) { final String drl = "package org.drools.compiler.integrationtests\n" + "import " + Mailbox.FolderType.class.getCanonicalName() + ";\n" + "import " + Mailbox.class.getCanonicalName() + ";\n" + @@ -196,8 +191,9 @@ public void testExpressionConstraints4() { } } - @Test - public void testDeeplyNestedCompactExpressions() { + @ParameterizedTest(name = "KieBase type={0}") + @MethodSource("parameters") + public void testDeeplyNestedCompactExpressions(KieBaseTestConfiguration kieBaseTestConfiguration) { final String drl = "package org.drools\n" + "rule R1\n" + " when\n" + @@ -212,8 +208,9 @@ public void testDeeplyNestedCompactExpressions() { assertThat(kieBuilder.getResults().getMessages()).isNotEmpty(); } - @Test - public void testConstraintConnectors() { + @ParameterizedTest(name = "KieBase type={0}") + @MethodSource("parameters") + public void testConstraintConnectors(KieBaseTestConfiguration kieBaseTestConfiguration) { final KieBase kbase = KieBaseUtil.getKieBaseFromClasspathResources("constraints-test", kieBaseTestConfiguration, "org/drools/compiler/integrationtests/test_ConstraintConnectors.drl"); final KieSession ksession = kbase.newKieSession(); @@ -268,8 +265,9 @@ public void testConstraintConnectors() { } } - @Test - public void testConnectorsAndOperators() { + @ParameterizedTest(name = "KieBase type={0}") + @MethodSource("parameters") + public void testConnectorsAndOperators(KieBaseTestConfiguration kieBaseTestConfiguration) { final String drl = "package org.drools.compiler\n" + "\n" + "import " + StockTick.class.getCanonicalName() + ";\n" + @@ -298,8 +296,9 @@ public void testConnectorsAndOperators() { } } - @Test - public void testConstraintExpression() { + @ParameterizedTest(name = "KieBase type={0}") + @MethodSource("parameters") + public void testConstraintExpression(KieBaseTestConfiguration kieBaseTestConfiguration) { final String drl = "package org.drools.compiler\n" + "import " + Person.class.getCanonicalName() + ";\n" + "rule \"test\"\n" + @@ -318,8 +317,9 @@ public void testConstraintExpression() { } } - @Test - public void testMethodConstraint() { + @ParameterizedTest(name = "KieBase type={0}") + @MethodSource("parameters") + public void testMethodConstraint(KieBaseTestConfiguration kieBaseTestConfiguration) { final String drl = "package org.drools.compiler\n" + "import " + Person.class.getCanonicalName() + ";\n" + "rule \"test\"\n" + @@ -340,8 +340,9 @@ public void testMethodConstraint() { } } - @Test - public void testDeepNestedConstraints() { + @ParameterizedTest(name = "KieBase type={0}") + @MethodSource("parameters") + public void testDeepNestedConstraints(KieBaseTestConfiguration kieBaseTestConfiguration) { final String drl = "package org.drools.compiler\n" + "import " + Person.class.getCanonicalName() + ";\n" + "import " + Cheese.class.getCanonicalName() + ";\n" + @@ -372,8 +373,9 @@ public void testDeepNestedConstraints() { } } - @Test - public void testMultiRestrictionFieldConstraint() { + @ParameterizedTest(name = "KieBase type={0}") + @MethodSource("parameters") + public void testMultiRestrictionFieldConstraint(KieBaseTestConfiguration kieBaseTestConfiguration) { final KieBase kbase = KieBaseUtil.getKieBaseFromClasspathResources("constraints-test", kieBaseTestConfiguration, "org/drools/compiler/integrationtests/test_MultiRestrictionFieldConstraint.drl"); final KieSession ksession = kbase.newKieSession(); @@ -438,8 +440,9 @@ public void testMultiRestrictionFieldConstraint() { } } - @Test - public void testNonBooleanConstraint() { + @ParameterizedTest(name = "KieBase type={0}") + @MethodSource("parameters") + public void testNonBooleanConstraint(KieBaseTestConfiguration kieBaseTestConfiguration) { final String drl = "package org.drools.compiler\n" + "import java.util.List\n" + "import " + Person.class.getCanonicalName() + ";\n" + @@ -457,8 +460,9 @@ public void testNonBooleanConstraint() { .isNotEmpty(); } - @Test - public void testVarargConstraint() { + @ParameterizedTest(name = "KieBase type={0}") + @MethodSource("parameters") + public void testVarargConstraint(KieBaseTestConfiguration kieBaseTestConfiguration) { // JBRULES-3268 final String drl = "package org.drools.compiler.test;\n" + "import " + VarargBean.class.getCanonicalName() + ";\n" + diff --git a/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/compiler/integrationtests/CustomOperatorOnlyDrlTest.java b/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/compiler/integrationtests/CustomOperatorOnlyDrlTest.java index 5ed622236b2..d6835f92ab5 100644 --- a/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/compiler/integrationtests/CustomOperatorOnlyDrlTest.java +++ b/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/compiler/integrationtests/CustomOperatorOnlyDrlTest.java @@ -21,7 +21,7 @@ import java.io.IOException; import java.io.ObjectInput; import java.io.ObjectOutput; -import java.util.Collection; +import java.util.stream.Stream; import org.drools.base.base.ValueResolver; import org.drools.base.base.ValueType; @@ -34,30 +34,22 @@ import org.drools.mvel.evaluators.VariableRestriction; import org.drools.testcoverage.common.util.KieBaseTestConfiguration; import org.drools.testcoverage.common.util.KieBaseUtil; -import org.drools.testcoverage.common.util.TestParametersUtil; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; +import org.drools.testcoverage.common.util.TestParametersUtil2; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; import org.kie.api.runtime.rule.FactHandle; import org.kie.internal.builder.conf.EvaluatorOption; -@RunWith(Parameterized.class) public class CustomOperatorOnlyDrlTest { - private final KieBaseTestConfiguration kieBaseTestConfiguration; - - public CustomOperatorOnlyDrlTest(final KieBaseTestConfiguration kieBaseTestConfiguration) { - this.kieBaseTestConfiguration = kieBaseTestConfiguration; - } - - @Parameterized.Parameters(name = "KieBase type={0}") - public static Collection getParameters() { + public static Stream parameters() { // TODO EM DROOLS-6302 - return TestParametersUtil.getKieBaseCloudConfigurations(false); + return TestParametersUtil2.getKieBaseCloudConfigurations(false).stream(); } - @Test - public void testCustomOperatorCombiningConstraints() { + @ParameterizedTest(name = "KieBase type={0}") + @MethodSource("parameters") + public void testCustomOperatorCombiningConstraints(KieBaseTestConfiguration kieBaseTestConfiguration) { // JBRULES-3517 final String drl = "declare GN\n" + diff --git a/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/compiler/integrationtests/CustomOperatorTest.java b/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/compiler/integrationtests/CustomOperatorTest.java index 8f7c8ef7aab..0161f772935 100644 --- a/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/compiler/integrationtests/CustomOperatorTest.java +++ b/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/compiler/integrationtests/CustomOperatorTest.java @@ -22,6 +22,7 @@ import java.io.ObjectInput; import java.io.ObjectOutput; import java.util.Collection; +import java.util.stream.Stream; import org.drools.base.base.ValueResolver; import org.drools.base.base.ValueType; @@ -36,10 +37,9 @@ import org.drools.testcoverage.common.model.Person; import org.drools.testcoverage.common.util.KieBaseTestConfiguration; import org.drools.testcoverage.common.util.KieBaseUtil; -import org.drools.testcoverage.common.util.TestParametersUtil; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; +import org.drools.testcoverage.common.util.TestParametersUtil2; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; import org.kie.api.KieBase; import org.kie.api.runtime.KieSession; import org.kie.api.runtime.rule.FactHandle; @@ -47,50 +47,45 @@ import static org.assertj.core.api.Assertions.assertThat; -@RunWith(Parameterized.class) public class CustomOperatorTest { - private final KieBaseTestConfiguration kieBaseTestConfiguration; - - public CustomOperatorTest(final KieBaseTestConfiguration kieBaseTestConfiguration) { - this.kieBaseTestConfiguration = kieBaseTestConfiguration; - } - - @Parameterized.Parameters(name = "KieBase type={0}") - public static Collection getParameters() { - return TestParametersUtil.getKieBaseCloudConfigurations(true); + public static Stream parameters() { + return TestParametersUtil2.getKieBaseCloudConfigurations(true).stream(); } - @Test - public void testCustomOperatorUsingCollections() { + @ParameterizedTest(name = "KieBase type={0}") + @MethodSource("parameters") + public void testCustomOperatorUsingCollections(KieBaseTestConfiguration kieBaseTestConfiguration) { String constraints = " $alice : Person(name == \"Alice\")\n" + " $bob : Person(name == \"Bob\", addresses supersetOf $alice.addresses)\n"; - customOperatorUsingCollections(constraints); + customOperatorUsingCollections(kieBaseTestConfiguration, constraints); } - @Test - public void testNoOperatorInstancesCreatedAtRuntime() { + @ParameterizedTest(name = "KieBase type={0}") + @MethodSource("parameters") + public void testNoOperatorInstancesCreatedAtRuntime(KieBaseTestConfiguration kieBaseTestConfiguration) { String constraints = " $alice : Person(name == \"Alice\")\n" + " $bob : Person(name == \"Bob\", addresses supersetOf $alice.addresses)\n" + " Person(name == \"Bob\", addresses supersetOf $alice.addresses)\n"; - customOperatorUsingCollections(constraints); + customOperatorUsingCollections(kieBaseTestConfiguration, constraints); assertThat(SupersetOfEvaluatorDefinition.INSTANCES_COUNTER).isEqualTo(0); } - @Test - public void testCustomOperatorUsingCollectionsInverted() { + @ParameterizedTest(name = "KieBase type={0}") + @MethodSource("parameters") + public void testCustomOperatorUsingCollectionsInverted(KieBaseTestConfiguration kieBaseTestConfiguration) { // DROOLS-6983 String constraints = " $bob : Person(name == \"Bob\")\n" + " $alice : Person(name == \"Alice\", $bob.addresses supersetOf this.addresses)\n"; - customOperatorUsingCollections(constraints); + customOperatorUsingCollections(kieBaseTestConfiguration, constraints); } - private void customOperatorUsingCollections(String constraints) { + private void customOperatorUsingCollections(KieBaseTestConfiguration kieBaseTestConfiguration, String constraints) { final String drl = "import " + Address.class.getCanonicalName() + ";\n" + "import " + Person.class.getCanonicalName() + ";\n" + @@ -210,8 +205,9 @@ public boolean evaluateAll(final Collection leftCollection, final Collection rig } } - @Test - public void testCustomOperatorOnKieModule() { + @ParameterizedTest(name = "KieBase type={0}") + @MethodSource("parameters") + public void testCustomOperatorOnKieModule(KieBaseTestConfiguration kieBaseTestConfiguration) { final String drl = "import " + Address.class.getCanonicalName() + ";\n" + "import " + Person.class.getCanonicalName() + ";\n" + "rule R when\n" + diff --git a/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/compiler/integrationtests/ErrorOnInsertLogicalTest.java b/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/compiler/integrationtests/ErrorOnInsertLogicalTest.java index 24fa39fcb7a..4fa3454a9c3 100644 --- a/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/compiler/integrationtests/ErrorOnInsertLogicalTest.java +++ b/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/compiler/integrationtests/ErrorOnInsertLogicalTest.java @@ -24,7 +24,7 @@ import org.drools.compiler.builder.impl.KnowledgeBuilderImpl; import org.drools.io.ReaderResource; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.kie.api.KieBase; import org.kie.api.KieBaseConfiguration; import org.kie.api.KieServices; diff --git a/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/compiler/integrationtests/FromSharingTest.java b/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/compiler/integrationtests/FromSharingTest.java index b90a9f29f6a..6766d061ca5 100644 --- a/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/compiler/integrationtests/FromSharingTest.java +++ b/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/compiler/integrationtests/FromSharingTest.java @@ -19,39 +19,31 @@ package org.drools.compiler.integrationtests; import java.util.ArrayList; -import java.util.Collection; import java.util.HashMap; import java.util.List; import java.util.Map; +import java.util.stream.Stream; import org.drools.testcoverage.common.model.Person; import org.drools.testcoverage.common.util.KieBaseTestConfiguration; import org.drools.testcoverage.common.util.KieBaseUtil; -import org.drools.testcoverage.common.util.TestParametersUtil; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; +import org.drools.testcoverage.common.util.TestParametersUtil2; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; import org.kie.api.KieBase; import org.kie.api.runtime.KieSession; import static org.assertj.core.api.Assertions.assertThat; -@RunWith(Parameterized.class) public class FromSharingTest { - private final KieBaseTestConfiguration kieBaseTestConfiguration; - - public FromSharingTest(final KieBaseTestConfiguration kieBaseTestConfiguration) { - this.kieBaseTestConfiguration = kieBaseTestConfiguration; - } - - @Parameterized.Parameters(name = "KieBase type={0}") - public static Collection getParameters() { - return TestParametersUtil.getKieBaseCloudConfigurations(true); + public static Stream parameters() { + return TestParametersUtil2.getKieBaseCloudConfigurations(true).stream(); } - @Test - public void testSharingFromWithoutHashCodeEquals() { + @ParameterizedTest(name = "KieBase type={0}") + @MethodSource("parameters") + public void testSharingFromWithoutHashCodeEquals(KieBaseTestConfiguration kieBaseTestConfiguration) { // DROOLS-2557 final String drl = "import " + PersonWithoutHashCodeEquals.class.getCanonicalName() + "\n" + @@ -189,8 +181,9 @@ public String toString() { } } - @Test - public void testFromSharingWithPropReactvityOnItsConstraint() { + @ParameterizedTest(name = "KieBase type={0}") + @MethodSource("parameters") + public void testFromSharingWithPropReactvityOnItsConstraint(KieBaseTestConfiguration kieBaseTestConfiguration) { // DROOLS-3606 final String drl = "import " + Person.class.getCanonicalName() + "\n" + diff --git a/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/compiler/integrationtests/ImmutableFactsTest.java b/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/compiler/integrationtests/ImmutableFactsTest.java index c16e4ff35d2..1267afe28d7 100644 --- a/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/compiler/integrationtests/ImmutableFactsTest.java +++ b/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/compiler/integrationtests/ImmutableFactsTest.java @@ -18,15 +18,14 @@ */ package org.drools.compiler.integrationtests; -import java.util.ArrayList; import java.util.Collection; +import java.util.stream.Stream; import org.drools.testcoverage.common.model.Person; import org.drools.testcoverage.common.util.KieBaseTestConfiguration; import org.drools.testcoverage.common.util.KieBaseUtil; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; import org.kie.api.KieBase; import org.kie.api.runtime.ClassObjectFilter; import org.kie.api.runtime.KieSession; @@ -34,25 +33,15 @@ import static org.assertj.core.api.Assertions.assertThat; -@RunWith(Parameterized.class) public class ImmutableFactsTest { - private final KieBaseTestConfiguration kieBaseTestConfiguration; - - public ImmutableFactsTest(final KieBaseTestConfiguration kieBaseTestConfiguration) { - this.kieBaseTestConfiguration = kieBaseTestConfiguration; - } - - @Parameterized.Parameters(name = "KieBase type={0}") - public static Collection getParameters() { - Collection parameters = new ArrayList<>(); - parameters.add(new Object[]{KieBaseTestConfiguration.CLOUD_IDENTITY_IMMUTABLE}); - parameters.add(new Object[]{KieBaseTestConfiguration.CLOUD_IDENTITY_IMMUTABLE_MODEL_PATTERN}); - return parameters; + public static Stream parameters() { + return Stream.of(KieBaseTestConfiguration.CLOUD_IDENTITY_IMMUTABLE, KieBaseTestConfiguration.CLOUD_IDENTITY_IMMUTABLE_MODEL_PATTERN); } - @Test - public void testAlphaConstraint() { + @ParameterizedTest(name = "KieBase type={0}") + @MethodSource("parameters") + public void testAlphaConstraint(KieBaseTestConfiguration kieBaseTestConfiguration) { final String drl = "package org.drools.compiler\n" + "import " + Person.class.getCanonicalName() + ";\n" + "rule R when\n" + @@ -95,8 +84,9 @@ public void testAlphaConstraint() { } } - @Test - public void testBetaConstraint() { + @ParameterizedTest(name = "KieBase type={0}") + @MethodSource("parameters") + public void testBetaConstraint(KieBaseTestConfiguration kieBaseTestConfiguration) { final String drl = "package org.drools.compiler\n" + "import " + Person.class.getCanonicalName() + ";\n" + "rule R when\n" + diff --git a/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/compiler/integrationtests/IndexingTest.java b/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/compiler/integrationtests/IndexingTest.java index 5426dc6f9ec..1d0e530e664 100644 --- a/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/compiler/integrationtests/IndexingTest.java +++ b/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/compiler/integrationtests/IndexingTest.java @@ -20,10 +20,10 @@ import java.math.BigDecimal; import java.util.ArrayList; -import java.util.Collection; import java.util.HashMap; import java.util.List; import java.util.Map; +import java.util.stream.Stream; import org.drools.ancompiler.CompiledNetwork; import org.drools.base.base.DroolsQuery; @@ -54,10 +54,10 @@ import org.drools.testcoverage.common.util.KieBaseTestConfiguration; import org.drools.testcoverage.common.util.KieBaseUtil; import org.drools.testcoverage.common.util.KieUtil; -import org.drools.testcoverage.common.util.TestParametersUtil; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; +import org.drools.testcoverage.common.util.TestParametersUtil2; +import org.junit.jupiter.api.Timeout; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; import org.kie.api.KieBase; import org.kie.api.definition.rule.Rule; import org.kie.api.definition.type.FactType; @@ -70,22 +70,15 @@ import static org.assertj.core.api.Assertions.assertThat; import static org.drools.core.util.DroolsTestUtil.rulestoMap; -@RunWith(Parameterized.class) public class IndexingTest { - private final KieBaseTestConfiguration kieBaseTestConfiguration; - - public IndexingTest(final KieBaseTestConfiguration kieBaseTestConfiguration) { - this.kieBaseTestConfiguration = kieBaseTestConfiguration; - } - - @Parameterized.Parameters(name = "KieBase type={0}") - public static Collection getParameters() { - return TestParametersUtil.getKieBaseCloudConfigurations(true); + public static Stream parameters() { + return TestParametersUtil2.getKieBaseCloudConfigurations(true).stream(); } - @Test() - public void testAlphaNodeSharing() { + @ParameterizedTest(name = "KieBase type={0}") + @MethodSource("parameters") + public void testAlphaNodeSharing(KieBaseTestConfiguration kieBaseTestConfiguration) { final String drl = "package org.drools.compiler.test\n" + "import " + Person.class.getCanonicalName() + "\n" + @@ -135,8 +128,10 @@ public void testAlphaNodeSharing() { } } - @Test(timeout = 10000) - public void testBuildsIndexedAlphaNodes() { + @ParameterizedTest(name = "KieBase type={0}") + @MethodSource("parameters") + @Timeout(10000) + public void testBuildsIndexedAlphaNodes(KieBaseTestConfiguration kieBaseTestConfiguration) { final String drl = "package org.drools.compiler.test\n" + "import " + Person.class.getCanonicalName() + "\n" + @@ -168,8 +163,10 @@ public void testBuildsIndexedAlphaNodes() { } } - @Test(timeout = 10000) - public void testBuildsIndexedMemory() { + @ParameterizedTest(name = "KieBase type={0}") + @MethodSource("parameters") + @Timeout(10000) + public void testBuildsIndexedMemory(KieBaseTestConfiguration kieBaseTestConfiguration) { // tests indexes are correctly built final String drl = "package org.drools.compiler.test\n" + @@ -247,8 +244,10 @@ public void testBuildsIndexedMemory() { } } - @Test(timeout = 10000) - public void testIndexingOnQueryUnification() { + @ParameterizedTest(name = "KieBase type={0}") + @MethodSource("parameters") + @Timeout(10000) + public void testIndexingOnQueryUnification(KieBaseTestConfiguration kieBaseTestConfiguration) { final String drl = "package org.drools.compiler.test \n" + "import " + Person.class.getCanonicalName() + "\n" + @@ -283,8 +282,10 @@ public void testIndexingOnQueryUnification() { } } - @Test(timeout = 10000) - public void testIndexingOnQueryUnificationWithNot() { + @ParameterizedTest(name = "KieBase type={0}") + @MethodSource("parameters") + @Timeout(10000) + public void testIndexingOnQueryUnificationWithNot(KieBaseTestConfiguration kieBaseTestConfiguration) { final String drl = "package org.drools.compiler.test \n" + "import " + Person.class.getCanonicalName() + "\n" + @@ -416,8 +417,10 @@ private void assertInsertedUpdatedDeleted(final Map insertUpdat assertThat(insertUpdateDeleteMap.get("deleted").intValue()).isEqualTo(expectedDeleted); } - @Test(timeout = 10000) - public void testFullFastIteratorResume() { + @ParameterizedTest(name = "KieBase type={0}") + @MethodSource("parameters") + @Timeout(10000) + public void testFullFastIteratorResume(KieBaseTestConfiguration kieBaseTestConfiguration) { final String drl = "package org.drools.compiler.test \n" + "import " + Person.class.getCanonicalName() + "\n" + @@ -496,8 +499,10 @@ public void rowUpdated(final Row row) { } } - @Test(timeout = 10000) - public void testRangeIndex() { + @ParameterizedTest(name = "KieBase type={0}") + @MethodSource("parameters") + @Timeout(10000) + public void testRangeIndex(KieBaseTestConfiguration kieBaseTestConfiguration) { final String drl = "import " + Cheese.class.getCanonicalName() + ";\n" + "rule R1\n" + "when\n" + @@ -519,8 +524,10 @@ public void testRangeIndex() { } } - @Test(timeout = 10000) - public void testRangeIndex2() { + @ParameterizedTest(name = "KieBase type={0}") + @MethodSource("parameters") + @Timeout(10000) + public void testRangeIndex2(KieBaseTestConfiguration kieBaseTestConfiguration) { final String drl = "import " + Cheese.class.getCanonicalName() + ";\n" + "rule R1\n" + "when\n" + @@ -542,8 +549,10 @@ public void testRangeIndex2() { } } - @Test(timeout = 10000) - public void testNotNode() { + @ParameterizedTest(name = "KieBase type={0}") + @MethodSource("parameters") + @Timeout(10000) + public void testNotNode(KieBaseTestConfiguration kieBaseTestConfiguration) { final String drl = "import " + Cheese.class.getCanonicalName() + ";\n" + "import " + Person.class.getCanonicalName() + ";\n" + "rule R1 salience 10\n" + @@ -570,8 +579,10 @@ public void testNotNode() { } } - @Test(timeout = 10000) - public void testNotNodeModifyRight() { + @ParameterizedTest(name = "KieBase type={0}") + @MethodSource("parameters") + @Timeout(10000) + public void testNotNodeModifyRight(KieBaseTestConfiguration kieBaseTestConfiguration) { final String drl = "import " + Cheese.class.getCanonicalName() + ";\n" + "import " + Person.class.getCanonicalName() + ";\n" + "rule R1 salience 10 when\n" + @@ -597,8 +608,10 @@ public void testNotNodeModifyRight() { } } - @Test(timeout = 10000) - public void testRange() { + @ParameterizedTest(name = "KieBase type={0}") + @MethodSource("parameters") + @Timeout(10000) + public void testRange(KieBaseTestConfiguration kieBaseTestConfiguration) { final String drl = "import " + Cheese.class.getCanonicalName() + ";\n" + "import " + Person.class.getCanonicalName() + ";\n" + "rule R1 salience 10 when\n" + @@ -624,8 +637,10 @@ public void testRange() { } } - @Test(timeout = 10000) - public void testRange2() throws IllegalAccessException, InstantiationException { + @ParameterizedTest(name = "KieBase type={0}") + @MethodSource("parameters") + @Timeout(10000) + public void testRange2(KieBaseTestConfiguration kieBaseTestConfiguration) throws IllegalAccessException, InstantiationException { final String drl = "package org.drools.compiler.test\n" + "declare A\n" + " a: int\n" + @@ -674,8 +689,9 @@ public void testRange2() throws IllegalAccessException, InstantiationException { } } - @Test - public void testHashingAfterRemoveRightTuple() { + @ParameterizedTest(name = "KieBase type={0}") + @MethodSource("parameters") + public void testHashingAfterRemoveRightTuple(KieBaseTestConfiguration kieBaseTestConfiguration) { // DROOLS-1326 final String drl = "package " + this.getClass().getPackage().getName() + ";\n" + "import " + MyPojo.class.getCanonicalName() + "\n" + @@ -776,8 +792,9 @@ public String toString() { } } - @Test - public void testRequireLeftReorderingWithRangeIndex() { + @ParameterizedTest(name = "KieBase type={0}") + @MethodSource("parameters") + public void testRequireLeftReorderingWithRangeIndex(KieBaseTestConfiguration kieBaseTestConfiguration) { // DROOLS-1326 final String drl = "import " + Queen.class.getCanonicalName() + ";\n" + "rule \"multipleQueensHorizontal\"\n" @@ -846,8 +863,10 @@ public int getRowIndex() { } } - @Test(timeout = 10000) - public void testBuildsIndexedMemoryWithThis() { + @ParameterizedTest(name = "KieBase type={0}") + @MethodSource("parameters") + @Timeout(10000) + public void testBuildsIndexedMemoryWithThis(KieBaseTestConfiguration kieBaseTestConfiguration) { // tests indexes are correctly built final String drl = "package org.drools.compiler.test\n" + @@ -879,8 +898,9 @@ public void testBuildsIndexedMemoryWithThis() { } } - @Test - public void testAlphaIndexWithBigDecimalCoercion() { + @ParameterizedTest(name = "KieBase type={0}") + @MethodSource("parameters") + public void testAlphaIndexWithBigDecimalCoercion(KieBaseTestConfiguration kieBaseTestConfiguration) { final String drl = "package org.drools.compiler.test\n" + "import " + Person.class.getCanonicalName() + "\n" + @@ -909,7 +929,7 @@ public void testAlphaIndexWithBigDecimalCoercion() { try { // BigDecimal Index is disabled - assertAlphaIndex(kbase, Person.class, 0); + assertAlphaIndex(kieBaseTestConfiguration, kbase, Person.class, 0); List list = new ArrayList<>(); ksession.setGlobal("list", list); @@ -924,8 +944,9 @@ public void testAlphaIndexWithBigDecimalCoercion() { } } - @Test - public void testBeta() { + @ParameterizedTest(name = "KieBase type={0}") + @MethodSource("parameters") + public void testBeta(KieBaseTestConfiguration kieBaseTestConfiguration) { final String drl = "package org.drools.compiler.test\n" + @@ -962,11 +983,11 @@ public void testBeta() { } } - private void assertAlphaIndex(KieBase kbase, Class clazz, int hashedSize) { + private void assertAlphaIndex(KieBaseTestConfiguration kieBaseTestConfiguration, KieBase kbase, Class clazz, int hashedSize) { final ObjectTypeNode otn = KieUtil.getObjectTypeNode(kbase, clazz); assertThat(otn).isNotNull(); ObjectSinkPropagator objectSinkPropagator = otn.getObjectSinkPropagator(); - if (this.kieBaseTestConfiguration.useAlphaNetworkCompiler()) { + if (kieBaseTestConfiguration.useAlphaNetworkCompiler()) { objectSinkPropagator = ((CompiledNetwork) objectSinkPropagator).getOriginalSinkPropagator(); } CompositeObjectSinkAdapter sinkAdapter = (CompositeObjectSinkAdapter) objectSinkPropagator; @@ -978,8 +999,9 @@ private void assertAlphaIndex(KieBase kbase, Class clazz, int hashedSize) { } } - @Test - public void testAlphaIndexWithBigDecimalDifferentScale() { + @ParameterizedTest(name = "KieBase type={0}") + @MethodSource("parameters") + public void testAlphaIndexWithBigDecimalDifferentScale(KieBaseTestConfiguration kieBaseTestConfiguration) { final String drl = "package org.drools.compiler.test\n" + "import " + Person.class.getCanonicalName() + "\n" + @@ -1008,7 +1030,7 @@ public void testAlphaIndexWithBigDecimalDifferentScale() { try { // BigDecimal Index is disabled - assertAlphaIndex(kbase, Person.class, 0); + assertAlphaIndex(kieBaseTestConfiguration, kbase, Person.class, 0); List list = new ArrayList<>(); ksession.setGlobal("list", list); @@ -1023,8 +1045,9 @@ public void testAlphaIndexWithBigDecimalDifferentScale() { } } - @Test - public void testBetaIndexWithBigDecimalDifferentScale() { + @ParameterizedTest(name = "KieBase type={0}") + @MethodSource("parameters") + public void testBetaIndexWithBigDecimalDifferentScale(KieBaseTestConfiguration kieBaseTestConfiguration) { final String drl = "package org.drools.compiler.test\n" + "import " + Person.class.getCanonicalName() + "\n" + @@ -1057,8 +1080,9 @@ public void testBetaIndexWithBigDecimalDifferentScale() { } } - @Test - public void testAlphaIndexOnField() { + @ParameterizedTest(name = "KieBase type={0}") + @MethodSource("parameters") + public void testAlphaIndexOnField(KieBaseTestConfiguration kieBaseTestConfiguration) { final String drl = "package org.drools.compiler.test\n" + "import " + Person.class.getCanonicalName() + "\n" + @@ -1086,7 +1110,7 @@ public void testAlphaIndexOnField() { KieSession ksession = kbase.newKieSession(); try { - assertAlphaIndex(kbase, Person.class, 3); + assertAlphaIndex(kieBaseTestConfiguration, kbase, Person.class, 3); List list = new ArrayList<>(); ksession.setGlobal("list", list); @@ -1100,8 +1124,9 @@ public void testAlphaIndexOnField() { } } - @Test - public void testAlphaIndexOnThis() { + @ParameterizedTest(name = "KieBase type={0}") + @MethodSource("parameters") + public void testAlphaIndexOnThis(KieBaseTestConfiguration kieBaseTestConfiguration) { final String drl = "package org.drools.compiler.test\n" + "global java.util.List list\n" + @@ -1128,7 +1153,7 @@ public void testAlphaIndexOnThis() { KieSession ksession = kbase.newKieSession(); try { - assertAlphaIndex(kbase, Integer.class, 3); + assertAlphaIndex(kieBaseTestConfiguration, kbase, Integer.class, 3); List list = new ArrayList<>(); ksession.setGlobal("list", list); @@ -1141,41 +1166,47 @@ public void testAlphaIndexOnThis() { } } - public void betaIndexWithBigDecimalAndInt() { + @ParameterizedTest(name = "KieBase type={0}") + @MethodSource("parameters") + public void betaIndexWithBigDecimalAndInt(KieBaseTestConfiguration kieBaseTestConfiguration) { String constraints = "salary == $p1.salary, age == $p1.age"; - betaIndexWithBigDecimalWithAdditionalBetaConstraint(constraints, new Person("John", 30, new BigDecimal("10")), new Person("Paul", 30, new BigDecimal("10")), true, 1); - betaIndexWithBigDecimalWithAdditionalBetaConstraint(constraints, new Person("John", 30, new BigDecimal("10")), new Person("Paul", 28, new BigDecimal("10")), false, 1); + betaIndexWithBigDecimalWithAdditionalBetaConstraint(kieBaseTestConfiguration, constraints, new Person("John", 30, new BigDecimal("10")), new Person("Paul", 30, new BigDecimal("10")), true, 1); + betaIndexWithBigDecimalWithAdditionalBetaConstraint(kieBaseTestConfiguration, constraints, new Person("John", 30, new BigDecimal("10")), new Person("Paul", 28, new BigDecimal("10")), false, 1); } - @Test - public void betaIndexWithIntAndBigDecimal() { + @ParameterizedTest(name = "KieBase type={0}") + @MethodSource("parameters") + public void betaIndexWithIntAndBigDecimal(KieBaseTestConfiguration kieBaseTestConfiguration) { String constraints = "age == $p1.age, salary == $p1.salary"; - betaIndexWithBigDecimalWithAdditionalBetaConstraint(constraints, new Person("John", 30, new BigDecimal("10")), new Person("Paul", 30, new BigDecimal("10")), true, 1); - betaIndexWithBigDecimalWithAdditionalBetaConstraint(constraints, new Person("John", 30, new BigDecimal("10")), new Person("Paul", 28, new BigDecimal("10")), false, 1); + betaIndexWithBigDecimalWithAdditionalBetaConstraint(kieBaseTestConfiguration, constraints, new Person("John", 30, new BigDecimal("10")), new Person("Paul", 30, new BigDecimal("10")), true, 1); + betaIndexWithBigDecimalWithAdditionalBetaConstraint(kieBaseTestConfiguration, constraints, new Person("John", 30, new BigDecimal("10")), new Person("Paul", 28, new BigDecimal("10")), false, 1); } - @Test - public void betaIndexWithIntAndBigDecimalAndString() { + @ParameterizedTest(name = "KieBase type={0}") + @MethodSource("parameters") + public void betaIndexWithIntAndBigDecimalAndString(KieBaseTestConfiguration kieBaseTestConfiguration) { String constraints = "age == $p1.age, salary == $p1.salary, likes == $p1.likes"; - betaIndexWithBigDecimalWithAdditionalBetaConstraint(constraints, new Person("John", 30, new BigDecimal("10"), "dog"), new Person("Paul", 30, new BigDecimal("10"), "dog"), true, 2); - betaIndexWithBigDecimalWithAdditionalBetaConstraint(constraints, new Person("John", 30, new BigDecimal("10"), "dog"), new Person("Paul", 30, new BigDecimal("10"), "cat"), false, 2); + betaIndexWithBigDecimalWithAdditionalBetaConstraint(kieBaseTestConfiguration, constraints, new Person("John", 30, new BigDecimal("10"), "dog"), new Person("Paul", 30, new BigDecimal("10"), "dog"), true, 2); + betaIndexWithBigDecimalWithAdditionalBetaConstraint(kieBaseTestConfiguration, constraints, new Person("John", 30, new BigDecimal("10"), "dog"), new Person("Paul", 30, new BigDecimal("10"), "cat"), false, 2); } - @Test - public void betaIndexWithIntInequalityAndBigDecimal() { + @ParameterizedTest(name = "KieBase type={0}") + @MethodSource("parameters") + public void betaIndexWithIntInequalityAndBigDecimal(KieBaseTestConfiguration kieBaseTestConfiguration) { String constraints = "age > $p1.age, salary == $p1.salary"; - betaIndexWithBigDecimalWithAdditionalBetaConstraint(constraints, new Person("John", 30, new BigDecimal("10")), new Person("Paul", 40, new BigDecimal("10")), true, 0); - betaIndexWithBigDecimalWithAdditionalBetaConstraint(constraints, new Person("John", 30, new BigDecimal("10")), new Person("Paul", 28, new BigDecimal("10")), false, 0); + betaIndexWithBigDecimalWithAdditionalBetaConstraint(kieBaseTestConfiguration, constraints, new Person("John", 30, new BigDecimal("10")), new Person("Paul", 40, new BigDecimal("10")), true, 0); + betaIndexWithBigDecimalWithAdditionalBetaConstraint(kieBaseTestConfiguration, constraints, new Person("John", 30, new BigDecimal("10")), new Person("Paul", 28, new BigDecimal("10")), false, 0); } - @Test - public void betaIndexWithBigDecimalOnly() { + @ParameterizedTest(name = "KieBase type={0}") + @MethodSource("parameters") + public void betaIndexWithBigDecimalOnly(KieBaseTestConfiguration kieBaseTestConfiguration) { String constraints = "salary == $p1.salary"; - betaIndexWithBigDecimalWithAdditionalBetaConstraint(constraints, new Person("John", 30, new BigDecimal("10")), new Person("Paul", 28, new BigDecimal("10")), true, 0); - betaIndexWithBigDecimalWithAdditionalBetaConstraint(constraints, new Person("John", 30, new BigDecimal("10")), new Person("Paul", 28, new BigDecimal("20")), false, 0); + betaIndexWithBigDecimalWithAdditionalBetaConstraint(kieBaseTestConfiguration, constraints, new Person("John", 30, new BigDecimal("10")), new Person("Paul", 28, new BigDecimal("10")), true, 0); + betaIndexWithBigDecimalWithAdditionalBetaConstraint(kieBaseTestConfiguration, constraints, new Person("John", 30, new BigDecimal("10")), new Person("Paul", 28, new BigDecimal("20")), false, 0); } - private void betaIndexWithBigDecimalWithAdditionalBetaConstraint(String constraints, Person firstPerson, Person secondPerson, boolean shouldMatch, int expectedIndexCount) { + private void betaIndexWithBigDecimalWithAdditionalBetaConstraint(KieBaseTestConfiguration kieBaseTestConfiguration, String constraints, Person firstPerson, Person secondPerson, boolean shouldMatch, int expectedIndexCount) { final String drl = "package org.drools.compiler.test\n" + "import " + Person.class.getCanonicalName() + "\n" + diff --git a/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/compiler/integrationtests/JoinNodeRangeIndexingTest.java b/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/compiler/integrationtests/JoinNodeRangeIndexingTest.java index d1616208a80..001e8ba6a3b 100644 --- a/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/compiler/integrationtests/JoinNodeRangeIndexingTest.java +++ b/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/compiler/integrationtests/JoinNodeRangeIndexingTest.java @@ -20,12 +20,12 @@ import java.math.BigDecimal; import java.util.ArrayList; -import java.util.Collection; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; +import java.util.stream.Stream; import org.drools.ancompiler.CompiledNetwork; import org.drools.core.common.BetaConstraints; @@ -41,10 +41,9 @@ import org.drools.testcoverage.common.util.KieBaseTestConfiguration; import org.drools.testcoverage.common.util.KieBaseUtil; import org.drools.testcoverage.common.util.KieUtil; -import org.drools.testcoverage.common.util.TestParametersUtil; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; +import org.drools.testcoverage.common.util.TestParametersUtil2; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; import org.kie.api.KieBase; import org.kie.api.builder.KieModule; import org.kie.api.conf.BetaRangeIndexOption; @@ -52,27 +51,20 @@ import static org.assertj.core.api.Assertions.assertThat; -@RunWith(Parameterized.class) public class JoinNodeRangeIndexingTest { - private final KieBaseTestConfiguration kieBaseTestConfiguration; - - public JoinNodeRangeIndexingTest(final KieBaseTestConfiguration kieBaseTestConfiguration) { - this.kieBaseTestConfiguration = kieBaseTestConfiguration; - } - - @Parameterized.Parameters(name = "KieBase type={0}") - public static Collection getParameters() { - return TestParametersUtil.getKieBaseCloudConfigurations(true); + public static Stream parameters() { + return TestParametersUtil2.getKieBaseCloudConfigurations(true).stream(); } - private KieBase getKieBaseWithRangeIndexOption(String drl) { + private KieBase getKieBaseWithRangeIndexOption(KieBaseTestConfiguration kieBaseTestConfiguration, String drl) { KieModule kieModule = KieUtil.getKieModuleFromDrls("indexing-test", kieBaseTestConfiguration, drl); return KieBaseUtil.newKieBaseFromKieModuleWithAdditionalOptions(kieModule, kieBaseTestConfiguration, BetaRangeIndexOption.ENABLED); } - @Test - public void testRangeIndexForJoin() { + @ParameterizedTest(name = "KieBase type={0}") + @MethodSource("parameters") + public void testRangeIndexForJoin(KieBaseTestConfiguration kieBaseTestConfiguration) { final String drl = "import " + Person.class.getCanonicalName() + ";\n" + "import " + Pet.class.getCanonicalName() + ";\n" + "rule R1\n" + @@ -82,9 +74,9 @@ public void testRangeIndexForJoin() { "then\n" + "end\n"; - final KieBase kbase = getKieBaseWithRangeIndexOption(drl); + final KieBase kbase = getKieBaseWithRangeIndexOption(kieBaseTestConfiguration, drl); - assertIndexedTrue(kbase, Person.class); + assertIndexedTrue(kieBaseTestConfiguration, kbase, Person.class); final KieSession ksession = kbase.newKieSession(); try { @@ -97,20 +89,20 @@ public void testRangeIndexForJoin() { } } - private void assertIndexedTrue(KieBase kbase, Class factClass) { - assertIndexed(kbase, factClass, true); + private void assertIndexedTrue(KieBaseTestConfiguration kieBaseTestConfiguration, KieBase kbase, Class factClass) { + assertIndexed(kieBaseTestConfiguration, kbase, factClass, true); } - private void assertIndexedFalse(KieBase kbase, Class factClass) { - assertIndexed(kbase, factClass, false); + private void assertIndexedFalse(KieBaseTestConfiguration kieBaseTestConfiguration, KieBase kbase, Class factClass) { + assertIndexed(kieBaseTestConfiguration, kbase, factClass, false); } - private void assertIndexed(KieBase kbase, Class factClass, boolean isIndexed) { + private void assertIndexed(KieBaseTestConfiguration kieBaseTestConfiguration, KieBase kbase, Class factClass, boolean isIndexed) { final ObjectTypeNode otn = KieUtil.getObjectTypeNode(kbase, factClass); assertThat(otn).isNotNull(); ObjectSinkPropagator objectSinkPropagator = otn.getObjectSinkPropagator(); - if (this.kieBaseTestConfiguration.useAlphaNetworkCompiler()) { + if (kieBaseTestConfiguration.useAlphaNetworkCompiler()) { objectSinkPropagator = ((CompiledNetwork) objectSinkPropagator).getOriginalSinkPropagator(); } @@ -128,8 +120,9 @@ private void assertIndexed(KieBase kbase, Class factClass, boolean isIndexed) assertThat(isPassedForJoinNode).isTrue(); } - @Test - public void testCoercionBigDecimalVsInt() { + @ParameterizedTest(name = "KieBase type={0}") + @MethodSource("parameters") + public void testCoercionBigDecimalVsInt(KieBaseTestConfiguration kieBaseTestConfiguration) { final String drl = "package org.drools.compiler.integrationtests;\n" + "import " + Cheese.class.getCanonicalName() + ";\n" + "import " + Primitives.class.getCanonicalName() + ";\n" + @@ -144,9 +137,9 @@ public void testCoercionBigDecimalVsInt() { // Integer is coerced to BigDecimal - final KieBase kbase = getKieBaseWithRangeIndexOption(drl); + final KieBase kbase = getKieBaseWithRangeIndexOption(kieBaseTestConfiguration, drl); - assertIndexedTrue(kbase, Primitives.class); + assertIndexedTrue(kieBaseTestConfiguration, kbase, Primitives.class); final KieSession ksession = kbase.newKieSession(); try { @@ -170,8 +163,9 @@ public void testCoercionBigDecimalVsInt() { } } - @Test - public void testCoercionIntVsBigDecimal() { + @ParameterizedTest(name = "KieBase type={0}") + @MethodSource("parameters") + public void testCoercionIntVsBigDecimal(KieBaseTestConfiguration kieBaseTestConfiguration) { final String drl = "package org.drools.compiler.integrationtests;\n" + "import " + Person.class.getCanonicalName() + ";\n" + "import " + Primitives.class.getCanonicalName() + ";\n" + @@ -187,9 +181,9 @@ public void testCoercionIntVsBigDecimal() { // BigDecimal is coerced to Integer - final KieBase kbase = getKieBaseWithRangeIndexOption(drl); + final KieBase kbase = getKieBaseWithRangeIndexOption(kieBaseTestConfiguration, drl); - assertIndexedTrue(kbase, Primitives.class); + assertIndexedTrue(kieBaseTestConfiguration, kbase, Primitives.class); final KieSession ksession = kbase.newKieSession(); try { @@ -215,8 +209,9 @@ public void testCoercionIntVsBigDecimal() { } } - @Test - public void testCoercionStringVsIntWithMap() { + @ParameterizedTest(name = "KieBase type={0}") + @MethodSource("parameters") + public void testCoercionStringVsIntWithMap(KieBaseTestConfiguration kieBaseTestConfiguration) { final String drl = "package org.drools.compiler.integrationtests;\n" + "import " + Map.class.getCanonicalName() + ";\n" + @@ -232,10 +227,10 @@ public void testCoercionStringVsIntWithMap() { // Integer is coerced to String (thus, String comparison) - final KieBase kbase = getKieBaseWithRangeIndexOption(drl); + final KieBase kbase = getKieBaseWithRangeIndexOption(kieBaseTestConfiguration, drl); // We don't index this case - assertIndexedFalse(kbase, Cheese.class); + assertIndexedFalse(kieBaseTestConfiguration, kbase, Cheese.class); final KieSession ksession = kbase.newKieSession(); try { @@ -263,8 +258,9 @@ public void testCoercionStringVsIntWithMap() { } } - @Test - public void testCoercionIntVsStringWithMap() { + @ParameterizedTest(name = "KieBase type={0}") + @MethodSource("parameters") + public void testCoercionIntVsStringWithMap(KieBaseTestConfiguration kieBaseTestConfiguration) { // we don't enable range index for this case final String drl = "package org.drools.compiler.integrationtests;\n" + "import " + Cheese.class.getCanonicalName() + ";\n" + @@ -280,10 +276,10 @@ public void testCoercionIntVsStringWithMap() { // String is coerced to Integer (thus, Number comparison) - final KieBase kbase = getKieBaseWithRangeIndexOption(drl); + final KieBase kbase = getKieBaseWithRangeIndexOption(kieBaseTestConfiguration, drl); // We don't index this case - assertIndexedFalse(kbase, MapHolder.class); + assertIndexedFalse(kieBaseTestConfiguration, kbase, MapHolder.class); final KieSession ksession = kbase.newKieSession(); try { @@ -327,8 +323,9 @@ public void setMap(Map map) { } - @Test - public void testJoinWithGlobal() { + @ParameterizedTest(name = "KieBase type={0}") + @MethodSource("parameters") + public void testJoinWithGlobal(KieBaseTestConfiguration kieBaseTestConfiguration) { final String drl = "import " + Person.class.getCanonicalName() + ";\n" + "global Integer minAge;\n" + "rule R1\n" + @@ -339,7 +336,7 @@ public void testJoinWithGlobal() { // Actually, [age > minAge] becomes an AlphaNode and doesn't use index. - final KieBase kbase = getKieBaseWithRangeIndexOption(drl); + final KieBase kbase = getKieBaseWithRangeIndexOption(kieBaseTestConfiguration, drl); final KieSession ksession = kbase.newKieSession(); try { @@ -351,8 +348,9 @@ public void testJoinWithGlobal() { } } - @Test - public void testInsertUpdateDelete() { + @ParameterizedTest(name = "KieBase type={0}") + @MethodSource("parameters") + public void testInsertUpdateDelete(KieBaseTestConfiguration kieBaseTestConfiguration) { final String drl = "import " + Person.class.getCanonicalName() + ";\n" + "import " + Pet.class.getCanonicalName() + ";\n" + "global java.util.Set result;\n" + @@ -388,9 +386,9 @@ public void testInsertUpdateDelete() { " delete($pet);\n" + "end\n"; - final KieBase kbase = getKieBaseWithRangeIndexOption(drl); + final KieBase kbase = getKieBaseWithRangeIndexOption(kieBaseTestConfiguration, drl); - assertIndexedTrue(kbase, Person.class); + assertIndexedTrue(kieBaseTestConfiguration, kbase, Person.class); final KieSession ksession = kbase.newKieSession(); try { @@ -425,8 +423,9 @@ public void testInsertUpdateDelete() { } } - @Test - public void testBoxed() { + @ParameterizedTest(name = "KieBase type={0}") + @MethodSource("parameters") + public void testBoxed(KieBaseTestConfiguration kieBaseTestConfiguration) { final String drl = "import " + Person.class.getCanonicalName() + ";\n" + "import " + IntegerHolder.class.getCanonicalName() + ";\n" + "rule R1\n" + @@ -436,9 +435,9 @@ public void testBoxed() { "then\n" + "end\n"; - final KieBase kbase = getKieBaseWithRangeIndexOption(drl); + final KieBase kbase = getKieBaseWithRangeIndexOption(kieBaseTestConfiguration, drl); - assertIndexedTrue(kbase, Person.class); + assertIndexedTrue(kieBaseTestConfiguration, kbase, Person.class); final KieSession ksession = kbase.newKieSession(); try { @@ -451,8 +450,9 @@ public void testBoxed() { } } - @Test - public void testBoxed2() { + @ParameterizedTest(name = "KieBase type={0}") + @MethodSource("parameters") + public void testBoxed2(KieBaseTestConfiguration kieBaseTestConfiguration) { final String drl = "import " + Person.class.getCanonicalName() + ";\n" + "import " + IntegerHolder.class.getCanonicalName() + ";\n" + "rule R1\n" + @@ -462,9 +462,9 @@ public void testBoxed2() { "then\n" + "end\n"; - final KieBase kbase = getKieBaseWithRangeIndexOption(drl); + final KieBase kbase = getKieBaseWithRangeIndexOption(kieBaseTestConfiguration, drl); - assertIndexedTrue(kbase, IntegerHolder.class); + assertIndexedTrue(kieBaseTestConfiguration, kbase, IntegerHolder.class); final KieSession ksession = kbase.newKieSession(); try { @@ -489,8 +489,9 @@ public Integer getValue() { } } - @Test - public void testMultipleFacts() { + @ParameterizedTest(name = "KieBase type={0}") + @MethodSource("parameters") + public void testMultipleFacts(KieBaseTestConfiguration kieBaseTestConfiguration) { final String drl = "import " + Person.class.getCanonicalName() + ";\n" + "import " + Pet.class.getCanonicalName() + ";\n" + @@ -503,9 +504,9 @@ public void testMultipleFacts() { " result.add( $person.getName() + \" > \" + $pet.getName() );\n" + "end\n"; - final KieBase kbase = getKieBaseWithRangeIndexOption(drl); + final KieBase kbase = getKieBaseWithRangeIndexOption(kieBaseTestConfiguration, drl); - assertIndexedTrue(kbase, Person.class); + assertIndexedTrue(kieBaseTestConfiguration, kbase, Person.class); final KieSession ksession = kbase.newKieSession(); Set result = new HashSet<>(); diff --git a/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/compiler/integrationtests/KieBaseIncludeTest.java b/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/compiler/integrationtests/KieBaseIncludeTest.java index 46006bac4d9..673f159457e 100644 --- a/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/compiler/integrationtests/KieBaseIncludeTest.java +++ b/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/compiler/integrationtests/KieBaseIncludeTest.java @@ -20,14 +20,14 @@ import java.io.File; import java.io.IOException; +import java.util.stream.Stream; import org.drools.compiler.kie.builder.impl.DrlProject; import org.drools.compiler.kie.builder.impl.InternalKieModule; import org.drools.core.util.FileManager; import org.drools.model.codegen.ExecutableModelProject; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; import org.kie.api.KieServices; import org.kie.api.builder.KieBuilder; import org.kie.api.builder.KieFileSystem; @@ -40,21 +40,15 @@ import static org.assertj.core.api.Assertions.assertThat; -@RunWith(Parameterized.class) public class KieBaseIncludeTest { - private final Class projectType; - public KieBaseIncludeTest(boolean useModel) { - this.projectType = useModel ? ExecutableModelProject.class : DrlProject.class; + public static Stream> parameters() { + return Stream.of(ExecutableModelProject.class, DrlProject.class); } - @Parameterized.Parameters(name = "{0}") - public static Object[] params() { - return new Object[] {false, true}; - } - - @Test - public void testKJarIncludedDependency() throws Exception { + @ParameterizedTest(name = "{0}") + @MethodSource("parameters") + public void testKJarIncludedDependency(Class projectType) throws Exception { String rule = "package org.test rule R when String() then end"; KieServices ks = KieServices.Factory.get(); @@ -64,7 +58,7 @@ public void testKJarIncludedDependency() throws Exception { FileManager fileManager = new FileManager(); fileManager.setUp(); - InternalKieModule kJar1 = createKieJar( ks, includedReleaseId, rule ); + InternalKieModule kJar1 = createKieJar(projectType, ks, includedReleaseId, rule ); fileManager.tearDown(); fileManager = new FileManager(); @@ -90,7 +84,7 @@ public void testKJarIncludedDependency() throws Exception { fileManager.tearDown(); } - private InternalKieModule createKieJar(KieServices ks, ReleaseId releaseId, String... rules) throws IOException { + private InternalKieModule createKieJar(Class projectType, KieServices ks, ReleaseId releaseId, String... rules) throws IOException { KieModuleModel kproj = ks.newKieModuleModel(); KieBaseModel kieBaseModel1 = kproj.newKieBaseModel("KBase1"); KieSessionModel ksession1 = kieBaseModel1.newKieSessionModel("KSession1"); diff --git a/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/compiler/integrationtests/MultiSheetsTest.java b/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/compiler/integrationtests/MultiSheetsTest.java index 8e37053a634..94255c44875 100644 --- a/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/compiler/integrationtests/MultiSheetsTest.java +++ b/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/compiler/integrationtests/MultiSheetsTest.java @@ -18,16 +18,15 @@ */ package org.drools.compiler.integrationtests; -import java.util.Collection; +import java.util.stream.Stream; import org.drools.compiler.kie.builder.impl.DrlProject; import org.drools.testcoverage.common.model.Person; import org.drools.testcoverage.common.model.Result; import org.drools.testcoverage.common.util.KieBaseTestConfiguration; -import org.drools.testcoverage.common.util.TestParametersUtil; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; +import org.drools.testcoverage.common.util.TestParametersUtil2; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; import org.kie.api.KieServices; import org.kie.api.builder.KieBuilder; import org.kie.api.builder.KieFileSystem; @@ -38,41 +37,37 @@ import static org.assertj.core.api.Assertions.assertThat; -@RunWith(Parameterized.class) public class MultiSheetsTest { - private final KieBaseTestConfiguration kieBaseTestConfiguration; - - public MultiSheetsTest(final KieBaseTestConfiguration kieBaseTestConfiguration) { - this.kieBaseTestConfiguration = kieBaseTestConfiguration; - } - - @Parameterized.Parameters(name = "KieBase type={0}") - public static Collection getParameters() { - return TestParametersUtil.getKieBaseCloudConfigurations(true); + public static Stream parameters() { + return TestParametersUtil2.getKieBaseCloudConfigurations(true).stream(); } - @Test - public void testNoSheet() { - check(null, "Mario can drink"); + @ParameterizedTest(name = "KieBase type={0}") + @MethodSource("parameters") + public void testNoSheet(KieBaseTestConfiguration kieBaseTestConfiguration) { + check(kieBaseTestConfiguration, null, "Mario can drink"); } - @Test - public void testSheet1() { - check("Sheet1", "Mario can drink"); + @ParameterizedTest(name = "KieBase type={0}") + @MethodSource("parameters") + public void testSheet1(KieBaseTestConfiguration kieBaseTestConfiguration) { + check(kieBaseTestConfiguration, "Sheet1", "Mario can drink"); } - @Test - public void testSheet2() { - check("Sheet2", "Mario can drive"); + @ParameterizedTest(name = "KieBase type={0}") + @MethodSource("parameters") + public void testSheet2(KieBaseTestConfiguration kieBaseTestConfiguration) { + check(kieBaseTestConfiguration, "Sheet2", "Mario can drive"); } - @Test - public void testSheet12() { - check("Sheet1,Sheet2", "Mario can drink", "Mario can drive"); + @ParameterizedTest(name = "KieBase type={0}") + @MethodSource("parameters") + public void testSheet12(KieBaseTestConfiguration kieBaseTestConfiguration) { + check(kieBaseTestConfiguration, "Sheet1,Sheet2", "Mario can drink", "Mario can drive"); } - private void check(String sheets, String... results) { + private void check(KieBaseTestConfiguration kieBaseTestConfiguration, String sheets, String... results) { KieServices ks = KieServices.get(); KieResources kr = ks.getResources(); @@ -89,7 +84,7 @@ private void check(String sheets, String... results) { kfs.writeKModuleXML( kproj.toXML() ); - KieBuilder kb = buildDTable( ks, kfs ); + KieBuilder kb = buildDTable(kieBaseTestConfiguration, ks, kfs); KieContainer kc = ks.newKieContainer(kb.getKieModule().getReleaseId()); KieSession sessionDtable = kc.newKieSession( "dtable" ); @@ -102,7 +97,7 @@ private void check(String sheets, String... results) { } } - private KieBuilder buildDTable( KieServices ks, KieFileSystem kfs ) { + private KieBuilder buildDTable(KieBaseTestConfiguration kieBaseTestConfiguration, KieServices ks, KieFileSystem kfs) { if (kieBaseTestConfiguration.getExecutableModelProjectClass().isPresent()) { return ks.newKieBuilder( kfs ).buildAll(kieBaseTestConfiguration.getExecutableModelProjectClass().get()); } else { diff --git a/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/compiler/integrationtests/PassivePatternTest.java b/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/compiler/integrationtests/PassivePatternTest.java index f6646b0209c..f1fc19a9b55 100644 --- a/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/compiler/integrationtests/PassivePatternTest.java +++ b/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/compiler/integrationtests/PassivePatternTest.java @@ -19,37 +19,29 @@ package org.drools.compiler.integrationtests; import java.util.ArrayList; -import java.util.Collection; import java.util.List; +import java.util.stream.Stream; import org.drools.testcoverage.common.util.KieBaseTestConfiguration; import org.drools.testcoverage.common.util.KieBaseUtil; -import org.drools.testcoverage.common.util.TestParametersUtil; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; +import org.drools.testcoverage.common.util.TestParametersUtil2; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; import org.kie.api.KieBase; import org.kie.api.runtime.KieSession; import static java.util.Arrays.asList; import static org.assertj.core.api.Assertions.assertThat; -@RunWith(Parameterized.class) public class PassivePatternTest { - private final KieBaseTestConfiguration kieBaseTestConfiguration; - - public PassivePatternTest(final KieBaseTestConfiguration kieBaseTestConfiguration) { - this.kieBaseTestConfiguration = kieBaseTestConfiguration; - } - - @Parameterized.Parameters(name = "KieBase type={0}") - public static Collection getParameters() { - return TestParametersUtil.getKieBaseCloudConfigurations(true); + public static Stream parameters() { + return TestParametersUtil2.getKieBaseCloudConfigurations(true).stream(); } - @Test - public void testPassiveInsert() { + @ParameterizedTest(name = "KieBase type={0}") + @MethodSource("parameters") + public void testPassiveInsert(KieBaseTestConfiguration kieBaseTestConfiguration) { final String drl = "global java.util.List list\n" + "rule R when\n" + diff --git a/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/compiler/integrationtests/PropertyChangeSupportTest.java b/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/compiler/integrationtests/PropertyChangeSupportTest.java index 4dd9b680800..08c7bd59f7a 100644 --- a/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/compiler/integrationtests/PropertyChangeSupportTest.java +++ b/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/compiler/integrationtests/PropertyChangeSupportTest.java @@ -21,7 +21,7 @@ import java.beans.PropertyChangeListener; import java.beans.PropertyChangeSupport; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.kie.api.io.ResourceType; import org.kie.api.runtime.KieSession; import org.kie.internal.utils.KieHelper; diff --git a/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/compiler/integrationtests/PropertyReactivityTest.java b/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/compiler/integrationtests/PropertyReactivityTest.java index f678d176e3c..f3b580b0ecf 100644 --- a/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/compiler/integrationtests/PropertyReactivityTest.java +++ b/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/compiler/integrationtests/PropertyReactivityTest.java @@ -18,18 +18,17 @@ */ package org.drools.compiler.integrationtests; -import java.util.Collection; import java.util.HashMap; import java.util.Map; +import java.util.stream.Stream; import org.drools.testcoverage.common.model.Person; import org.drools.testcoverage.common.util.KieBaseTestConfiguration; import org.drools.testcoverage.common.util.KieSessionTestConfiguration; import org.drools.testcoverage.common.util.KieUtil; -import org.drools.testcoverage.common.util.TestParametersUtil; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; +import org.drools.testcoverage.common.util.TestParametersUtil2; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; import org.kie.api.KieBase; import org.kie.api.KieServices; import org.kie.api.builder.KieModule; @@ -41,22 +40,15 @@ import static org.assertj.core.api.Assertions.assertThat; -@RunWith(Parameterized.class) public class PropertyReactivityTest { - private final KieBaseTestConfiguration kieBaseTestConfiguration; - - public PropertyReactivityTest(final KieBaseTestConfiguration kieBaseTestConfiguration) { - this.kieBaseTestConfiguration = kieBaseTestConfiguration; - } - - @Parameterized.Parameters(name = "KieBase type={0}") - public static Collection getParameters() { - return TestParametersUtil.getKieBaseCloudConfigurations(true); + public static Stream parameters() { + return TestParametersUtil2.getKieBaseCloudConfigurations(true).stream(); } - @Test - public void testDisablePropertyReactivity() { + @ParameterizedTest(name = "KieBase type={0}") + @MethodSource("parameters") + public void testDisablePropertyReactivity(KieBaseTestConfiguration kieBaseTestConfiguration) { // DROOLS-5746 final String drl = "import " + Person.class.getCanonicalName() + "\n" + diff --git a/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/compiler/integrationtests/RuleChainingTest.java b/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/compiler/integrationtests/RuleChainingTest.java index 81c0dc86405..b40a316aacc 100644 --- a/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/compiler/integrationtests/RuleChainingTest.java +++ b/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/compiler/integrationtests/RuleChainingTest.java @@ -20,10 +20,9 @@ import org.drools.testcoverage.common.util.KieBaseTestConfiguration; import org.drools.testcoverage.common.util.KieBaseUtil; -import org.drools.testcoverage.common.util.TestParametersUtil; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; +import org.drools.testcoverage.common.util.TestParametersUtil2; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; import org.kie.api.KieBase; import org.kie.api.event.rule.AfterMatchFiredEvent; import org.kie.api.event.rule.AgendaEventListener; @@ -34,8 +33,8 @@ import org.mockito.ArgumentCaptor; import org.mockito.Mockito; -import java.util.Collection; import java.util.List; +import java.util.stream.Stream; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.ArgumentMatchers.any; @@ -43,22 +42,15 @@ import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; -@RunWith(Parameterized.class) public class RuleChainingTest { - private final KieBaseTestConfiguration kieBaseTestConfiguration; - - public RuleChainingTest(final KieBaseTestConfiguration kieBaseTestConfiguration) { - this.kieBaseTestConfiguration = kieBaseTestConfiguration; - } - - @Parameterized.Parameters(name = "KieBase type={0}") - public static Collection getParameters() { - return TestParametersUtil.getKieBaseCloudConfigurations(true); + public static Stream parameters() { + return TestParametersUtil2.getKieBaseCloudConfigurations(true).stream(); } - @Test - public void testRuleChainingWithLogicalInserts() { + @ParameterizedTest(name = "KieBase type={0}") + @MethodSource("parameters") + public void testRuleChainingWithLogicalInserts(KieBaseTestConfiguration kieBaseTestConfiguration) { final String drl = "package com.sample\n" + " \n" + "declare Some\n" + @@ -126,8 +118,9 @@ public void testRuleChainingWithLogicalInserts() { } } - @Test - public void testDoubleInsertLogical() { + @ParameterizedTest(name = "KieBase type={0}") + @MethodSource("parameters") + public void testDoubleInsertLogical(KieBaseTestConfiguration kieBaseTestConfiguration) { // DROOLS-7525 final String drl = "package org.test;\n" + diff --git a/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/compiler/integrationtests/SharingTest.java b/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/compiler/integrationtests/SharingTest.java index 485b3097808..80bce07aedf 100644 --- a/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/compiler/integrationtests/SharingTest.java +++ b/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/compiler/integrationtests/SharingTest.java @@ -20,8 +20,8 @@ import java.math.BigDecimal; import java.util.ArrayList; -import java.util.Collection; import java.util.List; +import java.util.stream.Stream; import org.drools.base.base.ClassObjectType; import org.drools.kiesession.rulebase.InternalKnowledgeBase; @@ -36,28 +36,19 @@ import org.drools.testcoverage.common.model.Person; import org.drools.testcoverage.common.util.KieBaseTestConfiguration; import org.drools.testcoverage.common.util.KieBaseUtil; -import org.drools.testcoverage.common.util.TestParametersUtil; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; +import org.drools.testcoverage.common.util.TestParametersUtil2; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; import org.kie.api.KieBase; import org.kie.api.runtime.KieSession; import org.kie.api.runtime.rule.Agenda; import static org.assertj.core.api.Assertions.assertThat; -@RunWith(Parameterized.class) public class SharingTest { - - private final KieBaseTestConfiguration kieBaseTestConfiguration; - - public SharingTest(final KieBaseTestConfiguration kieBaseTestConfiguration) { - this.kieBaseTestConfiguration = kieBaseTestConfiguration; - } - - @Parameterized.Parameters(name = "KieBase type={0}") - public static Collection getParameters() { - return TestParametersUtil.getKieBaseCloudConfigurations(true); + + public static Stream parameters() { + return TestParametersUtil2.getKieBaseCloudConfigurations(true).stream(); } public static class TestStaticUtils { @@ -81,8 +72,9 @@ public static enum TestEnum { CCC; } - @Test - public void testDontShareAlphaWithStaticMethod() { + @ParameterizedTest(name = "KieBase type={0}") + @MethodSource("parameters") + public void testDontShareAlphaWithStaticMethod(KieBaseTestConfiguration kieBaseTestConfiguration) { // DROOLS-6418 final String drl1 = "package c;\n" + "import " + TestObject.class.getCanonicalName() + "\n" + @@ -148,8 +140,9 @@ private void assertNonHashableConstraint(ObjectTypeNode otn, String expected) { } } - @Test - public void testDontShareAlphaWithNonFinalField() { + @ParameterizedTest(name = "KieBase type={0}") + @MethodSource("parameters") + public void testDontShareAlphaWithNonFinalField(KieBaseTestConfiguration kieBaseTestConfiguration) { // DROOLS-6418 final String drl = "package com.example;\n" + "import " + TestObject.class.getCanonicalName() + "\n" + @@ -184,8 +177,9 @@ public void testDontShareAlphaWithNonFinalField() { } } - @Test - public void testShareAlphaWithFinalField() { + @ParameterizedTest(name = "KieBase type={0}") + @MethodSource("parameters") + public void testShareAlphaWithFinalField(KieBaseTestConfiguration kieBaseTestConfiguration) { // DROOLS-6418 final String drl = "package com.example;\n" + "import " + TestObject.class.getCanonicalName() + "\n" + @@ -225,8 +219,9 @@ public void testShareAlphaWithFinalField() { } } - @Test - public void testShareAlphaWithNestedFinalField() { + @ParameterizedTest(name = "KieBase type={0}") + @MethodSource("parameters") + public void testShareAlphaWithNestedFinalField(KieBaseTestConfiguration kieBaseTestConfiguration) { // DROOLS-6418 final String drl = "package com.example;\n" + "import " + TestObject.class.getCanonicalName() + "\n" + @@ -263,8 +258,9 @@ public void testShareAlphaWithNestedFinalField() { } } - @Test - public void testShareAlphaWithEnum() { + @ParameterizedTest(name = "KieBase type={0}") + @MethodSource("parameters") + public void testShareAlphaWithEnum(KieBaseTestConfiguration kieBaseTestConfiguration) { // DROOLS-6418 final String drl = "package com.example;\n" + "import " + TestObject.class.getCanonicalName() + "\n" + @@ -298,8 +294,9 @@ public void testShareAlphaWithEnum() { } } - @Test - public void testDontShareAlphaWithBigDecimalConstructor() { + @ParameterizedTest(name = "KieBase type={0}") + @MethodSource("parameters") + public void testDontShareAlphaWithBigDecimalConstructor(KieBaseTestConfiguration kieBaseTestConfiguration) { // DROOLS-6418 final String drl = "package com.example;\n" + "import " + Person.class.getCanonicalName() + "\n" + @@ -333,8 +330,9 @@ public void testDontShareAlphaWithBigDecimalConstructor() { } } - @Test - public void testShouldAlphaShareNotEqualsInDifferentPackages() { + @ParameterizedTest(name = "KieBase type={0}") + @MethodSource("parameters") + public void testShouldAlphaShareNotEqualsInDifferentPackages(KieBaseTestConfiguration kieBaseTestConfiguration) { // DROOLS-1404 final String drl1 = "package c;\n" + "import " + TestObject.class.getCanonicalName() + "\n" + @@ -369,8 +367,9 @@ public void testShouldAlphaShareNotEqualsInDifferentPackages() { } } - @Test - public void testShouldAlphaShareNotEqualsInDifferentPackages2() { + @ParameterizedTest(name = "KieBase type={0}") + @MethodSource("parameters") + public void testShouldAlphaShareNotEqualsInDifferentPackages2(KieBaseTestConfiguration kieBaseTestConfiguration) { // DROOLS-1404 final String drl1 = "package c;\n" + "import " + FactWithList.class.getCanonicalName() + "\n" + @@ -408,8 +407,9 @@ public void testShouldAlphaShareNotEqualsInDifferentPackages2() { } } - @Test - public void testSubnetworkSharing() { + @ParameterizedTest(name = "KieBase type={0}") + @MethodSource("parameters") + public void testSubnetworkSharing(KieBaseTestConfiguration kieBaseTestConfiguration) { final String drl = "import " + A.class.getCanonicalName() + "\n" + "import " + B.class.getCanonicalName() + "\n" + diff --git a/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/compiler/integrationtests/StreamsTest.java b/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/compiler/integrationtests/StreamsTest.java index 65c323457ba..82341ecac21 100644 --- a/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/compiler/integrationtests/StreamsTest.java +++ b/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/compiler/integrationtests/StreamsTest.java @@ -22,6 +22,7 @@ import java.util.Collection; import java.util.List; import java.util.concurrent.TimeUnit; +import java.util.stream.Stream; import org.drools.base.base.ClassObjectType; import org.drools.core.common.InternalFactHandle; @@ -36,10 +37,10 @@ import org.drools.testcoverage.common.util.KieBaseUtil; import org.drools.testcoverage.common.util.KieSessionTestConfiguration; import org.drools.testcoverage.common.util.KieUtil; -import org.drools.testcoverage.common.util.TestParametersUtil; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; +import org.drools.testcoverage.common.util.TestParametersUtil2; +import org.junit.jupiter.api.Timeout; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; import org.kie.api.KieBase; import org.kie.api.builder.KieBuilder; import org.kie.api.definition.type.FactType; @@ -61,22 +62,16 @@ /** * Tests related to the stream support features */ -@RunWith(Parameterized.class) public class StreamsTest { - private final KieBaseTestConfiguration kieBaseTestConfiguration; - - public StreamsTest(final KieBaseTestConfiguration kieBaseTestConfiguration) { - this.kieBaseTestConfiguration = kieBaseTestConfiguration; - } - - @Parameterized.Parameters(name = "KieBase type={0}") - public static Collection getParameters() { - return TestParametersUtil.getKieBaseStreamConfigurations(true); + public static Stream parameters() { + return TestParametersUtil2.getKieBaseStreamConfigurations(true).stream(); } - @Test(timeout = 10000) - public void testEventAssertion() { + @ParameterizedTest(name = "KieBase type={0}") + @MethodSource("parameters") + @Timeout(10000) + public void testEventAssertion(KieBaseTestConfiguration kieBaseTestConfiguration) { final String drl = "package org.drools.compiler\n" + "\n" + "import " + StockTick.class.getCanonicalName() + ";\n" + @@ -155,8 +150,9 @@ public void testEventAssertion() { } } - @Test - public void testEntryPointReference() { + @ParameterizedTest(name = "KieBase type={0}") + @MethodSource("parameters") + public void testEntryPointReference(KieBaseTestConfiguration kieBaseTestConfiguration) { final KieBase kbase = KieBaseUtil.getKieBaseFromClasspathResources("stream-test", kieBaseTestConfiguration, "org/drools/compiler/integrationtests/test_EntryPointReference.drl"); final KieSession session = kbase.newKieSession(); @@ -195,8 +191,10 @@ public void testEntryPointReference() { } } - @Test(timeout = 10000) - public void testModifyRetracOnEntryPointFacts() { + @ParameterizedTest(name = "KieBase type={0}") + @MethodSource("parameters") + @Timeout(10000) + public void testModifyRetracOnEntryPointFacts(KieBaseTestConfiguration kieBaseTestConfiguration) { final String drl = "package org.drools.compiler\n" + "import " + StockTick.class.getCanonicalName() + ";\n" + @@ -265,8 +263,9 @@ public void testModifyRetracOnEntryPointFacts() { } } - @Test - public void testModifyOnEntryPointFacts() { + @ParameterizedTest(name = "KieBase type={0}") + @MethodSource("parameters") + public void testModifyOnEntryPointFacts(KieBaseTestConfiguration kieBaseTestConfiguration) { final String drl = "package org.drools.compiler\n" + "import " + StockTick.class.getCanonicalName() + ";\n" + "declare StockTick\n" + @@ -322,8 +321,10 @@ public void testModifyOnEntryPointFacts() { } } - @Test(timeout = 10000) - public void testEntryPointWithAccumulateAndMVEL() { + @ParameterizedTest(name = "KieBase type={0}") + @MethodSource("parameters") + @Timeout(10000) + public void testEntryPointWithAccumulateAndMVEL(KieBaseTestConfiguration kieBaseTestConfiguration) { final String drl = "package org.drools.compiler\n" + "import " + StockTick.class.getCanonicalName() + ";\n" + "rule R1 dialect 'mvel'\n" + @@ -356,8 +357,10 @@ public void testEntryPointWithAccumulateAndMVEL() { } } - @Test(timeout = 10000) - public void testGetEntryPointList() { + @ParameterizedTest(name = "KieBase type={0}") + @MethodSource("parameters") + @Timeout(10000) + public void testGetEntryPointList(KieBaseTestConfiguration kieBaseTestConfiguration) { final KieBase kbase = KieBaseUtil.getKieBaseFromClasspathResources("stream-test", kieBaseTestConfiguration, "org/drools/compiler/integrationtests/test_EntryPointReference.drl"); final KieSession session = kbase.newKieSession(); @@ -378,8 +381,10 @@ public void testGetEntryPointList() { } } - @Test(timeout = 10000) - public void testEventDoesNotExpireIfNotInPattern() { + @ParameterizedTest(name = "KieBase type={0}") + @MethodSource("parameters") + @Timeout(10000) + public void testEventDoesNotExpireIfNotInPattern(KieBaseTestConfiguration kieBaseTestConfiguration) { final String drl = "package org.drools.compiler\n" + "import " + StockTick.class.getCanonicalName() + ";\n" + "declare StockTick\n" + @@ -423,8 +428,10 @@ public void testEventDoesNotExpireIfNotInPattern() { } } - @Test(timeout = 10000) - public void testEventExpirationSetToZero() { + @ParameterizedTest(name = "KieBase type={0}") + @MethodSource("parameters") + @Timeout(10000) + public void testEventExpirationSetToZero(KieBaseTestConfiguration kieBaseTestConfiguration) { final String drl = "package org.drools.compiler\n" + "import " + StockTick.class.getCanonicalName() + ";\n" + "declare StockTick\n" + @@ -471,8 +478,10 @@ public void testEventExpirationSetToZero() { } } - @Test(timeout = 10000) - public void testEventExpirationValue() { + @ParameterizedTest(name = "KieBase type={0}") + @MethodSource("parameters") + @Timeout(10000) + public void testEventExpirationValue(KieBaseTestConfiguration kieBaseTestConfiguration) { final String drl1 = "package org.drools.pkg1\n" + "import " + StockTick.class.getCanonicalName() + ";\n" + "declare StockTick\n" + @@ -505,8 +514,10 @@ public void testEventExpirationValue() { } } - @Test(timeout = 10000) - public void testDeclaredEntryPoint() { + @ParameterizedTest(name = "KieBase type={0}") + @MethodSource("parameters") + @Timeout(10000) + public void testDeclaredEntryPoint(KieBaseTestConfiguration kieBaseTestConfiguration) { final String drl = "package org.jboss.qa.brms.declaredep\n" + "declare entry-point UnusedEntryPoint\n" + "end\n" + @@ -527,8 +538,9 @@ public void testDeclaredEntryPoint() { } } - @Test - public void testWindowDeclaration() { + @ParameterizedTest(name = "KieBase type={0}") + @MethodSource("parameters") + public void testWindowDeclaration(KieBaseTestConfiguration kieBaseTestConfiguration) { final String drl = "package org.drools.compiler\n" + "import " + StockTick.class.getCanonicalName() + ";\n" + "declare StockTick\n" + @@ -576,8 +588,10 @@ public void testWindowDeclaration() { } } - @Test(timeout = 10000) - public void testWindowDeclaration2() { + @ParameterizedTest(name = "KieBase type={0}") + @MethodSource("parameters") + @Timeout(10000) + public void testWindowDeclaration2(KieBaseTestConfiguration kieBaseTestConfiguration) { final String drl = "package org.drools.compiler\n" + "declare Double\n" + " @role(event)\n" + @@ -618,8 +632,10 @@ public void testWindowDeclaration2() { } } - @Test(timeout = 10000) - public void testMultipleWindows() { + @ParameterizedTest(name = "KieBase type={0}") + @MethodSource("parameters") + @Timeout(10000) + public void testMultipleWindows(KieBaseTestConfiguration kieBaseTestConfiguration) { final String drl = "package org.drools.compiler\n" + "import " + StockTick.class.getCanonicalName() + ";\n" + "declare StockTick\n" + @@ -656,8 +672,9 @@ public void testMultipleWindows() { } } - @Test - public void testWindowWithEntryPointCompilationError() { + @ParameterizedTest(name = "KieBase type={0}") + @MethodSource("parameters") + public void testWindowWithEntryPointCompilationError(KieBaseTestConfiguration kieBaseTestConfiguration) { final String drl = "import " + Cheese.class.getCanonicalName() + ";\n" + "declare window X\n" + " Cheese( type == \"gorgonzola\" ) over window:time(1m) from entry-point Z\n" + @@ -674,8 +691,10 @@ public void testWindowWithEntryPointCompilationError() { .isNotEmpty(); } - @Test(timeout = 10000) - public void testAtomicActivationFiring() throws Exception { + @ParameterizedTest(name = "KieBase type={0}") + @MethodSource("parameters") + @Timeout(10000) + public void testAtomicActivationFiring(KieBaseTestConfiguration kieBaseTestConfiguration) throws Exception { // JBRULES-3383 final String drl = "package org.drools.compiler.test\n" + "declare Event\n" + diff --git a/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/compiler/integrationtests/SubnetworkCEPTest.java b/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/compiler/integrationtests/SubnetworkCEPTest.java index 219a2f44382..c9732da2c91 100644 --- a/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/compiler/integrationtests/SubnetworkCEPTest.java +++ b/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/compiler/integrationtests/SubnetworkCEPTest.java @@ -18,34 +18,26 @@ */ package org.drools.compiler.integrationtests; -import java.util.Collection; +import java.util.stream.Stream; import org.drools.testcoverage.common.util.KieBaseTestConfiguration; import org.drools.testcoverage.common.util.KieBaseUtil; -import org.drools.testcoverage.common.util.TestParametersUtil; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; +import org.drools.testcoverage.common.util.TestParametersUtil2; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; import org.kie.api.KieBase; import org.kie.api.runtime.KieSession; import org.kie.api.runtime.rule.FactHandle; -@RunWith(Parameterized.class) public class SubnetworkCEPTest { - private final KieBaseTestConfiguration kieBaseTestConfiguration; - - public SubnetworkCEPTest(final KieBaseTestConfiguration kieBaseTestConfiguration) { - this.kieBaseTestConfiguration = kieBaseTestConfiguration; - } - - @Parameterized.Parameters(name = "KieBase type={0}") - public static Collection getParameters() { - return TestParametersUtil.getKieBaseStreamConfigurations(true); + public static Stream parameters() { + return TestParametersUtil2.getKieBaseStreamConfigurations(true).stream(); } - @Test - public void testNPEOnFlushingOfUnlinkedPmem() { + @ParameterizedTest(name = "KieBase type={0}") + @MethodSource("parameters") + public void testNPEOnFlushingOfUnlinkedPmem(KieBaseTestConfiguration kieBaseTestConfiguration) { // DROOLS-1285 final String drl = "import " + SubnetworkTest.A.class.getCanonicalName() + "\n" + diff --git a/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/compiler/integrationtests/SubnetworkTest.java b/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/compiler/integrationtests/SubnetworkTest.java index dadf5387ac3..223e2883be9 100644 --- a/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/compiler/integrationtests/SubnetworkTest.java +++ b/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/compiler/integrationtests/SubnetworkTest.java @@ -20,10 +20,10 @@ import org.drools.testcoverage.common.util.KieBaseTestConfiguration; import org.drools.testcoverage.common.util.KieBaseUtil; -import org.drools.testcoverage.common.util.TestParametersUtil; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; +import org.drools.testcoverage.common.util.TestParametersUtil2; +import org.junit.jupiter.api.Timeout; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; import org.kie.api.KieBase; import org.kie.api.definition.type.Role; import org.kie.api.runtime.KieSession; @@ -33,25 +33,17 @@ import java.awt.Dimension; import java.util.ArrayList; -import java.util.Collection; import java.util.List; import java.util.concurrent.atomic.AtomicInteger; +import java.util.stream.Stream; import static java.util.Arrays.asList; import static org.assertj.core.api.Assertions.assertThat; -@RunWith(Parameterized.class) public class SubnetworkTest { - private final KieBaseTestConfiguration kieBaseTestConfiguration; - - public SubnetworkTest(final KieBaseTestConfiguration kieBaseTestConfiguration) { - this.kieBaseTestConfiguration = kieBaseTestConfiguration; - } - - @Parameterized.Parameters(name = "KieBase type={0}") - public static Collection getParameters() { - return TestParametersUtil.getKieBaseCloudConfigurations(true); + public static Stream parameters() { + return TestParametersUtil2.getKieBaseCloudConfigurations(true).stream(); } @Role(Role.Type.EVENT) @@ -69,8 +61,10 @@ public static class C { } - @Test(timeout = 10000) - public void testRightStagingOnSharedSubnetwork() { + @ParameterizedTest(name = "KieBase type={0}") + @MethodSource("parameters") + @Timeout(10000) + public void testRightStagingOnSharedSubnetwork(KieBaseTestConfiguration kieBaseTestConfiguration) { // RHBRMS-2624 final String drl = "import " + AtomicInteger.class.getCanonicalName() + ";\n" + @@ -107,8 +101,10 @@ public void testRightStagingOnSharedSubnetwork() { } } - @Test(timeout = 10000) - public void testUpdateOnSharedSubnetwork() { + @ParameterizedTest(name = "KieBase type={0}") + @MethodSource("parameters") + @Timeout(10000) + public void testUpdateOnSharedSubnetwork(KieBaseTestConfiguration kieBaseTestConfiguration) { // DROOLS-1360 final String drl = "import " + AtomicInteger.class.getCanonicalName() + ";\n" + @@ -154,8 +150,10 @@ public void testUpdateOnSharedSubnetwork() { } } - @Test(timeout = 10000) - public void testSubNeworkNotRemoveRightRemove() { + @ParameterizedTest(name = "KieBase type={0}") + @MethodSource("parameters") + @Timeout(10000) + public void testSubNeworkNotRemoveRightRemove(KieBaseTestConfiguration kieBaseTestConfiguration) { final String drl = "import " + Dimension.class.getCanonicalName() + ";\n" + "global java.util.List list;\n" + @@ -188,8 +186,10 @@ public void testSubNeworkNotRemoveRightRemove() { } } - @Test(timeout = 10000) - public void testSubNeworkNotRemoveLeftRemove() { + @ParameterizedTest(name = "KieBase type={0}") + @MethodSource("parameters") + @Timeout(10000) + public void testSubNeworkNotRemoveLeftRemove(KieBaseTestConfiguration kieBaseTestConfiguration) { final String drl = "import " + Dimension.class.getCanonicalName() + ";\n" + "global java.util.List list;\n" + @@ -226,8 +226,10 @@ public void testSubNeworkNotRemoveLeftRemove() { } } - @Test(timeout = 10000) - public void testSubNeworkQueryTest() { + @ParameterizedTest(name = "KieBase type={0}") + @MethodSource("parameters") + @Timeout(10000) + public void testSubNeworkQueryTest(KieBaseTestConfiguration kieBaseTestConfiguration) { final String drl = "import " + Dimension.class.getCanonicalName() + ";\n" + "global java.util.List list;\n" + @@ -273,16 +275,20 @@ public void testSubNeworkQueryTest() { } } - @Test(timeout = 10000) - public void testSubNetworks() { + @ParameterizedTest(name = "KieBase type={0}") + @MethodSource("parameters") + @Timeout(10000) + public void testSubNetworks(KieBaseTestConfiguration kieBaseTestConfiguration) { final KieBase kieBase = KieBaseUtil.getKieBaseFromClasspathResources("subnetwork-test", kieBaseTestConfiguration, "org/drools/compiler/integrationtests/test_SubNetworks.drl"); final KieSession session = kieBase.newKieSession(); session.dispose(); } - @Test(timeout = 10000) - public void testSubnetworkSharingWith2SinksFromLia() { + @ParameterizedTest(name = "KieBase type={0}") + @MethodSource("parameters") + @Timeout(10000) + public void testSubnetworkSharingWith2SinksFromLia(KieBaseTestConfiguration kieBaseTestConfiguration) { // DROOLS-1656 final String drl = "import " + X.class.getCanonicalName() + "\n" + @@ -340,8 +346,10 @@ public void testSubnetworkSharingWith2SinksFromLia() { } } - @Test(timeout = 10000) - public void testSubnetworkSharingWith2SinksAfterLia() { + @ParameterizedTest(name = "KieBase type={0}") + @MethodSource("parameters") + @Timeout(10000) + public void testSubnetworkSharingWith2SinksAfterLia(KieBaseTestConfiguration kieBaseTestConfiguration) { // DROOLS-1656 final String drl = "import " + X.class.getCanonicalName() + "\n" + @@ -460,19 +468,21 @@ public void setId(final int id) { } } - @Test - public void subnetworkSharingWith2SinksAndRightTupleDelete_shouldNotThrowNPE() { + @ParameterizedTest(name = "KieBase type={0}") + @MethodSource("parameters") + public void subnetworkSharingWith2SinksAndRightTupleDelete_shouldNotThrowNPE(KieBaseTestConfiguration kieBaseTestConfiguration) { // DROOLS-7420 - testFromCollectInSubnetwork(true); + testFromCollectInSubnetwork(kieBaseTestConfiguration, true); } - @Test - public void subnetworkNoSharingWith2SinksAndRightTupleDelete_shouldNotThrowNPE() { + @ParameterizedTest(name = "KieBase type={0}") + @MethodSource("parameters") + public void subnetworkNoSharingWith2SinksAndRightTupleDelete_shouldNotThrowNPE(KieBaseTestConfiguration kieBaseTestConfiguration) { // DROOLS-7420 - testFromCollectInSubnetwork(false); + testFromCollectInSubnetwork(kieBaseTestConfiguration, false); } - private void testFromCollectInSubnetwork(boolean nodeSharing) { + private void testFromCollectInSubnetwork(KieBaseTestConfiguration kieBaseTestConfiguration, boolean nodeSharing) { String accConstraint = nodeSharing ? "" : "size > 0"; final String drl = "import " + List.class.getCanonicalName() + ";\n" + diff --git a/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/compiler/integrationtests/UnexpectedLoopTest.java b/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/compiler/integrationtests/UnexpectedLoopTest.java index 4a700f65084..af5a2f1c61b 100644 --- a/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/compiler/integrationtests/UnexpectedLoopTest.java +++ b/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/compiler/integrationtests/UnexpectedLoopTest.java @@ -18,39 +18,32 @@ */ package org.drools.compiler.integrationtests; -import java.util.Collection; import java.util.List; +import java.util.stream.Stream; import org.drools.compiler.integrationtests.model.CalcFact; import org.drools.compiler.integrationtests.model.Item; import org.drools.compiler.integrationtests.model.RecordFact; import org.drools.testcoverage.common.util.KieBaseTestConfiguration; import org.drools.testcoverage.common.util.KieBaseUtil; -import org.drools.testcoverage.common.util.TestParametersUtil; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; +import org.drools.testcoverage.common.util.TestParametersUtil2; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; import org.kie.api.KieBase; import org.kie.api.runtime.KieSession; import static org.assertj.core.api.Assertions.assertThat; -@RunWith(Parameterized.class) public class UnexpectedLoopTest { - private final KieBaseTestConfiguration kieBaseTestConfiguration; - public UnexpectedLoopTest(final KieBaseTestConfiguration kieBaseTestConfiguration) { - this.kieBaseTestConfiguration = kieBaseTestConfiguration; + public static Stream parameters() { + return TestParametersUtil2.getKieBaseCloudConfigurations(true).stream(); } - @Parameterized.Parameters(name = "KieBase type={0}") - public static Collection getParameters() { - return TestParametersUtil.getKieBaseCloudConfigurations(true); - } - - @Test - public void joinFromFromPeerUpdate_shouldNotLoop() { + @ParameterizedTest(name = "KieBase type={0}") + @MethodSource("parameters") + public void joinFromFromPeerUpdate_shouldNotLoop(KieBaseTestConfiguration kieBaseTestConfiguration) { final KieBase kieBase = KieBaseUtil.getKieBaseFromClasspathResources(getClass(), kieBaseTestConfiguration, "org/drools/compiler/integrationtests/joinFromFrom.drl"); diff --git a/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/compiler/integrationtests/operators/AndTest.java b/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/compiler/integrationtests/operators/AndTest.java index cd4564ac5a7..bd2d2c3b6a7 100644 --- a/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/compiler/integrationtests/operators/AndTest.java +++ b/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/compiler/integrationtests/operators/AndTest.java @@ -19,38 +19,30 @@ package org.drools.compiler.integrationtests.operators; import java.util.ArrayList; -import java.util.Collection; import java.util.List; +import java.util.stream.Stream; import org.drools.testcoverage.common.model.Cheese; import org.drools.testcoverage.common.model.Message; import org.drools.testcoverage.common.util.KieBaseTestConfiguration; import org.drools.testcoverage.common.util.KieBaseUtil; -import org.drools.testcoverage.common.util.TestParametersUtil; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; +import org.drools.testcoverage.common.util.TestParametersUtil2; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; import org.kie.api.KieBase; import org.kie.api.runtime.KieSession; import static org.assertj.core.api.Assertions.assertThat; -@RunWith(Parameterized.class) public class AndTest { - private final KieBaseTestConfiguration kieBaseTestConfiguration; - - public AndTest(final KieBaseTestConfiguration kieBaseTestConfiguration) { - this.kieBaseTestConfiguration = kieBaseTestConfiguration; - } - - @Parameterized.Parameters(name = "KieBase type={0}") - public static Collection getParameters() { - return TestParametersUtil.getKieBaseCloudConfigurations(true); + public static Stream parameters() { + return TestParametersUtil2.getKieBaseCloudConfigurations(true).stream(); } - @Test - public void testExplicitAnd() { + @ParameterizedTest(name = "KieBase type={0}") + @MethodSource("parameters") + public void testExplicitAnd(KieBaseTestConfiguration kieBaseTestConfiguration) { final String drl = "package HelloWorld\n" + " \n" + "import " + Message.class.getCanonicalName() + ";\n" + diff --git a/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/compiler/integrationtests/operators/ContainsTest.java b/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/compiler/integrationtests/operators/ContainsTest.java index a2e7b4bc73c..21597f74be4 100644 --- a/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/compiler/integrationtests/operators/ContainsTest.java +++ b/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/compiler/integrationtests/operators/ContainsTest.java @@ -19,8 +19,8 @@ package org.drools.compiler.integrationtests.operators; import java.util.ArrayList; -import java.util.Collection; import java.util.List; +import java.util.stream.Stream; import org.drools.testcoverage.common.model.Cheese; import org.drools.testcoverage.common.model.Cheesery; @@ -29,31 +29,23 @@ import org.drools.testcoverage.common.model.Primitives; import org.drools.testcoverage.common.util.KieBaseTestConfiguration; import org.drools.testcoverage.common.util.KieBaseUtil; -import org.drools.testcoverage.common.util.TestParametersUtil; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; +import org.drools.testcoverage.common.util.TestParametersUtil2; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; import org.kie.api.KieBase; import org.kie.api.runtime.KieSession; import static org.assertj.core.api.Assertions.assertThat; -@RunWith(Parameterized.class) public class ContainsTest { - private final KieBaseTestConfiguration kieBaseTestConfiguration; - - public ContainsTest(final KieBaseTestConfiguration kieBaseTestConfiguration) { - this.kieBaseTestConfiguration = kieBaseTestConfiguration; - } - - @Parameterized.Parameters(name = "KieBase type={0}") - public static Collection getParameters() { - return TestParametersUtil.getKieBaseCloudConfigurations(true); + public static Stream parameters() { + return TestParametersUtil2.getKieBaseCloudConfigurations(true).stream(); } - @Test - public void testContainsCheese() { + @ParameterizedTest(name = "KieBase type={0}") + @MethodSource("parameters") + public void testContainsCheese(KieBaseTestConfiguration kieBaseTestConfiguration) { final String drl = "package org.drools.compiler.integrationtests.operators;\n" + "\n" + "import " + Cheese.class.getCanonicalName() + ";\n" + @@ -106,8 +98,9 @@ public void testContainsCheese() { } } - @Test - public void testContainsInArray() { + @ParameterizedTest(name = "KieBase type={0}") + @MethodSource("parameters") + public void testContainsInArray(KieBaseTestConfiguration kieBaseTestConfiguration) { final String drl = "package org.drools.compiler.integrationtests.operators\n" + "import " + Primitives.class.getCanonicalName() + " ;\n" + @@ -151,8 +144,9 @@ public void testContainsInArray() { } } - @Test - public void testNotContainsOperator() { + @ParameterizedTest(name = "KieBase type={0}") + @MethodSource("parameters") + public void testNotContainsOperator(KieBaseTestConfiguration kieBaseTestConfiguration) { // JBRULES-2404: "not contains" operator doesn't work on nested fields final String str = "package org.drools.compiler.integrationtests.operators\n" + "import " + Order.class.getCanonicalName() + " ;\n" + diff --git a/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/compiler/integrationtests/operators/EnabledTest.java b/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/compiler/integrationtests/operators/EnabledTest.java index a3c837bf20f..38d63f05d14 100644 --- a/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/compiler/integrationtests/operators/EnabledTest.java +++ b/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/compiler/integrationtests/operators/EnabledTest.java @@ -19,17 +19,17 @@ package org.drools.compiler.integrationtests.operators; import java.util.ArrayList; -import java.util.Collection; import java.util.List; +import java.util.stream.Stream; import org.drools.testcoverage.common.model.MyFact; import org.drools.testcoverage.common.model.Person; import org.drools.testcoverage.common.util.KieBaseTestConfiguration; import org.drools.testcoverage.common.util.KieBaseUtil; import org.drools.testcoverage.common.util.KieUtil; -import org.drools.testcoverage.common.util.TestParametersUtil; -import org.junit.Test; -import org.junit.runner.RunWith; +import org.drools.testcoverage.common.util.TestParametersUtil2; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; import org.junit.runners.Parameterized; import org.kie.api.KieBase; import org.kie.api.KieServices; @@ -45,22 +45,16 @@ import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; -@RunWith(Parameterized.class) public class EnabledTest { - private final KieBaseTestConfiguration kieBaseTestConfiguration; - - public EnabledTest(final KieBaseTestConfiguration kieBaseTestConfiguration) { - this.kieBaseTestConfiguration = kieBaseTestConfiguration; - } - @Parameterized.Parameters(name = "KieBase type={0}") - public static Collection getParameters() { - return TestParametersUtil.getKieBaseCloudConfigurations(false); + public static Stream parameters() { + return TestParametersUtil2.getKieBaseCloudConfigurations(false).stream(); } - @Test - public void testEnabledExpression() { + @ParameterizedTest(name = "KieBase type={0}") + @MethodSource("parameters") + public void testEnabledExpression(KieBaseTestConfiguration kieBaseTestConfiguration) { final String drl = "package org.drools.compiler.integrationtests.operators;\n" + "import " + Person.class.getCanonicalName() + ";\n" + @@ -129,8 +123,9 @@ public void testEnabledExpression() { } } - @Test - public void testEnabledExpression2() { + @ParameterizedTest(name = "KieBase type={0}") + @MethodSource("parameters") + public void testEnabledExpression2(KieBaseTestConfiguration kieBaseTestConfiguration) { final String drl = "import " + MyFact.class.getName() + ";\n" + "rule R1\n" + " enabled( rule.name == $f.name )" + diff --git a/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/compiler/integrationtests/operators/EqualsTest.java b/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/compiler/integrationtests/operators/EqualsTest.java index 7c68e02c6ee..fd5e809f11a 100644 --- a/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/compiler/integrationtests/operators/EqualsTest.java +++ b/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/compiler/integrationtests/operators/EqualsTest.java @@ -27,30 +27,22 @@ import org.drools.testcoverage.common.util.KieBaseTestConfiguration; import org.drools.testcoverage.common.util.KieBaseUtil; import org.drools.testcoverage.common.util.TestParametersUtil; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; import org.kie.api.KieBase; import org.kie.api.runtime.KieSession; import static org.assertj.core.api.Assertions.assertThat; -@RunWith(Parameterized.class) public class EqualsTest { - private final KieBaseTestConfiguration kieBaseTestConfiguration; - - public EqualsTest(final KieBaseTestConfiguration kieBaseTestConfiguration) { - this.kieBaseTestConfiguration = kieBaseTestConfiguration; - } - - @Parameterized.Parameters(name = "KieBase type={0}") - public static Collection getParameters() { + public static Collection parameters() { return TestParametersUtil.getKieBaseCloudConfigurations(true); } - @Test - public void testEqualitySupport() { + @ParameterizedTest(name = "KieBase type={0}") + @MethodSource("parameters") + public void testEqualitySupport(KieBaseTestConfiguration kieBaseTestConfiguration) { final String drl = "package org.drools.compiler.integrationtests.operators\n" + "import " + PersonWithSpecificEquals.class.getCanonicalName() + " ;\n" + @@ -92,8 +84,9 @@ public void testEqualitySupport() { } } - @Test - public void testNotEqualsOperator() { + @ParameterizedTest(name = "KieBase type={0}") + @MethodSource("parameters") + public void testNotEqualsOperator(KieBaseTestConfiguration kieBaseTestConfiguration) { // JBRULES-3003: restriction evaluation returns 'false' for "trueField != falseField" final String str = "package org.drools.compiler.integrationtests.operators\n" + @@ -124,8 +117,9 @@ public void testNotEqualsOperator() { } } - @Test - public void testCharComparisons() { + @ParameterizedTest(name = "KieBase type={0}") + @MethodSource("parameters") + public void testCharComparisons(KieBaseTestConfiguration kieBaseTestConfiguration) { final String drl = "package org.drools.compiler.integrationtests.operators\n" + "import " + Primitives.class.getCanonicalName() + " ;\n" + diff --git a/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/compiler/integrationtests/operators/EvalRewriteTest.java b/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/compiler/integrationtests/operators/EvalRewriteTest.java index a24bae0c194..c6e8a5856df 100644 --- a/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/compiler/integrationtests/operators/EvalRewriteTest.java +++ b/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/compiler/integrationtests/operators/EvalRewriteTest.java @@ -19,38 +19,30 @@ package org.drools.compiler.integrationtests.operators; import java.util.ArrayList; -import java.util.Collection; import java.util.List; +import java.util.stream.Stream; import org.drools.testcoverage.common.model.Order; import org.drools.testcoverage.common.model.OrderItem; import org.drools.testcoverage.common.util.KieBaseTestConfiguration; import org.drools.testcoverage.common.util.KieBaseUtil; -import org.drools.testcoverage.common.util.TestParametersUtil; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; +import org.drools.testcoverage.common.util.TestParametersUtil2; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; import org.kie.api.KieBase; import org.kie.api.runtime.KieSession; import static org.assertj.core.api.Assertions.assertThat; -@RunWith(Parameterized.class) public class EvalRewriteTest { - private final KieBaseTestConfiguration kieBaseTestConfiguration; - - public EvalRewriteTest(final KieBaseTestConfiguration kieBaseTestConfiguration) { - this.kieBaseTestConfiguration = kieBaseTestConfiguration; - } - - @Parameterized.Parameters(name = "KieBase type={0}") - public static Collection getParameters() { - return TestParametersUtil.getKieBaseCloudConfigurations(true); + public static Stream parameters() { + return TestParametersUtil2.getKieBaseCloudConfigurations(true).stream(); } - @Test - public void testEvalRewrite() { + @ParameterizedTest(name = "KieBase type={0}") + @MethodSource("parameters") + public void testEvalRewrite(KieBaseTestConfiguration kieBaseTestConfiguration) { final String drl = "package org.drools.compiler.integrationtests.operators\n" + "import " + OrderItem.class.getCanonicalName() + " ;\n" + @@ -147,8 +139,9 @@ public void testEvalRewrite() { } } - @Test - public void testEvalRewriteMatches() { + @ParameterizedTest(name = "KieBase type={0}") + @MethodSource("parameters") + public void testEvalRewriteMatches(KieBaseTestConfiguration kieBaseTestConfiguration) { final String drl = "package org.drools.compiler.integrationtests.operators;\n" + "import " + OrderItem.class.getCanonicalName() + " ;\n" + @@ -199,8 +192,9 @@ public void testEvalRewriteMatches() { } } - @Test - public void testEvalRewriteWithSpecialOperators() { + @ParameterizedTest(name = "KieBase type={0}") + @MethodSource("parameters") + public void testEvalRewriteWithSpecialOperators(KieBaseTestConfiguration kieBaseTestConfiguration) { final String drl = "package org.drools.compiler\n" + "import " + OrderItem.class.getCanonicalName() + " ;\n" + diff --git a/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/compiler/integrationtests/operators/EvalTest.java b/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/compiler/integrationtests/operators/EvalTest.java index 5f728494d27..bac22467050 100644 --- a/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/compiler/integrationtests/operators/EvalTest.java +++ b/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/compiler/integrationtests/operators/EvalTest.java @@ -21,8 +21,8 @@ import java.lang.reflect.InvocationTargetException; import java.math.BigDecimal; import java.util.ArrayList; -import java.util.Collection; import java.util.List; +import java.util.stream.Stream; import org.drools.core.reteoo.ReteDumper; import org.drools.testcoverage.common.model.Cheese; @@ -33,10 +33,9 @@ import org.drools.testcoverage.common.util.KieBaseTestConfiguration; import org.drools.testcoverage.common.util.KieBaseUtil; import org.drools.testcoverage.common.util.KieUtil; -import org.drools.testcoverage.common.util.TestParametersUtil; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; +import org.drools.testcoverage.common.util.TestParametersUtil2; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; import org.kie.api.KieBase; import org.kie.api.KieServices; import org.kie.api.builder.KieModule; @@ -47,22 +46,15 @@ import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.fail; -@RunWith(Parameterized.class) public class EvalTest { - private final KieBaseTestConfiguration kieBaseTestConfiguration; - - public EvalTest(final KieBaseTestConfiguration kieBaseTestConfiguration) { - this.kieBaseTestConfiguration = kieBaseTestConfiguration; - } - - @Parameterized.Parameters(name = "KieBase type={0}") - public static Collection getParameters() { - return TestParametersUtil.getKieBaseCloudConfigurations(true); + public static Stream parameters() { + return TestParametersUtil2.getKieBaseCloudConfigurations(true).stream(); } - @Test - public void testEvalDefaultCompiler() { + @ParameterizedTest(name = "KieBase type={0}") + @MethodSource("parameters") + public void testEvalDefaultCompiler(KieBaseTestConfiguration kieBaseTestConfiguration) { final String drl = "package org.drools.compiler.integrationtests.operators;\n" + "import " + Cheese.class.getCanonicalName() + ";\n" + "global java.util.List list;\n" + @@ -96,8 +88,9 @@ public void testEvalDefaultCompiler() { } } - @Test - public void testEvalNoPatterns() { + @ParameterizedTest(name = "KieBase type={0}") + @MethodSource("parameters") + public void testEvalNoPatterns(KieBaseTestConfiguration kieBaseTestConfiguration) { final String drl = "package org.drools.compiler.integrationtests.operators\n" + "global java.util.List list\n" + "rule \"no patterns1\"\n" + @@ -145,8 +138,9 @@ public void testEvalNoPatterns() { } } - @Test - public void testEvalMore() { + @ParameterizedTest(name = "KieBase type={0}") + @MethodSource("parameters") + public void testEvalMore(KieBaseTestConfiguration kieBaseTestConfiguration) { final String drl = "package org.drools.compiler.integrationtests.operators\n" + "import " + Cheese.class.getCanonicalName() + ";\n" + @@ -186,8 +180,9 @@ public void testEvalMore() { } } - @Test - public void testEvalCE() { + @ParameterizedTest(name = "KieBase type={0}") + @MethodSource("parameters") + public void testEvalCE(KieBaseTestConfiguration kieBaseTestConfiguration) { final String drl = "package org.drools.compiler.integrationtests.operators\n" + "import " + Person.class.getCanonicalName() + ";\n" + "rule \"inline eval\"\n" + @@ -217,8 +212,9 @@ public void testEvalCE() { } } - @Test - public void testEvalException() { + @ParameterizedTest(name = "KieBase type={0}") + @MethodSource("parameters") + public void testEvalException(KieBaseTestConfiguration kieBaseTestConfiguration) { final String drl = "package org.drools.compiler.integrationtests.operators;\n" + "import " + Cheese.class.getCanonicalName() + ";\n" + "function boolean throwException(Object object) {\n" + @@ -251,8 +247,9 @@ public void testEvalException() { } } - @Test - public void testEvalInline() { + @ParameterizedTest(name = "KieBase type={0}") + @MethodSource("parameters") + public void testEvalInline(KieBaseTestConfiguration kieBaseTestConfiguration) { final String drl = "package org.drools.compiler.integrationtests.operators;\n" + "import " + Person.class.getCanonicalName() + ";\n" + "rule \"inline eval\"\n" + @@ -281,8 +278,9 @@ public void testEvalInline() { } } - @Test - public void testEvalWithLineBreaks() { + @ParameterizedTest(name = "KieBase type={0}") + @MethodSource("parameters") + public void testEvalWithLineBreaks(KieBaseTestConfiguration kieBaseTestConfiguration) { final String drl = "package org.drools.compiler.integrationtests.operators;\n" + "\n" + "global java.util.List results\n" + @@ -317,8 +315,9 @@ public void testEvalWithLineBreaks() { } } - @Test - public void testEvalWithBigDecimal() { + @ParameterizedTest(name = "KieBase type={0}") + @MethodSource("parameters") + public void testEvalWithBigDecimal(KieBaseTestConfiguration kieBaseTestConfiguration) { final String drl = "package org.drools.compiler.integrationtests.operators;\n" + "import java.math.BigDecimal; \n" + @@ -350,8 +349,9 @@ public void testEvalWithBigDecimal() { } } - @Test - public void testFieldBiningsAndEvalSharing() { + @ParameterizedTest(name = "KieBase type={0}") + @MethodSource("parameters") + public void testFieldBiningsAndEvalSharing(KieBaseTestConfiguration kieBaseTestConfiguration) { final String drl = "package org.drools.compiler\n" + "import " + Person.class.getCanonicalName() + ";\n" + "global java.util.List list;\n" + @@ -373,11 +373,12 @@ public void testFieldBiningsAndEvalSharing() { " then\n" + " list.add(\"rule2 fired\");\n" + "end "; - evalSharingTest(drl); + evalSharingTest(kieBaseTestConfiguration, drl); } - @Test - public void testFieldBiningsAndPredicateSharing() { + @ParameterizedTest(name = "KieBase type={0}") + @MethodSource("parameters") + public void testFieldBiningsAndPredicateSharing(KieBaseTestConfiguration kieBaseTestConfiguration) { final String drl = "package org.drools.compiler.integrationtests.operators;\n" + "import " + Person.class.getCanonicalName() + ";\n" + "global java.util.List list;\n" + @@ -397,10 +398,10 @@ public void testFieldBiningsAndPredicateSharing() { " then\n" + " list.add(\"rule2 fired\");\n" + "end"; - evalSharingTest(drl); + evalSharingTest(kieBaseTestConfiguration, drl); } - private void evalSharingTest(final String drl) { + private void evalSharingTest(KieBaseTestConfiguration kieBaseTestConfiguration, final String drl) { final KieBase kbase = KieBaseUtil.getKieBaseFromKieModuleFromDrl("eval-test", kieBaseTestConfiguration, drl); @@ -423,8 +424,9 @@ private void evalSharingTest(final String drl) { } } - @Test - public void testCastingInsideEvals() { + @ParameterizedTest(name = "KieBase type={0}") + @MethodSource("parameters") + public void testCastingInsideEvals(KieBaseTestConfiguration kieBaseTestConfiguration) { final String drl = "package org.drools.compiler.integrationtests.operators\n" + "\n" + "global java.lang.Integer value;\n" + @@ -452,8 +454,9 @@ public void testCastingInsideEvals() { } } - @Test - public void testAlphaEvalWithOrCE() { + @ParameterizedTest(name = "KieBase type={0}") + @MethodSource("parameters") + public void testAlphaEvalWithOrCE(KieBaseTestConfiguration kieBaseTestConfiguration) { final String drl = "package org.drools.compiler.integrationtests.operators;\n" + "import " + FactA.class.getCanonicalName() + ";\n" + "import " + FactB.class.getCanonicalName() + ";\n" + @@ -491,8 +494,9 @@ public void testAlphaEvalWithOrCE() { } } - @Test - public void testModifyWithLiaToEval() { + @ParameterizedTest(name = "KieBase type={0}") + @MethodSource("parameters") + public void testModifyWithLiaToEval(KieBaseTestConfiguration kieBaseTestConfiguration) { final String drl = "package org.drools.compiler.integrationtests.operators;\n" + "import " + Person.class.getCanonicalName() + "\n" + @@ -527,8 +531,9 @@ public void testModifyWithLiaToEval() { } } - @Test - public void testBigDecimalWithFromAndEval() { + @ParameterizedTest(name = "KieBase type={0}") + @MethodSource("parameters") + public void testBigDecimalWithFromAndEval(KieBaseTestConfiguration kieBaseTestConfiguration) { final String drl = "package org.drools.compiler.integrationtests.operators;\n" + "rule \"Test Rule\"\n" + "when\n" + @@ -548,8 +553,9 @@ public void testBigDecimalWithFromAndEval() { } } - @Test - public void testPredicate() { + @ParameterizedTest(name = "KieBase type={0}") + @MethodSource("parameters") + public void testPredicate(KieBaseTestConfiguration kieBaseTestConfiguration) { final String drl = "package org.drools.compiler.integrationtests.operators;\n" + "import " + Person.class.getCanonicalName() + "\n" + "global java.util.List list;\n" + @@ -588,8 +594,9 @@ public void testPredicate() { } } - @Test - public void testPredicateException() { + @ParameterizedTest(name = "KieBase type={0}") + @MethodSource("parameters") + public void testPredicateException(KieBaseTestConfiguration kieBaseTestConfiguration) { final String drl = "package org.drools.compiler.integrationtests.operators;\n" + "import " + Cheese.class.getCanonicalName() + ";\n" + "function boolean throwException(Object object) {\n" + diff --git a/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/compiler/integrationtests/operators/ExistsTest.java b/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/compiler/integrationtests/operators/ExistsTest.java index e4c9d13e39f..5a114a6d3b3 100644 --- a/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/compiler/integrationtests/operators/ExistsTest.java +++ b/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/compiler/integrationtests/operators/ExistsTest.java @@ -20,39 +20,31 @@ import java.math.BigDecimal; import java.util.ArrayList; -import java.util.Collection; import java.util.List; +import java.util.stream.Stream; import org.drools.testcoverage.common.model.AFact; import org.drools.testcoverage.common.model.Cheese; import org.drools.testcoverage.common.util.KieBaseTestConfiguration; import org.drools.testcoverage.common.util.KieBaseUtil; -import org.drools.testcoverage.common.util.TestParametersUtil; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; +import org.drools.testcoverage.common.util.TestParametersUtil2; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; import org.kie.api.KieBase; import org.kie.api.runtime.KieSession; import org.kie.api.runtime.rule.FactHandle; import static org.assertj.core.api.Assertions.assertThat; -@RunWith(Parameterized.class) public class ExistsTest { - private final KieBaseTestConfiguration kieBaseTestConfiguration; - - public ExistsTest(final KieBaseTestConfiguration kieBaseTestConfiguration) { - this.kieBaseTestConfiguration = kieBaseTestConfiguration; - } - - @Parameterized.Parameters(name = "KieBase type={0}") - public static Collection getParameters() { - return TestParametersUtil.getKieBaseCloudConfigurations(true); + public static Stream parameters() { + return TestParametersUtil2.getKieBaseCloudConfigurations(true).stream(); } - @Test - public void testExistsIterativeModifyBug() { + @ParameterizedTest(name = "KieBase type={0}") + @MethodSource("parameters") + public void testExistsIterativeModifyBug(KieBaseTestConfiguration kieBaseTestConfiguration) { // JBRULES-2809 // This bug occurs when a tuple is modified, the remove/add puts it onto the memory end // However before this was done it would attempt to find the next tuple, starting from itself @@ -113,8 +105,9 @@ public void testExistsIterativeModifyBug() { } } - @Test - public void testNodeSharingNotExists() { + @ParameterizedTest(name = "KieBase type={0}") + @MethodSource("parameters") + public void testNodeSharingNotExists(KieBaseTestConfiguration kieBaseTestConfiguration) { final String drl = "package org.drools.compiler.integrationtests.operators;\n" + "import " + Cheese.class.getCanonicalName() + ";\n" + @@ -156,8 +149,9 @@ public void testNodeSharingNotExists() { } } - @Test - public void testLastMemoryEntryExistsBug() { + @ParameterizedTest(name = "KieBase type={0}") + @MethodSource("parameters") + public void testLastMemoryEntryExistsBug(KieBaseTestConfiguration kieBaseTestConfiguration) { // JBRULES-2809 // This occurs when a blocker is the last in the node's memory, or if there is only one fact in the node // And it gets no opportunity to rematch with itself @@ -208,8 +202,9 @@ public void testLastMemoryEntryExistsBug() { } } - @Test - public void testExistsWithOrAndSubnetwork() { + @ParameterizedTest(name = "KieBase type={0}") + @MethodSource("parameters") + public void testExistsWithOrAndSubnetwork(KieBaseTestConfiguration kieBaseTestConfiguration) { // DROOLS-6550 final String drl = "package org.drools.compiler.integrationtests.operators;\n" + @@ -245,8 +240,9 @@ public void testExistsWithOrAndSubnetwork() { } } - @Test - public void testSharedExistsWithNot() { + @ParameterizedTest(name = "KieBase type={0}") + @MethodSource("parameters") + public void testSharedExistsWithNot(KieBaseTestConfiguration kieBaseTestConfiguration) { // DROOLS-6710 final String drl = "package org.drools.compiler.integrationtests.operators;\n" + @@ -289,8 +285,9 @@ public void testSharedExistsWithNot() { } } - @Test - public void existsAndNotWithSingleCoercion_shouldNotMatchExists() { + @ParameterizedTest(name = "KieBase type={0}") + @MethodSource("parameters") + public void existsAndNotWithSingleCoercion_shouldNotMatchExists(KieBaseTestConfiguration kieBaseTestConfiguration) { // KIE-766 final String drl = "package org.drools.compiler.integrationtests.operators;\n" + @@ -331,8 +328,9 @@ public void existsAndNotWithSingleCoercion_shouldNotMatchExists() { } } - @Test - public void existsAndNotWithMultipleCoercion_shouldNotMatchExists() { + @ParameterizedTest(name = "KieBase type={0}") + @MethodSource("parameters") + public void existsAndNotWithMultipleCoercion_shouldNotMatchExists(KieBaseTestConfiguration kieBaseTestConfiguration) { // KIE-766 final String drl = "package org.drools.compiler.integrationtests.operators;\n" + @@ -373,8 +371,9 @@ public void existsAndNotWithMultipleCoercion_shouldNotMatchExists() { } } - @Test - public void existsAndNotWithBigDecimals_shouldNotMatchExists() { + @ParameterizedTest(name = "KieBase type={0}") + @MethodSource("parameters") + public void existsAndNotWithBigDecimals_shouldNotMatchExists(KieBaseTestConfiguration kieBaseTestConfiguration) { // KIE-766 final String drl = "package org.drools.compiler.integrationtests.operators;\n" + diff --git a/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/compiler/integrationtests/operators/ForAllTest.java b/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/compiler/integrationtests/operators/ForAllTest.java index 6ece353028a..7b1a6f500bf 100644 --- a/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/compiler/integrationtests/operators/ForAllTest.java +++ b/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/compiler/integrationtests/operators/ForAllTest.java @@ -20,131 +20,138 @@ import java.text.SimpleDateFormat; import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collection; import java.util.Collections; import java.util.Date; import java.util.List; import java.util.Locale; +import java.util.stream.Stream; import org.drools.testcoverage.common.model.Person; import org.drools.testcoverage.common.util.KieBaseTestConfiguration; import org.drools.testcoverage.common.util.KieBaseUtil; -import org.drools.testcoverage.common.util.TestParametersUtil; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; +import org.drools.testcoverage.common.util.TestParametersUtil2; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; import org.kie.api.KieBase; import org.kie.api.definition.type.FactType; import org.kie.api.runtime.KieSession; import static org.assertj.core.api.Assertions.assertThat; -@RunWith(Parameterized.class) public class ForAllTest { - private final KieBaseTestConfiguration kieBaseTestConfiguration; - - public ForAllTest(final KieBaseTestConfiguration kieBaseTestConfiguration) { - this.kieBaseTestConfiguration = kieBaseTestConfiguration; - } - - @Parameterized.Parameters(name = "KieBase type={0}") - public static Collection getParameters() { - return TestParametersUtil.getKieBaseCloudConfigurations(true); + public static Stream parameters() { + return TestParametersUtil2.getKieBaseCloudConfigurations(true).stream(); } - @Test - public void test1P1CFiring1() { - check("age >= 18", 1, new Person("Mario", 45)); + @ParameterizedTest(name = "KieBase type={0}") + @MethodSource("parameters") + public void test1P1CFiring1(KieBaseTestConfiguration kieBaseTestConfiguration) { + check(kieBaseTestConfiguration, "age >= 18", 1, new Person("Mario", 45)); } - @Test - public void test1P1CFiring2() { - check("age == 8 || == 45", 1, new Person("Mario", 45), new Person("Sofia", 8)); + @ParameterizedTest(name = "KieBase type={0}") + @MethodSource("parameters") + public void test1P1CFiring2(KieBaseTestConfiguration kieBaseTestConfiguration) { + check(kieBaseTestConfiguration, "age == 8 || == 45", 1, new Person("Mario", 45), new Person("Sofia", 8)); } - @Test - public void test1P1CNotFiring() { - check("age >= 18", 0, new Person("Sofia", 8)); + @ParameterizedTest(name = "KieBase type={0}") + @MethodSource("parameters") + public void test1P1CNotFiring(KieBaseTestConfiguration kieBaseTestConfiguration) { + check(kieBaseTestConfiguration, "age >= 18", 0, new Person("Sofia", 8)); } - @Test - public void test1P1CNotFiringWithAnd() { - check("name == \"Sofia\" && age >= 18", 0, new Person("Sofia", 8)); + @ParameterizedTest(name = "KieBase type={0}") + @MethodSource("parameters") + public void test1P1CNotFiringWithAnd(KieBaseTestConfiguration kieBaseTestConfiguration) { + check(kieBaseTestConfiguration, "name == \"Sofia\" && age >= 18", 0, new Person("Sofia", 8)); } - @Test - public void test1P1CNotFiringWithParenthesis() { - check("(name == \"Sofia\" && age >= 18)", 0, new Person("Sofia", 8)); + @ParameterizedTest(name = "KieBase type={0}") + @MethodSource("parameters") + public void test1P1CNotFiringWithParenthesis(KieBaseTestConfiguration kieBaseTestConfiguration) { + check(kieBaseTestConfiguration, "(name == \"Sofia\" && age >= 18)", 0, new Person("Sofia", 8)); } - @Test - public void test1P1CNotFiringWithOr() { - check("age >= 18 || name == \"Mario\"", 0, new Person("Sofia", 8)); + @ParameterizedTest(name = "KieBase type={0}") + @MethodSource("parameters") + public void test1P1CNotFiringWithOr(KieBaseTestConfiguration kieBaseTestConfiguration) { + check(kieBaseTestConfiguration, "age >= 18 || name == \"Mario\"", 0, new Person("Sofia", 8)); } - @Test - public void test1P1CNotFiringWithParenthesisAndOr() { - check("(name == \"Sofia\" && age >= 18) || name == \"Mario\"", 0, new Person("Sofia", 8)); + @ParameterizedTest(name = "KieBase type={0}") + @MethodSource("parameters") + public void test1P1CNotFiringWithParenthesisAndOr(KieBaseTestConfiguration kieBaseTestConfiguration) { + check(kieBaseTestConfiguration, "(name == \"Sofia\" && age >= 18) || name == \"Mario\"", 0, new Person("Sofia", 8)); } - @Test - public void test1P2CFiring() { - check("age >= 18, name.startsWith(\"M\")", 1, new Person("Mario", 45), new Person("Mark", 43)); + @ParameterizedTest(name = "KieBase type={0}") + @MethodSource("parameters") + public void test1P2CFiring(KieBaseTestConfiguration kieBaseTestConfiguration) { + check(kieBaseTestConfiguration, "age >= 18, name.startsWith(\"M\")", 1, new Person("Mario", 45), new Person("Mark", 43)); } - @Test - public void test1P2CFiringWithIn() { - check("age >= 18, name in(\"Mario\", \"Mark\")", 1, new Person("Mario", 45), new Person("Mark", 43)); + @ParameterizedTest(name = "KieBase type={0}") + @MethodSource("parameters") + public void test1P2CFiringWithIn(KieBaseTestConfiguration kieBaseTestConfiguration) { + check(kieBaseTestConfiguration, "age >= 18, name in(\"Mario\", \"Mark\")", 1, new Person("Mario", 45), new Person("Mark", 43)); } - @Test - public void test1P2CNotFiring1() { - check("age >= 18, name.startsWith(\"M\")", 0, new Person("Mario", 45), new Person("Mark", 43), new Person("Edson", 40)); + @ParameterizedTest(name = "KieBase type={0}") + @MethodSource("parameters") + public void test1P2CNotFiring1(KieBaseTestConfiguration kieBaseTestConfiguration) { + check(kieBaseTestConfiguration, "age >= 18, name.startsWith(\"M\")", 0, new Person("Mario", 45), new Person("Mark", 43), new Person("Edson", 40)); } - @Test - public void test1P2CNotFiring2() { - check("age < 18, name.startsWith(\"M\")", 0, new Person("Sofia", 8)); + @ParameterizedTest(name = "KieBase type={0}") + @MethodSource("parameters") + public void test1P2CNotFiring2(KieBaseTestConfiguration kieBaseTestConfiguration) { + check(kieBaseTestConfiguration, "age < 18, name.startsWith(\"M\")", 0, new Person("Sofia", 8)); } - @Test - public void test2P1CFiring() { - check("age >= 18", "name.startsWith(\"M\")", 1, new Person("Mario", 45), new Person("Sofia", 8)); + @ParameterizedTest(name = "KieBase type={0}") + @MethodSource("parameters") + public void test2P1CFiring(KieBaseTestConfiguration kieBaseTestConfiguration) { + check(kieBaseTestConfiguration, "age >= 18", "name.startsWith(\"M\")", 1, new Person("Mario", 45), new Person("Sofia", 8)); } - @Test - public void test2P1CNotFiring() { - check("age >= 1", "name.startsWith(\"M\")", 0, new Person("Mario", 45), new Person("Sofia", 8)); + @ParameterizedTest(name = "KieBase type={0}") + @MethodSource("parameters") + public void test2P1CNotFiring(KieBaseTestConfiguration kieBaseTestConfiguration) { + check(kieBaseTestConfiguration, "age >= 1", "name.startsWith(\"M\")", 0, new Person("Mario", 45), new Person("Sofia", 8)); } - @Test - public void test2P2CFiring() { - check("", "age >= 18, name.startsWith(\"M\")", 1, new Person("Mario", 45), new Person("Mark", 43)); + @ParameterizedTest(name = "KieBase type={0}") + @MethodSource("parameters") + public void test2P2CFiring(KieBaseTestConfiguration kieBaseTestConfiguration) { + check(kieBaseTestConfiguration, "", "age >= 18, name.startsWith(\"M\")", 1, new Person("Mario", 45), new Person("Mark", 43)); } - @Test - public void test2P2CNotFiring1() { - check("", "age >= 18, name.startsWith(\"M\")", 0, new Person("Mario", 45), new Person("Mark", 43), new Person("Edson", 40)); + @ParameterizedTest(name = "KieBase type={0}") + @MethodSource("parameters") + public void test2P2CNotFiring1(KieBaseTestConfiguration kieBaseTestConfiguration) { + check(kieBaseTestConfiguration, "", "age >= 18, name.startsWith(\"M\")", 0, new Person("Mario", 45), new Person("Mark", 43), new Person("Edson", 40)); } - @Test - public void test2P3CFiring() { - check("name.length() < 6", "age >= 18, name.startsWith(\"M\")", 1, new Person("Mario", 45), new Person("Mark", 43), new Person("Daniele", 43)); + @ParameterizedTest(name = "KieBase type={0}") + @MethodSource("parameters") + public void test2P3CFiring(KieBaseTestConfiguration kieBaseTestConfiguration) { + check(kieBaseTestConfiguration, "name.length() < 6", "age >= 18, name.startsWith(\"M\")", 1, new Person("Mario", 45), new Person("Mark", 43), new Person("Daniele", 43)); } - @Test - public void testNoFiring() { + @ParameterizedTest(name = "KieBase type={0}") + @MethodSource("parameters") + public void testNoFiring(KieBaseTestConfiguration kieBaseTestConfiguration) { // DROOLS-5915 - check("", "age >= 18", 0); + check(kieBaseTestConfiguration, "", "age >= 18", 0); } - private void check(String constraints1, int expectedFires, Object... objs) { - check( constraints1, null, expectedFires, objs ); + private void check(KieBaseTestConfiguration kieBaseTestConfiguration, String constraints1, int expectedFires, Object... objs) { + check( kieBaseTestConfiguration, constraints1, null, expectedFires, objs ); } - private void check(String constraints1, String constraints2, int expectedFires, Object... objs) { + private void check(KieBaseTestConfiguration kieBaseTestConfiguration, String constraints1, String constraints2, int expectedFires, Object... objs) { final String drl = "package org.drools.compiler.integrationtests.operators;\n" + "import " + Person.class.getCanonicalName() + ";\n" + @@ -173,8 +180,9 @@ private void check(String constraints1, String constraints2, int expectedFires, } } - @Test - public void testWithDate() throws Exception { + @ParameterizedTest(name = "KieBase type={0}") + @MethodSource("parameters") + public void testWithDate(KieBaseTestConfiguration kieBaseTestConfiguration) throws Exception { // DROOLS-4925 String pkg = "org.drools.compiler.integrationtests.operators"; @@ -206,8 +214,9 @@ public void testWithDate() throws Exception { assertThat(ksession.fireAllRules()).isEqualTo(1); } - @Test - public void testWithIndexedAlpha() throws Exception { + @ParameterizedTest(name = "KieBase type={0}") + @MethodSource("parameters") + public void testWithIndexedAlpha(KieBaseTestConfiguration kieBaseTestConfiguration) throws Exception { // DROOLS-5019 String pkg = "org.drools.compiler.integrationtests.operators"; @@ -237,8 +246,9 @@ public void testWithIndexedAlpha() throws Exception { assertThat(ksession2.fireAllRules()).isEqualTo(0); } - @Test - public void testForallWithNotEqualConstraint() throws Exception { + @ParameterizedTest(name = "KieBase type={0}") + @MethodSource("parameters") + public void testForallWithNotEqualConstraint(KieBaseTestConfiguration kieBaseTestConfiguration) throws Exception { // DROOLS-5100 String drl = @@ -256,8 +266,9 @@ public void testForallWithNotEqualConstraint() throws Exception { assertThat(ksession.fireAllRules()).isEqualTo(1); } - @Test - public void testForallWithNotEqualConstraintOnDate() throws Exception { + @ParameterizedTest(name = "KieBase type={0}") + @MethodSource("parameters") + public void testForallWithNotEqualConstraintOnDate(KieBaseTestConfiguration kieBaseTestConfiguration) throws Exception { // DROOLS-5224 String drl = @@ -316,17 +327,19 @@ public String toString() { } } - @Test - public void testForallWithEmptyListConstraintCombinedWithOrFiring() throws Exception { - checkForallWithEmptyListConstraintCombinedWithOrFiring(true); + @ParameterizedTest(name = "KieBase type={0}") + @MethodSource("parameters") + public void testForallWithEmptyListConstraintCombinedWithOrFiring(KieBaseTestConfiguration kieBaseTestConfiguration) throws Exception { + checkForallWithEmptyListConstraintCombinedWithOrFiring(kieBaseTestConfiguration, true); } - @Test - public void testForallWithEmptyListConstraintCombinedWithOrNotFiring() throws Exception { - checkForallWithEmptyListConstraintCombinedWithOrFiring(false); + @ParameterizedTest(name = "KieBase type={0}") + @MethodSource("parameters") + public void testForallWithEmptyListConstraintCombinedWithOrNotFiring(KieBaseTestConfiguration kieBaseTestConfiguration) throws Exception { + checkForallWithEmptyListConstraintCombinedWithOrFiring(kieBaseTestConfiguration, false); } - private void checkForallWithEmptyListConstraintCombinedWithOrFiring(boolean firing) { + private void checkForallWithEmptyListConstraintCombinedWithOrFiring(KieBaseTestConfiguration kieBaseTestConfiguration, boolean firing) { // DROOLS-5682 String drl = @@ -348,39 +361,45 @@ private void checkForallWithEmptyListConstraintCombinedWithOrFiring(boolean firi assertThat(ksession.fireAllRules()).isEqualTo(firing ? 1 : 0); } - @Test - public void testForallWithMultipleConstraints() throws Exception { - checkForallWithComplexExpression("value > 1, value < 10"); + @ParameterizedTest(name = "KieBase type={0}") + @MethodSource("parameters") + public void testForallWithMultipleConstraints(KieBaseTestConfiguration kieBaseTestConfiguration) throws Exception { + checkForallWithComplexExpression(kieBaseTestConfiguration, "value > 1, value < 10"); } - @Test - public void testForallWithAnd() throws Exception { - checkForallWithComplexExpression("value > 1 && value < 10"); + @ParameterizedTest(name = "KieBase type={0}") + @MethodSource("parameters") + public void testForallWithAnd(KieBaseTestConfiguration kieBaseTestConfiguration) throws Exception { + checkForallWithComplexExpression(kieBaseTestConfiguration, "value > 1 && value < 10"); } - @Test - public void testForallWithAndInMultipleConstraints() throws Exception { - checkForallWithComplexExpression("value > 1, value > 2 && value < 10"); + @ParameterizedTest(name = "KieBase type={0}") + @MethodSource("parameters") + public void testForallWithAndInMultipleConstraints(KieBaseTestConfiguration kieBaseTestConfiguration) throws Exception { + checkForallWithComplexExpression(kieBaseTestConfiguration, "value > 1, value > 2 && value < 10"); } - @Test - public void testForallWithOr() throws Exception { - checkForallWithComplexExpression("value < 1 || value > 50"); + @ParameterizedTest(name = "KieBase type={0}") + @MethodSource("parameters") + public void testForallWithOr(KieBaseTestConfiguration kieBaseTestConfiguration) throws Exception { + checkForallWithComplexExpression(kieBaseTestConfiguration, "value < 1 || value > 50"); } - @Test - public void testForallWithIn() throws Exception { + @ParameterizedTest(name = "KieBase type={0}") + @MethodSource("parameters") + public void testForallWithIn(KieBaseTestConfiguration kieBaseTestConfiguration) throws Exception { // DROOLS-6560 - checkForallWithComplexExpression("value in (1, 43)"); + checkForallWithComplexExpression(kieBaseTestConfiguration, "value in (1, 43)"); } - @Test - public void testForallWithNotIn() throws Exception { + @ParameterizedTest(name = "KieBase type={0}") + @MethodSource("parameters") + public void testForallWithNotIn(KieBaseTestConfiguration kieBaseTestConfiguration) throws Exception { // DROOLS-6560 - checkForallWithComplexExpression("value not in (1, 42)"); + checkForallWithComplexExpression(kieBaseTestConfiguration, "value not in (1, 42)"); } - private void checkForallWithComplexExpression(String expression) throws Exception { + private void checkForallWithComplexExpression(KieBaseTestConfiguration kieBaseTestConfiguration, String expression) throws Exception { // DROOLS-6469 String drl = "package test\n" + diff --git a/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/compiler/integrationtests/operators/FormulaTest.java b/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/compiler/integrationtests/operators/FormulaTest.java index eea8a94149c..fd2efe890f7 100644 --- a/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/compiler/integrationtests/operators/FormulaTest.java +++ b/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/compiler/integrationtests/operators/FormulaTest.java @@ -18,36 +18,28 @@ */ package org.drools.compiler.integrationtests.operators; -import java.util.Collection; +import java.util.stream.Stream; import org.drools.testcoverage.common.model.Person; import org.drools.testcoverage.common.util.KieBaseTestConfiguration; import org.drools.testcoverage.common.util.KieBaseUtil; -import org.drools.testcoverage.common.util.TestParametersUtil; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; +import org.drools.testcoverage.common.util.TestParametersUtil2; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; import org.kie.api.KieBase; import org.kie.api.runtime.KieSession; import static org.assertj.core.api.Assertions.assertThat; -@RunWith(Parameterized.class) public class FormulaTest { - private final KieBaseTestConfiguration kieBaseTestConfiguration; - - public FormulaTest(final KieBaseTestConfiguration kieBaseTestConfiguration) { - this.kieBaseTestConfiguration = kieBaseTestConfiguration; - } - - @Parameterized.Parameters(name = "KieBase type={0}") - public static Collection getParameters() { - return TestParametersUtil.getKieBaseCloudConfigurations(true); + public static Stream parameters() { + return TestParametersUtil2.getKieBaseCloudConfigurations(true).stream(); } - @Test - public void testConstants() { + @ParameterizedTest(name = "KieBase type={0}") + @MethodSource("parameters") + public void testConstants(KieBaseTestConfiguration kieBaseTestConfiguration) { final String drl = "package org.drools.compiler.integrationtests.operators;\n" + "import " + Person.class.getCanonicalName() + ";\n" + @@ -74,8 +66,9 @@ public void testConstants() { } } - @Test - public void testBoundField() { + @ParameterizedTest(name = "KieBase type={0}") + @MethodSource("parameters") + public void testBoundField(KieBaseTestConfiguration kieBaseTestConfiguration) { final String drl = "package org.drools.compiler.integrationtests.operators;\n" + "import " + Person.class.getCanonicalName() + ";\n" + diff --git a/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/compiler/integrationtests/operators/FromOnlyExecModelTest.java b/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/compiler/integrationtests/operators/FromOnlyExecModelTest.java index 290736d2d63..c30ab9cce99 100644 --- a/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/compiler/integrationtests/operators/FromOnlyExecModelTest.java +++ b/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/compiler/integrationtests/operators/FromOnlyExecModelTest.java @@ -18,34 +18,28 @@ */ package org.drools.compiler.integrationtests.operators; -import java.util.Collection; import java.util.HashMap; +import java.util.stream.Stream; import org.drools.testcoverage.common.util.KieBaseTestConfiguration; import org.drools.model.functions.NativeImageTestUtil; -import org.drools.testcoverage.common.util.TestParametersUtil; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; +import org.drools.testcoverage.common.util.TestParametersUtil2; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; import static org.drools.compiler.integrationtests.operators.FromTest.testFromSharingCommon; -@RunWith(Parameterized.class) public class FromOnlyExecModelTest { - protected final KieBaseTestConfiguration kieBaseTestConfiguration; - public FromOnlyExecModelTest(KieBaseTestConfiguration kieBaseTestConfiguration1) { - this.kieBaseTestConfiguration = kieBaseTestConfiguration1; + public static Stream parameters() { + return TestParametersUtil2.getKieBaseCloudOnlyExecModelConfiguration().stream(); } - @Parameterized.Parameters(name = "KieBase type={0}") - public static Collection getParameters() { - return TestParametersUtil.getKieBaseCloudOnlyExecModelConfiguration(); - } - - @Test // KOGITO-3771 - public void testFromSharingWithNativeImage() { + // KOGITO-3771 + @ParameterizedTest + @MethodSource("parameters") + public void testFromSharingWithNativeImage(KieBaseTestConfiguration kieBaseTestConfiguration) { try { NativeImageTestUtil.setNativeImage(); testFromSharingCommon(kieBaseTestConfiguration, new HashMap<>(), 2, 2); @@ -55,8 +49,9 @@ public void testFromSharingWithNativeImage() { } // This test that the node sharing isn't working without lambda externalisation - @Test - public void testFromSharingWithNativeImageWithoutLambdaExternalisation() { + @ParameterizedTest(name = "KieBase type={0}") + @MethodSource("parameters") + public void testFromSharingWithNativeImageWithoutLambdaExternalisation(KieBaseTestConfiguration kieBaseTestConfiguration) { try { NativeImageTestUtil.setNativeImage(); HashMap properties = new HashMap<>(); diff --git a/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/compiler/integrationtests/operators/FromTest.java b/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/compiler/integrationtests/operators/FromTest.java index 212c091146d..de7fe255ae3 100644 --- a/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/compiler/integrationtests/operators/FromTest.java +++ b/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/compiler/integrationtests/operators/FromTest.java @@ -20,7 +20,6 @@ import java.util.ArrayList; import java.util.Arrays; -import java.util.Collection; import java.util.HashMap; import java.util.List; import java.util.Map; @@ -50,11 +49,10 @@ import org.drools.testcoverage.common.util.KieBaseUtil; import org.drools.testcoverage.common.util.KieSessionTestConfiguration; import org.drools.testcoverage.common.util.KieUtil; -import org.drools.testcoverage.common.util.TestParametersUtil; -import org.junit.Ignore; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; +import org.drools.testcoverage.common.util.TestParametersUtil2; +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; import org.kie.api.KieBase; import org.kie.api.KieBaseConfiguration; import org.kie.api.KieServices; @@ -70,18 +68,10 @@ import static org.assertj.core.api.Assertions.assertThat; -@RunWith(Parameterized.class) public class FromTest { - private final KieBaseTestConfiguration kieBaseTestConfiguration; - - public FromTest(final KieBaseTestConfiguration kieBaseTestConfiguration) { - this.kieBaseTestConfiguration = kieBaseTestConfiguration; - } - - @Parameterized.Parameters(name = "KieBase type={0}") - public static Collection getParameters() { - return TestParametersUtil.getKieBaseCloudConfigurations(true); + public static Stream parameters() { + return TestParametersUtil2.getKieBaseCloudConfigurations(true).stream(); } public static class ListsContainer { @@ -97,8 +87,9 @@ public Number getSingleValue() { } - @Test - public void testFromSharing() { + @ParameterizedTest(name = "KieBase type={0}") + @MethodSource("parameters") + public void testFromSharing(KieBaseTestConfiguration kieBaseTestConfiguration) { testFromSharingCommon(kieBaseTestConfiguration, new HashMap<>(), 2, 2); } @@ -144,8 +135,9 @@ public static void testFromSharingCommon(KieBaseTestConfiguration kieBaseTestCon } } - @Test - public void testFromSharingWithPropertyReactive() { + @ParameterizedTest(name = "KieBase type={0}") + @MethodSource("parameters") + public void testFromSharingWithPropertyReactive(KieBaseTestConfiguration kieBaseTestConfiguration) { // As above but with property reactive as default final String drl = fromSharingRule(); // property reactive as default: @@ -218,8 +210,9 @@ private static ObjectTypeNode insertObjectFireRules(InternalKnowledgeBase kbase, return epn.getObjectTypeNodes().get(new ClassObjectType(ListsContainer.class)); } - @Test - public void testFromSharingWithAccumulate() { + @ParameterizedTest(name = "KieBase type={0}") + @MethodSource("parameters") + public void testFromSharingWithAccumulate(KieBaseTestConfiguration kieBaseTestConfiguration) { final String drl = "package org.drools.compiler.integrationtests.operators;\n" + "\n" + @@ -299,8 +292,9 @@ public void testFromSharingWithAccumulate() { } } - @Test - public void testFromWithSingleValue() { + @ParameterizedTest(name = "KieBase type={0}") + @MethodSource("parameters") + public void testFromWithSingleValue(KieBaseTestConfiguration kieBaseTestConfiguration) { // DROOLS-1243 final String drl = "import " + ListsContainer.class.getCanonicalName() + "\n" + @@ -330,8 +324,9 @@ public void testFromWithSingleValue() { } } - @Test - public void testFromWithSingleValueAndIncompatibleType() { + @ParameterizedTest(name = "KieBase type={0}") + @MethodSource("parameters") + public void testFromWithSingleValueAndIncompatibleType(KieBaseTestConfiguration kieBaseTestConfiguration) { // DROOLS-1243 final String drl = "import " + ListsContainer.class.getCanonicalName() + "\n" + @@ -358,8 +353,9 @@ public Number getSingleValue() { return this.wrapped; } } - @Test - public void testFromWithInterfaceAndAbstractClass() { + @ParameterizedTest(name = "KieBase type={0}") + @MethodSource("parameters") + public void testFromWithInterfaceAndAbstractClass(KieBaseTestConfiguration kieBaseTestConfiguration) { final String drl = "import " + Container2.class.getCanonicalName() + "\n" + "import " + Comparable.class.getCanonicalName() + "\n" + @@ -411,8 +407,9 @@ public CustomInteger(final int initialValue) { super(initialValue); } } - @Test - public void testFromWithInterfaceAndConcreteClass() { + @ParameterizedTest(name = "KieBase type={0}") + @MethodSource("parameters") + public void testFromWithInterfaceAndConcreteClass(KieBaseTestConfiguration kieBaseTestConfiguration) { final String drl = "import " + Container2b.class.getCanonicalName() + "\n" + "import " + CustomIntegerMarker.class.getCanonicalName() + "\n" + @@ -459,8 +456,9 @@ public Integer getSingleValue() { } } - @Test - public void testFromWithInterfaceAndFinalClass() { + @ParameterizedTest(name = "KieBase type={0}") + @MethodSource("parameters") + public void testFromWithInterfaceAndFinalClass(KieBaseTestConfiguration kieBaseTestConfiguration) { final String drl = "import " + Container3.class.getCanonicalName() + "\n" + "import " + CustomIntegerMarker.class.getCanonicalName() + "\n" + @@ -478,8 +476,9 @@ public void testFromWithInterfaceAndFinalClass() { assertThat(kieBuilder.getResults().getMessages()).isNotEmpty(); } - @Test - public void testBasicFrom() { + @ParameterizedTest(name = "KieBase type={0}") + @MethodSource("parameters") + public void testBasicFrom(KieBaseTestConfiguration kieBaseTestConfiguration) { final String drl = "package org.drools.compiler.integrationtests.operators;\n" + "import " + Cheese.class.getCanonicalName() + ";\n" + @@ -578,8 +577,10 @@ public List toList(final Object object1, } } - @Test @Ignore - public void testFromWithParams() { + @ParameterizedTest(name = "KieBase type={0}") + @MethodSource("parameters") + @Disabled + public void testFromWithParams(KieBaseTestConfiguration kieBaseTestConfiguration) { final String drl = "package org.drools.compiler.integrationtests.operators;\n" + " \n" + @@ -666,8 +667,9 @@ public Query(String pattern, String column) { } } - @Test - public void testFromWithNewConstructor() { + @ParameterizedTest(name = "KieBase type={0}") + @MethodSource("parameters") + public void testFromWithNewConstructor(KieBaseTestConfiguration kieBaseTestConfiguration) { final String drl = "package org.drools.compiler.integrationtests.operators\n" + "\n" + @@ -693,8 +695,9 @@ public void testFromWithNewConstructor() { /** * JBRULES-1415 Certain uses of from causes NullPointerException in WorkingMemoryLogger */ - @Test - public void testFromDeclarationWithWorkingMemoryLogger() { + @ParameterizedTest(name = "KieBase type={0}") + @MethodSource("parameters") + public void testFromDeclarationWithWorkingMemoryLogger(KieBaseTestConfiguration kieBaseTestConfiguration) { final String drl = "package org.drools.compiler.integrationtests.operators;\n" + "import " + Cheesery.class.getCanonicalName() + ";\n" + "import " + Cheese.class.getCanonicalName() + ";\n" + @@ -729,8 +732,9 @@ public void testFromDeclarationWithWorkingMemoryLogger() { } } - @Test - public void testFromArrayIteration() { + @ParameterizedTest(name = "KieBase type={0}") + @MethodSource("parameters") + public void testFromArrayIteration(KieBaseTestConfiguration kieBaseTestConfiguration) { final String drl = "package org.drools.compiler.integrationtests.operators;\n" + "import " + DomainObject.class.getCanonicalName() + ";\n" + @@ -766,8 +770,9 @@ public void testFromArrayIteration() { } } - @Test - public void testFromExprFollowedByNot() { + @ParameterizedTest(name = "KieBase type={0}") + @MethodSource("parameters") + public void testFromExprFollowedByNot(KieBaseTestConfiguration kieBaseTestConfiguration) { final String drl = "package org.drools.compiler.integrationtests.operators;\n" + "import " + Person.class.getCanonicalName() + ";\n" + @@ -802,8 +807,9 @@ public void testFromExprFollowedByNot() { } } - @Test - public void testFromNestedAccessors() { + @ParameterizedTest(name = "KieBase type={0}") + @MethodSource("parameters") + public void testFromNestedAccessors(KieBaseTestConfiguration kieBaseTestConfiguration) { final String drl = "package org.drools.compiler.integrationtests.operators;\n" + "import " + Order.class.getCanonicalName() + ";\n" + @@ -843,8 +849,9 @@ public void testFromNestedAccessors() { } } - @Test - public void testFromNodeWithMultipleBetas() { + @ParameterizedTest(name = "KieBase type={0}") + @MethodSource("parameters") + public void testFromNodeWithMultipleBetas(KieBaseTestConfiguration kieBaseTestConfiguration) { final String drl = "import " + Person.class.getCanonicalName() + ";\n" + "import " + Cheese.class.getCanonicalName() + ";\n" + "import " + Address.class.getCanonicalName() + ";\n" + @@ -872,8 +879,9 @@ public void testFromNodeWithMultipleBetas() { } } - @Test - public void testFromWithStrictModeOn() { + @ParameterizedTest(name = "KieBase type={0}") + @MethodSource("parameters") + public void testFromWithStrictModeOn(KieBaseTestConfiguration kieBaseTestConfiguration) { // JBRULES-3533 final String drl = "import java.util.Map;\n" + @@ -892,17 +900,19 @@ public void testFromWithStrictModeOn() { assertThat(kieBuilder.getResults().getMessages()).isNotEmpty(); } - @Test - public void testJavaImplicitWithFrom() { - testDialectWithFrom("java"); + @ParameterizedTest(name = "KieBase type={0}") + @MethodSource("parameters") + public void testJavaImplicitWithFrom(KieBaseTestConfiguration kieBaseTestConfiguration) { + testDialectWithFrom(kieBaseTestConfiguration, "java"); } - @Test - public void testMVELImplicitWithFrom() { - testDialectWithFrom("mvel"); + @ParameterizedTest(name = "KieBase type={0}") + @MethodSource("parameters") + public void testMVELImplicitWithFrom(KieBaseTestConfiguration kieBaseTestConfiguration) { + testDialectWithFrom(kieBaseTestConfiguration, "mvel"); } - private void testDialectWithFrom(final String dialect) { + private void testDialectWithFrom(KieBaseTestConfiguration kieBaseTestConfiguration, final String dialect) { final String drl = "" + "package org.drools.compiler.test \n" + "import java.util.List \n" + @@ -931,8 +941,9 @@ private void testDialectWithFrom(final String dialect) { } } - @Test - public void testMultipleFroms() { + @ParameterizedTest(name = "KieBase type={0}") + @MethodSource("parameters") + public void testMultipleFroms(KieBaseTestConfiguration kieBaseTestConfiguration) { final String drl = "package org.drools.compiler.integrationtests.operators;\n" + "import java.util.List;\n" + @@ -975,8 +986,9 @@ public void testMultipleFroms() { } } - @Test - public void testNetworkBuildErrorAcrossEntryPointsAndFroms() { + @ParameterizedTest(name = "KieBase type={0}") + @MethodSource("parameters") + public void testNetworkBuildErrorAcrossEntryPointsAndFroms(KieBaseTestConfiguration kieBaseTestConfiguration) { final String drl = "package org.drools.compiler.integrationtests.operators;\n" + "import " + Person.class.getCanonicalName() + ";\n" + "import " + Cheese.class.getCanonicalName() + ";\n" + @@ -1016,8 +1028,9 @@ public void testNetworkBuildErrorAcrossEntryPointsAndFroms() { } } - @Test - public void testUpdateFromCollect() { + @ParameterizedTest(name = "KieBase type={0}") + @MethodSource("parameters") + public void testUpdateFromCollect(KieBaseTestConfiguration kieBaseTestConfiguration) { // DROOLS-6504 final String drl = "import " + List.class.getCanonicalName() + ";\n" + @@ -1088,25 +1101,27 @@ public List getValues() { " modify($p){setAge(10)};\n" + "end\n"; - @Test - public void testJoinAndFrom() { + @ParameterizedTest(name = "KieBase type={0}") + @MethodSource("parameters") + public void testJoinAndFrom(KieBaseTestConfiguration kieBaseTestConfiguration) { // DROOLS-6821 // Add JoinNode first - runKSessionWithAgendaGroup(RULE_HEAD + + runKSessionWithAgendaGroup(kieBaseTestConfiguration, RULE_HEAD + RULE_WITH_JOIN + RULE_WITH_FROM); } - @Test - public void testFromAndJoin() { + @ParameterizedTest(name = "KieBase type={0}") + @MethodSource("parameters") + public void testFromAndJoin(KieBaseTestConfiguration kieBaseTestConfiguration) { // DROOLS-6821 // Add FromNode first - runKSessionWithAgendaGroup(RULE_HEAD + + runKSessionWithAgendaGroup(kieBaseTestConfiguration, RULE_HEAD + RULE_WITH_FROM + RULE_WITH_JOIN); } - private void runKSessionWithAgendaGroup(String drl) { + private void runKSessionWithAgendaGroup(KieBaseTestConfiguration kieBaseTestConfiguration, String drl) { final KieBase kbase = KieBaseUtil.getKieBaseFromKieModuleFromDrl("from-test", kieBaseTestConfiguration, drl); diff --git a/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/compiler/integrationtests/operators/InTest.java b/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/compiler/integrationtests/operators/InTest.java index f1e28fec62d..dd232dbdf94 100644 --- a/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/compiler/integrationtests/operators/InTest.java +++ b/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/compiler/integrationtests/operators/InTest.java @@ -18,36 +18,29 @@ */ package org.drools.compiler.integrationtests.operators; -import java.util.Collection; +import java.util.stream.Stream; import org.drools.testcoverage.common.model.Person; import org.drools.testcoverage.common.util.KieBaseTestConfiguration; import org.drools.testcoverage.common.util.KieBaseUtil; -import org.drools.testcoverage.common.util.TestParametersUtil; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; +import org.drools.testcoverage.common.util.TestParametersUtil2; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; import org.kie.api.KieBase; import org.kie.api.runtime.KieSession; import static org.assertj.core.api.Assertions.assertThat; -@RunWith(Parameterized.class) public class InTest { - private final KieBaseTestConfiguration kieBaseTestConfiguration; - public InTest(final KieBaseTestConfiguration kieBaseTestConfiguration) { - this.kieBaseTestConfiguration = kieBaseTestConfiguration; + public static Stream parameters() { + return TestParametersUtil2.getKieBaseCloudConfigurations(true).stream(); } - @Parameterized.Parameters(name = "KieBase type={0}") - public static Collection getParameters() { - return TestParametersUtil.getKieBaseCloudConfigurations(true); - } - - @Test - public void testInOperator() { + @ParameterizedTest(name = "KieBase type={0}") + @MethodSource("parameters") + public void testInOperator(KieBaseTestConfiguration kieBaseTestConfiguration) { final String drl = "package org.drools.compiler.integrationtests.operators;\n" + "import " + Person.class.getCanonicalName() + ";\n" + "rule \"test in\"\n" + @@ -78,8 +71,9 @@ public void testInOperator() { } } - @Test - public void testNegatedIn() { + @ParameterizedTest(name = "KieBase type={0}") + @MethodSource("parameters") + public void testNegatedIn(KieBaseTestConfiguration kieBaseTestConfiguration) { final String drl = "package org.drools.compiler.integrationtests.operators;\n" + "import " + Person.class.getCanonicalName() + ";\n" + "rule \"test negated in\"\n" + diff --git a/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/compiler/integrationtests/operators/InstanceOfTest.java b/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/compiler/integrationtests/operators/InstanceOfTest.java index ec125b917ba..1d13b9e8953 100644 --- a/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/compiler/integrationtests/operators/InstanceOfTest.java +++ b/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/compiler/integrationtests/operators/InstanceOfTest.java @@ -18,37 +18,29 @@ */ package org.drools.compiler.integrationtests.operators; -import java.util.Collection; +import java.util.stream.Stream; import org.drools.testcoverage.common.model.LongAddress; import org.drools.testcoverage.common.model.Person; import org.drools.testcoverage.common.util.KieBaseTestConfiguration; import org.drools.testcoverage.common.util.KieBaseUtil; -import org.drools.testcoverage.common.util.TestParametersUtil; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; +import org.drools.testcoverage.common.util.TestParametersUtil2; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; import org.kie.api.KieBase; import org.kie.api.runtime.KieSession; import static org.assertj.core.api.Assertions.assertThat; -@RunWith(Parameterized.class) public class InstanceOfTest { - private final KieBaseTestConfiguration kieBaseTestConfiguration; - - public InstanceOfTest(final KieBaseTestConfiguration kieBaseTestConfiguration) { - this.kieBaseTestConfiguration = kieBaseTestConfiguration; - } - - @Parameterized.Parameters(name = "KieBase type={0}") - public static Collection getParameters() { - return TestParametersUtil.getKieBaseCloudConfigurations(true); + public static Stream parameters() { + return TestParametersUtil2.getKieBaseCloudConfigurations(true).stream(); } - @Test - public void testInstanceof() { + @ParameterizedTest(name = "KieBase type={0}") + @MethodSource("parameters") + public void testInstanceof(KieBaseTestConfiguration kieBaseTestConfiguration) { // JBRULES-3591 final String drl = "import " + Person.class.getCanonicalName() + ";\n" + "import " + LongAddress.class.getCanonicalName() + ";\n" + diff --git a/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/compiler/integrationtests/operators/MatchesTest.java b/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/compiler/integrationtests/operators/MatchesTest.java index 2019fd37f48..662d6c293d6 100644 --- a/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/compiler/integrationtests/operators/MatchesTest.java +++ b/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/compiler/integrationtests/operators/MatchesTest.java @@ -19,40 +19,32 @@ package org.drools.compiler.integrationtests.operators; import java.util.ArrayList; -import java.util.Collection; import java.util.HashMap; import java.util.List; import java.util.Map; +import java.util.stream.Stream; import org.drools.testcoverage.common.model.Cheese; import org.drools.testcoverage.common.model.Person; import org.drools.testcoverage.common.util.KieBaseTestConfiguration; import org.drools.testcoverage.common.util.KieBaseUtil; -import org.drools.testcoverage.common.util.TestParametersUtil; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; +import org.drools.testcoverage.common.util.TestParametersUtil2; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; import org.kie.api.KieBase; import org.kie.api.runtime.KieSession; import static org.assertj.core.api.Assertions.assertThat; -@RunWith(Parameterized.class) public class MatchesTest { - private final KieBaseTestConfiguration kieBaseTestConfiguration; - - public MatchesTest(final KieBaseTestConfiguration kieBaseTestConfiguration) { - this.kieBaseTestConfiguration = kieBaseTestConfiguration; - } - - @Parameterized.Parameters(name = "KieBase type={0}") - public static Collection getParameters() { - return TestParametersUtil.getKieBaseCloudConfigurations(true); + public static Stream parameters() { + return TestParametersUtil2.getKieBaseCloudConfigurations(true).stream(); } - @Test - public void testMatchesMVEL() { + @ParameterizedTest(name = "KieBase type={0}") + @MethodSource("parameters") + public void testMatchesMVEL(KieBaseTestConfiguration kieBaseTestConfiguration) { final String drl = "package org.drools.compiler.integrationtests.operators;\n" + "import java.util.Map;\n" + @@ -107,8 +99,9 @@ private String getMatchesDRL() { "end"; } - @Test - public void testMatchesMVEL2() { + @ParameterizedTest(name = "KieBase type={0}") + @MethodSource("parameters") + public void testMatchesMVEL2(KieBaseTestConfiguration kieBaseTestConfiguration) { final KieBase kbase = KieBaseUtil.getKieBaseFromKieModuleFromDrl("matches-test", kieBaseTestConfiguration, getMatchesDRL()); @@ -125,8 +118,9 @@ public void testMatchesMVEL2() { } } - @Test - public void testMatchesMVEL3() { + @ParameterizedTest(name = "KieBase type={0}") + @MethodSource("parameters") + public void testMatchesMVEL3(KieBaseTestConfiguration kieBaseTestConfiguration) { final KieBase kbase = KieBaseUtil.getKieBaseFromKieModuleFromDrl("matches-test", kieBaseTestConfiguration, getMatchesDRL()); @@ -143,8 +137,9 @@ public void testMatchesMVEL3() { } } - @Test - public void testMatchesNotMatchesCheese() { + @ParameterizedTest(name = "KieBase type={0}") + @MethodSource("parameters") + public void testMatchesNotMatchesCheese(KieBaseTestConfiguration kieBaseTestConfiguration) { final String drl = "package org.drools.compiler.integrationtests.operators;\n" + "import " + Cheese.class.getCanonicalName() + ";\n" + @@ -222,19 +217,21 @@ public void testMatchesNotMatchesCheese() { } } - @Test - public void testNotMatchesSucceeds() { + @ParameterizedTest(name = "KieBase type={0}") + @MethodSource("parameters") + public void testNotMatchesSucceeds(KieBaseTestConfiguration kieBaseTestConfiguration) { // JBRULES-2914: Rule misfires due to "not matches" not working - testMatchesSuccessFail("-..x..xrwx", 0); + testMatchesSuccessFail(kieBaseTestConfiguration, "-..x..xrwx", 0); } - @Test - public void testNotMatchesFails() { + @ParameterizedTest(name = "KieBase type={0}") + @MethodSource("parameters") + public void testNotMatchesFails(KieBaseTestConfiguration kieBaseTestConfiguration) { // JBRULES-2914: Rule misfires due to "not matches" not working - testMatchesSuccessFail("d..x..xrwx", 1); + testMatchesSuccessFail(kieBaseTestConfiguration, "d..x..xrwx", 1); } - private void testMatchesSuccessFail(final String personName, final int expectedFireCount) { + private void testMatchesSuccessFail(KieBaseTestConfiguration kieBaseTestConfiguration, final String personName, final int expectedFireCount) { final String drl = "package org.drools.compiler.integrationtests.operators;\n" + "import " + Person.class.getCanonicalName() + ";\n" + "rule NotMatches\n" + diff --git a/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/compiler/integrationtests/operators/MathTest.java b/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/compiler/integrationtests/operators/MathTest.java index b6aeac7eccd..9a305878136 100644 --- a/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/compiler/integrationtests/operators/MathTest.java +++ b/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/compiler/integrationtests/operators/MathTest.java @@ -20,39 +20,31 @@ import java.io.Serializable; import java.util.ArrayList; -import java.util.Collection; import java.util.List; import java.util.Random; +import java.util.stream.Stream; import org.drools.testcoverage.common.model.Person; import org.drools.testcoverage.common.util.KieBaseTestConfiguration; import org.drools.testcoverage.common.util.KieBaseUtil; -import org.drools.testcoverage.common.util.TestParametersUtil; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; +import org.drools.testcoverage.common.util.TestParametersUtil2; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; import org.kie.api.KieBase; import org.kie.api.runtime.KieSession; import org.kie.api.runtime.rule.FactHandle; import static org.assertj.core.api.Assertions.assertThat; -@RunWith(Parameterized.class) public class MathTest { - private final KieBaseTestConfiguration kieBaseTestConfiguration; - - public MathTest(final KieBaseTestConfiguration kieBaseTestConfiguration) { - this.kieBaseTestConfiguration = kieBaseTestConfiguration; - } - - @Parameterized.Parameters(name = "KieBase type={0}") - public static Collection getParameters() { - return TestParametersUtil.getKieBaseCloudConfigurations(true); + public static Stream parameters() { + return TestParametersUtil2.getKieBaseCloudConfigurations(true).stream(); } - @Test - public void testAddition() { + @ParameterizedTest(name = "KieBase type={0}") + @MethodSource("parameters") + public void testAddition(KieBaseTestConfiguration kieBaseTestConfiguration) { final String drl = "package org.drools.compiler.integrationtests.operators;\n" + "import " + Person.class.getCanonicalName() + ";\n" + @@ -118,8 +110,9 @@ public Integer getValue() { } - @Test - public void testNumberComparisons() { + @ParameterizedTest(name = "KieBase type={0}") + @MethodSource("parameters") + public void testNumberComparisons(KieBaseTestConfiguration kieBaseTestConfiguration) { final String drl = "package org.drools.compiler.integrationtests.operators;\n" + "import " + RandomNumber.class.getCanonicalName() + ";\n" + "import " + Guess.class.getCanonicalName() + ";\n" + @@ -197,8 +190,9 @@ public void testNumberComparisons() { } } - @Test - public void testShiftOperator() { + @ParameterizedTest(name = "KieBase type={0}") + @MethodSource("parameters") + public void testShiftOperator(KieBaseTestConfiguration kieBaseTestConfiguration) { final String drl = "dialect \"mvel\"\n" + "rule kickOff\n" + "when\n" + diff --git a/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/compiler/integrationtests/operators/MemberOfTest.java b/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/compiler/integrationtests/operators/MemberOfTest.java index 8bc640f4de1..70da7ae21ca 100644 --- a/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/compiler/integrationtests/operators/MemberOfTest.java +++ b/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/compiler/integrationtests/operators/MemberOfTest.java @@ -19,8 +19,8 @@ package org.drools.compiler.integrationtests.operators; import java.util.ArrayList; -import java.util.Collection; import java.util.List; +import java.util.stream.Stream; import org.drools.testcoverage.common.model.Cheese; import org.drools.testcoverage.common.model.Cheesery; @@ -28,31 +28,23 @@ import org.drools.testcoverage.common.model.Pet; import org.drools.testcoverage.common.util.KieBaseTestConfiguration; import org.drools.testcoverage.common.util.KieBaseUtil; -import org.drools.testcoverage.common.util.TestParametersUtil; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; +import org.drools.testcoverage.common.util.TestParametersUtil2; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; import org.kie.api.KieBase; import org.kie.api.runtime.KieSession; import static org.assertj.core.api.Assertions.assertThat; -@RunWith(Parameterized.class) public class MemberOfTest { - private final KieBaseTestConfiguration kieBaseTestConfiguration; - - public MemberOfTest(final KieBaseTestConfiguration kieBaseTestConfiguration) { - this.kieBaseTestConfiguration = kieBaseTestConfiguration; - } - - @Parameterized.Parameters(name = "KieBase type={0}") - public static Collection getParameters() { - return TestParametersUtil.getKieBaseCloudConfigurations(true); + public static Stream parameters() { + return TestParametersUtil2.getKieBaseCloudConfigurations(true).stream(); } - @Test - public void testMemberOfAndNotMemberOf() { + @ParameterizedTest(name = "KieBase type={0}") + @MethodSource("parameters") + public void testMemberOfAndNotMemberOf(KieBaseTestConfiguration kieBaseTestConfiguration) { final String drl = "package org.drools.compiler.test;\n" + "\n" + @@ -108,8 +100,9 @@ public void testMemberOfAndNotMemberOf() { } } - @Test - public void testMemberOfWithOr() { + @ParameterizedTest(name = "KieBase type={0}") + @MethodSource("parameters") + public void testMemberOfWithOr(KieBaseTestConfiguration kieBaseTestConfiguration) { final String drl = "package org.drools.compiler.integrationtests.operators;\n" + diff --git a/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/compiler/integrationtests/operators/NotTest.java b/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/compiler/integrationtests/operators/NotTest.java index 9cdd7ed1a35..02a99666cab 100644 --- a/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/compiler/integrationtests/operators/NotTest.java +++ b/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/compiler/integrationtests/operators/NotTest.java @@ -20,8 +20,8 @@ import java.math.BigDecimal; import java.util.ArrayList; -import java.util.Collection; import java.util.List; +import java.util.stream.Stream; import org.drools.base.base.ClassObjectType; import org.drools.core.common.InternalFactHandle; @@ -40,10 +40,9 @@ import org.drools.testcoverage.common.model.Person; import org.drools.testcoverage.common.util.KieBaseTestConfiguration; import org.drools.testcoverage.common.util.KieBaseUtil; -import org.drools.testcoverage.common.util.TestParametersUtil; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; +import org.drools.testcoverage.common.util.TestParametersUtil2; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; import org.kie.api.KieBase; import org.kie.api.runtime.KieSession; import org.kie.api.runtime.rule.FactHandle; @@ -51,22 +50,15 @@ import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.fail; -@RunWith(Parameterized.class) public class NotTest { - private final KieBaseTestConfiguration kieBaseTestConfiguration; - - public NotTest(final KieBaseTestConfiguration kieBaseTestConfiguration) { - this.kieBaseTestConfiguration = kieBaseTestConfiguration; - } - - @Parameterized.Parameters(name = "KieBase type={0}") - public static Collection getParameters() { - return TestParametersUtil.getKieBaseCloudConfigurations(true); + public static Stream parameters() { + return TestParametersUtil2.getKieBaseCloudConfigurations(true).stream(); } - @Test - public void testLastMemoryEntryNotBug() { + @ParameterizedTest(name = "KieBase type={0}") + @MethodSource("parameters") + public void testLastMemoryEntryNotBug(KieBaseTestConfiguration kieBaseTestConfiguration) { // JBRULES-2809 // This occurs when a blocker is the last in the node's memory, or if there is only one fact in the node // And it gets no opportunity to rematch with itself @@ -117,8 +109,9 @@ public void testLastMemoryEntryNotBug() { } } - @Test - public void testNegatedConstaintInNot() { + @ParameterizedTest(name = "KieBase type={0}") + @MethodSource("parameters") + public void testNegatedConstaintInNot(KieBaseTestConfiguration kieBaseTestConfiguration) { final String drl = "package org.drools.compiler.integrationtests.operators;\n" + @@ -140,8 +133,9 @@ public void testNegatedConstaintInNot() { } } - @Test - public void testMissingRootBlockerEquality() { + @ParameterizedTest(name = "KieBase type={0}") + @MethodSource("parameters") + public void testMissingRootBlockerEquality(KieBaseTestConfiguration kieBaseTestConfiguration) { // DROOLS-6636 final String drl = "package org.drools.compiler.integrationtests.operators;\n" + @@ -270,8 +264,9 @@ public String toString() { } } - @Test - public void testNotWithInnerJoin() { + @ParameterizedTest(name = "KieBase type={0}") + @MethodSource("parameters") + public void testNotWithInnerJoin(KieBaseTestConfiguration kieBaseTestConfiguration) { // DROOLS-6652 final String drl = "package org.drools.compiler.integrationtests.operators;\n" + @@ -312,8 +307,9 @@ public void testNotWithInnerJoin() { assertThat(results.get(0)).isEqualTo("Paris"); } - @Test - public void testNotWithUnification() { + @ParameterizedTest(name = "KieBase type={0}") + @MethodSource("parameters") + public void testNotWithUnification(KieBaseTestConfiguration kieBaseTestConfiguration) { // DROOLS-7629 final String drl = "package org.drools.compiler.integrationtests.operators;\n" + diff --git a/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/compiler/integrationtests/operators/OrTest.java b/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/compiler/integrationtests/operators/OrTest.java index be828e8ec5b..16d6b7a28e3 100644 --- a/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/compiler/integrationtests/operators/OrTest.java +++ b/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/compiler/integrationtests/operators/OrTest.java @@ -19,8 +19,8 @@ package org.drools.compiler.integrationtests.operators; import java.util.ArrayList; -import java.util.Collection; import java.util.List; +import java.util.stream.Stream; import org.drools.core.common.InternalFactHandle; import org.drools.testcoverage.common.model.Cheese; @@ -32,10 +32,9 @@ import org.drools.testcoverage.common.util.KieBaseTestConfiguration; import org.drools.testcoverage.common.util.KieBaseUtil; import org.drools.testcoverage.common.util.KieUtil; -import org.drools.testcoverage.common.util.TestParametersUtil; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; +import org.drools.testcoverage.common.util.TestParametersUtil2; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; import org.kie.api.KieBase; import org.kie.api.builder.KieBuilder; import org.kie.api.definition.type.FactType; @@ -44,22 +43,15 @@ import static org.assertj.core.api.Assertions.assertThat; -@RunWith(Parameterized.class) public class OrTest { - private final KieBaseTestConfiguration kieBaseTestConfiguration; - - public OrTest(final KieBaseTestConfiguration kieBaseTestConfiguration) { - this.kieBaseTestConfiguration = kieBaseTestConfiguration; - } - - @Parameterized.Parameters(name = "KieBase type={0}") - public static Collection getParameters() { - return TestParametersUtil.getKieBaseCloudConfigurations(true); + public static Stream parameters() { + return TestParametersUtil2.getKieBaseCloudConfigurations(true).stream(); } - @Test - public void testOr() { + @ParameterizedTest(name = "KieBase type={0}") + @MethodSource("parameters") + public void testOr(KieBaseTestConfiguration kieBaseTestConfiguration) { final String drl = "package org.drools.compiler.integrationtests.operators;\n" + "import " + Cheese.class.getCanonicalName() + ";\n" + @@ -105,8 +97,9 @@ public void testOr() { } } - @Test - public void testOrCE() { + @ParameterizedTest(name = "KieBase type={0}") + @MethodSource("parameters") + public void testOrCE(KieBaseTestConfiguration kieBaseTestConfiguration) { final String drl = "package org.drools.compiler.integrationtests.operators;\n" + "import " + Cheese.class.getCanonicalName() + ";\n" + @@ -148,8 +141,9 @@ public void testOrCE() { } } - @Test - public void testOrCEFollowedByEval() { + @ParameterizedTest(name = "KieBase type={0}") + @MethodSource("parameters") + public void testOrCEFollowedByEval(KieBaseTestConfiguration kieBaseTestConfiguration) { final String drl = "package org.drools.compiler.integrationtests.operators;\n" + "import " + FactA.class.getCanonicalName() + ";\n" + "import " + FactB.class.getCanonicalName() + ";\n" + @@ -184,8 +178,9 @@ public void testOrCEFollowedByEval() { } } - @Test - public void testOrWithAndUsingNestedBindings() { + @ParameterizedTest(name = "KieBase type={0}") + @MethodSource("parameters") + public void testOrWithAndUsingNestedBindings(KieBaseTestConfiguration kieBaseTestConfiguration) { final String drl = "package org.drools.compiler.integrationtests.operators;\n" + "import " + Person.class.getCanonicalName() + ";\n" + "global java.util.List mlist\n" + @@ -268,8 +263,9 @@ public void testOrWithAndUsingNestedBindings() { } } - @Test - public void testOrWithBinding() { + @ParameterizedTest(name = "KieBase type={0}") + @MethodSource("parameters") + public void testOrWithBinding(KieBaseTestConfiguration kieBaseTestConfiguration) { final String drl = "package org.drools.compiler.integrationtests.operators;\n" + "import " + Cheese.class.getCanonicalName() + ";\n" + @@ -314,8 +310,9 @@ public void testOrWithBinding() { } } - @Test - public void testOrWithFrom() { + @ParameterizedTest(name = "KieBase type={0}") + @MethodSource("parameters") + public void testOrWithFrom(KieBaseTestConfiguration kieBaseTestConfiguration) { // JBRULES-2274: Rule does not fire as expected using deep object model and nested 'or' clause final String drl = "package org.drools.compiler.integrationtests.operators;\n" + "import " + Order.class.getCanonicalName() + ";\n" @@ -354,8 +351,9 @@ public void testOrWithFrom() { } } - @Test - public void testOrWithReturnValueRestriction() { + @ParameterizedTest(name = "KieBase type={0}") + @MethodSource("parameters") + public void testOrWithReturnValueRestriction(KieBaseTestConfiguration kieBaseTestConfiguration) { final String drl = "package org.drools.compiler.integrationtests.operators;\n" + @@ -385,8 +383,9 @@ public void testOrWithReturnValueRestriction() { } } - @Test - public void testBindingsWithOr() throws InstantiationException, IllegalAccessException { + @ParameterizedTest(name = "KieBase type={0}") + @MethodSource("parameters") + public void testBindingsWithOr(KieBaseTestConfiguration kieBaseTestConfiguration) throws InstantiationException, IllegalAccessException { // JBRULES-2917: matching of field==v1 || field==v2 breaks when variable binding is added final String drl = "package org.drools.compiler.integrationtests.operators;\n" + "declare Assignment\n" + @@ -424,8 +423,9 @@ public void testBindingsWithOr() throws InstantiationException, IllegalAccessExc } } - @Test - public void testConstraintConnectorOr() { + @ParameterizedTest(name = "KieBase type={0}") + @MethodSource("parameters") + public void testConstraintConnectorOr(KieBaseTestConfiguration kieBaseTestConfiguration) { final String drl = "package org.drools.compiler.integrationtests.operators;\n" + "import " + Person.class.getCanonicalName() + ";\n" + @@ -478,8 +478,9 @@ public void testConstraintConnectorOr() { } } - @Test - public void testVariableBindingWithOR() throws Exception{ + @ParameterizedTest(name = "KieBase type={0}") + @MethodSource("parameters") + public void testVariableBindingWithOR(KieBaseTestConfiguration kieBaseTestConfiguration) throws Exception{ // JBRULES-3390 final String drl1 = "package org.drools.compiler.integrationtests.operators; \n" + "declare A\n" + @@ -549,8 +550,9 @@ public void testVariableBindingWithOR() throws Exception{ } } - @Test - public void testRestrictionsWithOr() { + @ParameterizedTest(name = "KieBase type={0}") + @MethodSource("parameters") + public void testRestrictionsWithOr(KieBaseTestConfiguration kieBaseTestConfiguration) { // JBRULES-2203: NullPointerException When Using Conditional Element "or" in LHS Together with a Return Value Restriction final String drl = "package org.drools.compiler.integrationtests.operators;\n" + "import " + Cheese.class.getCanonicalName() + ";\n" + @@ -577,8 +579,9 @@ public void testRestrictionsWithOr() { } } - @Test - public void testEmptyIdentifier() { + @ParameterizedTest(name = "KieBase type={0}") + @MethodSource("parameters") + public void testEmptyIdentifier(KieBaseTestConfiguration kieBaseTestConfiguration) { final String drl = "package org.drools.compiler.integrationtests.operators;\n" + "import " + Cheese.class.getCanonicalName() + ";\n" + @@ -635,8 +638,9 @@ public void testEmptyIdentifier() { } } - @Test - public void testIndexAfterOr() { + @ParameterizedTest(name = "KieBase type={0}") + @MethodSource("parameters") + public void testIndexAfterOr(KieBaseTestConfiguration kieBaseTestConfiguration) { // DROOLS-1604 final String drl = "import " + Person.class.getCanonicalName() + ";" + @@ -674,8 +678,9 @@ public void testIndexAfterOr() { } } - @Test - public void testOrWithDifferenceOffsetsForConsequence() { + @ParameterizedTest(name = "KieBase type={0}") + @MethodSource("parameters") + public void testOrWithDifferenceOffsetsForConsequence(KieBaseTestConfiguration kieBaseTestConfiguration) { // DROOLS-1604 final String drl = "import " + Person.class.getCanonicalName() + ";" + diff --git a/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/compiler/integrationtests/operators/SoundsLikeTest.java b/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/compiler/integrationtests/operators/SoundsLikeTest.java index d44158f5cc3..0ff2098af41 100644 --- a/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/compiler/integrationtests/operators/SoundsLikeTest.java +++ b/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/compiler/integrationtests/operators/SoundsLikeTest.java @@ -18,40 +18,31 @@ */ package org.drools.compiler.integrationtests.operators; -import java.util.Collection; import java.util.stream.Stream; import org.drools.testcoverage.common.model.Person; import org.drools.testcoverage.common.util.KieBaseTestConfiguration; import org.drools.testcoverage.common.util.KieBaseUtil; -import org.drools.testcoverage.common.util.TestParametersUtil; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; +import org.drools.testcoverage.common.util.TestParametersUtil2; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; import org.kie.api.KieBase; import org.kie.api.runtime.KieSession; import static org.assertj.core.api.Assertions.assertThat; -@RunWith(Parameterized.class) public class SoundsLikeTest { - private final KieBaseTestConfiguration kieBaseTestConfiguration; - - public SoundsLikeTest(final KieBaseTestConfiguration kieBaseTestConfiguration) { - this.kieBaseTestConfiguration = kieBaseTestConfiguration; - } - - @Parameterized.Parameters(name = "KieBase type={0}") - public static Collection getParameters() { - return TestParametersUtil.getKieBaseCloudConfigurations(true); + public static Stream parameters() { + return TestParametersUtil2.getKieBaseCloudConfigurations(true).stream(); } - @Test - public void testSoundsLike() { + @ParameterizedTest(name = "KieBase type={0}") + @MethodSource("parameters") + public void testSoundsLike(KieBaseTestConfiguration kieBaseTestConfiguration) { // JBRULES-2991: Operator soundslike is broken - testFiredRules("package org.drools.compiler.integrationtests.operators;\n" + + testFiredRules(kieBaseTestConfiguration, "package org.drools.compiler.integrationtests.operators;\n" + "import " + Person.class.getCanonicalName() + ";\n" + "rule SoundsLike\n" + "when\n" + @@ -63,11 +54,12 @@ public void testSoundsLike() { "Bob"); } - @Test - public void testSoundsLikeNegativeCase() { + @ParameterizedTest(name = "KieBase type={0}") + @MethodSource("parameters") + public void testSoundsLikeNegativeCase(KieBaseTestConfiguration kieBaseTestConfiguration) { // JBRULES-2991: Operator soundslike is broken - testFiredRules("package org.drools.compiler.integrationtests.operators;\n" + + testFiredRules(kieBaseTestConfiguration, "package org.drools.compiler.integrationtests.operators;\n" + "import " + Person.class.getCanonicalName() + ";\n" + "rule SoundsLike\n" + "when\n" + @@ -78,11 +70,12 @@ public void testSoundsLikeNegativeCase() { "Mark"); } - @Test - public void testNotSoundsLike() { + @ParameterizedTest(name = "KieBase type={0}") + @MethodSource("parameters") + public void testNotSoundsLike(KieBaseTestConfiguration kieBaseTestConfiguration) { // JBRULES-2991: Operator soundslike is broken - testFiredRules("package org.drools.compiler.integrationtests.operators;\n" + + testFiredRules(kieBaseTestConfiguration, "package org.drools.compiler.integrationtests.operators;\n" + "import " + Person.class.getCanonicalName() + ";\n" + "rule NotSoundsLike\n" + "when\n" + @@ -93,11 +86,12 @@ public void testNotSoundsLike() { "John"); } - @Test - public void testNotSoundsLikeNegativeCase() { + @ParameterizedTest(name = "KieBase type={0}") + @MethodSource("parameters") + public void testNotSoundsLikeNegativeCase(KieBaseTestConfiguration kieBaseTestConfiguration) { // JBRULES-2991: Operator soundslike is broken - testFiredRules("package org.drools.compiler.integrationtests.operators;\n" + + testFiredRules(kieBaseTestConfiguration, "package org.drools.compiler.integrationtests.operators;\n" + "import " + Person.class.getCanonicalName() + ";\n" + "rule NotSoundsLike\n" + "when\n" + @@ -108,7 +102,8 @@ public void testNotSoundsLikeNegativeCase() { "Bob"); } - private void testFiredRules(final String rule, + private void testFiredRules(KieBaseTestConfiguration kieBaseTestConfiguration, + final String rule, final int firedRulesCount, final String... persons) { final KieBase kbase = KieBaseUtil.getKieBaseFromKieModuleFromDrl("sounds-like-test", diff --git a/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/mvel/compiler/lang/DRLExprParserTest.java b/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/mvel/compiler/lang/DRLExprParserTest.java index 08eeb33edae..3a59b507301 100644 --- a/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/mvel/compiler/lang/DRLExprParserTest.java +++ b/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/mvel/compiler/lang/DRLExprParserTest.java @@ -25,6 +25,7 @@ import org.drools.drl.ast.descr.ConstraintConnectiveDescr; import org.drools.drl.ast.descr.RelationalExprDescr; import org.drools.drl.parser.DrlExprParser; +import org.drools.drl.parser.DrlExprParserFactory; import org.junit.After; import org.junit.Before; import org.junit.Test; @@ -42,7 +43,7 @@ public class DRLExprParserTest { @Before public void setUp() throws Exception { new EvaluatorRegistry(); - this.parser = new DrlExprParser(LanguageLevelOption.DRL6); + this.parser = DrlExprParserFactory.getDrlExprParser(LanguageLevelOption.DRL6); } @After @@ -181,7 +182,7 @@ public void testBindingWithRestrictions() throws Exception { AtomicExprDescr right = (AtomicExprDescr) rel.getRight(); assertThat(right.getExpression()).isEqualTo("value"); - + rel = (RelationalExprDescr) result.getDescrs().get( 1 ); assertThat(rel.getOperator()).isEqualTo("<"); diff --git a/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/mvel/compiler/lang/DRLIncompleteCodeTest.java b/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/mvel/compiler/lang/DRLIncompleteCodeTest.java deleted file mode 100644 index 04ba8d26389..00000000000 --- a/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/mvel/compiler/lang/DRLIncompleteCodeTest.java +++ /dev/null @@ -1,250 +0,0 @@ -/** - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you 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 - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package org.drools.mvel.compiler.lang; - -import java.util.LinkedList; - -import org.antlr.runtime.RecognitionException; -import org.drools.compiler.builder.impl.EvaluatorRegistry; -import org.drools.drl.ast.descr.PackageDescr; -import org.drools.drl.parser.DrlParser; -import org.drools.drl.parser.DroolsParserException; -import org.drools.drl.parser.lang.Location; -import org.junit.Before; -import org.junit.Ignore; -import org.junit.Test; -import org.kie.internal.builder.conf.LanguageLevelOption; - -import static org.assertj.core.api.Assertions.assertThat; - -public class DRLIncompleteCodeTest { - - @Before - public void setup() { - // just initialising the static operator definitions - new EvaluatorRegistry(); - } - - @Test - @Ignore - public void testIncompleteCode1() throws DroolsParserException, - RecognitionException { - String input = "package a.b.c import a.b.c.* rule MyRule when Class ( property memberOf collexction "; - DrlParser parser = new DrlParser(LanguageLevelOption.DRL5); - PackageDescr descr = parser.parse(true, input); - System.out.println(parser.getErrors()); - - assertThat(descr).isNotNull(); - assertThat(descr.getNamespace()).isEqualTo("a.b.c"); - assertThat(descr.getImports().get(0) - .getTarget()).isEqualTo("a.b.c.*"); - - assertThat(getLastIntegerValue(parser.getEditorSentences().get(2) - .getContent())).isEqualTo(Location.LOCATION_LHS_INSIDE_CONDITION_END); - } - - @Test - public void testIncompleteCode2() throws DroolsParserException, - RecognitionException { - String input = "rule MyRule when Class ( property memberOf collection "; - DrlParser parser = new DrlParser(LanguageLevelOption.DRL5); - PackageDescr descr = parser.parse(true, input); - - assertThat(descr).isNotNull(); - assertThat(getLastIntegerValue(parser.getEditorSentences().get(0) - .getContent())).isEqualTo(Location.LOCATION_LHS_INSIDE_CONDITION_END); - } - - @Test - public void testIncompleteCode3() throws DroolsParserException, - RecognitionException { - String input = "rule MyRule when Class ( property > somevalue ) then end query MyQuery Class ( property == collection ) end "; - DrlParser parser = new DrlParser(LanguageLevelOption.DRL5); - PackageDescr descr = parser.parse(true, input); - - assertThat(descr).isNotNull(); - assertThat(descr.getRules().get(0).getName()).isEqualTo("MyRule"); - - assertThat(descr).isNotNull(); - assertThat(descr.getRules().get(1).getName()).isEqualTo("MyQuery"); - - assertThat(getLastIntegerValue(parser - .getEditorSentences().get(0).getContent())).isEqualTo(Location.LOCATION_RHS); - } - - @Test - public void testIncompleteCode4() throws DroolsParserException, - RecognitionException { - String input = "package a.b.c import a.b.c.*" - + " rule MyRule when Class ( property == collection ) then end " - + " query MyQuery Class ( property == collection ) end "; - DrlParser parser = new DrlParser(LanguageLevelOption.DRL5); - PackageDescr descr = parser.parse(true, input); - - assertThat(descr.getNamespace()).isEqualTo("a.b.c"); - assertThat(descr.getImports().get(0) - .getTarget()).isEqualTo("a.b.c.*"); - - assertThat(descr).isNotNull(); - assertThat(descr.getRules().get(0).getName()).isEqualTo("MyRule"); - - assertThat(descr).isNotNull(); - assertThat(descr.getRules().get(1).getName()).isEqualTo("MyQuery"); - } - - @Test - public void testIncompleteCode5() throws DroolsParserException, - RecognitionException { - String input = "package a.b.c import a.b.c.*" - + " rule MyRule when Class ( property memberOf collection ) then end " - + " query MyQuery Class ( property memberOf collection ) end "; - DrlParser parser = new DrlParser(LanguageLevelOption.DRL5); - PackageDescr descr = parser.parse(true, input); - - assertThat(descr).isNotNull(); - } - - @Test - public void testIncompleteCode6() throws DroolsParserException, - RecognitionException { - String input = "packe 1111.111 import a.b.c.*" - + " rule MyRule when Class ( property memberOf collection ) then end " - + " query MyQuery Class ( property memberOf collection ) end "; - DrlParser parser = new DrlParser(LanguageLevelOption.DRL5); - PackageDescr descr = parser.parse(true, input); - - assertThat(descr).isNotNull(); - } - - @Test - public void testIncompleteCode7() throws DroolsParserException, - RecognitionException { - String input = "package a.b.c imrt a.b.c.*" - + " rule MyRule when Class ( property memberOf collection ) then end " - + " query MyQuery Class ( property memberOf collection ) end "; - DrlParser parser = new DrlParser(LanguageLevelOption.DRL5); - PackageDescr descr = parser.parse(true, input); - - assertThat(descr).isNotNull(); - } - - @Test - public void testIncompleteCode8() throws DroolsParserException, - RecognitionException { - String input = "package a.b.c import a.1111.c.*" - + " rule MyRule when Class ( property memberOf collection ) then end " - + " query MyQuery Class ( property memberOf collection ) end "; - DrlParser parser = new DrlParser(LanguageLevelOption.DRL5); - PackageDescr descr = parser.parse(true, input); - System.out.println(parser.getErrors()); - - assertThat(descr.getNamespace()).isEqualTo("a.b.c"); - // FIXME: assertEquals(2, descr.getRules().size()); - assertThat(parser.hasErrors()).isEqualTo(true); - } - - @Test @Ignore - public void testIncompleteCode9() throws DroolsParserException, - RecognitionException { - String input = "package a.b.c import a.b.c.*" - + " rule MyRule xxxxx Class ( property memberOf collection ) then end " - + " query MyQuery Class ( property memberOf collection ) end "; - DrlParser parser = new DrlParser(LanguageLevelOption.DRL5); - PackageDescr descr = parser.parse(true, input); - - assertThat(descr.getNamespace()).isEqualTo("a.b.c"); - assertThat(descr.getImports().get(0) - .getTarget()).isEqualTo("a.b.c.*"); - - assertThat(descr.getRules().size()).isEqualTo(1); - assertThat(descr.getRules().get(0).getName()).isEqualTo("MyQuery"); - } - - @Test @Ignore - public void testIncompleteCode10() throws DroolsParserException, - RecognitionException { - String input = "package a.b.c import a.b.c.*" - + " rule MyRule xxxxx Class ( property memberOf " - + " query MyQuery Class ( property memberOf collection ) end "; - DrlParser parser = new DrlParser(LanguageLevelOption.DRL5); - PackageDescr descr = parser.parse(true, input); - - assertThat(descr.getNamespace()).isEqualTo("a.b.c"); - assertThat(descr.getImports().get(0) - .getTarget()).isEqualTo("a.b.c.*"); - - assertThat(descr.getRules().size()).isEqualTo(0); - } - - @Test - public void testIncompleteCode11() throws DroolsParserException, - RecognitionException { - String input = "package a.b.c import a.b.c.*" - + " rule MyRule when Class ( property memberOf collection ) then end " - + " qzzzzuery MyQuery Class ( property "; - DrlParser parser = new DrlParser(LanguageLevelOption.DRL5); - PackageDescr descr = parser.parse(true, input); - - assertThat(descr.getNamespace()).isEqualTo("a.b.c"); - assertThat(descr.getImports().get(0) - .getTarget()).isEqualTo("a.b.c.*"); - - assertThat(descr).isNotNull(); - assertThat(descr.getRules().get(0).getName()).isEqualTo("MyRule"); - } - - @Test - public void testIncompleteCode12() throws DroolsParserException, - RecognitionException { - String input = "package a.b.c " + "import a.b.c.* " + "rule MyRule" - + " when " + " m: Message( ) " + " " + " then" - + "end "; - DrlParser parser = new DrlParser(LanguageLevelOption.DRL5); - PackageDescr descr = parser.parse(true, input); - assertThat(descr).isNotNull(); - - assertThat(descr.getNamespace()).isEqualTo("a.b.c"); - assertThat(descr.getImports().get(0) - .getTarget()).isEqualTo("a.b.c.*"); - } - - @Test - public void testIncompleteCode13() throws DroolsParserException, - RecognitionException { - String input = "package com.sample " - + "import com.sample.DroolsTest.Message; " - + "rule \"Hello World\"" + " when " + " then" + " \\\" " - + "end "; - DrlParser parser = new DrlParser(LanguageLevelOption.DRL5); - PackageDescr descr = parser.parse(true, input); - assertThat(descr).isNotNull(); - } - - @SuppressWarnings("unchecked") - private int getLastIntegerValue(LinkedList list) { - // System.out.println(list.toString()); - int lastIntergerValue = -1; - for (Object object : list) { - if (object instanceof Integer) { - lastIntergerValue = (Integer) object; - } - } - return lastIntergerValue; - } -} diff --git a/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/mvel/compiler/lang/DescrDumperTest.java b/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/mvel/compiler/lang/DescrDumperTest.java index 649b43c37fe..0af0bc01635 100644 --- a/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/mvel/compiler/lang/DescrDumperTest.java +++ b/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/mvel/compiler/lang/DescrDumperTest.java @@ -24,6 +24,7 @@ import org.drools.drl.ast.descr.AtomicExprDescr; import org.drools.drl.ast.descr.BindingDescr; import org.drools.drl.ast.descr.ConstraintConnectiveDescr; +import org.drools.drl.parser.DrlExprParserFactory; import org.drools.mvel.evaluators.MatchesEvaluatorsDefinition; import org.drools.mvel.evaluators.SetEvaluatorsDefinition; import org.junit.Before; @@ -358,7 +359,7 @@ public void testProcessImplicitConstraints() throws Exception { } public ConstraintConnectiveDescr parse( final String constraint ) { - DrlExprParser parser = new DrlExprParser(LanguageLevelOption.DRL6); + DrlExprParser parser = DrlExprParserFactory.getDrlExprParser(LanguageLevelOption.DRL6); ConstraintConnectiveDescr result = parser.parse( constraint ); assertThat(parser.hasErrors()).as(parser.getErrors().toString()).isFalse(); diff --git a/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/mvel/compiler/lang/RuleParserTest.java b/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/mvel/compiler/lang/RuleParserTest.java index 3ad7c622d01..1566604d241 100644 --- a/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/mvel/compiler/lang/RuleParserTest.java +++ b/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/mvel/compiler/lang/RuleParserTest.java @@ -110,26 +110,6 @@ public void testPackage() throws Exception { assertThat(pkg.getName()).isEqualTo("foo.bar.baz"); } - @Test - public void testPackageWithError() throws Exception { - final String source = "package 12 foo.bar.baz"; - final DrlParser parser = new DrlParser(LanguageLevelOption.DRL6); - final PackageDescr pkg = parser.parse( true, - new StringReader( source ) ); - assertThat(parser.hasErrors()).isTrue(); - assertThat(pkg.getName()).isEqualTo("foo.bar.baz"); - } - - @Test - public void testPackageWithError2() throws Exception { - final String source = "package 12 12312 231"; - final DrlParser parser = new DrlParser(LanguageLevelOption.DRL6); - final PackageDescr pkg = parser.parse( true, - new StringReader( source ) ); - assertThat(parser.hasErrors()).isTrue(); - assertThat(pkg.getName()).isEqualTo(""); - } - @Test public void testCompilationUnit() throws Exception { final String source = "package foo; import com.foo.Bar; import com.foo.Baz;"; diff --git a/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/mvel/integrationtests/AlphaNodeTest.java b/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/mvel/integrationtests/AlphaNodeTest.java index d4089c34601..6d14f2355c6 100644 --- a/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/mvel/integrationtests/AlphaNodeTest.java +++ b/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/mvel/integrationtests/AlphaNodeTest.java @@ -48,6 +48,8 @@ public static Collection getParameters() { @Test public void testAlpha() { + + String str = "import " + Person.class.getCanonicalName() + "\n" + "rule R1 when\n" + diff --git a/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/mvel/integrationtests/StrictAnnotationTest.java b/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/mvel/integrationtests/StrictAnnotationTest.java index cc3a605be16..602b8ead083 100644 --- a/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/mvel/integrationtests/StrictAnnotationTest.java +++ b/drools-test-coverage/test-compiler-integration/src/test/java/org/drools/mvel/integrationtests/StrictAnnotationTest.java @@ -32,10 +32,13 @@ import org.drools.core.common.DefaultEventHandle; import org.drools.core.impl.RuleBaseFactory; +import org.drools.drl.parser.DrlParser; import org.drools.testcoverage.common.util.KieBaseTestConfiguration; import org.drools.testcoverage.common.util.KieBaseUtil; import org.drools.testcoverage.common.util.KieUtil; import org.drools.testcoverage.common.util.TestParametersUtil; +import org.junit.Assume; +import org.junit.BeforeClass; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; @@ -70,6 +73,12 @@ public static Collection getParameters() { return TestParametersUtil.getKieBaseCloudConfigurations(false); } + @BeforeClass + public static void checkSkip() { + // if new antlr4 parser is enabled, skip this test, because DRL6_STRICT is not supported + Assume.assumeFalse(DrlParser.ANTLR4_PARSER_ENABLED); + } + @Test public void testUnknownAnnotation() { String str = diff --git a/drools-test-coverage/test-compiler-integration/src/test/resources/logback-test.xml b/drools-test-coverage/test-compiler-integration/src/test/resources/logback-test.xml index ce4cf145c90..715224c2777 100644 --- a/drools-test-coverage/test-compiler-integration/src/test/resources/logback-test.xml +++ b/drools-test-coverage/test-compiler-integration/src/test/resources/logback-test.xml @@ -34,6 +34,7 @@ + diff --git a/drools-test-coverage/test-suite/src/test/java/org/drools/testcoverage/common/util/TestParametersUtil2.java b/drools-test-coverage/test-suite/src/test/java/org/drools/testcoverage/common/util/TestParametersUtil2.java new file mode 100644 index 00000000000..46011c70122 --- /dev/null +++ b/drools-test-coverage/test-suite/src/test/java/org/drools/testcoverage/common/util/TestParametersUtil2.java @@ -0,0 +1,324 @@ +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you 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 + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.drools.testcoverage.common.util; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collection; +import java.util.HashSet; +import java.util.List; +import java.util.Set; +import java.util.stream.Collectors; + +import org.drools.model.codegen.ExecutableModelProject; + +/** + * Utility class that holds default tests parameters. + */ +public final class TestParametersUtil2 { + + private static final boolean TEST_WITH_ALPHA_NETWORK = Boolean.valueOf(System.getProperty("alphanetworkCompilerEnabled")); + + /** + * Get all KieBaseConfigurations for tests based on specified engine configurations. + * @param engineConfigurations Engine configurations for tests. They should contain every configuration that + * should be tested. What is not specified, is not returned as part of KieBaseConfigurations. + * @return + */ + public static Collection getKieBaseConfigurations(final EngineTestConfiguration... engineConfigurations) { + if (engineConfigurations == null || engineConfigurations.length == 0) { + throw new IllegalArgumentException("No parameters specified! Please provide some required parameters"); + } + final Collection parameters = new ArrayList<>(); + for (final KieBaseTestConfiguration testConfiguration : KieBaseTestConfiguration.values()) { + if (isTestConfigurationValid(testConfiguration, engineConfigurations)) { + parameters.add(testConfiguration); + } + } + return parameters; + } + + /** + * Checks, if a test configuration matches specified engine configurations. Take note that the engine configurations + * can contain contradictory configurations on first sight. This is because they should include all + * configurations requested for tests. E.g. a test could require both combinations with executable model on and also off. + * + * @param testConfiguration A configuration that is checked if it matches the specified engine configurations + * @param engineConfigurations Specified engine configurations for tests + * @return true, if the test configuration is valid for specified engine configurations, otherwise false + */ + private static boolean isTestConfigurationValid(final KieBaseTestConfiguration testConfiguration, + final EngineTestConfiguration[] engineConfigurations) { + final Set engineTestConfigurationSet = new HashSet<>(Arrays.asList(engineConfigurations)); + + if (testConfiguration.isImmutable() && !engineTestConfigurationSet.contains(EngineTestConfiguration.IMMUTABLE_KIE_BASE)) { + return false; + } + + if (testConfiguration.isStreamMode() && !engineTestConfigurationSet.contains(EngineTestConfiguration.STREAM_MODE)) { + return false; + } + + if (!testConfiguration.isStreamMode() && !engineTestConfigurationSet.contains(EngineTestConfiguration.CLOUD_MODE)) { + return false; + } + + if (testConfiguration.isIdentity() && !engineTestConfigurationSet.contains(EngineTestConfiguration.IDENTITY_MODE)) { + return false; + } + + if (!testConfiguration.isIdentity() && !engineTestConfigurationSet.contains(EngineTestConfiguration.EQUALITY_MODE)) { + return false; + } + + if (testConfiguration.useAlphaNetworkCompiler() + && !engineTestConfigurationSet.contains(EngineTestConfiguration.ALPHA_NETWORK_COMPILER_TRUE)) { + return false; + } + + if (!testConfiguration.useAlphaNetworkCompiler() + && !engineTestConfigurationSet.contains(EngineTestConfiguration.ALPHA_NETWORK_COMPILER_FALSE)) { + return false; + } + + if (!testConfiguration.getExecutableModelProjectClass().isPresent() + && !engineTestConfigurationSet.contains(EngineTestConfiguration.EXECUTABLE_MODEL_OFF)) { + return false; + } + + if (testConfiguration.getExecutableModelProjectClass().isPresent()) { + if (testConfiguration.getExecutableModelProjectClass().get().equals(ExecutableModelProject.class) + && !engineTestConfigurationSet.contains(EngineTestConfiguration.EXECUTABLE_MODEL_PATTERN)) { + return false; + } + } + return true; + } + + /** + * Prepares collection of KieBaseTestConfiguration. + * @return Collection of KieBaseTestConfiguration for parameterized tests. + */ + public static Collection getKieBaseConfigurations() { + final List engineTestConfigurations = Arrays.stream(EngineTestConfiguration.values()) + .filter(config -> (TEST_WITH_ALPHA_NETWORK || config != EngineTestConfiguration.ALPHA_NETWORK_COMPILER_TRUE) + && config != EngineTestConfiguration.EQUALITY_MODE + && config != EngineTestConfiguration.IMMUTABLE_KIE_BASE) + .collect(Collectors.toList()); + return getKieBaseConfigurations(engineTestConfigurations.toArray(new EngineTestConfiguration[]{})); + } + + /** + * Prepares collection of stream KieBaseTestConfiguration. + * @return Collection of KieBaseTestConfiguration for parameterized tests. + * @param testAlsoExecutableModel If true, the configurations returned contain configurations with executable model. + */ + public static Collection getKieBaseStreamConfigurations(final boolean testAlsoExecutableModel) { + return getKieBaseStreamOrCloudConfigurations(EngineTestConfiguration.STREAM_MODE, testAlsoExecutableModel); + } + + /** + * Prepares collection of stream KieBaseTestConfiguration. + * @return Collection of KieBaseTestConfiguration for parameterized tests. + * @param testAlsoExecutableModel If true, the configurations returned contain configurations with executable model. + * @param testEquality If true, the configurations returned contain configurations with EQUALITY_MODE instead of IDENTITY_MODE. + */ + public static Collection getKieBaseStreamConfigurations(final boolean testAlsoExecutableModel, final boolean testEquality) { + return getKieBaseStreamOrCloudConfigurations(EngineTestConfiguration.STREAM_MODE, testAlsoExecutableModel, testEquality); + } + + /** + * Prepares collection of stream KieBaseTestConfiguration. + * @return Collection of KieBaseTestConfiguration for parameterized tests. + * @param testAlsoExecutableModel If true, the configurations returned contain configurations with executable model. + */ + public static Collection getKieBaseCloudConfigurations(final boolean testAlsoExecutableModel) { + return getKieBaseStreamOrCloudConfigurations(EngineTestConfiguration.CLOUD_MODE, testAlsoExecutableModel); + } + + /** + * Prepares collection of stream KieBaseTestConfiguration. + * @return Collection of KieBaseTestConfiguration for parameterized tests. + * @param testAlsoExecutableModel If true, the configurations returned contain configurations with executable model. + * @param testEquality If true, the configurations returned contain configurations with EQUALITY_MODE instead of IDENTITY_MODE. + */ + public static Collection getKieBaseCloudConfigurations(final boolean testAlsoExecutableModel, final boolean testEquality) { + return getKieBaseStreamOrCloudConfigurations(EngineTestConfiguration.CLOUD_MODE, testAlsoExecutableModel, testEquality); + } + + private static Collection getKieBaseStreamOrCloudConfigurations(final EngineTestConfiguration streamOrCloudConfig, + final boolean testAlsoExecutableModel) { + // Testing just IDENTITY_MODE by default, leaving EQUALITY_MODE to specialized tests. + return getKieBaseStreamOrCloudConfigurations(streamOrCloudConfig, testAlsoExecutableModel, false); + } + + private static Collection getKieBaseStreamOrCloudConfigurations(final EngineTestConfiguration streamOrCloudConfig, + final boolean testAlsoExecutableModel, final boolean testEquality) { + final List engineTestConfigurations = new ArrayList<>(); + engineTestConfigurations.add(streamOrCloudConfig); + if (testEquality) { + engineTestConfigurations.add(EngineTestConfiguration.EQUALITY_MODE); + } else { + engineTestConfigurations.add(EngineTestConfiguration.IDENTITY_MODE); + } + engineTestConfigurations.add(EngineTestConfiguration.EXECUTABLE_MODEL_OFF); + engineTestConfigurations.add(EngineTestConfiguration.ALPHA_NETWORK_COMPILER_FALSE); + + if (TEST_WITH_ALPHA_NETWORK) { + engineTestConfigurations.add(EngineTestConfiguration.ALPHA_NETWORK_COMPILER_TRUE); + } + + if (testAlsoExecutableModel) { + engineTestConfigurations.add(EngineTestConfiguration.EXECUTABLE_MODEL_PATTERN); + } + + return getKieBaseConfigurations(engineTestConfigurations.toArray(new EngineTestConfiguration[]{})); + } + + public static Collection getKieBaseCloudOnlyExecModelConfiguration() { + final List engineTestConfigurations = new ArrayList<>(); + engineTestConfigurations.add(EngineTestConfiguration.CLOUD_MODE); + engineTestConfigurations.add(EngineTestConfiguration.IDENTITY_MODE); + engineTestConfigurations.add(EngineTestConfiguration.ALPHA_NETWORK_COMPILER_FALSE); + engineTestConfigurations.add(EngineTestConfiguration.EXECUTABLE_MODEL_PATTERN); + + return getKieBaseConfigurations(engineTestConfigurations.toArray(new EngineTestConfiguration[]{})); + } + + /** + * Prepares various combinations of KieBaseTestConfiguration and KieSessionTestConfiguration. + * @return Collection of combinations for parameterized tests. + */ + public static Collection getKieBaseAndKieSessionConfigurations() { + final Collection parameters = new ArrayList<>(); + // These are wrapped in an array, because these are parameters for JUnit Parameterized runner. + Collection kieBaseConfigurations = getKieBaseCloudConfigurations(true); + for (final KieSessionTestConfiguration kieSessionTestConfiguration : KieSessionTestConfiguration.values()) { + for (final KieBaseTestConfiguration kieBaseConfigWrapped : kieBaseConfigurations) { + parameters.add(new Object[]{kieBaseConfigWrapped, kieSessionTestConfiguration}); + } + } + + kieBaseConfigurations = getKieBaseStreamConfigurations(true); + for (final KieBaseTestConfiguration kieBaseConfigWrapped : kieBaseConfigurations) { + parameters.add(new Object[]{kieBaseConfigWrapped, KieSessionTestConfiguration.STATEFUL_REALTIME}); + parameters.add(new Object[]{kieBaseConfigWrapped, KieSessionTestConfiguration.STATEFUL_PSEUDO}); + } + + return parameters; + } + + /** + * Prepares various combinations of KieBaseTestConfiguration and KieSessionTestConfiguration. + * Use only stateful kie sessions. + * @return Collection of combinations for parameterized tests. + */ + public static Collection getKieBaseAndStatefulKieSessionConfigurations() { + final Collection parameters = new ArrayList<>(); + final Collection kieBaseConfigurations = getKieBaseConfigurations(); + for (final KieBaseTestConfiguration kieBaseConfigWrapped : kieBaseConfigurations) { + parameters.add(new Object[]{kieBaseConfigWrapped, KieSessionTestConfiguration.STATEFUL_REALTIME}); + if ((kieBaseConfigWrapped).isStreamMode()) { + parameters.add(new Object[]{kieBaseConfigWrapped, KieSessionTestConfiguration.STATEFUL_PSEUDO}); + } + } + + return parameters; + } + + /** + * Prepares various combinations of KieBaseTestConfiguration and KieSessionTestConfiguration. + * Use only stream kie bases and stateful kie sessions. + * @return Collection of combinations for parameterized tests. + */ + public static Collection getStreamKieBaseAndStatefulKieSessionConfigurations() { + final Collection parameters = new ArrayList<>(); + final Collection kieBaseConfigurations = getKieBaseStreamConfigurations(true); + for (final KieBaseTestConfiguration kieBaseConfigWrapped : kieBaseConfigurations) { + parameters.add(new Object[]{kieBaseConfigWrapped, KieSessionTestConfiguration.STATEFUL_REALTIME}); + parameters.add(new Object[]{kieBaseConfigWrapped, KieSessionTestConfiguration.STATEFUL_PSEUDO}); + } + + return parameters; + } + + /** + * Returns KieBaseTestConfiguration instance with Equality while other properties are the same as original. + */ + public static KieBaseTestConfiguration getEqualityInstanceOf(KieBaseTestConfiguration orig) { + for (final KieBaseTestConfiguration config : KieBaseTestConfiguration.values()) { + if (!config.isIdentity() + && config.isStreamMode() == orig.isStreamMode() + && config.useAlphaNetworkCompiler() == orig.useAlphaNetworkCompiler() + && config.getExecutableModelProjectClass().equals(orig.getExecutableModelProjectClass())) { + return config; + } + } + throw new RuntimeException("Cannot find Equality instance of " + orig); + } + + /** + * Returns KieBaseTestConfiguration instance with Identity while other properties are the same as original. + */ + public static KieBaseTestConfiguration getIdentityInstanceOf(KieBaseTestConfiguration orig) { + for (final KieBaseTestConfiguration config : KieBaseTestConfiguration.values()) { + if (config.isIdentity() + && config.isStreamMode() == orig.isStreamMode() + && config.useAlphaNetworkCompiler() == orig.useAlphaNetworkCompiler() + && config.getExecutableModelProjectClass().equals(orig.getExecutableModelProjectClass())) { + return config; + } + } + throw new RuntimeException("Cannot find Identity instance of " + orig); + } + + /** + * Returns KieBaseTestConfiguration instance with Stream while other properties are the same as original. + */ + public static KieBaseTestConfiguration getStreamInstanceOf(KieBaseTestConfiguration orig) { + for (final KieBaseTestConfiguration config : KieBaseTestConfiguration.values()) { + if (config.isStreamMode() + && config.isIdentity() == orig.isIdentity() + && config.useAlphaNetworkCompiler() == orig.useAlphaNetworkCompiler() + && config.getExecutableModelProjectClass().equals(orig.getExecutableModelProjectClass())) { + return config; + } + } + throw new RuntimeException("Cannot find Stream instance of " + orig); + } + + /** + * Returns KieBaseTestConfiguration instance with Cloud while other properties are the same as original. + */ + public static KieBaseTestConfiguration getCloudInstanceOf(KieBaseTestConfiguration orig) { + for (final KieBaseTestConfiguration config : KieBaseTestConfiguration.values()) { + if (!config.isStreamMode() + && config.isIdentity() == orig.isIdentity() + && config.useAlphaNetworkCompiler() == orig.useAlphaNetworkCompiler() + && config.getExecutableModelProjectClass().equals(orig.getExecutableModelProjectClass())) { + return config; + } + } + throw new RuntimeException("Cannot find Cloud instance of " + orig); + } + + private TestParametersUtil2() { + // Creating instances of util classes should not be possible. + } +} diff --git a/drools-test-coverage/test-suite/src/test/java/org/drools/testcoverage/functional/parser/DrlParserTest.java b/drools-test-coverage/test-suite/src/test/java/org/drools/testcoverage/functional/parser/DrlParserTest.java index dadbe10e7b1..9aa85201e2a 100644 --- a/drools-test-coverage/test-suite/src/test/java/org/drools/testcoverage/functional/parser/DrlParserTest.java +++ b/drools-test-coverage/test-suite/src/test/java/org/drools/testcoverage/functional/parser/DrlParserTest.java @@ -34,7 +34,7 @@ public DrlParserTest(final File file, final KieBaseTestConfiguration kieBaseTest super(file, kieBaseTestConfiguration); } - @Parameters + @Parameters(name = "{index}: {0}, {1}") public static Collection getParameters() { return getTestParamsFromFiles(getFiles("drl")); } diff --git a/drools-traits/pom.xml b/drools-traits/pom.xml index f2c5f685fd1..70d75678a7b 100644 --- a/drools-traits/pom.xml +++ b/drools-traits/pom.xml @@ -184,10 +184,10 @@ - junit - junit + org.junit.jupiter + junit-jupiter test - + org.mockito mockito-core diff --git a/drools-traits/src/test/java/org/drools/traits/UseOfRuleFlowGroupPlusLockOnTest.java b/drools-traits/src/test/java/org/drools/traits/UseOfRuleFlowGroupPlusLockOnTest.java index 76a68c0a133..12460df4967 100644 --- a/drools-traits/src/test/java/org/drools/traits/UseOfRuleFlowGroupPlusLockOnTest.java +++ b/drools-traits/src/test/java/org/drools/traits/UseOfRuleFlowGroupPlusLockOnTest.java @@ -19,8 +19,8 @@ package org.drools.traits; import org.drools.kiesession.agenda.DefaultAgenda; +import org.junit.jupiter.api.Test; import org.drools.core.reteoo.ReteDumper; -import org.junit.Test; import org.kie.api.KieBase; import org.kie.api.event.rule.DebugAgendaEventListener; import org.kie.api.io.ResourceType; diff --git a/drools-traits/src/test/java/org/drools/traits/compiler/CommonTraitTest.java b/drools-traits/src/test/java/org/drools/traits/compiler/CommonTraitTest.java index 7f42e4fd45e..efa4b0786d1 100644 --- a/drools-traits/src/test/java/org/drools/traits/compiler/CommonTraitTest.java +++ b/drools-traits/src/test/java/org/drools/traits/compiler/CommonTraitTest.java @@ -21,7 +21,7 @@ import org.drools.kiesession.rulebase.InternalKnowledgeBase; import org.drools.kiesession.rulebase.KnowledgeBaseFactory; import org.drools.traits.core.base.evaluators.IsAEvaluatorDefinition; -import org.junit.BeforeClass; +import org.junit.jupiter.api.BeforeAll; import org.kie.api.KieBase; import org.kie.api.io.ResourceType; import org.kie.internal.builder.KnowledgeBuilder; @@ -33,7 +33,7 @@ public class CommonTraitTest { - @BeforeClass + @BeforeAll public static void beforeClass() { System.setProperty(EvaluatorOption.PROPERTY_NAME + "isA", IsAEvaluatorDefinition.class.getName()); } diff --git a/drools-traits/src/test/java/org/drools/traits/compiler/factmodel/traits/LegacyTraitTest.java b/drools-traits/src/test/java/org/drools/traits/compiler/factmodel/traits/LegacyTraitTest.java index 6b54b117bfa..47f7e41b0d7 100644 --- a/drools-traits/src/test/java/org/drools/traits/compiler/factmodel/traits/LegacyTraitTest.java +++ b/drools-traits/src/test/java/org/drools/traits/compiler/factmodel/traits/LegacyTraitTest.java @@ -19,21 +19,19 @@ package org.drools.traits.compiler.factmodel.traits; import java.util.ArrayList; -import java.util.Arrays; import java.util.Collection; +import java.util.List; import org.drools.base.factmodel.traits.Trait; import org.drools.base.factmodel.traits.Traitable; import org.drools.kiesession.rulebase.InternalKnowledgeBase; import org.drools.kiesession.rulebase.KnowledgeBaseFactory; import org.drools.traits.compiler.CommonTraitTest; -import org.drools.traits.core.factmodel.LogicalTypeInconsistencyException; import org.drools.traits.core.factmodel.TraitFactoryImpl; import org.drools.traits.core.factmodel.VirtualPropertyMode; import org.drools.traits.core.util.StandaloneTraitFactory; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; import org.kie.api.KieBase; import org.kie.api.builder.Message; import org.kie.api.definition.type.PropertyReactive; @@ -47,41 +45,26 @@ import org.slf4j.LoggerFactory; import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.fail; import static org.drools.traits.compiler.factmodel.traits.TraitTestUtils.createStandaloneTraitFactory; -@RunWith(Parameterized.class) public class LegacyTraitTest extends CommonTraitTest { private static final Logger LOGGER = LoggerFactory.getLogger(LegacyTraitTest.class); - public VirtualPropertyMode mode; - - @Parameterized.Parameters - public static Collection modes() { - return Arrays.asList( new VirtualPropertyMode[][] - { - { VirtualPropertyMode.MAP }, - { VirtualPropertyMode.TRIPLES } - } ); - } - - public LegacyTraitTest( VirtualPropertyMode m ) { - this.mode = m; + public static Collection modes() { + return List.of(VirtualPropertyMode.MAP, VirtualPropertyMode.TRIPLES); } - - - private KieSession getSessionFromString( String drl ) { + private KieSession getSessionFromString(String drl) { KnowledgeBuilder knowledgeBuilder = KnowledgeBuilderFactory.newKnowledgeBuilder(); - knowledgeBuilder.add( ResourceFactory.newByteArrayResource( drl.getBytes() ), - ResourceType.DRL ); + knowledgeBuilder.add(ResourceFactory.newByteArrayResource(drl.getBytes()), + ResourceType.DRL); if (knowledgeBuilder.hasErrors()) { - throw new RuntimeException( knowledgeBuilder.getErrors().toString() ); + throw new RuntimeException(knowledgeBuilder.getErrors().toString()); } InternalKnowledgeBase kbase = KnowledgeBaseFactory.newKnowledgeBase(); - kbase.addPackages( knowledgeBuilder.getKnowledgePackages() ); + kbase.addPackages(knowledgeBuilder.getKnowledgePackages()); KieSession session = kbase.newKieSession(); return session; @@ -149,8 +132,9 @@ public void setPers(Pers pers) { } - @Test - public void traitWithPojoInterface() { + @ParameterizedTest + @MethodSource("modes") + public void traitWithPojoInterface(VirtualPropertyMode mode) { String source = "package org.drools.compiler.test;\n" + "import " + LegacyTraitTest.Procedure.class.getCanonicalName() + ";\n" + "import " + LegacyTraitTest.class.getCanonicalName() + ";\n" + @@ -160,7 +144,7 @@ public void traitWithPojoInterface() { // enhanced so that declaration is not needed // "declare ProcedureImpl end " + "declare trait ExtendedProcedure " + - " @role( event )" + + " @role(event)" + "end " + // Surgery must be declared as trait, since it does not extend Thing @@ -174,54 +158,54 @@ public void traitWithPojoInterface() { "when " + " $p : ExtendedProcedure() " + "then " + - " don( $p, Surgery.class ); " + + " don($p, Surgery.class); " + "end " + "rule 'Test 1' " + "dialect 'mvel' " + "when " + - " $s1 : ExtendedProcedure( $subject : subject ) " + - " $s2 : ExtendedProcedure( subject == $subject ) " + + " $s1 : ExtendedProcedure($subject : subject) " + + " $s2 : ExtendedProcedure(subject == $subject) " + "then " + "end " + "rule 'Test 2' " + "dialect 'mvel' " + "when " + - " $s1 : ExtendedProcedure( $subject : subject.name ) " + - " $s2 : ExtendedProcedure( subject.name == $subject ) " + + " $s1 : ExtendedProcedure($subject : subject.name) " + + " $s2 : ExtendedProcedure(subject.name == $subject) " + "then " + "end " + "rule 'Test 3' " + "dialect 'mvel' " + "when " + - " $s1 : ExtendedProcedure( ) " + + " $s1 : ExtendedProcedure() " + "then " + - " update( $s1 ); " + + " update($s1); " + "end " + "\n"; - KieSession ks = getSessionFromString( source ); - TraitFactoryImpl.setMode(mode, ks.getKieBase() ); + KieSession ks = getSessionFromString(source); + TraitFactoryImpl.setMode(mode, ks.getKieBase()); ExtendedProcedureImpl procedure1 = new ExtendedProcedureImpl(); ExtendedProcedureImpl procedure2 = new ExtendedProcedureImpl(); PatientImpl patient1 = new PatientImpl(); patient1.setName("John"); - procedure1.setSubject( patient1 ); + procedure1.setSubject(patient1); procedure1.setPers(new PatientImpl()); PatientImpl patient2 = new PatientImpl(); patient2.setName("John"); - procedure2.setSubject( patient2 ); + procedure2.setSubject(patient2); procedure2.setPers(new PatientImpl()); - ks.insert( procedure1 ); - ks.insert( procedure2 ); + ks.insert(procedure1); + ks.insert(procedure2); - ks.fireAllRules( 500 ); + ks.fireAllRules(500); } @@ -237,8 +221,9 @@ public static interface Trunk extends Root { } @Trait public static interface Foo extends Trunk { } - @Test - public void traitWithMixedInterfacesExtendingEachOther() { + @ParameterizedTest + @MethodSource("modes") + public void traitWithMixedInterfacesExtendingEachOther(VirtualPropertyMode mode) { String source = "package org.drools.compiler.test;" + "import " + BarImpl.class.getCanonicalName() + "; " + "import " + Foo.class.getCanonicalName() + "; " + @@ -256,67 +241,64 @@ public void traitWithMixedInterfacesExtendingEachOther() { "rule 'Bar Don'" + "when " + - " $b : BarImpl( this isA Foo.class, this not isA Foo2.class )\n" + + " $b : BarImpl(this isA Foo.class, this not isA Foo2.class)\n" + " String()\n" + "then " + - " list.add( 3 ); " + - " retract( $b ); " + + " list.add(3); " + + " retract($b); " + "end " + "rule 'Don Bar' " + "no-loop " + "when " + - " $b : Foo( ) " + + " $b : Foo() " + "then " + - " list.add( 1 ); " + - " don( $b, Foo2.class ); " + + " list.add(1); " + + " don($b, Foo2.class); " + "end " + "rule 'Cant really shed Foo but Foo2' " + "when " + " $b : Foo2() " + "then " + - " list.add( 2 ); " + - " shed( $b, Foo.class ); " + - " insert( \"done\" );" + + " list.add(2); " + + " shed($b, Foo.class); " + + " insert(\"done\");" + "end " + ""; - KieSession ks = getSessionFromString( source ); + KieSession ks = getSessionFromString(source); KieBase kieBase = ks.getKieBase(); TraitFactoryImpl.setMode(mode, kieBase); - ArrayList list = new ArrayList(); - ks.setGlobal( "list", list ); + List list = new ArrayList<>(); + ks.setGlobal("list", list); - ks.insert( new BarImpl() ); + ks.insert(new BarImpl()); int n = ks.fireAllRules(); - LOGGER.debug( list.toString() ); - assertThat(list).isEqualTo(Arrays.asList(1, 2, 3)); + LOGGER.debug(list.toString()); + assertThat(list).containsExactly(1, 2, 3); assertThat(n).isEqualTo(3); } - @Test - public void testTraitWithNonAccessorMethodShadowing() { + @ParameterizedTest + @MethodSource("modes") + public void testTraitWithNonAccessorMethodShadowing(VirtualPropertyMode mode) throws Exception { StandaloneTraitFactory factory = createStandaloneTraitFactory(); - try { - SomeInterface r = (SomeInterface) factory.don( new SomeClass(), SomeInterface.class ); - r.prepare(); - assertThat(r.getFoo()).isEqualTo(42); - assertThat(r.doThis("that")).isEqualTo("I did that"); - } catch ( LogicalTypeInconsistencyException e ) { - e.printStackTrace(); - fail( e.getMessage() ); - } + SomeInterface r = (SomeInterface) factory.don(new SomeClass(), SomeInterface.class); + r.prepare(); + assertThat(r.getFoo()).isEqualTo(42); + assertThat(r.doThis("that")).isEqualTo("I did that"); } - @Test() - public void testPojoExtendInterface() { + @ParameterizedTest + @MethodSource("modes") + public void testPojoExtendInterface(VirtualPropertyMode mode) { // DROOLS-697 // It is now allowed for a declared type to extend an interface // The interface itself will be added to the implements part of the generated class @@ -331,9 +313,9 @@ public void testPojoExtendInterface() { ""; KieHelper kh = new KieHelper(); - kh.addContent( s1, ResourceType.DRL ); + kh.addContent(s1, ResourceType.DRL); - assertThat(kh.verify().getMessages(Message.Level.ERROR).size()).isEqualTo(0); + assertThat(kh.verify().getMessages(Message.Level.ERROR)).isEmpty(); } } diff --git a/drools-traits/src/test/java/org/drools/traits/compiler/factmodel/traits/LogicalTraitTest.java b/drools-traits/src/test/java/org/drools/traits/compiler/factmodel/traits/LogicalTraitTest.java index f9217d22ac3..bedb76d286e 100644 --- a/drools-traits/src/test/java/org/drools/traits/compiler/factmodel/traits/LogicalTraitTest.java +++ b/drools-traits/src/test/java/org/drools/traits/compiler/factmodel/traits/LogicalTraitTest.java @@ -26,6 +26,7 @@ import org.drools.core.common.InternalFactHandle; import org.drools.base.factmodel.traits.CoreWrapper; +import org.drools.base.factmodel.traits.Thing; import org.drools.base.factmodel.traits.TraitField; import org.drools.base.factmodel.traits.Traitable; import org.drools.base.factmodel.traits.TraitableBean; @@ -66,12 +67,8 @@ public class LogicalTraitTest extends CommonTraitTest { public VirtualPropertyMode mode; @Parameterized.Parameters - public static Collection modes() { - return Arrays.asList( new VirtualPropertyMode[][] - { - { VirtualPropertyMode.MAP }, - { VirtualPropertyMode.TRIPLES } - } ); + public static Collection modes() { + return List.of(VirtualPropertyMode.MAP, VirtualPropertyMode.TRIPLES); } public LogicalTraitTest( VirtualPropertyMode m ) { @@ -80,7 +77,7 @@ public LogicalTraitTest( VirtualPropertyMode m ) { @Test - public void testShadowAlias() { + public void testShadowAlias() throws Exception { KnowledgeBuilder kbuilderImpl = KnowledgeBuilderFactory.newKnowledgeBuilder(); kbuilderImpl.add( ResourceFactory.newClassPathResource( "org/drools/compiler/factmodel/traits/testTraitedAliasing.drl" ), ResourceType.DRL ); @@ -94,7 +91,7 @@ public void testShadowAlias() { KieSession ks = kbase.newKieSession(); - ArrayList list = new ArrayList( ); + List list = new ArrayList<>( ); ks.setGlobal( "list", list ); ks.fireAllRules(); @@ -103,15 +100,11 @@ public void testShadowAlias() { LOGGER.debug( o.toString() ); } - try { - ks = SerializationHelper.getSerialisedStatefulKnowledgeSession(ks, true ); - } catch ( Exception e ) { - fail( e.getMessage(), e ); - } + ks = SerializationHelper.getSerialisedStatefulKnowledgeSession(ks, true ); LOGGER.debug( list.toString() ); - assertThat(list.contains(false)).isFalse(); - assertThat(list.size()).isEqualTo(8); + assertThat(list).doesNotContain(Boolean.FALSE); + assertThat(list).hasSize(8); } @@ -165,14 +158,14 @@ public void testShadowAliasTraitOnClass() { TraitFactoryImpl.setMode(mode, (InternalRuleBase) kbase); KieSession ks = kbase.newKieSession(); - ArrayList list = new ArrayList(); + List list = new ArrayList<>(); ks.setGlobal( "list", list ); ks.fireAllRules(); for ( Object o : ks.getObjects() ) { LOGGER.debug( o.toString() ); } - assertThat(list).isEqualTo(List.of("ok")); + assertThat(list).containsExactly("ok"); try { ks = SerializationHelper.getSerialisedStatefulKnowledgeSession( ks, true ); @@ -241,14 +234,14 @@ public void testShadowAliasClassOnTrait() { TraitFactoryImpl.setMode(mode, (InternalRuleBase) kbase); KieSession ks = kbase.newKieSession(); - ArrayList list = new ArrayList(); + List list = new ArrayList<>(); ks.setGlobal( "list", list ); ks.fireAllRules(); for ( Object o : ks.getObjects() ) { LOGGER.debug( o.toString() ); } - assertThat(list).isEqualTo(Arrays.asList("ok1", "ok2")); + assertThat(list).containsExactly("ok1", "ok2"); try { ks = SerializationHelper.getSerialisedStatefulKnowledgeSession( ks, true ); @@ -314,14 +307,14 @@ public void testShadowAliasTraitOnTrait() { TraitFactoryImpl.setMode(mode, (InternalRuleBase) kbase); KieSession ks = kbase.newKieSession(); - ArrayList list = new ArrayList(); + List list = new ArrayList<>(); ks.setGlobal( "list", list ); ks.fireAllRules(); for ( Object o : ks.getObjects() ) { LOGGER.debug( o.toString() ); } - assertThat(list).isEqualTo(List.of("ok")); + assertThat(list).containsExactly("ok"); try { ks = SerializationHelper.getSerialisedStatefulKnowledgeSession( ks, true ); @@ -391,8 +384,8 @@ public void initializationConflictManagement() { TraitFactoryImpl.setMode(mode, knowledgeBase ); KieSession knowledgeSession = knowledgeBase.newKieSession(); - ArrayList list = new ArrayList(); - ArrayList list2 = new ArrayList(); + List list = new ArrayList<>(); + List list2 = new ArrayList<>(); knowledgeSession.setGlobal( "list", list ); knowledgeSession.setGlobal( "list2", list2 ); @@ -404,8 +397,8 @@ public void initializationConflictManagement() { LOGGER.debug( list.toString() ); LOGGER.debug( list2.toString() ); - assertThat(list).isEqualTo(Arrays.asList("1", null, "xyz", "xyz", "7", "aaa")); - assertThat(list2).isEqualTo(Arrays.asList(18, null, 37, 99, 37)); + assertThat(list).containsExactly("1", null, "xyz", "xyz", "7", "aaa"); + assertThat(list2).containsExactly(18, null, 37, 99, 37); try { knowledgeSession = SerializationHelper.getSerialisedStatefulKnowledgeSession( knowledgeSession, true ); @@ -473,8 +466,8 @@ public void testInitializationConflictManagementPrimitiveTypes() { TraitFactoryImpl.setMode(mode, knowledgeBase ); KieSession knowledgeSession = knowledgeBase.newKieSession(); - ArrayList list = new ArrayList(); - ArrayList list2 = new ArrayList(); + List list = new ArrayList<>(); + List list2 = new ArrayList<>(); knowledgeSession.setGlobal( "list", list ); knowledgeSession.setGlobal( "list2", list2 ); @@ -486,8 +479,8 @@ public void testInitializationConflictManagementPrimitiveTypes() { LOGGER.debug( list.toString() ); LOGGER.debug( list2.toString() ); - assertThat(list).isEqualTo(Arrays.asList(1.0, 0.0, 16.3, 16.3, 0.0, -0.72)); - assertThat(list2).isEqualTo(Arrays.asList(18, 0, 37, 99, 0)); + assertThat(list).containsExactly(1.0, 0.0, 16.3, 16.3, 0.0, -0.72); + assertThat(list2).containsExactly(18, 0, 37, 99, 0); try { knowledgeSession = SerializationHelper.getSerialisedStatefulKnowledgeSession( knowledgeSession, true ); @@ -556,24 +549,20 @@ public void testHardGetSetOnLogicallyTraitedField() { TraitFactoryImpl.setMode(mode, knowledgeBase ); KieSession knowledgeSession = knowledgeBase.newKieSession(); - ArrayList list = new ArrayList(); + List list = new ArrayList<>(); knowledgeSession.setGlobal( "list", list ); knowledgeSession.fireAllRules(); - assertThat(list).isEqualTo(Arrays.asList(42)); + assertThat(list).containsExactly(42); knowledgeSession.insert( "x" ); knowledgeSession.fireAllRules(); - boolean found = false; - for ( Object o : knowledgeSession.getObjects( new ClassObjectFilter( Qty.class ) ) ) { - assertThat(((Qty) o).getNum()).isEqualTo((Integer) 99); - assertThat(((CoreWrapper) o)._getFieldTMS().get("num", Integer.class)).isEqualTo(99); - found = true; - } - assertThat(found).isTrue(); + Object o = knowledgeSession.getObjects(new ClassObjectFilter(Qty.class)).iterator().next(); + assertThat(((Qty) o).getNum()).isEqualTo((Integer) 99); + assertThat(((CoreWrapper) o)._getFieldTMS().get("num", Integer.class)).isEqualTo(99); - assertThat(list).isEqualTo(Arrays.asList(42, 99)); + assertThat(list).containsExactly(42, 99); knowledgeSession.dispose(); } @@ -783,7 +772,7 @@ public void shadowAliasSelf() { TraitFactoryImpl.setMode(mode, (InternalRuleBase) kbase); KieSession ks = kbase.newKieSession(); - ArrayList list = new ArrayList(); + List list = new ArrayList<>(); ks.setGlobal( "list", list ); ks.fireAllRules(); @@ -873,7 +862,7 @@ public void traitOnSet() { KieSession ks = kbase.newKieSession(); - ArrayList list = new ArrayList(); + List list = new ArrayList<>(); ks.setGlobal( "list", list ); int n = ks.fireAllRules(); @@ -985,13 +974,13 @@ public void testShadowAliasTraitOnClassLogicalRetract() { TraitFactoryImpl.setMode(mode, (InternalRuleBase) kbase); KieSession ks = kbase.newKieSession(); - ArrayList list = new ArrayList(); + List list = new ArrayList<>(); ks.setGlobal( "list", list ); FactHandle handle = ks.insert( "go" ); ks.fireAllRules(); - assertThat(list).isEqualTo(List.of("ok")); + assertThat(list).containsExactly("ok"); for ( Object o : ks.getObjects() ) { LOGGER.debug( o + " >> " + ((InternalFactHandle)ks.getFactHandle( o )).getEqualityKey() ); @@ -1001,16 +990,16 @@ public void testShadowAliasTraitOnClassLogicalRetract() { ks.fireAllRules(); for ( Object o : ks.getObjects( new ClassObjectFilter( ks.getKieBase().getFactType( "org.drools.test", "Y" ).getFactClass() ) ) ) { - assertThat(o instanceof TraitableBean).isTrue(); + assertThat(o).isInstanceOf(TraitableBean.class); TraitableBean tb = (TraitableBean) o; TraitField fld = tb._getFieldTMS().getRegisteredTraitField("fld" ); Set> types = fld.getRangeTypes(); - assertThat(types.size()).isEqualTo(2); + assertThat(types).hasSize(2); TraitField fld2 = tb._getFieldTMS().getRegisteredTraitField("fld2" ); Set> types2 = fld2.getRangeTypes(); - assertThat(types2.size()).isEqualTo(1); + assertThat(types2).hasSize(1); } try { @@ -1026,7 +1015,7 @@ public void testShadowAliasTraitOnClassLogicalRetract() { LOGGER.debug( list.toString() ); - assertThat(list).isEqualTo(Arrays.asList("ok", "ok2", "ok3")); + assertThat(list).containsExactly("ok", "ok2", "ok3"); } @@ -1109,19 +1098,19 @@ public void testShadowAliasClassOnTraitLogicalRetract() { TraitFactoryImpl.setMode(mode, (InternalRuleBase) kbase); KieSession ks = kbase.newKieSession(); - ArrayList list = new ArrayList(); + List list = new ArrayList<>(); ks.setGlobal( "list", list ); FactHandle handle = ks.insert( "go" ); ks.fireAllRules(); - assertThat(list).isEqualTo(Arrays.asList(1, 2)); + assertThat(list).containsExactly(1, 2); ks.retract( handle ); ks.fireAllRules(); for ( Object o : ks.getObjects( new ClassObjectFilter( ks.getKieBase().getFactType( "org.drools.test", "Y" ).getFactClass() ) ) ) { - assertThat(o instanceof TraitableBean).isTrue(); + assertThat(o).isInstanceOf(TraitableBean.class); } try { @@ -1131,7 +1120,7 @@ public void testShadowAliasClassOnTraitLogicalRetract() { } LOGGER.debug( list.toString() ); - assertThat(list).isEqualTo(Arrays.asList(1, 2, 1, 2)); + assertThat(list).containsExactly(1, 2, 1, 2); } @@ -1177,7 +1166,7 @@ public void testSerial() { TraitFactoryImpl.setMode(mode, (InternalRuleBase) kbase); KieSession ks = kbase.newKieSession(); - ArrayList list = new ArrayList(); + List list = new ArrayList(); ks.setGlobal( "list", list ); ks.fireAllRules(); @@ -1241,11 +1230,11 @@ public void testTraitMismatchTypes() KieSession ksession = loadKnowledgeBaseFromString(drl).newKieSession(); TraitFactoryImpl.setMode(mode, ksession.getKieBase()); - List list = new ArrayList(); + List list = new ArrayList<>(); ksession.setGlobal("list",list); ksession.fireAllRules(); - assertThat(list.size() == 1 && list.contains(null)).isTrue(); + assertThat(list).hasSize(1).containsNull(); } @Test @@ -1295,11 +1284,11 @@ public void testTraitMismatchTypes2() KieSession ksession = loadKnowledgeBaseFromString(drl).newKieSession(); TraitFactoryImpl.setMode(mode, ksession.getKieBase()); - List list = new ArrayList(); + List list = new ArrayList<>(); ksession.setGlobal("list",list); ksession.fireAllRules(); - assertThat(list.size() == 1 && list.contains(null)).isTrue(); + assertThat(list).hasSize(1).containsNull(); } @Test @@ -1349,13 +1338,13 @@ public void testTraitMismatchTypes3() KieSession ksession = loadKnowledgeBaseFromString(drl).newKieSession(); TraitFactoryImpl.setMode(mode, ksession.getKieBase()); - List list = new ArrayList(); + List list = new ArrayList<>(); ksession.setGlobal("list",list); ksession.fireAllRules(); LOGGER.debug( "list" + list ); - assertThat(list.size()).isEqualTo(1); + assertThat(list).hasSize(1); assertThat(list.get(0).getClass().getName()).isEqualTo("org.drools.base.factmodel.traits.test.Bar"); } } diff --git a/drools-traits/src/test/java/org/drools/traits/compiler/factmodel/traits/StandaloneTest.java b/drools-traits/src/test/java/org/drools/traits/compiler/factmodel/traits/StandaloneTest.java index 992ccdb8907..61b4d12d593 100644 --- a/drools-traits/src/test/java/org/drools/traits/compiler/factmodel/traits/StandaloneTest.java +++ b/drools-traits/src/test/java/org/drools/traits/compiler/factmodel/traits/StandaloneTest.java @@ -25,8 +25,8 @@ import org.drools.base.factmodel.traits.Thing; import org.drools.traits.core.util.StandaloneTraitFactory; import org.drools.wiring.api.classloader.ProjectClassLoader; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -39,7 +39,7 @@ public class StandaloneTest { private StandaloneTraitFactory factory; - @Before + @BeforeEach public void init() { ProjectClassLoader loader = ProjectClassLoader.createProjectClassLoader(); factory = createStandaloneTraitFactory(); @@ -100,7 +100,7 @@ public void testLegacy() throws LogicalTypeInconsistencyException { LOGGER.debug( "Is foo instance of Thing? : " + (foo instanceof Thing) ); assertThat(foo.getName()).isEqualTo("john doe"); - assertThat(foo instanceof Thing).isTrue(); + assertThat(foo).isInstanceOf(Thing.class); } diff --git a/drools-traits/src/test/java/org/drools/traits/compiler/factmodel/traits/TraitFieldsAndLegacyClassesTest.java b/drools-traits/src/test/java/org/drools/traits/compiler/factmodel/traits/TraitFieldsAndLegacyClassesTest.java index dbee7e2a6cc..0ecf89bd251 100644 --- a/drools-traits/src/test/java/org/drools/traits/compiler/factmodel/traits/TraitFieldsAndLegacyClassesTest.java +++ b/drools-traits/src/test/java/org/drools/traits/compiler/factmodel/traits/TraitFieldsAndLegacyClassesTest.java @@ -27,11 +27,10 @@ import org.drools.traits.compiler.ReviseTraitTestWithPRAlwaysCategory; import org.drools.traits.core.factmodel.TraitFactoryImpl; import org.drools.traits.core.factmodel.VirtualPropertyMode; -import org.junit.Ignore; -import org.junit.Test; import org.junit.experimental.categories.Category; -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; import org.kie.api.KieBase; import org.kie.api.definition.type.FactType; import org.kie.api.io.ResourceType; @@ -41,27 +40,18 @@ import static org.assertj.core.api.Assertions.assertThat; -@RunWith(Parameterized.class) public class TraitFieldsAndLegacyClassesTest extends CommonTraitTest { - public VirtualPropertyMode mode; - @Parameterized.Parameters - public static Collection modes() { - return Arrays.asList( new VirtualPropertyMode[][] - { - { VirtualPropertyMode.MAP }, - { VirtualPropertyMode.TRIPLES } - } ); + public static Collection modes() { + return List.of(VirtualPropertyMode.MAP , VirtualPropertyMode.TRIPLES ); } - public TraitFieldsAndLegacyClassesTest( VirtualPropertyMode m ) { - this.mode = m; - } - @Test - public void testTraitFieldUpdate0() { + @ParameterizedTest + @MethodSource("modes") + public void testTraitFieldUpdate0(VirtualPropertyMode mode) { String drl = "" + "package org.drools.factmodel.traits0;\n" + @@ -114,19 +104,21 @@ public void testTraitFieldUpdate0() { TraitFactoryImpl.setMode(mode, kBase ); KieSession knowledgeSession = kBase.newKieSession(); - List list = new ArrayList(); + List list = new ArrayList<>(); knowledgeSession.setGlobal("list", list); knowledgeSession.fireAllRules(); - assertThat(list.contains("correct")).isTrue(); - assertThat(list.size()).isEqualTo(1); + + assertThat(list).hasSize(1); + assertThat(list).contains("correct"); } - @Test - public void testTraitFieldUpdate1() { + @ParameterizedTest + @MethodSource("modes") + public void testTraitFieldUpdate1(VirtualPropertyMode mode) { String drl = "" + "package org.drools.factmodel.traits;\n" + @@ -202,18 +194,20 @@ public void testTraitFieldUpdate1() { TraitFactoryImpl.setMode(mode, kBase ); KieSession knowledgeSession = kBase.newKieSession(); - List list = new ArrayList(); + List list = new ArrayList<>(); knowledgeSession.setGlobal("list", list); knowledgeSession.fireAllRules(); - assertThat(list.contains("correct")).isTrue(); - assertThat(list.size()).isEqualTo(1); + + assertThat(list).hasSize(1); + assertThat(list).contains("correct"); } - @Test - public void testTraitFieldUpdate2() { + @ParameterizedTest + @MethodSource("modes") + public void testTraitFieldUpdate2(VirtualPropertyMode mode) { String drl = "" + "package org.drools.factmodel.traits2;\n" + @@ -301,17 +295,18 @@ public void testTraitFieldUpdate2() { KieSession knowledgeSession = kBase.newKieSession(); TraitFactoryImpl.setMode(mode, kBase ); - List list = new ArrayList(); + List list = new ArrayList<>(); knowledgeSession.setGlobal("list", list); knowledgeSession.fireAllRules(); - assertThat(list.contains("correct")).isTrue(); - assertThat(list.size()).isEqualTo(1); + assertThat(list).hasSize(1); + assertThat(list).contains("correct"); } - @Test - public void testTraitFieldUpdate3() { + @ParameterizedTest + @MethodSource("modes") + public void testTraitFieldUpdate3(VirtualPropertyMode mode) { String drl = "" + "package org.drools.factmodel.traits3;\n" + @@ -396,18 +391,20 @@ public void testTraitFieldUpdate3() { KieBase kBase = loadKnowledgeBaseFromString(drl); TraitFactoryImpl.setMode(mode, kBase ); KieSession knowledgeSession = kBase.newKieSession(); - List list = new ArrayList(); + List list = new ArrayList<>(); knowledgeSession.setGlobal("list", list); knowledgeSession.fireAllRules(); - assertThat(list.contains("correct")).isTrue(); - assertThat(list.size()).isEqualTo(1); + + assertThat(list).hasSize(1); + assertThat(list).contains("correct"); } @Category(ReviseTraitTestWithPRAlwaysCategory.class) - @Test - public void testTraitFieldUpdate4() { + @ParameterizedTest + @MethodSource("modes") + public void testTraitFieldUpdate4(VirtualPropertyMode mode) { String drl = "" + "package org.drools.factmodel.traits4;\n" + @@ -475,17 +472,18 @@ public void testTraitFieldUpdate4() { TraitFactoryImpl.setMode(mode, kBase ); KieSession knowledgeSession = kBase.newKieSession(); - List list = new ArrayList(); + List list = new ArrayList<>(); knowledgeSession.setGlobal("list", list); knowledgeSession.fireAllRules(); - assertThat(list.contains("correct")).isTrue(); - assertThat(list.size()).isEqualTo(1); + assertThat(list).hasSize(1); + assertThat(list).contains("correct"); } - @Test - public void testTraitFieldUpdate5() { + @ParameterizedTest + @MethodSource("modes") + public void testTraitFieldUpdate5(VirtualPropertyMode mode) { String drl = "" + "package org.drools.factmodel.traits5;\n" + @@ -559,17 +557,18 @@ public void testTraitFieldUpdate5() { TraitFactoryImpl.setMode(mode, kBase ); KieSession knowledgeSession = kBase.newKieSession(); - List list = new ArrayList(); + List list = new ArrayList<>(); knowledgeSession.setGlobal("list", list); knowledgeSession.fireAllRules(); - assertThat(list.contains("correct")).isTrue(); - assertThat(list.size()).isEqualTo(1); + assertThat(list).hasSize(1); + assertThat(list).contains("correct"); } - @Test - public void testTraitFieldUpdate6() { + @ParameterizedTest + @MethodSource("modes") + public void testTraitFieldUpdate6(VirtualPropertyMode mode) { String drl = "" + "package org.drools.factmodel.traits6;\n" + @@ -649,20 +648,20 @@ public void testTraitFieldUpdate6() { TraitFactoryImpl.setMode(mode, kBase ); KieSession knowledgeSession = kBase.newKieSession(); - List list = new ArrayList(); + List list = new ArrayList<>(); knowledgeSession.setGlobal("list", list); knowledgeSession.fireAllRules(); - assertThat(list.contains("correct")).isTrue(); - assertThat(list.contains("correct2")).isTrue(); - assertThat(list.size()).isEqualTo(2); + assertThat(list).hasSize(2); + assertThat(list).contains("correct", "correct2"); } - @Test - public void testTraitFieldUpdate7() { + @ParameterizedTest + @MethodSource("modes") + public void testTraitFieldUpdate7(VirtualPropertyMode mode) { String drl = "" + "package org.drools.factmodel.traits;\n" + @@ -733,20 +732,21 @@ public void testTraitFieldUpdate7() { TraitFactoryImpl.setMode(mode, kBase ); KieSession knowledgeSession = kBase.newKieSession(); - List list = new ArrayList(); + List list = new ArrayList<>(); knowledgeSession.setGlobal("list", list); knowledgeSession.fireAllRules(); - assertThat(list.contains("correct")).isTrue(); - assertThat(list.size()).isEqualTo(1); + assertThat(list).hasSize(1); + assertThat(list).contains("correct"); } - @Test - public void testTraitFieldUpdate8() { + @ParameterizedTest + @MethodSource("modes") + public void testTraitFieldUpdate8(VirtualPropertyMode mode) { String drl = "" + "package org.drools.factmodel.traits8;\n" + @@ -818,17 +818,18 @@ public void testTraitFieldUpdate8() { TraitFactoryImpl.setMode(mode, kBase ); KieSession knowledgeSession = kBase.newKieSession(); - List list = new ArrayList(); + List list = new ArrayList<>(); knowledgeSession.setGlobal("list", list); knowledgeSession.fireAllRules(); - assertThat(list.contains("correct")).isTrue(); - assertThat(list.size()).isEqualTo(1); + assertThat(list).hasSize(1); + assertThat(list).contains("correct"); } - @Test - public void testTraitFieldUpdate9() { + @ParameterizedTest + @MethodSource("modes") + public void testTraitFieldUpdate9(VirtualPropertyMode mode) { String drl = "" + "package org.drools.factmodel.traits9;\n" + @@ -909,17 +910,18 @@ public void testTraitFieldUpdate9() { TraitFactoryImpl.setMode(mode, kBase ); KieSession knowledgeSession = kBase.newKieSession(); - List list = new ArrayList(); + List list = new ArrayList<>(); knowledgeSession.setGlobal("list", list); knowledgeSession.fireAllRules(); - assertThat(list.contains("correct")).isTrue(); - assertThat(list.size()).isEqualTo(1); + assertThat(list).hasSize(1); + assertThat(list).contains("correct"); } - @Test - public void testTraitFieldUpdate10() { + @ParameterizedTest + @MethodSource("modes") + public void testTraitFieldUpdate10(VirtualPropertyMode mode) { String drl = "" + "package org.drools.factmodel.traits;\n" + @@ -1001,17 +1003,18 @@ public void testTraitFieldUpdate10() { TraitFactoryImpl.setMode(mode, kBase ); KieSession knowledgeSession = kBase.newKieSession(); - List list = new ArrayList(); + List list = new ArrayList<>(); knowledgeSession.setGlobal("list", list); knowledgeSession.fireAllRules(); - assertThat(list.contains("correct")).isTrue(); - assertThat(list.size()).isEqualTo(1); + assertThat(list).hasSize(1); + assertThat(list).contains("correct"); } - @Test - public void testTraitTwoParentOneChild() { + @ParameterizedTest + @MethodSource("modes") + public void testTraitTwoParentOneChild(VirtualPropertyMode mode) { String drl = "" + "package org.drools.factmodel.traits;\n" + @@ -1112,17 +1115,19 @@ public void testTraitTwoParentOneChild() { TraitFactoryImpl.setMode(mode, kBase ); KieSession knowledgeSession = kBase.newKieSession(); - List list = new ArrayList(); + List list = new ArrayList<>(); knowledgeSession.setGlobal("list", list); knowledgeSession.fireAllRules(); - assertThat(list.contains("correct")).isTrue(); - assertThat(list.size()).isEqualTo(1); + assertThat(list).hasSize(1); + assertThat(list).contains("correct"); } - @Test @Ignore - public void testTraitWithPositionArgs(){ + @ParameterizedTest + @Disabled + @MethodSource("modes") + public void testTraitWithPositionArgs(VirtualPropertyMode mode){ String drl = "" + "package org.drools.traits.test;\n" + @@ -1245,23 +1250,24 @@ public void testTraitWithPositionArgs(){ TraitFactoryImpl.setMode(mode, kBase ); KieSession kSession = kBase.newKieSession(); - List list = new ArrayList(); + List list = new ArrayList<>(); kSession.setGlobal("list", list); kSession.fireAllRules(); - assertThat(list.contains("initialized")).isTrue(); - assertThat(list.contains("student")).isTrue(); - assertThat(list.contains("IR citizen")).isTrue(); - assertThat(list.contains("US citizen")).isTrue(); - assertThat(list.contains("worker")).isTrue(); - assertThat(list.contains("You are working in US as student worker")).isTrue(); - assertThat(list.contains("You are studying and working at ASU")).isTrue(); + assertThat(list).contains("initialized"); + assertThat(list).contains("student"); + assertThat(list).contains("IR citizen"); + assertThat(list).contains("US citizen"); + assertThat(list).contains("worker"); + assertThat(list).contains("You are working in US as student worker"); + assertThat(list).contains("You are studying and working at ASU"); } - @Test - public void singlePositionTraitTest(){ + @ParameterizedTest + @MethodSource("modes") + public void singlePositionTraitTest(VirtualPropertyMode mode){ String drl = "" + diff --git a/drools-traits/src/test/java/org/drools/traits/compiler/factmodel/traits/TraitMapCoreTest.java b/drools-traits/src/test/java/org/drools/traits/compiler/factmodel/traits/TraitMapCoreTest.java index 97f8a3ac4da..d4d9cae880c 100644 --- a/drools-traits/src/test/java/org/drools/traits/compiler/factmodel/traits/TraitMapCoreTest.java +++ b/drools-traits/src/test/java/org/drools/traits/compiler/factmodel/traits/TraitMapCoreTest.java @@ -29,7 +29,8 @@ import org.drools.traits.core.factmodel.TraitFactoryImpl; import org.drools.base.factmodel.traits.Traitable; import org.drools.traits.core.factmodel.VirtualPropertyMode; -import org.junit.Test; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.Timeout; import org.kie.api.runtime.KieSession; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -40,7 +41,8 @@ public class TraitMapCoreTest extends CommonTraitTest { private static final Logger LOGGER = LoggerFactory.getLogger(TraitMapCoreTest.class); - @Test(timeout=10000) + @Test() + @Timeout(value = 10000) public void testMapCoreManyTraits( ) { String source = "package org.drools.test;\n" + "\n" + @@ -98,7 +100,8 @@ public void testMapCoreManyTraits( ) { assertThat(map.get("GPA")).isEqualTo(3.0); } - @Test(timeout=10000) + @Test() + @Timeout(value = 10000) public void donMapTest() { String source = "package org.drools.traits.test; \n" + "import java.util.*\n;" + @@ -138,19 +141,19 @@ public void donMapTest() { List list = new ArrayList(); ksession.setGlobal( "list", list ); - Map map = new HashMap(); + Map map = new HashMap<>(); map.put( "name", "john" ); map.put( "age", 18 ); ksession.insert( map ); ksession.fireAllRules(); - assertThat(map.containsKey("height")).isTrue(); - assertThat(184.0).isEqualTo(map.get("height")); + assertThat(map).containsEntry("height", 184.0); } - @Test(timeout=10000) + @Test() + @Timeout(value = 10000) public void testMapCore2( ) { String source = "package org.drools.base.factmodel.traits.test;\n" + "\n" + @@ -262,7 +265,8 @@ public void testMapCore2( ) { } - @Test(timeout=10000) + @Test() + @Timeout(value = 10000) public void testMapCoreAliasing( ) { String source = "package org.drools.base.factmodel.traits.test;\n" + "\n" + @@ -325,7 +329,8 @@ public void testMapCoreAliasing( ) { } - @Test(timeout=10000) + @Test() + @Timeout(value = 10000) public void testMapCoreAliasingLogicalTrueWithTypeClash( ) { String source = "package org.drools.base.factmodel.traits.test;\n" + "\n" + @@ -363,7 +368,7 @@ public void testMapCoreAliasingLogicalTrueWithTypeClash( ) { KieSession ks = loadKnowledgeBaseFromString( source ).newKieSession(); TraitFactoryImpl.setMode(VirtualPropertyMode.MAP, ks.getKieBase() ); - List list = new ArrayList(); + List list = new ArrayList<>(); ks.setGlobal( "list", list ); Map map = new HashMap( ); @@ -373,7 +378,8 @@ public void testMapCoreAliasingLogicalTrueWithTypeClash( ) { ks.fireAllRules(); - assertThat(list.size() == 1 && list.get(0) == null).isTrue(); + assertThat(list).hasSize(1); + assertThat(list.get(0)).isNull(); } @Test @@ -454,13 +460,11 @@ public void testDrools216(){ KieSession ksession = loadKnowledgeBaseFromString(drl).newKieSession(); TraitFactoryImpl.setMode(VirtualPropertyMode.MAP, ksession.getKieBase()); - List list = new ArrayList(); + List list = new ArrayList<>(); ksession.setGlobal( "list", list ); ksession.fireAllRules(); - assertThat(list.contains("initialized")).isTrue(); - assertThat(list.contains("student is donned")).isTrue(); - assertThat(list.contains("worker is donned")).isTrue(); + assertThat(list).contains("initialized", "student is donned", "worker is donned"); } @@ -541,13 +545,11 @@ public void testDrools217(){ KieSession ksession = loadKnowledgeBaseFromString(drl).newKieSession(); TraitFactoryImpl.setMode(VirtualPropertyMode.MAP, ksession.getKieBase()); - List list = new ArrayList(); + List list = new ArrayList<>(); ksession.setGlobal("list", list); ksession.fireAllRules(); - assertThat(list.contains("initialized")).isTrue(); - assertThat(list.contains("student is donned")).isTrue(); - assertThat(list.contains("worker is donned")).isTrue(); + assertThat(list).contains("initialized", "student is donned", "worker is donned"); } @Test @@ -656,15 +658,11 @@ public void testDrools218(){ KieSession ksession = loadKnowledgeBaseFromString(drl).newKieSession(); TraitFactoryImpl.setMode(VirtualPropertyMode.MAP, ksession.getKieBase()); - List list = new ArrayList(); + List list = new ArrayList<>(); ksession.setGlobal( "list", list ); ksession.fireAllRules(); - assertThat(list.contains("initialized")).isTrue(); - assertThat(list.contains("student is donned")).isTrue(); - assertThat(list.contains("worker is donned")).isTrue(); - assertThat(list.contains("studentworker is donned")).isTrue(); - assertThat(list.contains("tuitionWaiver is true")).isTrue(); + assertThat(list).contains("initialized", "student is donned", "worker is donned", "studentworker is donned", "tuitionWaiver is true"); } @Test @@ -758,16 +756,12 @@ public void testDrools219(){ KieSession ksession = loadKnowledgeBaseFromString(drl).newKieSession(); TraitFactoryImpl.setMode(VirtualPropertyMode.MAP, ksession.getKieBase()); - List list = new ArrayList(); + List list = new ArrayList<>(); ksession.setGlobal( "list", list ); ksession.fireAllRules(); - assertThat(list.contains("initialized")).isTrue(); - assertThat(list.contains("student is donned")).isTrue(); - assertThat(list.contains("student has ID and SSN")).isTrue(); - assertThat(list.contains("student has personID and socialSecurity")).isTrue(); - assertThat(list.contains("citizen has socialSecurity")).isTrue(); - assertThat(list.contains("person has personID")).isTrue(); + assertThat(list).contains("initialized", "student is donned", "student has ID and SSN", + "student has personID and socialSecurity", "citizen has socialSecurity", "person has personID"); } @Test @@ -827,7 +821,7 @@ public void testMapTraitsMismatchTypes() ksession.insert( map ); ksession.fireAllRules(); - assertThat(list.size()).isEqualTo(2); + assertThat(list).hasSize(2); assertThat(list.get(0)).isNull(); assertThat(list.get(1)).isNotNull(); } @@ -874,18 +868,18 @@ public void testMapTraitNoType() KieSession ksession = loadKnowledgeBaseFromString(drl).newKieSession(); TraitFactoryImpl.setMode(VirtualPropertyMode.MAP, ksession.getKieBase()); - List list = new ArrayList(); + List list = new ArrayList<>(); ksession.setGlobal("list",list); Map map = new HashMap(); // map.put("name", "hulu"); ksession.insert(map); ksession.fireAllRules(); - assertThat(list.contains("correct1")).isTrue(); - assertThat(list.contains("correct2")).isTrue(); + assertThat(list).contains("correct1", "correct2"); } - @Test(timeout=10000) + @Test() + @Timeout(value = 10000) public void testMapTraitMismatchTypes() { String drl = "" + @@ -930,7 +924,7 @@ public void testMapTraitMismatchTypes() ksession.insert(map); ksession.fireAllRules(); - assertThat(list.size()).isEqualTo(1); + assertThat(list).hasSize(1); assertThat(list.get(0)).isEqualTo(null); } @@ -995,7 +989,7 @@ public void testMapTraitPossibilities1() ksession.setGlobal("list",list); ksession.fireAllRules(); - assertThat(list.size()).isEqualTo(1); + assertThat(list).hasSize(1); assertThat(list.get(0)).isNotNull(); } @@ -1064,7 +1058,7 @@ public void testMapTraitPossibilities2() ksession.setGlobal("list",list); ksession.fireAllRules(); - assertThat(list.size()).isEqualTo(1); + assertThat(list).hasSize(1); assertThat(list.get(0)).isNotNull(); } @@ -1133,7 +1127,7 @@ public void testMapTraitPossibilities3() ksession.setGlobal("list",list); ksession.fireAllRules(); - assertThat(list.size()).isEqualTo(1); + assertThat(list).hasSize(1); assertThat(list.get(0)).isNotNull(); } @@ -1205,7 +1199,7 @@ public void testMapTraitPossibilities4() ksession.setGlobal("list",list); ksession.fireAllRules(); - assertThat(list.size()).isEqualTo(1); + assertThat(list).hasSize(1); assertThat(list.get(0)).isNotNull(); } @@ -1248,18 +1242,17 @@ public void donCustomMapTest() { List list = new ArrayList(); ksession.setGlobal( "list", list ); - HashMap map = new DomainMap(); + Map map = new DomainMap(); map.put( "name", "john" ); map.put( "age", 18 ); ksession.insert( map ); ksession.fireAllRules(); - assertThat(map.containsKey("height")).isTrue(); - assertThat(184.0).isEqualTo(map.get("height")); + assertThat(map).containsEntry("height", 184.0); - assertThat(ksession.getObjects().size()).isEqualTo(2); - assertThat(ksession.getObjects(new ClassObjectFilter( DomainMap.class )).size()).isEqualTo(1); + assertThat(ksession.getObjects()).hasSize(2); + assertThat(ksession.getObjects(new ClassObjectFilter( DomainMap.class ))).hasSize(1); } diff --git a/drools-traits/src/test/java/org/drools/traits/compiler/factmodel/traits/TraitTest.java b/drools-traits/src/test/java/org/drools/traits/compiler/factmodel/traits/TraitTest.java index 5b912937e0f..8c9142f1664 100644 --- a/drools-traits/src/test/java/org/drools/traits/compiler/factmodel/traits/TraitTest.java +++ b/drools-traits/src/test/java/org/drools/traits/compiler/factmodel/traits/TraitTest.java @@ -28,7 +28,6 @@ import org.drools.core.common.InternalWorkingMemory; import org.drools.core.common.ObjectTypeConfigurationRegistry; import org.drools.core.impl.InternalRuleBase; -import org.drools.core.reteoo.LeftTuple; import org.drools.core.reteoo.ObjectTypeConf; import org.drools.core.reteoo.ObjectTypeNode; import org.drools.core.reteoo.RuleTerminalNodeLeftTuple; @@ -44,7 +43,6 @@ import org.drools.traits.compiler.ReviseTraitTestWithPRAlwaysCategory; import org.drools.traits.core.factmodel.Entity; import org.drools.traits.core.factmodel.HierarchyEncoder; -import org.drools.traits.core.factmodel.LogicalTypeInconsistencyException; import org.drools.traits.core.factmodel.MapWrapper; import org.drools.traits.core.factmodel.TraitFactoryImpl; import org.drools.traits.core.factmodel.TraitProxyImpl; @@ -105,6 +103,8 @@ import java.util.concurrent.TimeUnit; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatException; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.assertj.core.api.Assertions.fail; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.times; @@ -114,43 +114,36 @@ public class TraitTest extends CommonTraitTest { private static final Logger LOGGER = LoggerFactory.getLogger(TraitTest.class); - - private static long t0; - - + public VirtualPropertyMode mode; @Parameterized.Parameters - public static Collection modes() { - return Arrays.asList( new VirtualPropertyMode[][] - { - { VirtualPropertyMode.MAP }, - { VirtualPropertyMode.TRIPLES } - } ); + public static Collection modes() { + return List.of(VirtualPropertyMode.MAP, VirtualPropertyMode.TRIPLES); } - public TraitTest( VirtualPropertyMode m ) { + public TraitTest(VirtualPropertyMode m) { this.mode = m; } - private KieSession getSession( String... ruleFiles ) { + private KieSession getSession(String... ruleFiles) { KieHelper kieHelper = new KieHelper(); for (String file : ruleFiles) { - kieHelper.kfs.write( new ClassPathResource( file ) ); + kieHelper.kfs.write(new ClassPathResource(file)); } return kieHelper.build().newKieSession(); } - private KieSession getSessionFromString( String drl ) { - return new KieHelper().addContent( drl, ResourceType.DRL ).build().newKieSession(); + private KieSession getSessionFromString(String drl) { + return new KieHelper().addContent(drl, ResourceType.DRL).build().newKieSession(); } - private KieBase getKieBaseFromString( String drl, KieBaseOption... options ) { - return new KieHelper().addContent( drl, ResourceType.DRL ).build(options); + private KieBase getKieBaseFromString(String drl, KieBaseOption... options) { + return new KieHelper().addContent(drl, ResourceType.DRL).build(options); } @Test - public void testRetract( ) { + public void testRetract() { String drl = "package org.drools.compiler.trait.test; \n" + "import org.drools.base.factmodel.traits.Traitable; \n" + "" + @@ -159,16 +152,16 @@ public void testRetract( ) { "" + "rule Init when then\n" + " Foo foo = new Foo(); \n" + - " don( foo, Bar.class ); \n" + + " don(foo, Bar.class); \n" + "end\n" + "rule Retract \n" + "when\n" + " $bar : Bar()\n" + "then\n" + - " delete( $bar ); \n" + + " delete($bar); \n" + "end\n"; - KieSession ks = getSessionFromString( drl ); + KieSession ks = getSessionFromString(drl); TraitFactoryImpl.setMode(mode, ks.getKieBase()); assertThat(ks.fireAllRules()).isEqualTo(2); @@ -177,59 +170,47 @@ public void testRetract( ) { LOGGER.debug(o.toString()); } - assertThat(ks.getObjects().size()).isEqualTo(0); + assertThat(ks.getObjects()).isEmpty(); } @Test - public void testTraitWrapGetAndSet() { + public void testTraitWrapGetAndSet() throws Exception { String source = "org/drools/compiler/factmodel/traits/testTraitDon.drl"; KnowledgeBuilder kbuilder = KnowledgeBuilderFactory.newKnowledgeBuilder(); - Resource res = ResourceFactory.newClassPathResource( source ); + Resource res = ResourceFactory.newClassPathResource(source); assertThat(res).isNotNull(); - kbuilder.add( res, - ResourceType.DRL ); + kbuilder.add(res, ResourceType.DRL); if (kbuilder.hasErrors()) { - fail( kbuilder.getErrors().toString() ); + fail(kbuilder.getErrors().toString()); } InternalRuleBase kb = KnowledgeBaseFactory.newKnowledgeBase(); - TraitFactoryImpl.setMode(mode, kb ); - kb.addPackages( kbuilder.getKnowledgePackages() ); + TraitFactoryImpl.setMode(mode, kb); + kb.addPackages(kbuilder.getKnowledgePackages()); TraitFactoryImpl tFactory = (TraitFactoryImpl) RuntimeComponentFactory.get().getTraitFactory(kb); - try { - FactType impClass = kb.getFactType( "org.drools.compiler.trait.test", - "Imp" ); - TraitableBean imp = (TraitableBean) impClass.newInstance(); - Class trait = kb.getFactType( "org.drools.compiler.trait.test", - "Student" ).getFactClass(); - - TraitProxyImpl proxy = (TraitProxyImpl) tFactory.getProxy(imp, - trait ); + FactType impClass = kb.getFactType("org.drools.compiler.trait.test", "Imp"); + TraitableBean imp = (TraitableBean) impClass.newInstance(); + Class trait = kb.getFactType("org.drools.compiler.trait.test", "Student").getFactClass(); - Map virtualFields = imp._getDynamicProperties(); - Map wrapper = proxy.getFields(); + TraitProxyImpl proxy = (TraitProxyImpl) tFactory.getProxy(imp, trait, false); - wrapper.put( "name", - "john" ); + Map virtualFields = imp._getDynamicProperties(); + Map wrapper = proxy.getFields(); - wrapper.put( "virtualField", - "xyz" ); + wrapper.put("name", "john"); - wrapper.entrySet(); - assertThat(wrapper.size()).isEqualTo(4); - assertThat(virtualFields.size()).isEqualTo(2); + wrapper.put("virtualField", "xyz"); - assertThat(wrapper.get("name")).isEqualTo("john"); - assertThat(wrapper.get("virtualField")).isEqualTo("xyz"); + wrapper.entrySet(); + assertThat(wrapper).hasSize(4); + assertThat(virtualFields).hasSize(2); - assertThat(impClass.get(imp, - "name")).isEqualTo("john"); + assertThat(wrapper.get("name")).isEqualTo("john"); + assertThat(wrapper.get("virtualField")).isEqualTo("xyz"); - } catch (Exception e) { - fail( e.getMessage(), e ); - } + assertThat(impClass.get(imp, "name")).isEqualTo("john"); } @@ -237,35 +218,32 @@ public void testTraitWrapGetAndSet() { public void testTraitShed() { String source = "org/drools/compiler/factmodel/traits/testTraitShed.drl"; - KieSession ks = getSession( source ); - TraitFactoryImpl.setMode(mode, ks.getKieBase() ); + KieSession ks = getSession(source); + TraitFactoryImpl.setMode(mode, ks.getKieBase()); - List info = new ArrayList(); - ks.setGlobal( "list", - info ); + List info = new ArrayList<>(); + ks.setGlobal("list", info); - assertThat(info.isEmpty()).isTrue(); + assertThat(info).isEmpty(); ks.fireAllRules(); - assertThat(info.contains("Student")).isTrue(); - assertThat(info.size()).isEqualTo(1); + assertThat(info).contains("Student"); + assertThat(info).hasSize(1); - ks.insert( "hire" ); + ks.insert("hire"); ks.fireAllRules(); - Collection c = ks.getObjects(); - - assertThat(info.contains("Worker")).isTrue(); - assertThat(info.size()).isEqualTo(2); + assertThat(info).contains("Worker"); + assertThat(info).hasSize(2); - ks.insert( "check" ); + ks.insert("check"); ks.fireAllRules(); - assertThat(info.size()).isEqualTo(4); - assertThat(info.contains("Conflict")).isTrue(); - assertThat(info.contains("Nothing")).isTrue(); + assertThat(info).hasSize(4); + assertThat(info).contains("Conflict"); + assertThat(info).contains("Nothing"); } @@ -273,47 +251,45 @@ public void testTraitShed() { public void testTraitDon() { String source = "org/drools/compiler/factmodel/traits/testTraitDon.drl"; - KieSession ks = getSession( source ); - TraitFactoryImpl.setMode(mode, ks.getKieBase() ); + KieSession ks = getSession(source); + TraitFactoryImpl.setMode(mode, ks.getKieBase()); - List info = new ArrayList(); - ks.setGlobal( "list", - info ); + List info = new ArrayList<>(); + ks.setGlobal("list", info); ks.fireAllRules(); Collection wm = ks.getObjects(); - ks.insert( "go" ); + ks.insert("go"); ks.fireAllRules(); - assertThat(info.contains("DON")).isTrue(); - assertThat(info.contains("SHED")).isTrue(); + assertThat(info).contains("DON"); + assertThat(info).contains("SHED"); - Iterator it = wm.iterator(); + Iterator it = wm.iterator(); Object x = it.next(); - if ( x instanceof String ) { + if (x instanceof String) { x = it.next(); } LOGGER.debug(x.getClass().toString()); LOGGER.debug(x.getClass().getSuperclass().toString()); - LOGGER.debug(Arrays.asList(x.getClass().getInterfaces()).toString()); + LOGGER.debug(List.of(x.getClass().getInterfaces()).toString()); } @Test public void testMixin() { String source = "org/drools/compiler/factmodel/traits/testTraitMixin.drl"; - KieSession ks = getSession( source ); - TraitFactoryImpl.setMode(mode, ks.getKieBase() ); + KieSession ks = getSession(source); + TraitFactoryImpl.setMode(mode, ks.getKieBase()); - List info = new ArrayList(); - ks.setGlobal( "list", - info ); + List info = new ArrayList<>(); + ks.setGlobal("list", info); ks.fireAllRules(); - assertThat(info.contains("27")).isTrue(); + assertThat(info).contains("27"); } @@ -321,19 +297,18 @@ public void testMixin() { public void traitMethodsWithObjects() { String source = "org/drools/compiler/factmodel/traits/testTraitWrapping.drl"; - KieSession ks = getSession( source ); - TraitFactoryImpl.setMode(mode, ks.getKieBase() ); + KieSession ks = getSession(source); + TraitFactoryImpl.setMode(mode, ks.getKieBase()); - List errors = new ArrayList(); - ks.setGlobal( "list", - errors ); + List errors = new ArrayList<>(); + ks.setGlobal("list", errors); ks.fireAllRules(); if (!errors.isEmpty()) { LOGGER.error(errors.toString()); } - assertThat(errors.isEmpty()).isTrue(); + assertThat(errors).isEmpty(); } @@ -342,655 +317,506 @@ public void traitMethodsWithObjects() { public void traitMethodsWithPrimitives() { String source = "org/drools/compiler/factmodel/traits/testTraitWrappingPrimitives.drl"; - KieSession ks = getSession( source ); - TraitFactoryImpl.setMode(mode, ks.getKieBase() ); + KieSession ks = getSession(source); + TraitFactoryImpl.setMode(mode, ks.getKieBase()); - List errors = new ArrayList(); - ks.setGlobal( "list", - errors ); + List errors = new ArrayList<>(); + ks.setGlobal("list", errors); ks.fireAllRules(); if (!errors.isEmpty()) { LOGGER.error(errors.toString()); } - assertThat(errors.isEmpty()).isTrue(); + assertThat(errors).isEmpty(); } @Test - public void testTraitProxy() { + public void testTraitProxy() throws Exception { String source = "org/drools/compiler/factmodel/traits/testTraitDon.drl"; KnowledgeBuilder kbuilder = KnowledgeBuilderFactory.newKnowledgeBuilder(); - Resource res = ResourceFactory.newClassPathResource( source ); + Resource res = ResourceFactory.newClassPathResource(source); assertThat(res).isNotNull(); - kbuilder.add( res, - ResourceType.DRL ); + kbuilder.add(res, ResourceType.DRL); if (kbuilder.hasErrors()) { - fail( kbuilder.getErrors().toString() ); + fail(kbuilder.getErrors().toString()); } InternalRuleBase kb = KnowledgeBaseFactory.newKnowledgeBase(); - kb.addPackages( kbuilder.getKnowledgePackages() ); - TraitFactoryImpl.setMode(mode, kb ); + kb.addPackages(kbuilder.getKnowledgePackages()); + TraitFactoryImpl.setMode(mode, kb); TraitFactoryImpl tFactory = (TraitFactoryImpl) RuntimeComponentFactory.get().getTraitFactory(kb); - try { - FactType impClass = kb.getFactType( "org.drools.compiler.trait.test", - "Imp" ); - TraitableBean imp = (TraitableBean) impClass.newInstance(); - impClass.set( imp, - "name", - "aaa" ); - - Class trait = kb.getFactType( "org.drools.compiler.trait.test", - "Student" ).getFactClass(); - Class trait2 = kb.getFactType( "org.drools.compiler.trait.test", - "Role" ).getFactClass(); - - assertThat(trait).isNotNull(); - TraitProxyImpl proxy = (TraitProxyImpl) tFactory.getProxy(imp, - trait ); - proxy.getFields().put( "field", - "xyz" ); - // proxy.getFields().put("name", "aaa"); - - assertThat(proxy).isNotNull(); - - TraitProxyImpl proxy2 = (TraitProxyImpl) tFactory.getProxy(imp, - trait ); - assertThat(proxy).isSameAs(proxy2); - - TraitProxyImpl proxy3 = (TraitProxyImpl) tFactory.getProxy(imp, - trait2 ); - assertThat(proxy3).isNotNull(); - assertThat(proxy3.getFields().get("field")).isEqualTo("xyz"); - assertThat(proxy3.getFields().get("name")).isEqualTo("aaa"); - - TraitableBean imp2 = (TraitableBean) impClass.newInstance(); - impClass.set( imp2, - "name", - "aaa" ); - TraitProxyImpl proxy4 = (TraitProxyImpl) tFactory.getProxy(imp2, - trait ); - // proxy4.getFields().put("name", "aaa"); - proxy4.getFields().put( "field", - "xyz" ); - - assertThat(proxy4).isEqualTo(proxy2); - - } catch (InstantiationException | IllegalAccessException | LogicalTypeInconsistencyException e) { - fail( e.getMessage(), e ); - } + FactType impClass = kb.getFactType("org.drools.compiler.trait.test", "Imp"); + TraitableBean imp = (TraitableBean) impClass.newInstance(); + impClass.set(imp, "name", "aaa"); + + Class trait = kb.getFactType("org.drools.compiler.trait.test", "Student").getFactClass(); + Class trait2 = kb.getFactType("org.drools.compiler.trait.test", "Role").getFactClass(); + + assertThat(trait).isNotNull(); + TraitProxyImpl proxy = (TraitProxyImpl) tFactory.getProxy(imp, trait, false); + proxy.getFields().put("field", "xyz"); + // proxy.getFields().put("name", "aaa"); + + assertThat(proxy).isNotNull(); + + TraitProxyImpl proxy2 = (TraitProxyImpl) tFactory.getProxy(imp, trait, false); + assertThat(proxy).isSameAs(proxy2); + + TraitProxyImpl proxy3 = (TraitProxyImpl) tFactory.getProxy(imp, trait2, false); + assertThat(proxy3).isNotNull(); + assertThat(proxy3.getFields().get("field")).isEqualTo("xyz"); + assertThat(proxy3.getFields().get("name")).isEqualTo("aaa"); + + TraitableBean imp2 = (TraitableBean) impClass.newInstance(); + impClass.set(imp2, "name", "aaa"); + TraitProxyImpl proxy4 = (TraitProxyImpl) tFactory.getProxy(imp2, trait, false); + // proxy4.getFields().put("name", "aaa"); + proxy4.getFields().put("field", "xyz"); + + assertThat(proxy4).isEqualTo(proxy2); } @Test - public void testWrapperSize() { + public void testWrapperSize() throws Exception { String source = "org/drools/compiler/factmodel/traits/testTraitDon.drl"; KnowledgeBuilder kbuilder = KnowledgeBuilderFactory.newKnowledgeBuilder(); - Resource res = ResourceFactory.newClassPathResource( source ); + Resource res = ResourceFactory.newClassPathResource(source); assertThat(res).isNotNull(); - kbuilder.add( res, - ResourceType.DRL ); + kbuilder.add(res, ResourceType.DRL); if (kbuilder.hasErrors()) { - fail( kbuilder.getErrors().toString() ); + fail(kbuilder.getErrors().toString()); } InternalRuleBase kb = KnowledgeBaseFactory.newKnowledgeBase(); - kb.addPackages( kbuilder.getKnowledgePackages() ); + kb.addPackages(kbuilder.getKnowledgePackages()); - TraitFactoryImpl.setMode(mode, kb ); + TraitFactoryImpl.setMode(mode, kb); TraitFactoryImpl tFactory = (TraitFactoryImpl) RuntimeComponentFactory.get().getTraitFactory(kb); - try { - FactType impClass = kb.getFactType( "org.drools.compiler.trait.test", - "Imp" ); - TraitableBean imp = (TraitableBean) impClass.newInstance(); - FactType traitClass = kb.getFactType( "org.drools.compiler.trait.test", - "Student" ); - Class trait = traitClass.getFactClass(); - TraitProxyImpl proxy = (TraitProxyImpl) tFactory.getProxy(imp, - trait ); - - Map virtualFields = imp._getDynamicProperties(); - Map wrapper = proxy.getFields(); - assertThat(wrapper.size()).isEqualTo(3); - assertThat(virtualFields.size()).isEqualTo(1); - - impClass.set(imp, - "name", - "john"); - assertThat(wrapper.size()).isEqualTo(3); - assertThat(virtualFields.size()).isEqualTo(1); - - proxy.getFields().put( "school", - "skol" ); - assertThat(wrapper.size()).isEqualTo(3); - assertThat(virtualFields.size()).isEqualTo(1); - - proxy.getFields().put( "surname", - "xxx" ); - assertThat(wrapper.size()).isEqualTo(4); - assertThat(virtualFields.size()).isEqualTo(2); - - // FactType indClass = kb.getFactType("org.drools.compiler.trait.test","Entity"); - // TraitableBean ind = (TraitableBean) indClass.newInstance(); - TraitableBean ind = new Entity(); - - TraitProxyImpl proxy2 = (TraitProxyImpl) tFactory.getProxy(ind, - trait ); - - Map virtualFields2 = ind._getDynamicProperties(); - Map wrapper2 = proxy2.getFields(); - assertThat(wrapper2.size()).isEqualTo(3); - assertThat(virtualFields2.size()).isEqualTo(3); - - traitClass.set( proxy2, - "name", - "john" ); - assertThat(wrapper2.size()).isEqualTo(3); - assertThat(virtualFields2.size()).isEqualTo(3); - - proxy2.getFields().put( "school", - "skol" ); - assertThat(wrapper2.size()).isEqualTo(3); - assertThat(virtualFields2.size()).isEqualTo(3); - - proxy2.getFields().put( "surname", - "xxx" ); - assertThat(wrapper2.size()).isEqualTo(4); - assertThat(virtualFields2.size()).isEqualTo(4); - - FactType traitClass2 = kb.getFactType( "org.drools.compiler.trait.test", - "Role" ); - Class trait2 = traitClass2.getFactClass(); - // TraitableBean ind2 = (TraitableBean) indClass.newInstance(); - TraitableBean ind2 = new Entity(); - - TraitProxyImpl proxy99 = (TraitProxyImpl) tFactory.getProxy(ind2, - trait2 ); - - proxy99.getFields().put( "surname", - "xxx" ); - proxy99.getFields().put( "name", - "xyz" ); - proxy99.getFields().put( "school", - "skol" ); - - assertThat(proxy99.getFields().size()).isEqualTo(3); - - TraitProxyImpl proxy100 = (TraitProxyImpl) tFactory.getProxy(ind2, - trait ); - - assertThat(proxy100.getFields().size()).isEqualTo(4); - - } catch ( Exception e ) { - fail( e.getMessage(), e ); - } + FactType impClass = kb.getFactType("org.drools.compiler.trait.test", "Imp"); + TraitableBean imp = (TraitableBean) impClass.newInstance(); + FactType traitClass = kb.getFactType("org.drools.compiler.trait.test", "Student"); + Class trait = traitClass.getFactClass(); + TraitProxyImpl proxy = (TraitProxyImpl) tFactory.getProxy(imp, trait, false); + + Map virtualFields = imp._getDynamicProperties(); + Map wrapper = proxy.getFields(); + assertThat(wrapper).hasSize(3); + assertThat(virtualFields).hasSize(1); + + impClass.set(imp, "name", "john"); + assertThat(wrapper).hasSize(3); + assertThat(virtualFields).hasSize(1); + + proxy.getFields().put("school", "skol"); + assertThat(wrapper).hasSize(3); + assertThat(virtualFields).hasSize(1); + + proxy.getFields().put("surname", "xxx"); + assertThat(wrapper).hasSize(4); + assertThat(virtualFields).hasSize(2); + + // FactType indClass = kb.getFactType("org.drools.compiler.trait.test","Entity"); + // TraitableBean ind = (TraitableBean) indClass.newInstance(); + TraitableBean ind = new Entity(); + + TraitProxyImpl proxy2 = (TraitProxyImpl) tFactory.getProxy(ind, trait, false); + + Map virtualFields2 = ind._getDynamicProperties(); + Map wrapper2 = proxy2.getFields(); + assertThat(wrapper2).hasSize(3); + assertThat(virtualFields2).hasSize(3); + + traitClass.set(proxy2, "name", "john"); + assertThat(wrapper2).hasSize(3); + assertThat(virtualFields2).hasSize(3); + + proxy2.getFields().put("school", "skol"); + assertThat(wrapper2).hasSize(3); + assertThat(virtualFields2).hasSize(3); + + proxy2.getFields().put("surname", "xxx"); + assertThat(wrapper2).hasSize(4); + assertThat(virtualFields2).hasSize(4); + + FactType traitClass2 = kb.getFactType("org.drools.compiler.trait.test", "Role"); + Class trait2 = traitClass2.getFactClass(); + // TraitableBean ind2 = (TraitableBean) indClass.newInstance(); + TraitableBean ind2 = new Entity(); + + TraitProxyImpl proxy99 = (TraitProxyImpl) tFactory.getProxy(ind2, trait2, false); + + proxy99.getFields().put("surname", "xxx"); + proxy99.getFields().put("name", "xyz"); + proxy99.getFields().put("school", "skol"); + + assertThat(proxy99.getFields()).hasSize(3); + + TraitProxyImpl proxy100 = (TraitProxyImpl) tFactory.getProxy(ind2, trait, false); + + assertThat(proxy100.getFields()).hasSize(4); } @Test - public void testWrapperEmpty() { + public void testWrapperEmpty() throws Exception { String source = "org/drools/compiler/factmodel/traits/testTraitDon.drl"; KnowledgeBuilder kbuilder = KnowledgeBuilderFactory.newKnowledgeBuilder(); - Resource res = ResourceFactory.newClassPathResource( source ); + Resource res = ResourceFactory.newClassPathResource(source); assertThat(res).isNotNull(); - kbuilder.add( res, - ResourceType.DRL ); + + kbuilder.add(res, ResourceType.DRL); if (kbuilder.hasErrors()) { - fail( kbuilder.getErrors().toString() ); + fail(kbuilder.getErrors().toString()); } InternalRuleBase kb = KnowledgeBaseFactory.newKnowledgeBase(); - kb.addPackages( kbuilder.getKnowledgePackages() ); - TraitFactoryImpl.setMode(mode, kb ); + kb.addPackages(kbuilder.getKnowledgePackages()); + TraitFactoryImpl.setMode(mode, kb); TraitFactoryImpl tFactory = (TraitFactoryImpl) RuntimeComponentFactory.get().getTraitFactory(kb); - try { - FactType impClass = kb.getFactType( "org.drools.compiler.trait.test", - "Imp" ); - TraitableBean imp = (TraitableBean) impClass.newInstance(); - - FactType studentClass = kb.getFactType( "org.drools.compiler.trait.test", - "Student" ); - Class trait = studentClass.getFactClass(); - TraitProxyImpl proxy = (TraitProxyImpl) tFactory.getProxy(imp, - trait ); - - Map virtualFields = imp._getDynamicProperties(); - Map wrapper = proxy.getFields(); - assertThat(wrapper.isEmpty()).isFalse(); - - studentClass.set( proxy, - "name", - "john" ); - assertThat(wrapper.isEmpty()).isFalse(); - studentClass.set( proxy, - "name", - null ); - assertThat(wrapper.isEmpty()).isFalse(); - - studentClass.set( proxy, - "age", - 32 ); - assertThat(wrapper.isEmpty()).isFalse(); - - studentClass.set( proxy, - "age", - null ); - assertThat(wrapper.isEmpty()).isFalse(); - - // FactType indClass = kb.getFactType("org.drools.compiler.trait.test","Entity"); - TraitableBean ind = new Entity(); - - FactType RoleClass = kb.getFactType( "org.drools.compiler.trait.test", - "Role" ); - Class trait2 = RoleClass.getFactClass(); - TraitProxyImpl proxy2 = (TraitProxyImpl) tFactory.getProxy(ind, - trait2 ); - - Map wrapper2 = proxy2.getFields(); - assertThat(wrapper2.isEmpty()).isTrue(); - - proxy2.getFields().put( "name", - "john" ); - assertThat(wrapper2.isEmpty()).isFalse(); - - proxy2.getFields().put( "name", - null ); - assertThat(wrapper2.isEmpty()).isFalse(); - - } catch (Exception e) { - fail( e.getMessage(), e ); - } + FactType impClass = kb.getFactType("org.drools.compiler.trait.test", "Imp"); + TraitableBean imp = (TraitableBean) impClass.newInstance(); + + FactType studentClass = kb.getFactType("org.drools.compiler.trait.test", "Student"); + Class trait = studentClass.getFactClass(); + TraitProxyImpl proxy = (TraitProxyImpl) tFactory.getProxy(imp, trait, false); + + Map wrapper = proxy.getFields(); + assertThat(wrapper).isNotEmpty(); + + studentClass.set(proxy, "name", "john"); + assertThat(wrapper).isNotEmpty(); + + studentClass.set(proxy, "name", null); + assertThat(wrapper).isNotEmpty(); + + studentClass.set(proxy, "age", 32); + assertThat(wrapper).isNotEmpty(); + + studentClass.set(proxy, "age", null); + assertThat(wrapper).isNotEmpty(); + + // FactType indClass = kb.getFactType("org.drools.compiler.trait.test","Entity"); + TraitableBean ind = new Entity(); + + FactType RoleClass = kb.getFactType("org.drools.compiler.trait.test", "Role"); + Class trait2 = RoleClass.getFactClass(); + TraitProxyImpl proxy2 = (TraitProxyImpl) tFactory.getProxy(ind, trait2, false); + + Map wrapper2 = proxy2.getFields(); + assertThat(wrapper2).isEmpty(); + + proxy2.getFields().put("name", "john"); + assertThat(wrapper2).isNotEmpty(); + + proxy2.getFields().put("name", null); + assertThat(wrapper2).isNotEmpty(); } @Test - public void testWrapperContainsKey() { + public void testWrapperContainsKey() throws Exception { String source = "org/drools/compiler/factmodel/traits/testTraitDon.drl"; KnowledgeBuilder kbuilder = KnowledgeBuilderFactory.newKnowledgeBuilder(); - Resource res = ResourceFactory.newClassPathResource( source ); + Resource res = ResourceFactory.newClassPathResource(source); assertThat(res).isNotNull(); - kbuilder.add( res, - ResourceType.DRL ); + kbuilder.add(res, ResourceType.DRL); if (kbuilder.hasErrors()) { - fail( kbuilder.getErrors().toString() ); + fail(kbuilder.getErrors().toString()); } InternalRuleBase kb = KnowledgeBaseFactory.newKnowledgeBase(); - kb.addPackages( kbuilder.getKnowledgePackages() ); + kb.addPackages(kbuilder.getKnowledgePackages()); - TraitFactoryImpl.setMode(mode, kb ); + TraitFactoryImpl.setMode(mode, kb); TraitFactoryImpl tFactory = (TraitFactoryImpl) RuntimeComponentFactory.get().getTraitFactory(kb); - try { - FactType impClass = kb.getFactType( "org.drools.compiler.trait.test", - "Imp" ); - TraitableBean imp = (TraitableBean) impClass.newInstance(); - impClass.set( imp, - "name", - "john" ); - - FactType traitClass = kb.getFactType( "org.drools.compiler.trait.test", - "Student" ); - Class trait = traitClass.getFactClass(); - TraitProxyImpl proxy = (TraitProxyImpl) tFactory.getProxy(imp, - trait ); - - Map virtualFields = imp._getDynamicProperties(); - Map wrapper = proxy.getFields(); - - assertThat(wrapper.containsKey("name")).isTrue(); - assertThat(wrapper.containsKey("school")).isTrue(); - assertThat(wrapper.containsKey("age")).isTrue(); - assertThat(wrapper.containsKey("surname")).isFalse(); - - proxy.getFields().put( "school", - "skol" ); - proxy.getFields().put( "surname", - "xxx" ); - assertThat(wrapper.containsKey("surname")).isTrue(); - - // FactType indClass = kb.getFactType("org.drools.compiler.trait.test","Entity"); - TraitableBean ind = new Entity(); - - TraitProxyImpl proxy2 = (TraitProxyImpl) tFactory.getProxy(ind, - trait ); - - Map virtualFields2 = ind._getDynamicProperties(); - Map wrapper2 = proxy2.getFields(); - assertThat(wrapper2.containsKey("name")).isTrue(); - assertThat(wrapper2.containsKey("school")).isTrue(); - assertThat(wrapper2.containsKey("age")).isTrue(); - assertThat(wrapper2.containsKey("surname")).isFalse(); - - traitClass.set( proxy2, - "name", - "john" ); - proxy2.getFields().put( "school", - "skol" ); - proxy2.getFields().put( "surname", - "xxx" ); - assertThat(wrapper2.containsKey("surname")).isTrue(); - - FactType traitClass2 = kb.getFactType( "org.drools.compiler.trait.test", - "Role" ); - Class trait2 = traitClass2.getFactClass(); - TraitableBean ind2 = new Entity(); - - TraitProxyImpl proxy99 = (TraitProxyImpl) tFactory.getProxy(ind2, - trait2 ); - Map wrapper99 = proxy99.getFields(); - - assertThat(wrapper99.containsKey("name")).isFalse(); - assertThat(wrapper99.containsKey("school")).isFalse(); - assertThat(wrapper99.containsKey("age")).isFalse(); - assertThat(wrapper99.containsKey("surname")).isFalse(); - - proxy99.getFields().put( "surname", - "xxx" ); - proxy99.getFields().put( "name", - "xyz" ); - proxy99.getFields().put( "school", - "skol" ); - - assertThat(wrapper99.containsKey("name")).isTrue(); - assertThat(wrapper99.containsKey("school")).isTrue(); - assertThat(wrapper99.containsKey("age")).isFalse(); - assertThat(wrapper99.containsKey("surname")).isTrue(); - assertThat(proxy99.getFields().size()).isEqualTo(3); - - TraitableBean ind0 = new Entity(); - - TraitProxyImpl proxy100 = (TraitProxyImpl) tFactory.getProxy(ind0, - trait2 ); - Map wrapper100 = proxy100.getFields(); - assertThat(wrapper100.containsKey("name")).isFalse(); - assertThat(wrapper100.containsKey("school")).isFalse(); - assertThat(wrapper100.containsKey("age")).isFalse(); - assertThat(wrapper100.containsKey("surname")).isFalse(); - - TraitProxyImpl proxy101 = (TraitProxyImpl) tFactory.getProxy(ind0, - trait ); - // object gains properties by virtue of another trait - // so new props are accessible even using the old proxy - assertThat(wrapper100.containsKey("name")).isTrue(); - assertThat(wrapper100.containsKey("school")).isTrue(); - assertThat(wrapper100.containsKey("age")).isTrue(); - assertThat(wrapper100.containsKey("surname")).isFalse(); - - } catch (Exception e) { - fail( e.getMessage(), e ); - } + FactType impClass = kb.getFactType("org.drools.compiler.trait.test", "Imp"); + TraitableBean imp = (TraitableBean) impClass.newInstance(); + impClass.set(imp, "name", "john"); + + FactType traitClass = kb.getFactType("org.drools.compiler.trait.test", "Student"); + Class trait = traitClass.getFactClass(); + TraitProxyImpl proxy = (TraitProxyImpl) tFactory.getProxy(imp, trait, false); + + Map wrapper = proxy.getFields(); + + assertThat(wrapper).containsKey("name"); + assertThat(wrapper).containsKey("school"); + assertThat(wrapper).containsKey("age"); + assertThat(wrapper).doesNotContainKey("surname"); + + proxy.getFields().put("school", "skol"); + proxy.getFields().put("surname", "xxx"); + assertThat(wrapper).containsKey("surname"); + + // FactType indClass = kb.getFactType("org.drools.compiler.trait.test","Entity"); + TraitableBean ind = new Entity(); + + TraitProxyImpl proxy2 = (TraitProxyImpl) tFactory.getProxy(ind, trait, false); + + Map wrapper2 = proxy2.getFields(); + assertThat(wrapper2).containsKey("name"); + assertThat(wrapper2).containsKey("school"); + assertThat(wrapper2).containsKey("age"); + assertThat(wrapper2).doesNotContainKey("surname"); + + traitClass.set(proxy2, "name", "john"); + proxy2.getFields().put("school", "skol"); + proxy2.getFields().put("surname", "xxx"); + assertThat(wrapper2).containsKey("surname"); + + FactType traitClass2 = kb.getFactType("org.drools.compiler.trait.test", "Role"); + Class trait2 = traitClass2.getFactClass(); + TraitableBean ind2 = new Entity(); + + TraitProxyImpl proxy99 = (TraitProxyImpl) tFactory.getProxy(ind2, trait2, false); + Map wrapper99 = proxy99.getFields(); + + assertThat(wrapper99).doesNotContainKey("name"); + assertThat(wrapper99).doesNotContainKey("school"); + assertThat(wrapper99).doesNotContainKey("age"); + assertThat(wrapper99).doesNotContainKey("surname"); + + proxy99.getFields().put("surname", "xxx"); + proxy99.getFields().put("name", "xyz"); + proxy99.getFields().put("school", "skol"); + + assertThat(wrapper99).containsKey("name"); + assertThat(wrapper99).containsKey("school"); + assertThat(wrapper99).doesNotContainKey("age"); + assertThat(wrapper99).containsKey("surname"); + assertThat(proxy99.getFields()).hasSize(3); + + TraitableBean ind0 = new Entity(); + + TraitProxyImpl proxy100 = (TraitProxyImpl) tFactory.getProxy(ind0, trait2, false); + Map wrapper100 = proxy100.getFields(); + assertThat(wrapper100).doesNotContainKey("name"); + assertThat(wrapper100).doesNotContainKey("school"); + assertThat(wrapper100).doesNotContainKey("age"); + assertThat(wrapper100).doesNotContainKey("surname"); + + TraitProxyImpl proxy101 = (TraitProxyImpl) tFactory.getProxy(ind0, trait, false); + // object gains properties by virtue of another trait + // so new props are accessible even using the old proxy + assertThat(wrapper100).containsKey("name"); + assertThat(wrapper100).containsKey("school"); + assertThat(wrapper100).containsKey("age"); + assertThat(wrapper100).doesNotContainKey("surname"); } @Test - public void testInternalComponents1( ) { + public void testInternalComponents1() throws Exception { String source = "org/drools/compiler/factmodel/traits/testTraitDon.drl"; KnowledgeBuilder kbuilder = KnowledgeBuilderFactory.newKnowledgeBuilder(); - Resource res = ResourceFactory.newClassPathResource( source ); + Resource res = ResourceFactory.newClassPathResource(source); assertThat(res).isNotNull(); - kbuilder.add( res, - ResourceType.DRL ); + kbuilder.add(res, ResourceType.DRL); if (kbuilder.hasErrors()) { - fail( kbuilder.getErrors().toString() ); + fail(kbuilder.getErrors().toString()); } InternalRuleBase kb = KnowledgeBaseFactory.newKnowledgeBase(); - kb.addPackages( kbuilder.getKnowledgePackages() ); + kb.addPackages(kbuilder.getKnowledgePackages()); - TraitFactoryImpl.setMode(mode, kb ); + TraitFactoryImpl.setMode(mode, kb); TraitFactoryImpl tFactory = (TraitFactoryImpl) RuntimeComponentFactory.get().getTraitFactory(kb); - try { - FactType impClass = kb.getFactType( "org.drools.compiler.trait.test", - "Imp" ); - TraitableBean imp = (TraitableBean) impClass.newInstance(); - FactType traitClass = kb.getFactType( "org.drools.compiler.trait.test", - "Student" ); - Class trait = traitClass.getFactClass(); - TraitProxyImpl proxy = (TraitProxyImpl) tFactory.getProxy(imp, - trait ); - Object proxyFields = proxy.getFields(); - Object coreTraits = imp._getTraitMap(); - Object coreProperties = imp._getDynamicProperties(); - - assertThat(proxy.getObject() instanceof TraitableBean).isTrue(); - - assertThat(proxyFields).isNotNull(); - assertThat(coreTraits).isNotNull(); - assertThat(coreProperties).isNotNull(); - - if ( mode == VirtualPropertyMode.MAP ) { - assertThat(proxyFields instanceof MapWrapper).isTrue(); - assertThat(coreTraits instanceof TraitTypeMapImpl).isTrue(); - assertThat(coreProperties instanceof HashMap).isTrue(); - } else { - assertThat(proxyFields.getClass().getName()).isEqualTo("org.drools.compiler.trait.test.Student.org.drools.compiler.trait.test.Imp_ProxyWrapper"); + FactType impClass = kb.getFactType("org.drools.compiler.trait.test", "Imp"); + TraitableBean imp = (TraitableBean) impClass.newInstance(); + FactType traitClass = kb.getFactType("org.drools.compiler.trait.test", "Student"); + Class trait = traitClass.getFactClass(); + TraitProxyImpl proxy = (TraitProxyImpl) tFactory.getProxy(imp, trait, false); + Object proxyFields = proxy.getFields(); + Object coreTraits = imp._getTraitMap(); + Object coreProperties = imp._getDynamicProperties(); - assertThat(proxyFields instanceof TripleBasedStruct).isTrue(); - assertThat(coreTraits instanceof TraitTypeMapImpl).isTrue(); - assertThat(coreProperties instanceof TripleBasedBean).isTrue(); - } + assertThat(proxyFields).isNotNull(); + assertThat(coreTraits).isNotNull(); + assertThat(coreProperties).isNotNull(); + if (mode == VirtualPropertyMode.MAP) { + assertThat(proxyFields).isInstanceOf(MapWrapper.class); + assertThat(coreTraits).isInstanceOf(TraitTypeMapImpl.class); + assertThat(coreProperties).isInstanceOf(HashMap.class); + } else { + assertThat(proxyFields.getClass().getName()).isEqualTo("org.drools.compiler.trait.test.Student.org.drools.compiler.trait.test.Imp_ProxyWrapper"); - StudentProxyImpl2 sp2 = new StudentProxyImpl2(new Imp2(), null ); - LOGGER.debug(sp2.toString()); + assertThat(proxyFields).isInstanceOf(TripleBasedStruct.class); + assertThat(coreTraits).isInstanceOf(TraitTypeMapImpl.class); + assertThat(coreProperties).isInstanceOf(TripleBasedBean.class); + } - } catch ( Exception e ) { - fail( e.getMessage(), e ); - } + + StudentProxyImpl2 sp2 = new StudentProxyImpl2(new Imp2(), null); + LOGGER.debug(sp2.toString()); } @Test - public void testWrapperKeySetAndValues() { + public void testWrapperKeySetAndValues() throws Exception { String source = "org/drools/compiler/factmodel/traits/testTraitDon.drl"; KnowledgeBuilder kbuilder = KnowledgeBuilderFactory.newKnowledgeBuilder(); - Resource res = ResourceFactory.newClassPathResource( source ); + Resource res = ResourceFactory.newClassPathResource(source); assertThat(res).isNotNull(); - kbuilder.add( res, - ResourceType.DRL ); + kbuilder.add(res, ResourceType.DRL); if (kbuilder.hasErrors()) { - fail( kbuilder.getErrors().toString() ); + fail(kbuilder.getErrors().toString()); } InternalRuleBase kb = KnowledgeBaseFactory.newKnowledgeBase(); - kb.addPackages( kbuilder.getKnowledgePackages() ); - TraitFactoryImpl.setMode(mode, kb ); + kb.addPackages(kbuilder.getKnowledgePackages()); + TraitFactoryImpl.setMode(mode, kb); TraitFactoryImpl tFactory = (TraitFactoryImpl) RuntimeComponentFactory.get().getTraitFactory(kb); - try { - FactType impClass = kb.getFactType( "org.drools.compiler.trait.test", - "Imp" ); - TraitableBean imp = (TraitableBean) impClass.newInstance(); - FactType traitClass = kb.getFactType( "org.drools.compiler.trait.test", - "Student" ); - Class trait = traitClass.getFactClass(); - TraitProxyImpl proxy = (TraitProxyImpl) tFactory.getProxy(imp, - trait ); - - impClass.set( imp, - "name", - "john" ); - proxy.getFields().put( "surname", - "xxx" ); - proxy.getFields().put( "name2", - "john" ); - proxy.getFields().put( "nfield", - null ); - - Set set = new HashSet(); - set.add( "name" ); - set.add( "surname" ); - set.add( "age" ); - set.add( "school" ); - set.add( "name2" ); - set.add( "nfield" ); - - assertThat(proxy.getFields().keySet().size()).isEqualTo(6); - assertThat(proxy.getFields().keySet()).isEqualTo(set); - - Collection col1 = proxy.getFields().values(); - Collection col2 = Arrays.asList( "john", - null, - 0, - "xxx", - "john", - null ); - - Comparator comp = new Comparator() { - - public int compare( Object o1, Object o2 ) { - if (o1 == null && o2 != null) { - return 1; - } - if (o1 != null && o2 == null) { - return -1; - } - if (o1 == null && o2 == null) { - return 0; - } - return o1.toString().compareTo( o2.toString() ); - } - }; - - Collections.sort( (List) col1, - comp ); - Collections.sort( (List) col2, - comp ); - assertThat(col2).isEqualTo(col1); - - assertThat(proxy.getFields().containsValue(null)).isTrue(); - assertThat(proxy.getFields().containsValue("john")).isTrue(); - assertThat(proxy.getFields().containsValue(0)).isTrue(); - assertThat(proxy.getFields().containsValue("xxx")).isTrue(); - assertThat(proxy.getFields().containsValue("randomString")).isFalse(); - assertThat(proxy.getFields().containsValue(-96)).isFalse(); - - } catch (Exception e) { - fail( e.getMessage(), e ); - } + FactType impClass = kb.getFactType("org.drools.compiler.trait.test", "Imp"); + TraitableBean imp = (TraitableBean) impClass.newInstance(); + FactType traitClass = kb.getFactType("org.drools.compiler.trait.test", "Student"); + Class trait = traitClass.getFactClass(); + TraitProxyImpl proxy = (TraitProxyImpl) tFactory.getProxy(imp, trait, false); + + impClass.set(imp, "name", "john"); + proxy.getFields().put("surname", "xxx"); + proxy.getFields().put("name2", "john"); + proxy.getFields().put("nfield", null); + + assertThat(proxy.getFields()).hasSize(6); + assertThat(proxy.getFields().keySet()).contains("name", "surname", "age", "school", "name2", "nfield"); + + List col1 = new ArrayList<>(proxy.getFields().values()); + List col2 = Arrays.asList("john", null, 0, "xxx", "john", null); + + Comparator comp = new Comparator() { + + public int compare(Object o1, Object o2) { + if (o1 == null && o2 != null) { + return 1; + } + if (o1 != null && o2 == null) { + return -1; + } + if (o1 == null && o2 == null) { + return 0; + } + return o1.toString().compareTo(o2.toString()); + } + }; + + Collections.sort(col1, comp); + Collections.sort(col2, comp); + assertThat(col2).isEqualTo(col1); + + assertThat(proxy.getFields()).containsValue(null); + assertThat(proxy.getFields()).containsValue("john"); + assertThat(proxy.getFields()).containsValue(0); + assertThat(proxy.getFields()).containsValue("xxx"); + assertThat(proxy.getFields()).doesNotContainValue("randomString"); + assertThat(proxy.getFields()).doesNotContainValue(-96); } @Test - public void testWrapperClearAndRemove() { + public void testWrapperClearAndRemove() throws Exception { String source = "org/drools/compiler/factmodel/traits/testTraitDon.drl"; KnowledgeBuilder kbuilder = KnowledgeBuilderFactory.newKnowledgeBuilder(); - Resource res = ResourceFactory.newClassPathResource( source ); + Resource res = ResourceFactory.newClassPathResource(source); assertThat(res).isNotNull(); - kbuilder.add( res, - ResourceType.DRL ); + kbuilder.add(res, ResourceType.DRL); if (kbuilder.hasErrors()) { - fail( kbuilder.getErrors().toString() ); + fail(kbuilder.getErrors().toString()); } InternalRuleBase kb = KnowledgeBaseFactory.newKnowledgeBase(); - kb.addPackages( kbuilder.getKnowledgePackages() ); - TraitFactoryImpl.setMode(mode, kb ); + kb.addPackages(kbuilder.getKnowledgePackages()); + TraitFactoryImpl.setMode(mode, kb); TraitFactoryImpl tFactory = (TraitFactoryImpl) RuntimeComponentFactory.get().getTraitFactory(kb); - try { - FactType impClass = kb.getFactType( "org.drools.compiler.trait.test", - "Imp" ); - TraitableBean imp = (TraitableBean) impClass.newInstance(); - impClass.set( imp, - "name", - "john" ); - FactType traitClass = kb.getFactType( "org.drools.compiler.trait.test", - "Student" ); - Class trait = traitClass.getFactClass(); - TraitProxyImpl proxy = (TraitProxyImpl) tFactory.getProxy(imp, - trait ); - - proxy.getFields().put( "surname", - "xxx" ); - proxy.getFields().put( "name2", - "john" ); - proxy.getFields().put( "nfield", - null ); - - Set set = new HashSet(); - set.add( "name" ); - set.add( "surname" ); - set.add( "age" ); - set.add( "school" ); - set.add( "name2" ); - set.add( "nfield" ); - - assertThat(proxy.getFields().keySet().size()).isEqualTo(6); - assertThat(proxy.getFields().keySet()).isEqualTo(set); - - proxy.getFields().clear(); - - Map fields = proxy.getFields(); - assertThat(fields.size()).isEqualTo(3); - assertThat(fields.containsKey("age")).isTrue(); - assertThat(fields.containsKey("school")).isTrue(); - assertThat(fields.containsKey("name")).isTrue(); - - assertThat(fields.get("age")).isEqualTo(0); - assertThat(fields.get("school")).isNull(); - assertThat(fields.get("name")).isNotNull(); - - proxy.getFields().put( "surname", - "xxx" ); - proxy.getFields().put( "name2", - "john" ); - proxy.getFields().put( "nfield", - null ); - proxy.getFields().put( "age", - 24 ); - - assertThat(proxy.getFields().get("name")).isEqualTo("john"); - assertThat(proxy.getFields().get("surname")).isEqualTo("xxx"); - assertThat(proxy.getFields().get("name2")).isEqualTo("john"); - assertThat(proxy.getFields().get("nfield")).isEqualTo(null); - assertThat(proxy.getFields().get("age")).isEqualTo(24); - assertThat(proxy.getFields().get("school")).isEqualTo(null); - - proxy.getFields().remove( "surname" ); - proxy.getFields().remove( "name2" ); - proxy.getFields().remove( "age" ); - proxy.getFields().remove( "school" ); - proxy.getFields().remove( "nfield" ); - assertThat(proxy.getFields().size()).isEqualTo(3); - - assertThat(proxy.getFields().get("age")).isEqualTo(0); - assertThat(proxy.getFields().get("school")).isEqualTo(null); - assertThat(proxy.getFields().get("name")).isEqualTo("john"); - - assertThat(proxy.getFields().get("nfield")).isEqualTo(null); - assertThat(proxy.getFields().containsKey("nfield")).isFalse(); - - assertThat(proxy.getFields().get("name2")).isEqualTo(null); - assertThat(proxy.getFields().containsKey("name2")).isFalse(); - - assertThat(proxy.getFields().get("surname")).isEqualTo(null); - assertThat(proxy.getFields().containsKey("surname")).isFalse(); - - } catch (Exception e) { - fail( e.getMessage(), e ); - } + FactType impClass = kb.getFactType("org.drools.compiler.trait.test", "Imp"); + TraitableBean imp = (TraitableBean) impClass.newInstance(); + impClass.set(imp, "name", "john"); + FactType traitClass = kb.getFactType("org.drools.compiler.trait.test", "Student"); + Class trait = traitClass.getFactClass(); + TraitProxyImpl proxy = (TraitProxyImpl) tFactory.getProxy(imp, trait, false); + + proxy.getFields().put("surname", "xxx"); + proxy.getFields().put("name2", "john"); + proxy.getFields().put("nfield", null); + + Set set = new HashSet<>(); + set.add("name"); + set.add("surname"); + set.add("age"); + set.add("school"); + set.add("name2"); + set.add("nfield"); + + assertThat(proxy.getFields()).hasSize(6); + assertThat(proxy.getFields().keySet()).isEqualTo(set); + + proxy.getFields().clear(); + + Map fields = proxy.getFields(); + assertThat(fields).hasSize(3); + assertThat(fields).containsKey("age"); + assertThat(fields).containsKey("school"); + assertThat(fields).containsKey("name"); + + assertThat(fields.get("age")).isEqualTo(0); + assertThat(fields.get("school")).isNull(); + assertThat(fields.get("name")).isNotNull(); + + proxy.getFields().put("surname", "xxx"); + proxy.getFields().put("name2", "john"); + proxy.getFields().put("nfield", null); + proxy.getFields().put("age", 24); + + assertThat(proxy.getFields().get("name")).isEqualTo("john"); + assertThat(proxy.getFields().get("surname")).isEqualTo("xxx"); + assertThat(proxy.getFields().get("name2")).isEqualTo("john"); + assertThat(proxy.getFields().get("nfield")).isEqualTo(null); + assertThat(proxy.getFields().get("age")).isEqualTo(24); + assertThat(proxy.getFields().get("school")).isEqualTo(null); + + proxy.getFields().remove("surname"); + proxy.getFields().remove("name2"); + proxy.getFields().remove("age"); + proxy.getFields().remove("school"); + proxy.getFields().remove("nfield"); + assertThat(proxy.getFields()).hasSize(3); + + assertThat(proxy.getFields().get("age")).isEqualTo(0); + assertThat(proxy.getFields().get("school")).isEqualTo(null); + assertThat(proxy.getFields().get("name")).isEqualTo("john"); + + assertThat(proxy.getFields().get("nfield")).isEqualTo(null); + assertThat(proxy.getFields()).doesNotContainKey("nfield"); + + assertThat(proxy.getFields().get("name2")).isEqualTo(null); + assertThat(proxy.getFields()).doesNotContainKey("name2"); + + assertThat(proxy.getFields().get("surname")).isEqualTo(null); + assertThat(proxy.getFields()).doesNotContainKey("surname"); } @Test - public void testIsAEvaluator( ) { + public void testIsAEvaluator() { String source = "package org.drools.compiler.trait.test;\n" + "\n" + "import org.drools.base.factmodel.traits.Traitable;\n" + @@ -1020,43 +846,42 @@ public void testIsAEvaluator( ) { "rule \"Init\"\n" + "when\n" + "then\n" + - " Imp core = new Imp( \"joe\" );\n" + - " insert( core );\n" + - " don( core, Person.class );\n" + - " don( core, Worker.class );\n" + + " Imp core = new Imp(\"joe\");\n" + + " insert(core);\n" + + " don(core, Person.class);\n" + + " don(core, Worker.class);\n" + "\n" + - " Imp core2 = new Imp( \"adam\" );\n" + - " insert( core2 );\n" + - " don( core2, Worker.class );\n" + + " Imp core2 = new Imp(\"adam\");\n" + + " insert(core2);\n" + + " don(core2, Worker.class);\n" + "end\n" + "\n" + "rule \"Mod\"\n" + "when\n" + - " $p : Person( name == \"joe\" )\n" + + " $p : Person(name == \"joe\")\n" + "then\n" + - " modify ($p) { setName( \"john\" ); }\n" + + " modify ($p) { setName(\"john\"); }\n" + "end\n" + "\n" + "rule \"Worker Students v6\"\n" + "when\n" + - " $x2 := Person( name == \"john\" )\n" + - " $x1 := Worker( core != $x2.core, this not isA $x2 )\n" + + " $x2 := Person(name == \"john\")\n" + + " $x1 := Worker(core != $x2.core, this not isA $x2)\n" + "then\n" + - " list.add( \"ok\" );\n" + + " list.add(\"ok\");\n" + "end\n" + "\n" + "\n"; - KieSession ks = getSessionFromString( source ); - TraitFactoryImpl.setMode(mode, ks.getKieBase() ); + KieSession ks = getSessionFromString(source); + TraitFactoryImpl.setMode(mode, ks.getKieBase()); - List info = new ArrayList(); - ks.setGlobal( "list", - info ); + List info = new ArrayList<>(); + ks.setGlobal("list", info); ks.fireAllRules(); LOGGER.debug(info.toString()); - assertThat(info.contains("ok")).isTrue(); + assertThat(info).contains("ok"); } @@ -1065,12 +890,11 @@ public void testIsAEvaluator( ) { public void testIsA() { String source = "org/drools/compiler/factmodel/traits/testTraitIsA.drl"; - KieSession ks = getSession( source ); - TraitFactoryImpl.setMode(mode, ks.getKieBase() ); + KieSession ks = getSession(source); + TraitFactoryImpl.setMode(mode, ks.getKieBase()); - List info = new ArrayList(); - ks.setGlobal( "list", - info ); + List info = new ArrayList<>(); + ks.setGlobal("list", info); ks.fireAllRules(); @@ -1078,9 +902,9 @@ public void testIsA() { int num = 10; LOGGER.debug(info.toString()); - assertThat(info.size()).isEqualTo(num); + assertThat(info).hasSize(num); for (int j = 0; j < num; j++) { - assertThat(info.contains("" + j)).isTrue(); + assertThat(info).contains("" + j); } } @@ -1091,26 +915,24 @@ public void testIsA() { public void testOverrideType() { String source = "org/drools/compiler/factmodel/traits/testTraitOverride.drl"; - KieSession ks = getSession( source ); - TraitFactoryImpl.setMode(mode, ks.getKieBase() ); + KieSession ks = getSession(source); + TraitFactoryImpl.setMode(mode, ks.getKieBase()); - List info = new ArrayList(); - ks.setGlobal( "list", - info ); + List info = new ArrayList<>(); + ks.setGlobal("list", info); - try { - ks.fireAllRules(); - fail( "An exception was expected since a trait can't override the type of a core class field with these settings " ); - } catch ( Throwable rde ) { - assertThat(rde.getCause() instanceof UnsupportedOperationException).isTrue(); - } + assertThatException() + .as("An exception was expected since a trait can't override the type of a core class field with these settings ") + .isThrownBy(() -> ks.fireAllRules()) + .extracting(e -> e.getCause()) + .isInstanceOf(UnsupportedOperationException.class); } @Test - public void testOverrideType2( ) { + public void testOverrideType2() { String drl = "package org.drools.compiler.trait.test; \n" + "import org.drools.base.factmodel.traits.Traitable; \n" + "" + @@ -1122,24 +944,23 @@ public void testOverrideType2( ) { "" + "rule Don when then\n" + " Face face = new Face(); \n" + - " don( face, Mask.class ); \n" + + " don(face, Mask.class); \n" + "end\n"; - KieSession ks = getSessionFromString( drl ); - TraitFactoryImpl.setMode(mode, ks.getKieBase() ); + KieSession ks = getSessionFromString(drl); + TraitFactoryImpl.setMode(mode, ks.getKieBase()); - try { - ks.fireAllRules(); - fail( "An exception was expected since a trait can't override the type of a core class field with these settings " ); - } catch ( Throwable rde ) { - assertThat(rde.getCause() instanceof UnsupportedOperationException).isTrue(); - } + assertThatException() + .as("An exception was expected since a trait can't override the type of a core class field with these settings ") + .isThrownBy(() -> ks.fireAllRules()) + .extracting(e -> e.getCause()) + .isInstanceOf(UnsupportedOperationException.class); } @Test - public void testOverrideType3( ) { + public void testOverrideType3() { String drl = "package org.drools.compiler.trait.test; \n" + "import org.drools.base.factmodel.traits.Traitable; \n" + "" + @@ -1151,18 +972,18 @@ public void testOverrideType3( ) { "" + "rule Don when then\n" + " Face face = new Face(); \n" + - " don( face, Mask.class ); \n" + + " don(face, Mask.class); \n" + "end\n"; - KieSession ks = getSessionFromString( drl ); - TraitFactoryImpl.setMode(mode, ks.getKieBase() ); + KieSession ks = getSessionFromString(drl); + TraitFactoryImpl.setMode(mode, ks.getKieBase()); - try { - ks.fireAllRules(); - fail( "An exception was expected since a trait can't override the type of a core class field with these settings " ); - } catch ( Throwable rde ) { - assertThat(rde.getCause() instanceof UnsupportedOperationException).isTrue(); - } + + assertThatException() + .as("An exception was expected since a trait can't override the type of a core class field with these settings ") + .isThrownBy(() -> ks.fireAllRules()) + .extracting(e -> e.getCause()) + .isInstanceOf(UnsupportedOperationException.class); } @@ -1170,55 +991,53 @@ public void testOverrideType3( ) { public void testTraitLegacy() { String source = "org/drools/compiler/factmodel/traits/testTraitLegacyTrait.drl"; - KieSession ks = getSession( source ); - TraitFactoryImpl.setMode(mode, ks.getKieBase() ); + KieSession ks = getSession(source); + TraitFactoryImpl.setMode(mode, ks.getKieBase()); - List info = new ArrayList(); - ks.setGlobal( "list", - info ); + List info = new ArrayList<>(); + ks.setGlobal("list", info); ks.fireAllRules(); printDebugInfoSessionObjects(ks.getObjects(), info); - assertThat(info.size()).isEqualTo(5); - assertThat(info.contains("OK")).isTrue(); - assertThat(info.contains("OK2")).isTrue(); - assertThat(info.contains("OK3")).isTrue(); - assertThat(info.contains("OK4")).isTrue(); - assertThat(info.contains("OK5")).isTrue(); + assertThat(info).hasSize(5); + assertThat(info).contains("OK"); + assertThat(info).contains("OK2"); + assertThat(info).contains("OK3"); + assertThat(info).contains("OK4"); + assertThat(info).contains("OK5"); } - private void printDebugInfoSessionObjects(final Collection facts, final List globalList) { - LOGGER.debug( " -------------- " + facts.size() + " ---------------- " ); + private void printDebugInfoSessionObjects(final Collection facts, final List globalList) { + LOGGER.debug(" -------------- " + facts.size() + " ---------------- "); for (Object o : facts) { - LOGGER.debug( "\t\t" + o ); + LOGGER.debug("\t\t" + o); } - LOGGER.debug( " -------------- ---------------- " ); - LOGGER.debug( globalList.toString() ); - LOGGER.debug( " -------------- ---------------- " ); + LOGGER.debug(" -------------- ---------------- "); + LOGGER.debug(globalList.toString()); + LOGGER.debug(" -------------- ---------------- "); } @Test public void testTraitCollections() { String source = "org/drools/compiler/factmodel/traits/testTraitCollections.drl"; - KieSession ks = getSession( source ); - TraitFactoryImpl.setMode(mode, ks.getKieBase() ); + KieSession ks = getSession(source); + TraitFactoryImpl.setMode(mode, ks.getKieBase()); - List info = new ArrayList(); - ks.setGlobal( "list", - info ); + List info = new ArrayList<>(); + ks.setGlobal("list", info); ks.fireAllRules(); printDebugInfoSessionObjects(ks.getObjects(), info); - assertThat(info.size()).isEqualTo(1); - assertThat(info.contains("OK")).isTrue(); + assertThat(info).hasSize(1); + assertThat(info).contains("OK"); } @@ -1226,20 +1045,19 @@ public void testTraitCollections() { public void testTraitCore() { String source = "org/drools/compiler/factmodel/traits/testTraitLegacyCore.drl"; - KieSession ks = getSession( source ); - TraitFactoryImpl.setMode(mode, ks.getKieBase() ); + KieSession ks = getSession(source); + TraitFactoryImpl.setMode(mode, ks.getKieBase()); - List info = new ArrayList(); - ks.setGlobal( "list", - info ); + List info = new ArrayList<>(); + ks.setGlobal("list", info); ks.fireAllRules(); printDebugInfoSessionObjects(ks.getObjects(), info); - assertThat(info.contains("OK")).isTrue(); - assertThat(info.contains("OK2")).isTrue(); - assertThat(info.size()).isEqualTo(2); + assertThat(info).contains("OK"); + assertThat(info).contains("OK2"); + assertThat(info).hasSize(2); } @@ -1247,17 +1065,16 @@ public void testTraitCore() { public void traitWithEquality() { String source = "org/drools/compiler/factmodel/traits/testTraitWithEquality.drl"; - KieSession ks = getSession( source ); - TraitFactoryImpl.setMode(mode, ks.getKieBase() ); + KieSession ks = getSession(source); + TraitFactoryImpl.setMode(mode, ks.getKieBase()); - List info = new ArrayList(); - ks.setGlobal( "list", - info ); + List info = new ArrayList<>(); + ks.setGlobal("list", info); ks.fireAllRules(); - assertThat(info.contains("DON")).isTrue(); - assertThat(info.contains("EQUAL")).isTrue(); + assertThat(info).contains("DON"); + assertThat(info).contains("EQUAL"); } @@ -1267,21 +1084,19 @@ public void traitDeclared() { List trueTraits = new ArrayList(); List untrueTraits = new ArrayList(); - KieSession ks = getSession( "org/drools/compiler/factmodel/traits/testDeclaredFactTrait.drl" ); - TraitFactoryImpl.setMode(mode, ks.getKieBase() ); + KieSession ks = getSession("org/drools/compiler/factmodel/traits/testDeclaredFactTrait.drl"); + TraitFactoryImpl.setMode(mode, ks.getKieBase()); - ks.setGlobal( "trueTraits", - trueTraits ); - ks.setGlobal( "untrueTraits", - untrueTraits ); + ks.setGlobal("trueTraits", trueTraits); + ks.setGlobal("untrueTraits", untrueTraits); ks.fireAllRules(); ks.dispose(); - assertThat(trueTraits.contains(1)).isTrue(); - assertThat(trueTraits.contains(2)).isFalse(); - assertThat(untrueTraits.contains(2)).isTrue(); - assertThat(untrueTraits.contains(1)).isFalse(); + assertThat(trueTraits).contains(1); + assertThat(trueTraits).doesNotContain(2); + assertThat(untrueTraits).contains(2); + assertThat(untrueTraits).doesNotContain(1); } @Test @@ -1290,41 +1105,38 @@ public void traitPojo() { List trueTraits = new ArrayList(); List untrueTraits = new ArrayList(); - KieSession session = getSession( "org/drools/compiler/factmodel/traits/testPojoFactTrait.drl" ); - TraitFactoryImpl.setMode(mode, session.getKieBase() ); + KieSession session = getSession("org/drools/compiler/factmodel/traits/testPojoFactTrait.drl"); + TraitFactoryImpl.setMode(mode, session.getKieBase()); - session.setGlobal( "trueTraits", - trueTraits ); - session.setGlobal( "untrueTraits", - untrueTraits ); + session.setGlobal("trueTraits", trueTraits); + session.setGlobal("untrueTraits", untrueTraits); session.fireAllRules(); session.dispose(); - assertThat(trueTraits.contains(1)).isTrue(); - assertThat(trueTraits.contains(2)).isFalse(); - assertThat(untrueTraits.contains(2)).isTrue(); - assertThat(untrueTraits.contains(1)).isFalse(); + assertThat(trueTraits).contains(1); + assertThat(trueTraits).doesNotContain(2); + assertThat(untrueTraits).contains(2); + assertThat(untrueTraits).doesNotContain(1); } @Test public void testIsAOperator() { String source = "org/drools/compiler/factmodel/traits/testTraitIsA2.drl"; - KieSession ksession = getSession( source ); - TraitFactoryImpl.setMode(mode, ksession.getKieBase() ); + KieSession ksession = getSession(source); + TraitFactoryImpl.setMode(mode, ksession.getKieBase()); - AgendaEventListener ael = mock( AgendaEventListener.class ); - ksession.addEventListener( ael ); + AgendaEventListener ael = mock(AgendaEventListener.class); + ksession.addEventListener(ael); - Person student = new Person("student", 18 ); - ksession.insert( student ); + Person student = new Person("student", 18); + ksession.insert(student); ksession.fireAllRules(); - ArgumentCaptor cap = ArgumentCaptor.forClass( AfterMatchFiredEvent.class ); - verify( ael, - times( 3 ) ).afterMatchFired( cap.capture() ); + ArgumentCaptor cap = ArgumentCaptor.forClass(AfterMatchFiredEvent.class); + verify(ael, times(3)).afterMatchFired(cap.capture()); List values = cap.getAllValues(); @@ -1351,7 +1163,7 @@ public void testManyTraits() { "" + "rule \"Nice\"\n" + "when\n" + - " $n : NiceMessage( $m : message )\n" + + " $n : NiceMessage($m : message)\n" + "then\n" + "end" + "\n" + @@ -1362,59 +1174,58 @@ public void testManyTraits() { " Message message = new Message();\n" + " message.setMessage(\"Hello World\");\n" + " insert(message);\n" + - " don( message, NiceMessage.class );\n" + + " don(message, NiceMessage.class);\n" + "\n" + " Message unreadMessage = new Message();\n" + " unreadMessage.setMessage(\"unread\");\n" + " insert(unreadMessage);\n" + - " don( unreadMessage, NiceMessage.class );\n" + + " don(unreadMessage, NiceMessage.class);\n" + "\n" + " Message oldMessage = new Message();\n" + " oldMessage.setMessage(\"old\");\n" + " insert(oldMessage);\n" + - " don( oldMessage, NiceMessage.class );" + + " don(oldMessage, NiceMessage.class);" + " list.add(\"OK\");\n" + " end"; - KieSession ksession = getSessionFromString( source ); - TraitFactoryImpl.setMode(mode, ksession.getKieBase() ); + KieSession ksession = getSessionFromString(source); + TraitFactoryImpl.setMode(mode, ksession.getKieBase()); - List list = new ArrayList(); - ksession.setGlobal( "list", list ); + List list = new ArrayList<>(); + ksession.setGlobal("list", list); - Person student = new Person( "student", 18 ); - ksession.insert( student ); + Person student = new Person("student", 18); + ksession.insert(student); ksession.fireAllRules(); - assertThat(list.size()).isEqualTo(1); - assertThat(list.contains("OK")).isTrue(); + assertThat(list).hasSize(1); + assertThat(list).contains("OK"); } @Test public void traitManyTimes() { - KieSession ksession = getSession( "org/drools/compiler/factmodel/traits/testTraitDonMultiple.drl" ); - TraitFactoryImpl.setMode(mode, ksession.getKieBase() ); + KieSession ksession = getSession("org/drools/compiler/factmodel/traits/testTraitDonMultiple.drl"); + TraitFactoryImpl.setMode(mode, ksession.getKieBase()); - List list = new ArrayList(); - ksession.setGlobal( "list", list ); + List list = new ArrayList<>(); + ksession.setGlobal("list", list); ksession.fireAllRules(); - for ( Object o : ksession.getObjects() ) { + for (Object o : ksession.getObjects()) { LOGGER.debug(o.toString()); } - Collection x = ksession.getObjects(); - assertThat(ksession.getObjects().size()).isEqualTo(2); + assertThat(ksession.getObjects()).hasSize(2); - assertThat(list.size()).isEqualTo(5); + assertThat(list).hasSize(5); assertThat(list.get(0)).isEqualTo(0); - assertThat(list.contains(1)).isTrue(); - assertThat(list.contains(2)).isTrue(); - assertThat(list.contains(3)).isTrue(); - assertThat(list.contains(4)).isTrue(); + assertThat(list).contains(1); + assertThat(list).contains(2); + assertThat(list).contains(3); + assertThat(list).contains(4); } // BZ #748752 @@ -1436,55 +1247,55 @@ public void traitsInBatchExecution() { "\n" + "rule \"create student\" \n" + " when\n" + - " $student : Person( age < 26 )\n" + + " $student : Person(age < 26)\n" + " then\n" + - " Student s = don( $student, Student.class );\n" + + " Student s = don($student, Student.class);\n" + " s.setSchool(\"Masaryk University\");\n" + "end\n" + "\n" + "rule \"print student\"\n" + " when\n" + - " student : Person( this isA Student )\n" + + " student : Person(this isA Student)\n" + " then" + - " list.add( 1 );\n" + + " list.add(1);\n" + "end\n" + "\n" + "rule \"print school\"\n" + " when\n" + - " Student( $school : school )\n" + + " Student($school : school)\n" + " then\n" + - " list.add( 2 );\n" + + " list.add(2);\n" + "end"; KnowledgeBuilder kbuilder = KnowledgeBuilderFactory.newKnowledgeBuilder(); - kbuilder.add( new ByteArrayResource( str.getBytes() ), ResourceType.DRL ); + kbuilder.add(new ByteArrayResource(str.getBytes()), ResourceType.DRL); if (kbuilder.hasErrors()) { throw new RuntimeException(kbuilder.getErrors().toString()); } - List list = new ArrayList(); + List list = new ArrayList<>(); KieBase kbase = kbuilder.newKieBase(); - TraitFactoryImpl.setMode(mode, kbase ); + TraitFactoryImpl.setMode(mode, kbase); StatelessKieSession ksession = kbase.newStatelessKieSession(); - ksession.setGlobal( "list", list ); + ksession.setGlobal("list", list); List> commands = new ArrayList>(); Person student = new Person("student", 18); - commands.add( CommandFactory.newInsert( student )); + commands.add(CommandFactory.newInsert(student)); LOGGER.debug("Starting execution..."); commands.add(CommandFactory.newFireAllRules()); ksession.execute(CommandFactory.newBatchExecution(commands)); LOGGER.debug("Finished..."); - assertThat(list.size()).isEqualTo(2); - assertThat(list.contains(1)).isTrue(); - assertThat(list.contains(2)).isTrue(); + assertThat(list).hasSize(2); + assertThat(list).contains(1); + assertThat(list).contains(2); } @Test(timeout=10000) @@ -1504,7 +1315,7 @@ public void testManyTraitsStateless() { "" + "rule \"Nice\"\n" + "when\n" + - " $n : NiceMessage( $m : message )\n" + + " $n : NiceMessage($m : message)\n" + "then\n" + "end" + "\n" + @@ -1515,32 +1326,32 @@ public void testManyTraitsStateless() { " Message message = new Message();\n" + " message.setMessage(\"Hello World\");\n" + " insert(message);\n" + - " don( message, NiceMessage.class );\n" + + " don(message, NiceMessage.class);\n" + "\n" + " Message unreadMessage = new Message();\n" + " unreadMessage.setMessage(\"unread\");\n" + " insert(unreadMessage);\n" + - " don( unreadMessage, NiceMessage.class );\n" + + " don(unreadMessage, NiceMessage.class);\n" + "\n" + " Message oldMessage = new Message();\n" + " oldMessage.setMessage(\"old\");\n" + " insert(oldMessage);\n" + - " don( oldMessage, NiceMessage.class );" + + " don(oldMessage, NiceMessage.class);" + " list.add(\"OK\");\n" + " end"; - KieBase kb = getKieBaseFromString( source ); - TraitFactoryImpl.setMode(mode, kb ); + KieBase kb = getKieBaseFromString(source); + TraitFactoryImpl.setMode(mode, kb); KieSession ksession = kb.newKieSession(); - List list = new ArrayList(); - ksession.setGlobal( "list", list ); + List list = new ArrayList<>(); + ksession.setGlobal("list", list); - ksession.execute( CommandFactory.newFireAllRules() ); + ksession.execute(CommandFactory.newFireAllRules()); - assertThat(list.size()).isEqualTo(1); - assertThat(list.contains("OK")).isTrue(); + assertThat(list).hasSize(1); + assertThat(list).contains("OK"); } @@ -1576,44 +1387,44 @@ public void testAliasing() { "rule \"create student\" \n" + " when\n" + " then\n" + - " Person p = new Person( \"davide\", \"UniBoh\", \"Floor84\", 1 ); \n" + - " Student s = don( p, Student.class );\n" + + " Person p = new Person(\"davide\", \"UniBoh\", \"Floor84\", 1); \n" + + " Student s = don(p, Student.class);\n" + "end\n" + "\n" + "rule \"print school\"\n" + " when\n" + - " $student : Student( $school : school == \"UniBoh\", $f : fields, fields[ \"workPlace\" ] == \"UniBoh\" )\n" + + " $student : Student($school : school == \"UniBoh\", $f : fields, fields[ \"workPlace\" ] == \"UniBoh\")\n" + " then \n " + - " $student.setRank( 99 ); \n" + - " $f.put( \"school\", \"Skool\" ); \n" + - - " list.add( $school );\n" + - " list.add( $f.get( \"school\" ) );\n" + - " list.add( $student.getSchool() );\n" + - " list.add( $f.keySet() );\n" + - " list.add( $f.entrySet() );\n" + - " list.add( $f.values() );\n" + - " list.add( $f.containsKey( \"school\" ) );\n" + - " list.add( $student.getRank() );\n" + - " list.add( $f.get( \"address\" ) );\n" + + " $student.setRank(99); \n" + + " $f.put(\"school\", \"Skool\"); \n" + + + " list.add($school);\n" + + " list.add($f.get(\"school\"));\n" + + " list.add($student.getSchool());\n" + + " list.add($f.keySet());\n" + + " list.add($f.entrySet());\n" + + " list.add($f.values());\n" + + " list.add($f.containsKey(\"school\"));\n" + + " list.add($student.getRank());\n" + + " list.add($f.get(\"address\"));\n" + "end"; - KieSession ksession = getSessionFromString( drl ); - TraitFactoryImpl.setMode(mode, ksession.getKieBase() ); + KieSession ksession = getSessionFromString(drl); + TraitFactoryImpl.setMode(mode, ksession.getKieBase()); - List list = new ArrayList(); - ksession.setGlobal( "list", list ); + List list = new ArrayList<>(); + ksession.setGlobal("list", list); ksession.fireAllRules(); - assertThat(list.size()).isEqualTo(9); - assertThat(list.contains("UniBoh")).isTrue(); - assertThat(list.contains("Skool")).isTrue(); - assertThat(((Collection) list.get(3)).containsAll(Arrays.asList("workPlace", "nomen", "level"))).isTrue(); - assertThat(((Collection) list.get(5)).containsAll(Arrays.asList("davide", "Skool", 0))).isTrue(); - assertThat(list.contains(true)).isTrue(); - assertThat(list.contains("Floor84")).isTrue(); - assertThat(list.contains(99)).isTrue(); + assertThat(list).hasSize(9); + assertThat(list).contains("UniBoh"); + assertThat(list).contains("Skool"); + assertThat((Collection) list.get(3)).contains("workPlace", "nomen", "level"); + assertThat((Collection) list.get(5)).contains("davide", "Skool", 0); + assertThat(list).contains(true); + assertThat(list).contains("Floor84"); + assertThat(list).contains(99); } @@ -1644,52 +1455,52 @@ public void testTraitLogicalRemoval() { "\n" + "rule \"Don Logical\"\n" + "when\n" + - " $s : String( this == \"trigger\" )\n" + + " $s : String(this == \"trigger\")\n" + "then\n" + - " Person p = new Person( \"john\" );\n" + - " insertLogical( p ); \n" + - " don( p, Student.class, true );\n" + + " Person p = new Person(\"john\");\n" + + " insertLogical(p); \n" + + " don(p, Student.class, true);\n" + "end\n" + " " + "rule \"Don Logical 2\"\n" + "when\n" + - " $s : String( this == \"trigger2\" )\n" + - " $p : Person( name == \"john\" )" + + " $s : String(this == \"trigger2\")\n" + + " $p : Person(name == \"john\")" + "then\n" + - " don( $p, Worker.class, true );\n" + + " don($p, Worker.class, true);\n" + "end"; KieSession ksession = getSessionFromString(drl); - TraitFactoryImpl.setMode(mode, ksession.getKieBase() ); + TraitFactoryImpl.setMode(mode, ksession.getKieBase()); - List list = new ArrayList(); - ksession.setGlobal( "list", list ); + List list = new ArrayList<>(); + ksession.setGlobal("list", list); - FactHandle h = ksession.insert( "trigger" ); + FactHandle h = ksession.insert("trigger"); ksession.fireAllRules(); - assertThat(ksession.getObjects().size()).isEqualTo(3); + assertThat(ksession.getObjects()).hasSize(3); - ksession.delete( h ); + ksession.delete(h); ksession.fireAllRules(); - assertThat(ksession.getObjects().size()).isEqualTo(0); + assertThat(ksession.getObjects()).isEmpty(); - FactHandle h1 = ksession.insert( "trigger" ); - FactHandle h2 = ksession.insert( "trigger2" ); + FactHandle h1 = ksession.insert("trigger"); + FactHandle h2 = ksession.insert("trigger2"); ksession.fireAllRules(); - assertThat(ksession.getObjects().size()).isEqualTo(5); + assertThat(ksession.getObjects()).hasSize(5); - ksession.delete( h2 ); + ksession.delete(h2); ksession.fireAllRules(); - assertThat(ksession.getObjects().size()).isEqualTo(3); + assertThat(ksession.getObjects()).hasSize(3); - ksession.delete( h1 ); + ksession.delete(h1); ksession.fireAllRules(); - assertThat(ksession.getObjects().size()).isEqualTo(0); + assertThat(ksession.getObjects()).isEmpty(); } @@ -1706,7 +1517,7 @@ public void testTMSConsistencyWithNonTraitableBeans() { "rule \"Init\"\n" + "when\n" + "then\n" + - " insertLogical( new Person( \"x\", 18 ) );\n" + + " insertLogical(new Person(\"x\", 18));\n" + "end\n" + "\n" + "declare trait Student\n" + @@ -1716,29 +1527,29 @@ public void testTMSConsistencyWithNonTraitableBeans() { "\n" + "rule \"Trait\"\n" + "when\n" + - " $p : Person( )\n" + + " $p : Person()\n" + "then\n" + - " don( $p, Student.class, true );\n" + + " don($p, Student.class, true);\n" + "end\n"; KnowledgeBuilder kbuilder = KnowledgeBuilderFactory.newKnowledgeBuilder(); - kbuilder.add( new ByteArrayResource( s1.getBytes() ), ResourceType.DRL ); - if ( kbuilder.hasErrors() ) { - fail( kbuilder.getErrors().toString() ); + kbuilder.add(new ByteArrayResource(s1.getBytes()), ResourceType.DRL); + if (kbuilder.hasErrors()) { + fail(kbuilder.getErrors().toString()); } InternalKnowledgeBase kbase = KnowledgeBaseFactory.newKnowledgeBase(); - kbase.addPackages( kbuilder.getKnowledgePackages() ); + kbase.addPackages(kbuilder.getKnowledgePackages()); KieSession ksession = kbase.newKieSession(); - TraitFactoryImpl.setMode(mode, ksession.getKieBase() ); + TraitFactoryImpl.setMode(mode, ksession.getKieBase()); ksession.fireAllRules(); - FactHandle personHandle = ksession.getFactHandles( new ClassObjectFilter( Person.class ) ).iterator().next(); + FactHandle personHandle = ksession.getFactHandles(new ClassObjectFilter(Person.class)).iterator().next(); InternalFactHandle h = ((InternalFactHandle) personHandle); - ObjectTypeConfigurationRegistry reg = h.getEntryPoint(( InternalWorkingMemory ) ksession).getObjectTypeConfigurationRegistry(); - ObjectTypeConf conf = reg.getOrCreateObjectTypeConf( h.getEntryPointId(), ((InternalFactHandle) personHandle).getObject() ); + ObjectTypeConfigurationRegistry reg = h.getEntryPoint((InternalWorkingMemory) ksession).getObjectTypeConfigurationRegistry(); + ObjectTypeConf conf = reg.getOrCreateObjectTypeConf(h.getEntryPointId(), ((InternalFactHandle) personHandle).getObject()); assertThat(conf.isTMSEnabled()).isTrue(); ksession.dispose(); @@ -1752,8 +1563,8 @@ public void testTMSConsistencyWithNonTraitableBeans() { public static class TBean { private String fld; public String getFld() { return fld; } - public void setFld( String fld ) { this.fld = fld; } - public TBean( String fld ) { this.fld = fld; } + public void setFld(String fld) { this.fld = fld; } + public TBean(String fld) { this.fld = fld; } } @@ -1777,46 +1588,44 @@ public void testTraitsLegacyWrapperCoherence() { "rule Init \n" + "when \n" + "then \n" + - " insert( new TBean(\"abc\") ); \n" + + " insert(new TBean(\"abc\")); \n" + "end \n" + "" + "rule Don \n" + "no-loop \n" + "when \n" + - " $b : TBean( ) \n" + + " $b : TBean() \n" + "then \n" + - " Mask m = don( $b, Mask.class ); \n" + - " modify (m) { setXyz( 10 ); } \n" + - " list.add( m ); \n" + + " Mask m = don($b, Mask.class); \n" + + " modify (m) { setXyz(10); } \n" + + " list.add(m); \n" + "end \n"; KnowledgeBuilder kbuilder = KnowledgeBuilderFactory.newKnowledgeBuilder(); - kbuilder.add( ResourceFactory.newByteArrayResource( str.getBytes() ), - ResourceType.DRL ); + kbuilder.add(ResourceFactory.newByteArrayResource(str.getBytes()), ResourceType.DRL); InternalKnowledgeBase kbase = KnowledgeBaseFactory.newKnowledgeBase(); - if ( kbuilder.hasErrors() ) { - fail( kbuilder.getErrors().toString() ); + if (kbuilder.hasErrors()) { + fail(kbuilder.getErrors().toString()); } - kbase.addPackages( kbuilder.getKnowledgePackages() ); + kbase.addPackages(kbuilder.getKnowledgePackages()); KieSession ksession = kbase.newKieSession(); - TraitFactoryImpl.setMode(mode, ksession.getKieBase() ); + TraitFactoryImpl.setMode(mode, ksession.getKieBase()); List list = new ArrayList(); - ksession.setGlobal("list", - list); + ksession.setGlobal("list", list); ksession.fireAllRules(); - Collection yOld = ksession.getObjects(); - assertThat(yOld.size()).isEqualTo(2); + Collection yOld = ksession.getObjects(); + assertThat(yOld).hasSize(2); TraitableBean coreOld = null; - for ( Object o : yOld ) { - if ( o instanceof TraitableBean ) { + for (Object o : yOld) { + if (o instanceof TraitableBean) { coreOld = (TraitableBean) o; break; } @@ -1826,57 +1635,51 @@ public void testTraitsLegacyWrapperCoherence() { assertThat(coreOld.getClass().getSuperclass()).isSameAs(TBean.class); assertThat(((TBean) coreOld).getFld()).isEqualTo("abc"); - assertThat(coreOld._getDynamicProperties().size()).isEqualTo(1); - assertThat(coreOld._getTraitMap().size()).isEqualTo(1); + assertThat(coreOld._getDynamicProperties()).hasSize(1); + assertThat(coreOld._getTraitMap()).hasSize(1); } @Test - public void testHasTypes() { + public void testHasTypes() throws Exception { String source = "org/drools/compiler/factmodel/traits/testTraitDon.drl"; KnowledgeBuilder kbuilder = KnowledgeBuilderFactory.newKnowledgeBuilder(); - Resource res = ResourceFactory.newClassPathResource( source ); + Resource res = ResourceFactory.newClassPathResource(source); assertThat(res).isNotNull(); kbuilder.add(res, ResourceType.DRL); - if ( kbuilder.hasErrors() ) { - fail( kbuilder.getErrors().toString() ); + if (kbuilder.hasErrors()) { + fail(kbuilder.getErrors().toString()); } InternalRuleBase kb = KnowledgeBaseFactory.newKnowledgeBase(); kb.addPackages(kbuilder.getKnowledgePackages()); TraitFactoryImpl traitBuilder = (TraitFactoryImpl) RuntimeComponentFactory.get().getTraitFactory(kb); - TraitFactoryImpl.setMode(mode, kb ); - - try { - FactType impClass = kb.getFactType("org.drools.compiler.trait.test","Imp"); - TraitableBean imp = (TraitableBean) impClass.newInstance(); - impClass.set(imp, "name", "aaabcd"); - - Class trait = kb.getFactType("org.drools.compiler.trait.test","Student").getFactClass(); - Class trait2 = kb.getFactType("org.drools.compiler.trait.test","Role").getFactClass(); + TraitFactoryImpl.setMode(mode, kb); - assertThat(trait).isNotNull(); + FactType impClass = kb.getFactType("org.drools.compiler.trait.test","Imp"); + TraitableBean imp = (TraitableBean) impClass.newInstance(); + impClass.set(imp, "name", "aaabcd"); - TraitProxyImpl proxy = (TraitProxyImpl) traitBuilder.getProxy(imp, trait); - Thing thing = traitBuilder.getProxy(imp, Thing.class); + Class trait = kb.getFactType("org.drools.compiler.trait.test","Student").getFactClass(); + Class trait2 = kb.getFactType("org.drools.compiler.trait.test","Role").getFactClass(); - TraitableBean core = proxy.getObject(); + assertThat(trait).isNotNull(); + TraitProxyImpl proxy = (TraitProxyImpl) traitBuilder.getProxy(imp, trait, false); + Thing thing = traitBuilder.getProxy(imp, Thing.class, false); - TraitProxyImpl proxy2 = (TraitProxyImpl) traitBuilder.getProxy(imp, trait); - Thing thing2 = traitBuilder.getProxy(imp, Thing.class); + TraitableBean core = proxy.getObject(); - assertThat(proxy2).isSameAs(proxy); - assertThat(thing2).isSameAs(thing); - assertThat(core.getTraits().size()).isEqualTo(2); + TraitProxyImpl proxy2 = (TraitProxyImpl) traitBuilder.getProxy(imp, trait, false); + Thing thing2 = traitBuilder.getProxy(imp, Thing.class, false); + assertThat(proxy2).isSameAs(proxy); + assertThat(thing2).isSameAs(thing); - } catch ( Exception e ) { - fail( e.getMessage(), e ); - } + assertThat(core.getTraits()).hasSize(2); } @Test @@ -1898,44 +1701,42 @@ public void testTraitRedundancy() { "rule \"Don\" \n" + "no-loop \n" + "when \n" + - " $p : IPerson( age < 30 ) \n" + + " $p : IPerson(age < 30) \n" + "then \n" + - " don( $p, IStudent.class );\n" + + " don($p, IStudent.class);\n" + "end \n" + "" + "rule \"Check\" \n" + "no-loop \n" + "when \n" + - " $p : IPerson( this isA IStudent ) \n" + + " $p : IPerson(this isA IStudent) \n" + "then \n" + - " modify ($p) { setAge( 37 ); } \n" + - " shed( $p, IStudent.class );\n" + + " modify ($p) { setAge(37); } \n" + + " shed($p, IStudent.class);\n" + "end \n"; KnowledgeBuilder kbuilder = KnowledgeBuilderFactory.newKnowledgeBuilder(); - kbuilder.add( ResourceFactory.newByteArrayResource( str.getBytes() ), - ResourceType.DRL ); + kbuilder.add(ResourceFactory.newByteArrayResource(str.getBytes()), ResourceType.DRL); InternalKnowledgeBase kbase = KnowledgeBaseFactory.newKnowledgeBase(); - if ( kbuilder.hasErrors() ) { - fail( kbuilder.getErrors().toString() ); + if (kbuilder.hasErrors()) { + fail(kbuilder.getErrors().toString()); } - kbase.addPackages( kbuilder.getKnowledgePackages() ); + kbase.addPackages(kbuilder.getKnowledgePackages()); KieSession ksession = kbase.newKieSession(); - TraitFactoryImpl.setMode(mode, ksession.getKieBase() ); + TraitFactoryImpl.setMode(mode, ksession.getKieBase()); List list = new ArrayList(); - ksession.setGlobal("list", - list); + ksession.setGlobal("list", list); - ksession.insert( new StudentImpl("skool", "john", 27 ) ); + ksession.insert(new StudentImpl("skool", "john", 27)); assertThat(ksession.fireAllRules()).isEqualTo(3); - for ( Object o : ksession.getObjects() ) { + for (Object o : ksession.getObjects()) { LOGGER.debug(o.toString()); } @@ -1963,34 +1764,34 @@ public void traitSimpleTypes() { " don($mark, PassMark.class);\n" + "end\n" + "" + - "rule \"Init\" when then insert( new ExamMark() ); end \n"; + "rule \"Init\" when then insert(new ExamMark()); end \n"; KnowledgeBuilder kbuilder = KnowledgeBuilderFactory.newKnowledgeBuilder(); - kbuilder.add( new ByteArrayResource( s1.getBytes() ), ResourceType.DRL ); - if ( kbuilder.hasErrors() ) { - fail( kbuilder.getErrors().toString() ); + kbuilder.add(new ByteArrayResource(s1.getBytes()), ResourceType.DRL); + if (kbuilder.hasErrors()) { + fail(kbuilder.getErrors().toString()); } InternalKnowledgeBase kbase = KnowledgeBaseFactory.newKnowledgeBase(); TraitFactoryImpl.setMode(mode, (InternalRuleBase) kbase); - kbase.addPackages( kbuilder.getKnowledgePackages() ); + kbase.addPackages(kbuilder.getKnowledgePackages()); KieSession ksession = kbase.newKieSession(); ksession.fireAllRules(); - for ( Object o : ksession.getObjects() ) { - if ( o instanceof TraitableBean ) { + for (Object o : ksession.getObjects()) { + if (o instanceof TraitableBean) { TraitableBean tb = (TraitableBean) o; - assertThat(tb._getTraitMap().size()).isEqualTo(1); + assertThat(tb._getTraitMap()).hasSize(1); BitSet bs = new BitSet(); - bs.set( 0 ); + bs.set(0); assertThat(tb.getCurrentTypeCode()).isEqualTo(bs); } - if ( o instanceof TraitProxyImpl) { + if (o instanceof TraitProxyImpl) { TraitProxyImpl tp = (TraitProxyImpl) o; - assertThat(tp.listAssignedOtnTypeCodes().size()).isEqualTo(0); + assertThat(tp.listAssignedOtnTypeCodes()).isEmpty(); } } } @@ -2020,55 +1821,55 @@ public void testTraitEncoding() { "when\n" + " $x : Entity()\n" + "then\n" + - " don( $x, A.class );\n" + + " don($x, A.class);\n" + "end\n" + "" + "rule \"donManyThing\"\n" + "when\n" + - " String( this == \"y\" ) \n" + + " String(this == \"y\") \n" + " $x : Entity()\n" + "then\n" + - " don( $x, B.class );\n" + - " don( $x, D.class );\n" + - " don( $x, F.class );\n" + - " don( $x, E.class );\n" + - " don( $x, I.class );\n" + - " don( $x, K.class );\n" + - " don( $x, J.class );\n" + - " don( $x, C.class );\n" + - " don( $x, H.class );\n" + - " don( $x, G.class );\n" + - " don( $x, L.class );\n" + - " don( $x, M.class );\n" + - " don( $x, N.class );\n" + + " don($x, B.class);\n" + + " don($x, D.class);\n" + + " don($x, F.class);\n" + + " don($x, E.class);\n" + + " don($x, I.class);\n" + + " don($x, K.class);\n" + + " don($x, J.class);\n" + + " don($x, C.class);\n" + + " don($x, H.class);\n" + + " don($x, G.class);\n" + + " don($x, L.class);\n" + + " don($x, M.class);\n" + + " don($x, N.class);\n" + "end\n" ; KnowledgeBuilder kbuilder = KnowledgeBuilderFactory.newKnowledgeBuilder(); - kbuilder.add( new ByteArrayResource( s1.getBytes() ), ResourceType.DRL ); - if ( kbuilder.hasErrors() ) { - fail( kbuilder.getErrors().toString() ); + kbuilder.add(new ByteArrayResource(s1.getBytes()), ResourceType.DRL); + if (kbuilder.hasErrors()) { + fail(kbuilder.getErrors().toString()); } InternalKnowledgeBase kbase = KnowledgeBaseFactory.newKnowledgeBase(); TraitFactoryImpl.setMode(mode, (InternalRuleBase) kbase); - kbase.addPackages( kbuilder.getKnowledgePackages() ); + kbase.addPackages(kbuilder.getKnowledgePackages()); TraitRegistryImpl tr = (TraitRegistryImpl) ((TraitRuntimeComponentFactory) RuntimeComponentFactory.get()).getTraitRegistry(kbase); - LOGGER.debug( tr.getHierarchy().toString() ); + LOGGER.debug(tr.getHierarchy().toString()); - Entity ent = new Entity( "x" ); + Entity ent = new Entity("x"); KieSession ksession = kbase.newKieSession(); - ksession.insert( ent ); + ksession.insert(ent); ksession.fireAllRules(); - assertThat(ent.getMostSpecificTraits().size()).isEqualTo(1); + assertThat(ent.getMostSpecificTraits()).hasSize(1); - ksession.insert( "y" ); + ksession.insert("y"); ksession.fireAllRules(); - LOGGER.debug( ent.getMostSpecificTraits().toString() ); - assertThat(ent.getMostSpecificTraits().size()).isEqualTo(2); + LOGGER.debug(ent.getMostSpecificTraits().toString()); + assertThat(ent.getMostSpecificTraits()).hasSize(2); } @@ -2076,56 +1877,56 @@ public void testTraitEncoding() { @Test public void testTraitActualTypeCodeWithEntities() { - testTraitActualTypeCodeWithEntities( "ent", mode ); + testTraitActualTypeCodeWithEntities("ent", mode); } @Test public void testTraitActualTypeCodeWithCoreMap() { - testTraitActualTypeCodeWithEntities( "kor", mode ); + testTraitActualTypeCodeWithEntities("kor", mode); } - void testTraitActualTypeCodeWithEntities( String trig, VirtualPropertyMode mode ) { + void testTraitActualTypeCodeWithEntities(String trig, VirtualPropertyMode mode) { KnowledgeBuilder kbuilder = KnowledgeBuilderFactory.newKnowledgeBuilder(); - kbuilder.add( new ClassPathResource( "org/drools/compiler/factmodel/traits/testComplexDonShed.drl" ), ResourceType.DRL ); - if ( kbuilder.hasErrors() ) { - fail( kbuilder.getErrors().toString() ); + kbuilder.add(new ClassPathResource("org/drools/compiler/factmodel/traits/testComplexDonShed.drl"), ResourceType.DRL); + if (kbuilder.hasErrors()) { + fail(kbuilder.getErrors().toString()); } InternalKnowledgeBase kbase = KnowledgeBaseFactory.newKnowledgeBase(); TraitFactoryImpl.setMode(mode, (KieBase) kbase); - kbase.addPackages( kbuilder.getKnowledgePackages() ); + kbase.addPackages(kbuilder.getKnowledgePackages()); KieSession ksession = kbase.newKieSession(); - ksession.insert( trig ); + ksession.insert(trig); ksession.fireAllRules(); - TraitableBean ent = (TraitableBean) ksession.getGlobal( "core" ); + TraitableBean ent = (TraitableBean) ksession.getGlobal("core"); assertThat(ent.getCurrentTypeCode()).isEqualTo(CodedHierarchyImpl.stringToBitSet("1")); - ksession.insert( "b" ); + ksession.insert("b"); ksession.fireAllRules(); assertThat(ent.getCurrentTypeCode()).isEqualTo(CodedHierarchyImpl.stringToBitSet("11")); - ksession.insert( "c" ); + ksession.insert("c"); ksession.fireAllRules(); assertThat(ent.getCurrentTypeCode()).isEqualTo(CodedHierarchyImpl.stringToBitSet("1011")); - ksession.insert( "e" ); + ksession.insert("e"); ksession.fireAllRules(); assertThat(ent.getCurrentTypeCode()).isEqualTo(CodedHierarchyImpl.stringToBitSet("11011")); - ksession.insert( "-c" ); + ksession.insert("-c"); ksession.fireAllRules(); assertThat(ent.getCurrentTypeCode()).isEqualTo(CodedHierarchyImpl.stringToBitSet("11")); - ksession.insert( "dg" ); + ksession.insert("dg"); ksession.fireAllRules(); assertThat(ent.getCurrentTypeCode()).isEqualTo(CodedHierarchyImpl.stringToBitSet("111111")); - ksession.insert( "-f" ); + ksession.insert("-f"); ksession.fireAllRules(); assertThat(ent.getCurrentTypeCode()).isEqualTo(CodedHierarchyImpl.stringToBitSet("111")); @@ -2148,75 +1949,73 @@ public void testTraitModifyCore() { "rule \"Init\" " + "when " + "then " + - " Person p = new Person( \"john\" ); " + - " insert( p ); " + + " Person p = new Person(\"john\"); " + + " insert(p); " + "end " + "" + "rule \"Don\" " + "no-loop " + "when " + - " $p : Person( name == \"john\" ) " + + " $p : Person(name == \"john\") " + "then " + - " don( $p, Student.class ); " + - " don( $p, Worker.class ); " + - " don( $p, StudentWorker.class ); " + - " don( $p, Assistant.class ); " + + " don($p, Student.class); " + + " don($p, Worker.class); " + + " don($p, StudentWorker.class); " + + " don($p, Assistant.class); " + "end " + "" + "rule \"Log S\" " + "when " + - " $t : Student() @Watch( name ) " + + " $t : Student() @Watch(name) " + "then " + - " list.add( $t.getName() ); " + + " list.add($t.getName()); " + "end " + "rule \"Log W\" " + "when " + - " $t : Worker() @Watch( name ) " + + " $t : Worker() @Watch(name) " + "then " + - " list.add( $t.getName() ); " + + " list.add($t.getName()); " + "end " + "rule \"Log SW\" " + "when " + - " $t : StudentWorker() @Watch( name ) " + + " $t : StudentWorker() @Watch(name) " + "then " + - " list.add( $t.getName() ); " + + " list.add($t.getName()); " + "end " + "rule \"Log RA\" " + "when " + - " $t : Assistant() @Watch( name ) " + + " $t : Assistant() @Watch(name) " + "then " + - " list.add( $t.getName() ); " + + " list.add($t.getName()); " + "end " + "" + "rule \"Mod\" " + "salience -10 " + "when " + - " $p : Person( name == \"john\" ) " + + " $p : Person(name == \"john\") " + "then " + - " modify ( $p ) { setName( \"alan\" ); } " + + " modify ($p) { setName(\"alan\"); } " + "end " + ""; KnowledgeBuilder kbuilder = KnowledgeBuilderFactory.newKnowledgeBuilder(); - kbuilder.add( new ByteArrayResource( s1.getBytes() ), ResourceType.DRL ); - if ( kbuilder.hasErrors() ) { - fail( kbuilder.getErrors().toString() ); + kbuilder.add(new ByteArrayResource(s1.getBytes()), ResourceType.DRL); + if (kbuilder.hasErrors()) { + fail(kbuilder.getErrors().toString()); } InternalKnowledgeBase kbase = KnowledgeBaseFactory.newKnowledgeBase(); TraitFactoryImpl.setMode(mode, (InternalRuleBase) kbase); - kbase.addPackages( kbuilder.getKnowledgePackages() ); + kbase.addPackages(kbuilder.getKnowledgePackages()); KieSession ksession = kbase.newKieSession(); - List list = new ArrayList(); - ksession.setGlobal( "list", list ); - + List list = new ArrayList<>(); + ksession.setGlobal("list", list); int k = ksession.fireAllRules(); - assertThat(list).isEqualTo(Arrays.asList("john", "john", "john", "john", "alan", "alan", "alan", "alan")); assertThat(k).isEqualTo(11); - + assertThat(list).containsExactly("john", "john", "john", "john", "alan", "alan", "alan", "alan"); } @@ -2237,71 +2036,71 @@ public void testTraitModifyCore2() { "rule \"Init\" " + "when " + "then " + - " Person p = new Person( \"john\" ); " + - " insert( p ); " + + " Person p = new Person(\"john\"); " + + " insert(p); " + "end " + "" + "rule \"Don\" " + "when " + - " $p : Person( name == \"john\" ) " + + " $p : Person(name == \"john\") " + "then " + - " don( $p, Worker.class ); " + - " don( $p, StudentWorker2.class ); " + - " don( $p, Assistant.class ); " + + " don($p, Worker.class); " + + " don($p, StudentWorker2.class); " + + " don($p, Assistant.class); " + "end " + "" + "rule \"Log S\" " + "when " + - " $t : Student() @watch( name ) " + + " $t : Student() @watch(name) " + "then " + "end " + "rule \"Log W\" " + "when " + - " $t : Worker() @watch( name ) " + + " $t : Worker() @watch(name) " + "then " + "end " + "rule \"Log SW\" " + "when " + - " $t : StudentWorker() @watch( name ) " + + " $t : StudentWorker() @watch(name) " + "then " + "end " + "rule \"Log RA\" " + "when " + - " $t : Assistant() @watch( name ) " + + " $t : Assistant() @watch(name) " + "then " + "end " + "rule \"Log Px\" " + "salience -1 " + "when " + - " $p : Person() @watch( name ) " + + " $p : Person() @watch(name) " + "then " + "end " + "" + "rule \"Mod\" " + "salience -10 " + "when " + - " String( this == \"go\" ) " + - " $p : Student( name == \"john\" ) " + + " String(this == \"go\") " + + " $p : Student(name == \"john\") " + "then " + - " modify ( $p ) { setName( \"alan\" ); } " + + " modify ($p) { setName(\"alan\"); } " + "end "; KnowledgeBuilder kbuilder = KnowledgeBuilderFactory.newKnowledgeBuilder(); - kbuilder.add( new ByteArrayResource( s1.getBytes() ), ResourceType.DRL ); - if ( kbuilder.hasErrors() ) { - fail( kbuilder.getErrors().toString() ); + kbuilder.add(new ByteArrayResource(s1.getBytes()), ResourceType.DRL); + if (kbuilder.hasErrors()) { + fail(kbuilder.getErrors().toString()); } InternalKnowledgeBase kbase = KnowledgeBaseFactory.newKnowledgeBase(); TraitFactoryImpl.setMode(mode, (KieBase) kbase); // not relevant - kbase.addPackages( kbuilder.getKnowledgePackages() ); + kbase.addPackages(kbuilder.getKnowledgePackages()); KieSession ksession = kbase.newKieSession(); int k = ksession.fireAllRules(); assertThat(k).isEqualTo(7); - ksession.insert( "go" ); + ksession.insert("go"); k = ksession.fireAllRules(); assertThat(k).isEqualTo(6); @@ -2324,48 +2123,48 @@ public void testTraitModifyCore2a() { "rule \"Init\" \n" + "when \n" + "then \n" + - " Person p = new Person( \"john\" ); \n" + - " insert( p ); \n" + + " Person p = new Person(\"john\"); \n" + + " insert(p); \n" + "end \n" + "" + "rule \"Don\" \n" + "when \n" + - " $p : Person( name == \"john\" ) \n" + + " $p : Person(name == \"john\") \n" + "then \n" + - " don( $p, Worker.class ); \n" + - " don( $p, StudentWorker.class ); \n" + + " don($p, Worker.class); \n" + + " don($p, StudentWorker.class); \n" + "end \n" + "" + "rule \"Log W\" \n" + "when \n" + - " $t : Worker( this isA StudentWorker ) @watch( name ) \n" + + " $t : Worker(this isA StudentWorker) @watch(name) \n" + "then \n" + - " list.add( true ); \n" + + " list.add(true); \n" + "end \n" + "rule \"Log SW\" \n" + "when \n" + - " $t : StudentWorker() @watch( name ) \n" + + " $t : StudentWorker() @watch(name) \n" + "then \n" + "end \n"; KnowledgeBuilder kbuilder = KnowledgeBuilderFactory.newKnowledgeBuilder(); - kbuilder.add( new ByteArrayResource( s1.getBytes() ), ResourceType.DRL ); - if ( kbuilder.hasErrors() ) { - fail( kbuilder.getErrors().toString() ); + kbuilder.add(new ByteArrayResource(s1.getBytes()), ResourceType.DRL); + if (kbuilder.hasErrors()) { + fail(kbuilder.getErrors().toString()); } InternalKnowledgeBase kbase = KnowledgeBaseFactory.newKnowledgeBase(); TraitFactoryImpl.setMode(mode, (KieBase) kbase); // not relevant - kbase.addPackages( kbuilder.getKnowledgePackages() ); + kbase.addPackages(kbuilder.getKnowledgePackages()); KieSession ksession = kbase.newKieSession(); - ArrayList list = new ArrayList( ); - ksession.setGlobal( "list", list ); + List list = new ArrayList<>(); + ksession.setGlobal("list", list); - int k = ksession.fireAllRules(); + ksession.fireAllRules(); - assertThat(list.contains(true)).isTrue(); - assertThat(list.size()).isEqualTo(1); + assertThat(list).hasSize(1); + assertThat(list).contains(true); } @@ -2397,80 +2196,80 @@ public void testTraitModifyCore3() { "" + "rule \"Init\" when \n" + "then \n" + - " insert( new Core() );" + + " insert(new Core());" + "end \n" + "" + "rule \"donManyThing\"\n" + "when\n" + - " $x : Core( id == 0 )\n" + + " $x : Core(id == 0)\n" + "then\n" + - " don( $x, A.class );\n" + - " don( $x, B.class );\n" + - " don( $x, D.class );\n" + - " don( $x, F.class );\n" + - " don( $x, E.class );\n" + - " don( $x, I.class );\n" + - " don( $x, K.class );\n" + - " don( $x, J.class );\n" + - " don( $x, C.class );\n" + - " don( $x, H.class );\n" + - " don( $x, G.class );\n" + - " don( $x, L.class );\n" + - " don( $x, M.class );\n" + - " don( $x, N.class );\n" + + " don($x, A.class);\n" + + " don($x, B.class);\n" + + " don($x, D.class);\n" + + " don($x, F.class);\n" + + " don($x, E.class);\n" + + " don($x, I.class);\n" + + " don($x, K.class);\n" + + " don($x, J.class);\n" + + " don($x, C.class);\n" + + " don($x, H.class);\n" + + " don($x, G.class);\n" + + " don($x, L.class);\n" + + " don($x, M.class);\n" + + " don($x, N.class);\n" + "end\n" + "\n" + "\n" + "\n" + - "rule \"Log A\" when $x : A( id == 1 ) then list.add( 1 ); end \n" + - "rule \"Log B\" when $x : B( id == 1 ) then list.add( 2 ); end \n" + - "rule \"Log C\" when $x : C( id == 1 ) then list.add( 3 ); end \n" + - "rule \"Log D\" when $x : D( id == 1 ) then list.add( 4 ); end \n" + - "rule \"Log E\" when $x : E( id == 1 ) then list.add( 5 ); end \n" + - "rule \"Log F\" when $x : F( id == 1 ) then list.add( 6 ); end \n" + - "rule \"Log G\" when $x : G( id == 1 ) then list.add( 7 ); end \n" + - "rule \"Log H\" when $x : H( id == 1 ) then list.add( 8 ); end \n" + - "rule \"Log I\" when $x : I( id == 1 ) then list.add( 9 ); end \n" + - "rule \"Log J\" when $x : J( id == 1 ) then list.add( 10 ); end \n" + - "rule \"Log K\" when $x : K( id == 1 ) then list.add( 11 ); end \n" + - "rule \"Log L\" when $x : L( id == 1 ) then list.add( 12 ); end \n" + - "rule \"Log M\" when $x : M( id == 1 ) then list.add( 13 ); end \n" + - "rule \"Log N\" when $x : N( id == 1 ) then list.add( 14 ); end \n" + + "rule \"Log A\" when $x : A(id == 1) then list.add(1); end \n" + + "rule \"Log B\" when $x : B(id == 1) then list.add(2); end \n" + + "rule \"Log C\" when $x : C(id == 1) then list.add(3); end \n" + + "rule \"Log D\" when $x : D(id == 1) then list.add(4); end \n" + + "rule \"Log E\" when $x : E(id == 1) then list.add(5); end \n" + + "rule \"Log F\" when $x : F(id == 1) then list.add(6); end \n" + + "rule \"Log G\" when $x : G(id == 1) then list.add(7); end \n" + + "rule \"Log H\" when $x : H(id == 1) then list.add(8); end \n" + + "rule \"Log I\" when $x : I(id == 1) then list.add(9); end \n" + + "rule \"Log J\" when $x : J(id == 1) then list.add(10); end \n" + + "rule \"Log K\" when $x : K(id == 1) then list.add(11); end \n" + + "rule \"Log L\" when $x : L(id == 1) then list.add(12); end \n" + + "rule \"Log M\" when $x : M(id == 1) then list.add(13); end \n" + + "rule \"Log N\" when $x : N(id == 1) then list.add(14); end \n" + "" + - "rule \"Log Core\" when $x : Core( $id : id ) then end \n" + + "rule \"Log Core\" when $x : Core($id : id) then end \n" + "" + "rule \"Mod\" \n" + "salience -10 \n" + "when \n" + - " String( this == \"go\" ) \n" + - " $x : Core( id == 0 ) \n" + + " String(this == \"go\") \n" + + " $x : Core(id == 0) \n" + "then \n" + - " modify ( $x ) { setId( 1 ); }" + + " modify ($x) { setId(1); }" + "end \n" + ""; KnowledgeBuilder kbuilder = KnowledgeBuilderFactory.newKnowledgeBuilder(); - kbuilder.add( new ByteArrayResource( s1.getBytes() ), ResourceType.DRL ); - if ( kbuilder.hasErrors() ) { - fail( kbuilder.getErrors().toString() ); + kbuilder.add(new ByteArrayResource(s1.getBytes()), ResourceType.DRL); + if (kbuilder.hasErrors()) { + fail(kbuilder.getErrors().toString()); } InternalKnowledgeBase kbase = KnowledgeBaseFactory.newKnowledgeBase(); TraitFactoryImpl.setMode(mode, (KieBase) kbase); // not relevant - kbase.addPackages( kbuilder.getKnowledgePackages() ); + kbase.addPackages(kbuilder.getKnowledgePackages()); - List list = new ArrayList(); + List list = new ArrayList<>(); KieSession ksession = kbase.newKieSession(); - ksession.setGlobal( "list", list ); + ksession.setGlobal("list", list); ksession.fireAllRules(); - ksession.insert( "go" ); + ksession.insert("go"); ksession.fireAllRules(); - assertThat(list.size()).isEqualTo(14); - for ( int j = 1; j <= 14; j++ ) { - assertThat(list.contains(j)).isTrue(); + assertThat(list).hasSize(14); + for (int j = 1; j <= 14; j++) { + assertThat(list).contains(j); } @@ -2515,77 +2314,74 @@ public void testTraitModifyCoreWithPropertyReactivity() { "rule \"Init\" \n" + "when \n" + "then \n" + - " Person p = new Person( 109.99, \"john\", 18 ); \n" + - " insert( p ); \n" + + " Person p = new Person(109.99, \"john\", 18); \n" + + " insert(p); \n" + "end \n" + "" + "rule \"Don\" \n" + "when \n" + - " $p : Person( name == \"john\" ) \n" + + " $p : Person(name == \"john\") \n" + "then \n" + - " don( $p, StudentWorker.class ); \n" + - " don( $p, Assistant.class ); \n" + + " don($p, StudentWorker.class); \n" + + " don($p, Assistant.class); \n" + "end \n" + "" + "rule \"Log S\" \n" + "when \n" + - " $t : Student( age == 44 ) \n" + + " $t : Student(age == 44) \n" + "then \n" + - " list.add( 1 );\n " + + " list.add(1);\n " + "end \n" + "rule \"Log W\" \n" + "when \n" + - " $t : Worker( name == \"alan\" ) \n" + + " $t : Worker(name == \"alan\") \n" + "then \n" + - " list.add( 2 );\n " + + " list.add(2);\n " + "end \n" + "rule \"Log SW\" \n" + "when \n" + - " $t : StudentWorker( age == 44 ) \n" + + " $t : StudentWorker(age == 44) \n" + "then \n" + - " list.add( 3 );\n " + + " list.add(3);\n " + "end \n" + "rule \"Log Pers\" \n" + "when \n" + - " $t : Person( age == 44 ) \n" + + " $t : Person(age == 44) \n" + "then \n" + - " list.add( 4 );\n " + + " list.add(4);\n " + "end \n" + "" + "rule \"Mod\" \n" + "salience -10 \n" + "when \n" + - " String( this == \"go\" ) \n" + - " $p : Student( name == \"john\" ) \n" + + " String(this == \"go\") \n" + + " $p : Student(name == \"john\") \n" + "then \n" + - " modify ( $p ) { setSchool( \"myschool\" ), setAge( 44 ), setName( \"alan\" ); } " + + " modify ($p) { setSchool(\"myschool\"), setAge(44), setName(\"alan\"); } " + "end \n"; KnowledgeBuilder kbuilder = KnowledgeBuilderFactory.newKnowledgeBuilder(); - kbuilder.add( new ByteArrayResource( s1.getBytes() ), ResourceType.DRL ); - if ( kbuilder.hasErrors() ) { - fail( kbuilder.getErrors().toString() ); + kbuilder.add(new ByteArrayResource(s1.getBytes()), ResourceType.DRL); + if (kbuilder.hasErrors()) { + fail(kbuilder.getErrors().toString()); } InternalKnowledgeBase kbase = KnowledgeBaseFactory.newKnowledgeBase(); TraitFactoryImpl.setMode(mode, (KieBase) kbase); // not relevant - kbase.addPackages( kbuilder.getKnowledgePackages() ); + kbase.addPackages(kbuilder.getKnowledgePackages()); List list = new ArrayList(); KieSession ksession = kbase.newKieSession(); - ksession.setGlobal( "list", list ); + ksession.setGlobal("list", list); int k = ksession.fireAllRules(); - ksession.insert( "go" ); + ksession.insert("go"); k = ksession.fireAllRules(); assertThat(k).isEqualTo(5); - assertThat(list.size()).isEqualTo(4); - assertThat(list.contains(1)).isTrue(); - assertThat(list.contains(2)).isTrue(); - assertThat(list.contains(3)).isTrue(); - assertThat(list.contains(4)).isTrue(); + assertThat(list).hasSize(4); + assertThat(list).contains(1, 2, 3, 4); } @@ -2609,22 +2405,22 @@ public void testTraitEncodeExtendingNonTrait() { KnowledgeBuilder kbuilder = KnowledgeBuilderFactory.newKnowledgeBuilder(); - kbuilder.add( new ByteArrayResource( s2.getBytes() ), ResourceType.DRL ); - if ( kbuilder.hasErrors() ) { - fail( kbuilder.getErrors().toString() ); + kbuilder.add(new ByteArrayResource(s2.getBytes()), ResourceType.DRL); + if (kbuilder.hasErrors()) { + fail(kbuilder.getErrors().toString()); } InternalRuleBase kbase = KnowledgeBaseFactory.newKnowledgeBase(); - TraitFactoryImpl.setMode(mode, kbase ); + TraitFactoryImpl.setMode(mode, kbase); - kbase.addPackages( kbuilder.getKnowledgePackages() ); + kbase.addPackages(kbuilder.getKnowledgePackages()); KnowledgeBuilder kbuilder2 = KnowledgeBuilderFactory.newKnowledgeBuilder(); - kbuilder2.add( new ByteArrayResource( s1.getBytes() ), ResourceType.DRL ); - if ( kbuilder2.hasErrors() ) { - fail( kbuilder2.getErrors().toString() ); + kbuilder2.add(new ByteArrayResource(s1.getBytes()), ResourceType.DRL); + if (kbuilder2.hasErrors()) { + fail(kbuilder2.getErrors().toString()); } - kbase.addPackages( kbuilder2.getKnowledgePackages() ); + kbase.addPackages(kbuilder2.getKnowledgePackages()); } @@ -2634,26 +2430,26 @@ public void testTraitEncodeExtendingNonTrait() { public void isAWithBackChaining() { String source = "org/drools/compiler/factmodel/traits/testTraitIsAWithBC.drl"; - KieSession ksession = getSession( source ); - TraitFactoryImpl.setMode(mode, ksession.getKieBase() ); + KieSession ksession = getSession(source); + TraitFactoryImpl.setMode(mode, ksession.getKieBase()); - List list = new ArrayList(); - ksession.setGlobal( "list", list ); + List list = new ArrayList<>(); + ksession.setGlobal("list", list); ksession.fireAllRules(); - ksession.insert( "Como" ); + ksession.insert("Como"); ksession.fireAllRules(); - assertThat(list.contains("Italy")).isTrue(); + assertThat(list).contains("Italy"); } @Test - public void testIsAEvaluatorOnClassification( ) { + public void testIsAEvaluatorOnClassification() { String source = "package t.x \n" + "\n" + "global java.util.List list; \n" + @@ -2674,7 +2470,7 @@ public void testIsAEvaluatorOnClassification( ) { "then\n" + " Entity o = new Entity();\n" + " insert(o);\n" + - " don( o, D.class ); \n" + + " don(o, D.class); \n" + "end\n" + "" + "rule Don when\n" + @@ -2684,35 +2480,34 @@ public void testIsAEvaluatorOnClassification( ) { "" + "rule \"Rule 0 >> http://t/x#D\"\n" + "when\n" + - " $t : org.drools.base.factmodel.traits.Thing( $c : core, this not isA t.x.E.class, this isA t.x.D.class ) " + + " $t : org.drools.base.factmodel.traits.Thing($c : core, this not isA t.x.E.class, this isA t.x.D.class) " + "then\n" + - " list.add( \"E\" ); \n" + - " don( $t, E.class ); \n" + + " list.add(\"E\"); \n" + + " don($t, E.class); \n" + "end\n" + "" + "rule React \n" + "when E() then \n" + - " list.add( \"X\" ); \n" + + " list.add(\"X\"); \n" + "end \n" ; - KieSession ks = getSessionFromString( source ); - TraitFactoryImpl.setMode(mode, ks.getKieBase() ); + KieSession ks = getSessionFromString(source); + TraitFactoryImpl.setMode(mode, ks.getKieBase()); - List list = new ArrayList(); - ks.setGlobal( "list", list ); + List list = new ArrayList<>(); + ks.setGlobal("list", list); ks.fireAllRules(); - assertThat(list.size()).isEqualTo(2); - assertThat(list.contains("E")).isTrue(); - assertThat(list.contains("X")).isTrue(); + assertThat(list).hasSize(2); + assertThat(list).contains("E", "X"); } @Test - public void testShedWithTMS( ) { + public void testShedWithTMS() { String source = "package t.x \n" + "\n" + "global java.util.List list; \n" + @@ -2733,8 +2528,8 @@ public void testShedWithTMS( ) { "then\n" + " Entity o = new Entity();\n" + " insert(o);\n" + - " don( o, Thing.class ); \n" + - " don( o, D.class ); \n" + + " don(o, Thing.class); \n" + + " don(o, D.class); \n" + "end\n" + "" + "rule Don when\n" + @@ -2744,15 +2539,15 @@ public void testShedWithTMS( ) { "" + "rule \"Rule 0 >> http://t/x#D\"\n" + "when\n" + - " $t : org.drools.base.factmodel.traits.Thing( $c : core, _isTop(), this not isA t.x.E.class, this isA t.x.D.class ) " + + " $t : org.drools.base.factmodel.traits.Thing($c : core, _isTop(), this not isA t.x.E.class, this isA t.x.D.class) " + "then\n" + - " list.add( \"E\" ); \n" + - " don( $t, E.class ); \n" + + " list.add(\"E\"); \n" + + " don($t, E.class); \n" + "end\n" + "" + "rule React \n" + "when $x : E() then \n" + - " list.add( \"X\" ); \n" + + " list.add(\"X\"); \n" + "end \n" + "" + "rule Shed \n" + @@ -2760,31 +2555,30 @@ public void testShedWithTMS( ) { " $s : String() \n" + " $d : Entity() \n" + "then \n" + - " delete( $s ); \n" + - " shed( $d, D.class );\n" + + " delete($s); \n" + + " shed($d, D.class);\n" + "end \n" + "" ; - KieSession ks = getSessionFromString( source ); - TraitFactoryImpl.setMode(mode, ks.getKieBase() ); + KieSession ks = getSessionFromString(source); + TraitFactoryImpl.setMode(mode, ks.getKieBase()); - List list = new ArrayList(); - ks.setGlobal( "list", list ); + List list = new ArrayList<>(); + ks.setGlobal("list", list); ks.fireAllRules(); - LOGGER.debug( list.toString() ); - assertThat(list.size()).isEqualTo(2); - assertThat(list.contains("E")).isTrue(); - assertThat(list.contains("X")).isTrue(); + LOGGER.debug(list.toString()); + assertThat(list).hasSize(2); + assertThat(list).contains("E", "X"); - ks.insert( "shed" ); + ks.insert("shed"); ks.fireAllRules(); - for ( Object o : ks.getObjects() ) { - LOGGER.debug( o.toString() ); + for (Object o : ks.getObjects()) { + LOGGER.debug(o.toString()); } - assertThat(ks.getObjects().size()).isEqualTo(3); + assertThat(ks.getObjects()).hasSize(3); } @@ -2812,7 +2606,7 @@ public void testTraitInitialization() { "declare Bar\n" + " @Traitable()\n" + " hardList : List \n" + - " moreList : List = Arrays.asList( 1, 2, 3 ) \n" + + " moreList : List = Arrays.asList(1, 2, 3) \n" + "\n" + "end\n" + "" + @@ -2820,46 +2614,46 @@ public void testTraitInitialization() { "then\n" + " Bar o = new Bar();\n" + " insert(o);\n" + - " Thing t = don( o, Thing.class ); \n" + - " t.getFields().put( \"otraList\", Arrays.asList( 42 ) ); \n" + - " don( o, Foo.class ); \n" + + " Thing t = don(o, Thing.class); \n" + + " t.getFields().put(\"otraList\", Arrays.asList(42)); \n" + + " don(o, Foo.class); \n" + "end\n" + "" + "rule Don when\n" + - " $x : Foo( $h : hardList, $s : softList, $o : otraList, $m : moreList, $i : primFld, $d : primDbl ) \n" + + " $x : Foo($h : hardList, $s : softList, $o : otraList, $m : moreList, $i : primFld, $d : primDbl) \n" + "then \n" + - " list.add( $h ); \n" + - " list.add( $s ); \n" + - " list.add( $o ); \n" + - " list.add( $m ); \n" + - " list.add( $i ); \n" + - " list.add( $d ); \n" + + " list.add($h); \n" + + " list.add($s); \n" + + " list.add($o); \n" + + " list.add($m); \n" + + " list.add($i); \n" + + " list.add($d); \n" + "end\n" + "" ; - KieSession ks = getSessionFromString( source ); - TraitFactoryImpl.setMode(mode, ks.getKieBase() ); + KieSession ks = getSessionFromString(source); + TraitFactoryImpl.setMode(mode, ks.getKieBase()); - List list = new ArrayList(); - ks.setGlobal( "list", list ); + List list = new ArrayList<>(); + ks.setGlobal("list", list); ks.fireAllRules(); - assertThat(list.size()).isEqualTo(6); - assertThat(list.contains(null)).isFalse(); + assertThat(list).hasSize(6); + assertThat(list).doesNotContainNull(); - List hard = (List) list.get( 0 ); - List soft = (List) list.get( 1 ); - List otra = (List) list.get( 2 ); - List more = (List) list.get( 3 ); + List hard = (List) list.get(0); + List soft = (List) list.get(1); + List otra = (List) list.get(2); + List more = (List) list.get(3); - assertThat(hard.isEmpty()).isTrue(); - assertThat(soft.isEmpty()).isTrue(); - assertThat(Arrays.asList(1, 2, 3)).isEqualTo(more); - assertThat(List.of(42)).isEqualTo(otra); + assertThat(hard).isEmpty(); + assertThat(soft).isEmpty(); + assertThat(more).containsExactly(1, 2, 3); + assertThat(otra).containsExactly(42); - assertThat(list.contains(3)).isTrue(); - assertThat(list.contains(0.421)).isTrue(); + assertThat(list).contains(3); + assertThat(list).contains(0.421); } @@ -2892,21 +2686,21 @@ public void testUnTraitedBean() { "end\n" + "" + "rule Check when\n" + - " $x : Bar( this not isA Foo ) \n" + + " $x : Bar(this not isA Foo) \n" + "then \n" + "end\n" + "rule Check2 when\n" + - " $x : Bar2( this not isA Foo ) \n" + + " $x : Bar2(this not isA Foo) \n" + "then \n" + "end\n" + ""; - KieSession ks = getSessionFromString( source ); - TraitFactoryImpl.setMode(mode, ks.getKieBase() ); + KieSession ks = getSessionFromString(source); + TraitFactoryImpl.setMode(mode, ks.getKieBase()); - List list = new ArrayList(); - ks.setGlobal( "list", list ); + List list = new ArrayList<>(); + ks.setGlobal("list", list); ks.fireAllRules(); } @@ -2914,7 +2708,7 @@ public void testUnTraitedBean() { @Test - public void testIsAOptimization( ) { + public void testIsAOptimization() { String source = "package t.x \n" + "import java.util.*; \n" + "import org.drools.base.factmodel.traits.Thing \n" + @@ -2937,44 +2731,44 @@ public void testIsAOptimization( ) { "rule Init when\n" + "then\n" + " Kore k = new Kore();\n" + - " don( k, E.class ); \n" + + " don(k, E.class); \n" + "end\n" + "" + "rule Check_1 when\n" + - " $x : Kore( this isA [ B, D ] ) \n" + + " $x : Kore(this isA [ B, D ]) \n" + "then \n" + - " list.add( \" B+D \" ); \n" + + " list.add(\" B+D \"); \n" + "end\n" + "" + "rule Check_2 when\n" + - " $x : Kore( this isA [ A ] ) \n" + + " $x : Kore(this isA [ A ]) \n" + "then \n" + - " list.add( \" A \" ); \n" + + " list.add(\" A \"); \n" + "end\n" + "rule Check_3 when\n" + - " $x : Kore( this not isA [ F ] ) \n" + + " $x : Kore(this not isA [ F ]) \n" + "then \n" + - " list.add( \" F \" ); \n" + + " list.add(\" F \"); \n" + "end\n" + ""; - KieSession ks = getSessionFromString( source ); - TraitFactoryImpl.setMode(mode, ks.getKieBase() ); + KieSession ks = getSessionFromString(source); + TraitFactoryImpl.setMode(mode, ks.getKieBase()); - List list = new ArrayList(); - ks.setGlobal( "list", list ); + List list = new ArrayList<>(); + ks.setGlobal("list", list); ks.fireAllRules(); - assertThat(list.size()).isEqualTo(3); + assertThat(list).hasSize(3); } @Test - public void testTypeRefractionOnInsert( ) { + public void testTypeRefractionOnInsert() { String source = "package t.x \n" + "import java.util.*; \n" + "import org.drools.base.factmodel.traits.Thing \n" + @@ -2997,37 +2791,37 @@ public void testTypeRefractionOnInsert( ) { "rule Init when\n" + "then\n" + " Kore k = new Kore();\n" + - " don( k, B.class ); \n" + - " don( k, C.class ); \n" + - " don( k, D.class ); \n" + - " don( k, E.class ); \n" + - " don( k, A.class ); \n" + - " don( k, F.class ); \n" + + " don(k, B.class); \n" + + " don(k, C.class); \n" + + " don(k, D.class); \n" + + " don(k, E.class); \n" + + " don(k, A.class); \n" + + " don(k, F.class); \n" + "end\n" + "" + "rule Check_1 when\n" + - " $x : A( ) \n" + + " $x : A() \n" + "then \n" + - " list.add( $x ); \n" + + " list.add($x); \n" + "end\n" + ""; - KieSession ks = getSessionFromString( source ); - TraitFactoryImpl.setMode(mode, ks.getKieBase() ); + KieSession ks = getSessionFromString(source); + TraitFactoryImpl.setMode(mode, ks.getKieBase()); - List list = new ArrayList(); - ks.setGlobal( "list", list ); + List list = new ArrayList<>(); + ks.setGlobal("list", list); ks.fireAllRules(); - assertThat(list.size()).isEqualTo(1); + assertThat(list).hasSize(1); } @Test - public void testTypeRefractionOnQuery( ) { + public void testTypeRefractionOnQuery() { String source = "declare BaseObject\n" + "@Traitable\n" + "id : String @key\n" + @@ -3057,19 +2851,19 @@ public void testTypeRefractionOnQuery( ) { "end"; - KieSession ks = getSessionFromString( source ); - TraitFactoryImpl.setMode(mode, ks.getKieBase() ); + KieSession ks = getSessionFromString(source); + TraitFactoryImpl.setMode(mode, ks.getKieBase()); ks.fireAllRules(); - QueryResults res = ks.getQueryResults( "QueryTraitA" ); + QueryResults res = ks.getQueryResults("QueryTraitA"); - assertThat(res.size()).isEqualTo(1); + assertThat(res).hasSize(1); } @Test - public void testTypeRefractionOnQuery2( ) { + public void testTypeRefractionOnQuery2() { String source = "package t.x \n" + "import java.util.*; \n" + "import org.drools.base.factmodel.traits.Thing \n" + @@ -3093,43 +2887,43 @@ public void testTypeRefractionOnQuery2( ) { "rule Init when\n" + "then\n" + " Kore k = new Kore();\n" + - " don( k, C.class ); \n" + - " don( k, D.class ); \n" + - " don( k, E.class ); \n" + - " don( k, B.class ); \n" + - " don( k, A.class ); \n" + - " don( k, F.class ); \n" + - " don( k, G.class ); \n" + - " shed( k, B.class ); \n" + + " don(k, C.class); \n" + + " don(k, D.class); \n" + + " don(k, E.class); \n" + + " don(k, B.class); \n" + + " don(k, A.class); \n" + + " don(k, F.class); \n" + + " don(k, G.class); \n" + + " shed(k, B.class); \n" + "end\n" + "" + "rule RuleA\n" + "when \n" + - " $x : A( ) \n" + + " $x : A() \n" + "then \n" + "end\n" + " \n" + "query queryA1\n" + - " $x := A( ) \n" + + " $x := A() \n" + "end\n" + ""; - KieSession ks = getSessionFromString( source ); - TraitFactoryImpl.setMode(mode, ks.getKieBase() ); + KieSession ks = getSessionFromString(source); + TraitFactoryImpl.setMode(mode, ks.getKieBase()); - List list = new ArrayList(); - ks.setGlobal( "list", list ); + List list = new ArrayList<>(); + ks.setGlobal("list", list); ks.fireAllRules(); QueryResults res; - res = ks.getQueryResults( "queryA1" ); - assertThat(res.size()).isEqualTo(1); + res = ks.getQueryResults("queryA1"); + assertThat(res).hasSize(1); } @Test - public void testNodePartitioningByProxies( ) { + public void testNodePartitioningByProxies() { String source = "package t.x " + "import java.util.*; " + "import org.drools.base.factmodel.traits.Thing " + @@ -3154,50 +2948,50 @@ public void testNodePartitioningByProxies( ) { "then " + " Kore k = new Kore(); " + - " don( k, C.class ); " + - " don( k, D.class ); " + - " don( k, B.class ); " + - " don( k, A.class ); " + - " don( k, F.class ); " + - " don( k, E.class ); " + - " don( k, G.class ); " + + " don(k, C.class); " + + " don(k, D.class); " + + " don(k, B.class); " + + " don(k, A.class); " + + " don(k, F.class); " + + " don(k, E.class); " + + " don(k, G.class); " + "end "; - for ( char c = 'A'; c <= 'G'; c++ ) { + for (char c = 'A'; c <= 'G'; c++) { String C = "" + c; source += "rule Rule" + C + - " when " + C + "() then list.add( '"+ C + "' ); end "; + " when " + C + "() then list.add('"+ C + "'); end "; } source += "rule RuleAll " + "when " + " A() B() C() D() E() F() G() " + "then " + - " list.add( 'Z' ); " + + " list.add('Z'); " + "end " + ""; - KieSession ks = getSessionFromString( source ); - TraitFactoryImpl.setMode(mode, ks.getKieBase() ); + KieSession ks = getSessionFromString(source); + TraitFactoryImpl.setMode(mode, ks.getKieBase()); - List list = new ArrayList(); - ks.setGlobal( "list", list ); + List list = new ArrayList<>(); + ks.setGlobal("list", list); ks.fireAllRules(); - LOGGER.debug( list.toString() ); - assertThat(list).isEqualTo(Arrays.asList('A', 'B', 'C', 'D', 'E', 'F', 'G', 'Z')); + LOGGER.debug(list.toString()); + assertThat(list).containsExactly('A', 'B', 'C', 'D', 'E', 'F', 'G', 'Z'); - for ( Object o : ks.getObjects(object -> object instanceof TraitableBean) ) { - Set otns = checkOTNPartitioning( (TraitableBean) o, ks ); - assertThat(otns.size()).isEqualTo(7); + for (Object o : ks.getObjects(object -> object instanceof TraitableBean)) { + Set otns = checkOTNPartitioning((TraitableBean) o, ks); + assertThat(otns).hasSize(7); } } @Test - public void testNodePartitioningByProxiesAfterShed( ) { + public void testNodePartitioningByProxiesAfterShed() { String source = "package t.x " + "import java.util.*; " + "import org.drools.base.factmodel.traits.Thing \n" + @@ -3222,22 +3016,22 @@ public void testNodePartitioningByProxiesAfterShed( ) { "then \n" + " Kore k = new Kore(); \n" + - " don( k, C.class ); \n" + - " don( k, D.class ); \n" + - " don( k, B.class ); \n" + - " don( k, A.class ); \n" + - " don( k, F.class ); \n" + - " don( k, E.class ); \n" + - " don( k, G.class ); \n" + - " shed( k, B.class ); \n" + + " don(k, C.class); \n" + + " don(k, D.class); \n" + + " don(k, B.class); \n" + + " don(k, A.class); \n" + + " don(k, F.class); \n" + + " don(k, E.class); \n" + + " don(k, G.class); \n" + + " shed(k, B.class); \n" + "end \n"; - for ( char c = 'A'; c <= 'G'; c++ ) { + for (char c = 'A'; c <= 'G'; c++) { String C = "" + c; source += "rule Rule" + C + " when \n" + C + "() \nthen\n" + " System.out.println(\"Rule " + C + "\");\n" + - " list.add( '"+ C + "' ); \n" + + " list.add('"+ C + "'); \n" + "end \n"; } @@ -3245,32 +3039,32 @@ public void testNodePartitioningByProxiesAfterShed( ) { "when \n" + " A() D() G() \n" + "then \n" + - " list.add( 'Z' ); \n" + + " list.add('Z'); \n" + "end \n" + ""; System.out.println(source); - KieSession ks = getSessionFromString( source ); - TraitFactoryImpl.setMode(mode, ks.getKieBase() ); + KieSession ks = getSessionFromString(source); + TraitFactoryImpl.setMode(mode, ks.getKieBase()); - List list = new ArrayList(); - ks.setGlobal( "list", list ); + List list = new ArrayList<>(); + ks.setGlobal("list", list); ks.fireAllRules(); - LOGGER.debug( list.toString() ); - assertThat(list).isEqualTo(Arrays.asList('A', 'D', 'G', 'Z')); + LOGGER.debug(list.toString()); + assertThat(list).containsExactly('A', 'D', 'G', 'Z'); - for ( Object o : ks.getObjects(object -> object instanceof TraitableBean) ) { - Set otns = checkOTNPartitioning( (TraitableBean) o, ks ); - assertThat(otns.size()).isEqualTo(3); + for (Object o : ks.getObjects(object -> object instanceof TraitableBean)) { + Set otns = checkOTNPartitioning((TraitableBean) o, ks); + assertThat(otns).hasSize(3); } } @Test - public void testTypeRefractionOnQueryWithIsA( ) { + public void testTypeRefractionOnQueryWithIsA() { String source = "package t.x \n" + "import java.util.*; \n" + "import org.drools.base.factmodel.traits.Thing \n" + @@ -3293,42 +3087,42 @@ public void testTypeRefractionOnQueryWithIsA( ) { "rule Init when\n" + "then\n" + " Kore k = new Kore();\n" + - " don( k, C.class ); \n" + - " don( k, D.class ); \n" + - " don( k, E.class ); \n" + - " don( k, B.class ); \n" + - " don( k, A.class ); \n" + - " don( k, F.class ); \n" + - " shed( k, B.class ); \n" + + " don(k, C.class); \n" + + " don(k, D.class); \n" + + " don(k, E.class); \n" + + " don(k, B.class); \n" + + " don(k, A.class); \n" + + " don(k, F.class); \n" + + " shed(k, B.class); \n" + "end\n" + "" + " \n" + "query queryA\n" + - " $x := Kore( this isA A ) \n" + + " $x := Kore(this isA A) \n" + "end\n" + ""; - KieSession ks = getSessionFromString( source ); - TraitFactoryImpl.setMode(mode, ks.getKieBase() ); + KieSession ks = getSessionFromString(source); + TraitFactoryImpl.setMode(mode, ks.getKieBase()); - List list = new ArrayList(); - ks.setGlobal( "list", list ); + List list = new ArrayList<>(); + ks.setGlobal("list", list); ks.fireAllRules(); - QueryResults res = ks.getQueryResults( "queryA" ); + QueryResults res = ks.getQueryResults("queryA"); Iterator iter = res.iterator(); - Object a = iter.next().get( "$x" ); - assertThat(iter.hasNext()).isFalse(); + Object a = iter.next().get("$x"); + assertThat(iter).isExhausted(); - assertThat(res.size()).isEqualTo(1); + assertThat(res).hasSize(1); } @Test - public void testCoreUpdate4( ) { + public void testCoreUpdate4() { String source = "package t.x \n" + "import java.util.*; \n" + "import org.drools.base.factmodel.traits.Thing \n" + @@ -3350,8 +3144,8 @@ public void testCoreUpdate4( ) { "rule Init \n" + "when\n" + "then\n" + - " Kore k = new Kore( 44 );\n" + - " insert( k ); \n" + + " Kore k = new Kore(44);\n" + + " insert(k); \n" + "end\n" + "" + "" + @@ -3360,27 +3154,27 @@ public void testCoreUpdate4( ) { "when\n" + " $x : Kore() \n" + "then \n" + - " don( $x, A.class ); \n" + + " don($x, A.class); \n" + "end\n" + "rule React \n" + "salience 1" + "when\n" + - " $x : Kore( this isA A.class ) \n" + + " $x : Kore(this isA A.class) \n" + "then \n" + - " list.add( $x ); \n" + + " list.add($x); \n" + "end\n" + ""; - KieSession ks = getSessionFromString( source ); - TraitFactoryImpl.setMode(mode, ks.getKieBase() ); + KieSession ks = getSessionFromString(source); + TraitFactoryImpl.setMode(mode, ks.getKieBase()); - List list = new ArrayList(); - ks.setGlobal( "list", list ); + List list = new ArrayList<>(); + ks.setGlobal("list", list); ks.fireAllRules(); - for ( Object o : ks.getObjects() ) { - LOGGER.debug( o.toString() ); + for (Object o : ks.getObjects()) { + LOGGER.debug(o.toString()); } - assertThat(list.size()).isEqualTo(1); + assertThat(list).hasSize(1); } @@ -3403,118 +3197,118 @@ public void traitLogicalSupportAnddelete() { " name : String\n" + "end\n" + "\n" + - "rule Init when then insert( new Person( \"john\" ) ); end \n" + + "rule Init when then insert(new Person(\"john\")); end \n" + "" + "rule \"Don Logical\"\n" + "when\n" + - " $s : String( this == \"trigger1\" )\n" + + " $s : String(this == \"trigger1\")\n" + " $p : Person() \n" + "then\n" + - " don( $p, Student.class, true );\n" + + " don($p, Student.class, true);\n" + "end\n" + "" + "rule \"Don Logical2\"\n" + "when\n" + - " $s : String( this == \"trigger2\" )\n" + + " $s : String(this == \"trigger2\")\n" + " $p : Person() \n" + "then\n" + - " don( $p, Student.class, true );\n" + + " don($p, Student.class, true);\n" + "end\n" + "" + "rule \"Undon \"\n" + "when\n" + - " $s : String( this == \"trigger3\" )\n" + + " $s : String(this == \"trigger3\")\n" + " $p : Person() \n" + "then\n" + - " shed( $p, org.drools.base.factmodel.traits.Thing.class ); " + - " delete( $s ); \n" + + " shed($p, org.drools.base.factmodel.traits.Thing.class); " + + " delete($s); \n" + "end\n" + " " + "rule \"Don Logical3\"\n" + "when\n" + - " $s : String( this == \"trigger4\" )\n" + + " $s : String(this == \"trigger4\")\n" + " $p : Person() \n" + "then\n" + - " don( $p, Student.class, true );" + + " don($p, Student.class, true);" + "end\n" + " " + "rule \"Undon 2\"\n" + "when\n" + - " $s : String( this == \"trigger5\" )\n" + + " $s : String(this == \"trigger5\")\n" + " $p : Person() \n" + "then\n" + - " delete( $s ); \n" + - " delete( $p ); \n" + + " delete($s); \n" + + " delete($p); \n" + "end\n" + ""; KieSession ksession = getSessionFromString(drl); - TraitFactoryImpl.setMode(mode, ksession.getKieBase() ); + TraitFactoryImpl.setMode(mode, ksession.getKieBase()); List list = new ArrayList(); - ksession.setGlobal( "list", list ); + ksession.setGlobal("list", list); - FactHandle h1 = ksession.insert( "trigger1" ); - FactHandle h2 = ksession.insert( "trigger2" ); + FactHandle h1 = ksession.insert("trigger1"); + FactHandle h2 = ksession.insert("trigger2"); ksession.fireAllRules(); - for ( Object o : ksession.getObjects() ) { - LOGGER.debug( o.toString() ); + for (Object o : ksession.getObjects()) { + LOGGER.debug(o.toString()); } - LOGGER.debug( "---------------------------------" ); + LOGGER.debug("---------------------------------"); - assertThat(ksession.getObjects().size()).isEqualTo(4); + assertThat(ksession.getObjects()).hasSize(4); - ksession.delete( h1 ); + ksession.delete(h1); ksession.fireAllRules(); - for ( Object o : ksession.getObjects() ) { - LOGGER.debug( o.toString() ); + for (Object o : ksession.getObjects()) { + LOGGER.debug(o.toString()); } - LOGGER.debug( "---------------------------------" ); + LOGGER.debug("---------------------------------"); - assertThat(ksession.getObjects().size()).isEqualTo(3); + assertThat(ksession.getObjects()).hasSize(3); - ksession.delete( h2 ); + ksession.delete(h2); ksession.fireAllRules(); - for ( Object o : ksession.getObjects() ) { - LOGGER.debug( o.toString() ); + for (Object o : ksession.getObjects()) { + LOGGER.debug(o.toString()); } - LOGGER.debug( "---------------------------------" ); + LOGGER.debug("---------------------------------"); - assertThat(ksession.getObjects().size()).isEqualTo(1); + assertThat(ksession.getObjects()).hasSize(1); - ksession.insert( "trigger3" ); + ksession.insert("trigger3"); ksession.fireAllRules(); - for ( Object o : ksession.getObjects() ) { - LOGGER.debug( o.toString()); + for (Object o : ksession.getObjects()) { + LOGGER.debug(o.toString()); } - LOGGER.debug( "---------------------------------" ); + LOGGER.debug("---------------------------------"); - assertThat(ksession.getObjects().size()).isEqualTo(1); + assertThat(ksession.getObjects()).hasSize(1); - ksession.insert( "trigger4" ); + ksession.insert("trigger4"); ksession.fireAllRules(); - for ( Object o : ksession.getObjects() ) { - LOGGER.debug( o.toString() ); + for (Object o : ksession.getObjects()) { + LOGGER.debug(o.toString()); } - LOGGER.debug( "---------------------------------" ); + LOGGER.debug("---------------------------------"); - assertThat(ksession.getObjects().size()).isEqualTo(3); + assertThat(ksession.getObjects()).hasSize(3); - ksession.insert( "trigger5" ); + ksession.insert("trigger5"); ksession.fireAllRules(); - for ( Object o : ksession.getObjects() ) { - LOGGER.debug( o.toString() ); + for (Object o : ksession.getObjects()) { + LOGGER.debug(o.toString()); } - LOGGER.debug( "---------------------------------" ); + LOGGER.debug("---------------------------------"); - assertThat(ksession.getObjects().size()).isEqualTo(1); + assertThat(ksession.getObjects()).hasSize(1); } @Test @@ -3534,18 +3328,18 @@ public void testShedThing() { "" + "rule \"Init\" when \n" + "then \n" + - " insert( new Core() );" + + " insert(new Core());" + "end \n" + "" + "rule \"donManyThing\"\n" + "when\n" + - " $x : Core( id == 0 )\n" + + " $x : Core(id == 0)\n" + "then\n" + - " don( $x, A.class );\n" + - " don( $x, B.class );\n" + - " don( $x, C.class );\n" + - " don( $x, D.class );\n" + - " don( $x, E.class );\n" + + " don($x, A.class);\n" + + " don($x, B.class);\n" + + " don($x, C.class);\n" + + " don($x, D.class);\n" + + " don($x, E.class);\n" + "end\n" + "\n" + "\n" + @@ -3553,38 +3347,38 @@ public void testShedThing() { "rule \"Mod\" \n" + "salience -10 \n" + "when \n" + - " $g : String( this == \"go\" ) \n" + - " $x : Core( id == 0 ) \n" + + " $g : String(this == \"go\") \n" + + " $x : Core(id == 0) \n" + "then \n" + - " shed( $x, Thing.class ); " + - " delete( $g ); \n\n" + + " shed($x, Thing.class); " + + " delete($g); \n\n" + "end \n" + ""; KnowledgeBuilder kbuilder = KnowledgeBuilderFactory.newKnowledgeBuilder(); - kbuilder.add( new ByteArrayResource( s1.getBytes() ), ResourceType.DRL ); - if ( kbuilder.hasErrors() ) { - fail( kbuilder.getErrors().toString() ); + kbuilder.add(new ByteArrayResource(s1.getBytes()), ResourceType.DRL); + if (kbuilder.hasErrors()) { + fail(kbuilder.getErrors().toString()); } InternalKnowledgeBase kbase = KnowledgeBaseFactory.newKnowledgeBase(); TraitFactoryImpl.setMode(mode, (KieBase) kbase); // not relevant - kbase.addPackages( kbuilder.getKnowledgePackages() ); + kbase.addPackages(kbuilder.getKnowledgePackages()); List list = new ArrayList(); KieSession ksession = kbase.newKieSession(); - ksession.setGlobal( "list", list ); + ksession.setGlobal("list", list); ksession.fireAllRules(); - ksession.insert( "go" ); + ksession.insert("go"); ksession.fireAllRules(); - for ( Object o : ksession.getObjects() ) { - LOGGER.debug( o.toString() ); + for (Object o : ksession.getObjects()) { + LOGGER.debug(o.toString()); } - assertThat(ksession.getObjects().size()).isEqualTo(1); + assertThat(ksession.getObjects()).hasSize(1); } @@ -3605,18 +3399,18 @@ public void testdeleteThings() { "" + "rule \"Init\" when \n" + "then \n" + - " insert( new Core() );" + + " insert(new Core());" + "end \n" + "" + "rule \"donManyThing\"\n" + "when\n" + - " $x : Core( id == 0 )\n" + + " $x : Core(id == 0)\n" + "then\n" + - " don( $x, A.class );\n" + - " don( $x, B.class );\n" + - " don( $x, C.class );\n" + - " don( $x, D.class );\n" + - " don( $x, E.class );\n" + + " don($x, A.class);\n" + + " don($x, B.class);\n" + + " don($x, C.class);\n" + + " don($x, D.class);\n" + + " don($x, E.class);\n" + "end\n" + "\n" + "\n" + @@ -3624,42 +3418,42 @@ public void testdeleteThings() { "rule \"Mod\" \n" + "salience -10 \n" + "when \n" + - " $g : String( this == \"go\" ) \n" + - " $x : Core( id == 0 ) \n" + + " $g : String(this == \"go\") \n" + + " $x : Core(id == 0) \n" + "then \n" + - " delete( $x ); \n\n" + - " delete( $g ); \n\n" + + " delete($x); \n\n" + + " delete($g); \n\n" + "end \n" + ""; KnowledgeBuilder kbuilder = KnowledgeBuilderFactory.newKnowledgeBuilder(); - kbuilder.add( new ByteArrayResource( s1.getBytes() ), ResourceType.DRL ); - if ( kbuilder.hasErrors() ) { - fail( kbuilder.getErrors().toString() ); + kbuilder.add(new ByteArrayResource(s1.getBytes()), ResourceType.DRL); + if (kbuilder.hasErrors()) { + fail(kbuilder.getErrors().toString()); } InternalKnowledgeBase kbase = KnowledgeBaseFactory.newKnowledgeBase(); TraitFactoryImpl.setMode(mode, (KieBase) kbase); // not relevant - kbase.addPackages( kbuilder.getKnowledgePackages() ); + kbase.addPackages(kbuilder.getKnowledgePackages()); List list = new ArrayList(); KieSession ksession = kbase.newKieSession(); - ksession.setGlobal( "list", list ); + ksession.setGlobal("list", list); ksession.fireAllRules(); - ksession.insert( "go" ); + ksession.insert("go"); ksession.fireAllRules(); - for ( Object o : ksession.getObjects() ) { - LOGGER.debug( o.toString() ); + for (Object o : ksession.getObjects()) { + LOGGER.debug(o.toString()); } - assertThat(ksession.getObjects().size()).isEqualTo(0); + assertThat(ksession.getObjects()).isEmpty(); } @Test - public void traitLogicalRemovalSimple( ) { + public void traitLogicalRemovalSimple() { String drl = "package org.drools.compiler.trait.test;\n" + "\n" + "import org.drools.base.factmodel.traits.Traitable;\n" + @@ -3685,34 +3479,34 @@ public void traitLogicalRemovalSimple( ) { "\n" + "rule \"Don Logical\"\n" + "when\n" + - " $s : String( this == \"trigger\" )\n" + + " $s : String(this == \"trigger\")\n" + "then\n" + - " Person p = new Person( \"john\" );\n" + - " insert( p ); \n" + - " don( p, Student.class, true );\n" + - " don( p, Worker.class );\n" + - " don( p, Scholar.class );\n" + + " Person p = new Person(\"john\");\n" + + " insert(p); \n" + + " don(p, Student.class, true);\n" + + " don(p, Worker.class);\n" + + " don(p, Scholar.class);\n" + "end"; KieSession ksession = getSessionFromString(drl); - TraitFactoryImpl.setMode(mode, ksession.getKieBase() ); + TraitFactoryImpl.setMode(mode, ksession.getKieBase()); - List list = new ArrayList(); - ksession.setGlobal( "list", list ); + List list = new ArrayList<>(); + ksession.setGlobal("list", list); - FactHandle h = ksession.insert( "trigger" ); + FactHandle h = ksession.insert("trigger"); ksession.fireAllRules(); - assertThat(ksession.getObjects().size()).isEqualTo(5); + assertThat(ksession.getObjects()).hasSize(5); - ksession.delete( h ); + ksession.delete(h); ksession.fireAllRules(); - for ( Object o : ksession.getObjects() ) { + for (Object o : ksession.getObjects()) { // lose the string and the Student proxy - LOGGER.debug( o.toString() ); + LOGGER.debug(o.toString()); } - assertThat(ksession.getObjects().size()).isEqualTo(3); + assertThat(ksession.getObjects()).hasSize(3); } @@ -3723,15 +3517,15 @@ public static class TraitableFoo { private String id; - public TraitableFoo( String id, int x, Object k ) { - setId( id ); + public TraitableFoo(String id, int x, Object k) { + setId(id); } public String getId() { return id; } - public void setId( String id ) { + public void setId(String id) { this.id = id; } } @@ -3740,14 +3534,14 @@ public void setId( String id ) { public static class XYZ extends TraitableFoo { public XYZ() { - super( null, 0, null ); + super(null, 0, null); } } @Test - public void testTraitDonLegacyClassWithoutEmptyConstructor( ) { + public void testTraitDonLegacyClassWithoutEmptyConstructor() { String drl = "package org.drools.compiler.trait.test;\n" + "\n" + "import " + TraitableFoo.class.getCanonicalName() + ";" + @@ -3760,30 +3554,30 @@ public void testTraitDonLegacyClassWithoutEmptyConstructor( ) { "rule \"Don\"\n" + "no-loop \n" + "when\n" + - " $f : TraitableFoo( )\n" + + " $f : TraitableFoo()\n" + "then\n" + - " Bar b = don( $f, Bar.class );\n" + + " Bar b = don($f, Bar.class);\n" + "end"; KieSession ksession = getSessionFromString(drl); - TraitFactoryImpl.setMode(mode, ksession.getKieBase() ); - ksession.addEventListener( new DebugAgendaEventListener( ) ); + TraitFactoryImpl.setMode(mode, ksession.getKieBase()); + ksession.addEventListener(new DebugAgendaEventListener()); - ksession.insert( new TraitableFoo( "xx", 0, null ) ); + ksession.insert(new TraitableFoo("xx", 0, null)); ksession.fireAllRules(); - for ( Object o : ksession.getObjects() ) { - LOGGER.debug( o.toString() ); + for (Object o : ksession.getObjects()) { + LOGGER.debug(o.toString()); } - assertThat(ksession.getObjects().size()).isEqualTo(2); + assertThat(ksession.getObjects()).hasSize(2); } @Test - public void testdeleteCoreObjectChained( ) { + public void testdeleteCoreObjectChained() { String source = "package org.drools.test;\n" + "import java.util.List; \n" + "import org.drools.base.factmodel.traits.Thing \n" + @@ -3805,8 +3599,8 @@ public void testdeleteCoreObjectChained( ) { "when\n" + " $s : String() \n" + "then\n" + - " Kore k = new Kore( 44 );\n" + - " insertLogical( k ); \n" + + " Kore k = new Kore(44);\n" + + " insertLogical(k); \n" + "end\n" + "" + "" + @@ -3815,7 +3609,7 @@ public void testdeleteCoreObjectChained( ) { "when\n" + " $x : Kore() \n" + "then \n" + - " don( $x, A.class ); \n" + + " don($x, A.class); \n" + "end\n" + "" + "" + @@ -3824,32 +3618,32 @@ public void testdeleteCoreObjectChained( ) { "when \n" + " $x : String() \n" + "then \n" + - " delete( $x ); \n" + + " delete($x); \n" + "end \n" + "\n"; - KieSession ks = getSessionFromString( source ); - TraitFactoryImpl.setMode(mode, ks.getKieBase() ); + KieSession ks = getSessionFromString(source); + TraitFactoryImpl.setMode(mode, ks.getKieBase()); List list = new ArrayList(); - ks.setGlobal( "list", list ); + ks.setGlobal("list", list); - ks.insert( "go" ); + ks.insert("go"); ks.fireAllRules(); - for ( Object o : ks.getObjects() ) { - LOGGER.debug( o.toString() ); + for (Object o : ks.getObjects()) { + LOGGER.debug(o.toString()); } - assertThat(ks.getObjects().size()).isEqualTo(0); + assertThat(ks.getObjects()).isEmpty(); ks.dispose(); } @Test - public void testUpdateLegacyClass( ) { + public void testUpdateLegacyClass() { String source = "package org.drools.text;\n" + "\n" + "global java.util.List list;\n" + @@ -3866,40 +3660,40 @@ public void testUpdateLegacyClass( ) { "rule \"Init\"\n" + "salience 10 \n" + "when\n" + - " $p : Person( this not isA Student )\n" + + " $p : Person(this not isA Student)\n" + "then\n" + - " don( $p, Student.class );\n" + + " don($p, Student.class);\n" + "end\n" + "\n" + "rule \"Go\"\n" + "when\n" + - " $s : String( this == \"X\" )\n" + + " $s : String(this == \"X\")\n" + " $p : Person()\n" + "then\n" + - " delete( $s ); \n" + - " modify( $p ) { setName( $s ); }\n" + + " delete($s); \n" + + " modify($p) { setName($s); }\n" + "end\n" + "\n" + "rule \"Mod\"\n" + "when\n" + - " Student( name == \"X\" )\n" + + " Student(name == \"X\")\n" + "then\n" + - " list.add( 0 );\n" + + " list.add(0);\n" + "end"; - KieSession ks = getSessionFromString( source ); - TraitFactoryImpl.setMode(mode, ks.getKieBase() ); + KieSession ks = getSessionFromString(source); + TraitFactoryImpl.setMode(mode, ks.getKieBase()); - List list = new ArrayList(); - ks.setGlobal( "list", list ); + List list = new ArrayList<>(); + ks.setGlobal("list", list); - ks.insert( new Person( "john", 32 ) ); - ks.insert( "X" ); + ks.insert(new Person("john", 32)); + ks.insert("X"); ks.fireAllRules(); - assertThat(list.contains(0)).isTrue(); - assertThat(list.size()).isEqualTo(1); + assertThat(list).hasSize(1); + assertThat(list).contains(0); ks.dispose(); } @@ -3924,7 +3718,7 @@ public void testSoftPropertyClash() { " fld2 : int = 4 \n" + " fld3 : double = 4.0 \n" + " fld4 : String = \"hello\" \n" + - " fldZ : String = \"hello\" @Alias( \"fld5\" )\n" + + " fldZ : String = \"hello\" @Alias(\"fld5\")\n" + "end\n" + "declare trait Worker\n" + " @propertyReactive \n" + @@ -3932,11 +3726,11 @@ public void testSoftPropertyClash() { " fld2 : String = \"b\" \n " + " fld3 : int = 11 \n " + " fld4 : Class = Object.class \n " + - " fldY : int = 42 @Alias( \"fld5\" )\n" + + " fldY : int = 42 @Alias(\"fld5\")\n" + "end\n" + "" + "rule \"Init\" when then \n" + - " insert( new Person() ); \n" + + " insert(new Person()); \n" + "end \n" + "" + "\n" + @@ -3944,45 +3738,45 @@ public void testSoftPropertyClash() { "when\n" + " $p : Person() \n" + "then\n" + - " Student $s = (Student) don( $p, Student.class );\n" + - " modify ( $s ) { setId( \"xyz\" ); } " + + " Student $s = (Student) don($p, Student.class);\n" + + " modify ($s) { setId(\"xyz\"); } " + " " + - " Worker $w = don( $p, Worker.class );\n" + - " modify ( $w ) { setId( 99 ); } " + + " Worker $w = don($p, Worker.class);\n" + + " modify ($w) { setId(99); } " + "end\n" + "\n" + "rule \"Stud\"\n" + "when\n" + - " $s : Student( $sid : id == \"xyz\", $f2 : fld2, $f3 : fld3, $f4 : fld4, $f5 : fldZ )\n" + + " $s : Student($sid : id == \"xyz\", $f2 : fld2, $f3 : fld3, $f4 : fld4, $f5 : fldZ)\n" + "then\n" + - " list.add( $sid ); \n" + - " list.add( $f2 ); \n" + - " list.add( $f3 ); \n" + - " list.add( $f4 ); \n" + - " list.add( $f5 ); \n" + + " list.add($sid); \n" + + " list.add($f2); \n" + + " list.add($f3); \n" + + " list.add($f4); \n" + + " list.add($f5); \n" + "end\n" + "\n" + "rule \"Mod\"\n" + "when\n" + - " $w : Worker( $wid : id == 99, $f2 : fld2, $f3 : fld3, $f4 : fld4, $f5 : fldY )\n" + + " $w : Worker($wid : id == 99, $f2 : fld2, $f3 : fld3, $f4 : fld4, $f5 : fldY)\n" + "then\n" + - " list.add( $wid ); \n" + - " list.add( $f2 ); \n" + - " list.add( $f3 ); \n" + - " list.add( $f4 ); \n" + - " list.add( $f5 ); \n" + + " list.add($wid); \n" + + " list.add($f2); \n" + + " list.add($f3); \n" + + " list.add($f4); \n" + + " list.add($f5); \n" + "end"; - KieSession ks = getSessionFromString( source ); - TraitFactoryImpl.setMode(mode, ks.getKieBase() ); + KieSession ks = getSessionFromString(source); + TraitFactoryImpl.setMode(mode, ks.getKieBase()); - List list = new ArrayList(); - ks.setGlobal( "list", list ); + List list = new ArrayList<>(); + ks.setGlobal("list", list); ks.fireAllRules(); - assertThat(list.size()).isEqualTo(5); - assertThat(list).isEqualTo(Arrays.asList(99, "b", 11, Object.class, 42)); + assertThat(list).hasSize(5); + assertThat(list).containsExactly(99, "b", 11, Object.class, 42); ks.dispose(); } @@ -4035,40 +3829,40 @@ public void testMultipleModifications() { "rule \"init\"\n" + "when\n" + "then\n" + - " insert( new Person(\"1234\",\"IR\",true,true) );\n" + + " insert(new Person(\"1234\",\"IR\",true,true));\n" + "end\n" + "\n" + "rule \"check for being student\"\n" + "when\n" + - " $p : Person( $ssn : ssn, $pob : pob, isStudent == true )\n" + + " $p : Person($ssn : ssn, $pob : pob, isStudent == true)\n" + "then\n" + - " Student st = (Student) don( $p , Student.class );\n" + - " modify( st ){\n" + - " setStudyingCountry( \"US\" );\n" + + " Student st = (Student) don($p , Student.class);\n" + + " modify(st){\n" + + " setStudyingCountry(\"US\");\n" + " }\n" + "end\n" + "\n" + "rule \"check for IR\"\n" + "when\n" + - " $p : Person( pob == \"IR\" )\n" + + " $p : Person(pob == \"IR\")\n" + "then\n" + - " don( $p , IRCitizen.class );\n" + + " don($p , IRCitizen.class);\n" + "end\n" + "\n" + "rule \"check for being US citizen\"\n" + "when\n" + - " $s : Student( studyingCountry == \"US\" )\n" + + " $s : Student(studyingCountry == \"US\")\n" + "then\n" + - " don( $s , USCitizen.class );\n" + + " don($s , USCitizen.class);\n" + "end\n" + "\n" + "rule \"check for being worker\"\n" + "when\n" + - " $p : Student( hasAssistantship == true, $sc : studyingCountry )\n" + + " $p : Student(hasAssistantship == true, $sc : studyingCountry)\n" + "then\n" + - " Worker wr = (Worker) don( $p , Worker.class );\n" + - " modify( wr ){\n" + - " setWorkingCountry( $sc );\n" + + " Worker wr = (Worker) don($p , Worker.class);\n" + + " modify(wr){\n" + + " setWorkingCountry($sc);\n" + " }\n" + "\n" + "end\n" + @@ -4076,27 +3870,26 @@ public void testMultipleModifications() { "rule \"Join Full\"\n" + "salience -1\n" + "when\n" + - " Student( ) // $sc := studyingCountry )\n" + - " USCitizen( )\n" + - " IRCitizen( ) // $pob := pob )\n" + - " Worker( ) // pob == $pob , workingCountry == $sc )\n" + + " Student() // $sc := studyingCountry)\n" + + " USCitizen()\n" + + " IRCitizen() // $pob := pob)\n" + + " Worker() // pob == $pob , workingCountry == $sc)\n" + "then\n" + - " list.add( 1 ); " + + " list.add(1); " + "end\n" + "\n" + "\n"; - KieSession ks = getSessionFromString( drl ); - TraitFactoryImpl.setMode(mode, ks.getKieBase() ); + KieSession ks = getSessionFromString(drl); + TraitFactoryImpl.setMode(mode, ks.getKieBase()); - List list = new ArrayList(); - ks.setGlobal( "list", list ); + List list = new ArrayList<>(); + ks.setGlobal("list", list); - HashMap map; ks.fireAllRules(); - assertThat(list.contains(1)).isTrue(); - assertThat(list.size()).isEqualTo(1); + assertThat(list).contains(1); + assertThat(list).hasSize(1); ks.dispose(); @@ -4122,71 +3915,51 @@ public void testPropagation() { "declare trait I extends E,H @propertyReactive end\n" + "declare trait J extends I @propertyReactive end\n" + "" + - "rule Init when then X x = new X(); insert( x ); don( x, F.class); end \n"+ - "rule Go when String( this == \"go\" ) $x : X() then don( $x, H.class); end \n" + - "rule Go2 when String( this == \"go2\" ) $x : X() then don( $x, D.class); end \n" + + "rule Init when then X x = new X(); insert(x); don(x, F.class); end \n"+ + "rule Go when String(this == \"go\") $x : X() then don($x, H.class); end \n" + + "rule Go2 when String(this == \"go2\") $x : X() then don($x, D.class); end \n" + ""; - for ( int j = 'A'; j <= 'J'; j ++ ) { + for (int j = 'A'; j <= 'J'; j ++) { String x = "" + (char) j; - drl += "rule \"Log " + x + "\" when " + x + "() then list.add( \"" + x + "\" ); end \n"; + drl += "rule \"Log " + x + "\" when " + x + "() then list.add(\"" + x + "\"); end \n"; - drl += "rule \"Log II" + x + "\" salience -1 when " + x + "( "; + drl += "rule \"Log II" + x + "\" salience -1 when " + x + "("; drl += "this isA H"; - drl += " ) then list.add( \"H" + x + "\" ); end \n"; + drl += ") then list.add(\"H" + x + "\"); end \n"; } - KieSession ks = new KieHelper().addContent( drl, ResourceType.DRL ).build().newKieSession(); - TraitFactoryImpl.setMode(mode, ks.getKieBase() ); + KieSession ks = new KieHelper().addContent(drl, ResourceType.DRL).build().newKieSession(); + TraitFactoryImpl.setMode(mode, ks.getKieBase()); - List list = new ArrayList(); - ks.setGlobal( "list", list ); + List list = new ArrayList<>(); + ks.setGlobal("list", list); ks.fireAllRules(); - assertThat(list.contains("A")).isTrue(); - assertThat(list.contains("B")).isTrue(); - assertThat(list.contains("C")).isTrue(); - assertThat(list.contains("E")).isTrue(); - assertThat(list.contains("F")).isTrue(); - assertThat(list.size()).isEqualTo(5); + assertThat(list).hasSize(5); + assertThat(list).contains("A", "B", "C", "E", "F"); list.clear(); - LOGGER.debug( "---------------------------------------" ); + LOGGER.debug("---------------------------------------"); - ks.insert( "go" ); + ks.insert("go"); ks.fireAllRules(); - assertThat(list.contains("H")).isTrue(); - assertThat(list.contains("G")).isTrue(); - assertThat(list.contains("HA")).isTrue(); - assertThat(list.contains("HB")).isTrue(); - assertThat(list.contains("HC")).isTrue(); - assertThat(list.contains("HE")).isTrue(); - assertThat(list.contains("HF")).isTrue(); - assertThat(list.contains("HG")).isTrue(); - assertThat(list.contains("HH")).isTrue(); - LOGGER.debug( list.toString() ); - assertThat(list.size()).isEqualTo(9); + assertThat(list).hasSize(9); + assertThat(list).contains("H", "G", "HA", "HB", "HC", "HE", "HF", "HG", "HH"); + LOGGER.debug(list.toString()); + list.clear(); - LOGGER.debug( "---------------------------------------" ); + LOGGER.debug("---------------------------------------"); - ks.insert( "go2" ); + ks.insert("go2"); ks.fireAllRules(); - assertThat(list.contains("D")).isTrue(); - assertThat(list.contains("HA")).isTrue(); - assertThat(list.contains("HB")).isTrue(); - assertThat(list.contains("HC")).isTrue(); - assertThat(list.contains("HE")).isTrue(); - assertThat(list.contains("HF")).isTrue(); - assertThat(list.contains("HG")).isTrue(); - assertThat(list.contains("HH")).isTrue(); - assertThat(list.contains("HH")).isTrue(); - assertThat(list.contains("HD")).isTrue(); - assertThat(list.size()).isEqualTo(9); + assertThat(list).hasSize(9); + assertThat(list).contains("D", "HA", "HB", "HC", "HE", "HF", "HG", "HH", "HH", "HD"); ks.dispose(); @@ -4205,25 +3978,25 @@ public void testParentBlockers() { "declare trait B @propertyReactive end\n" + "declare trait C extends A, B @propertyReactive end \n" + "" + - "rule Init when then X x = new X(); insert( x ); don( x, A.class); don( x, B.class); end \n"+ - "rule Go when String( this == \"go\" ) $x : X() then don( $x, C.class); end \n" + - "rule Go2 when String( this == \"go2\" ) $x : C() then end \n"; + "rule Init when then X x = new X(); insert(x); don(x, A.class); don(x, B.class); end \n"+ + "rule Go when String(this == \"go\") $x : X() then don($x, C.class); end \n" + + "rule Go2 when String(this == \"go2\") $x : C() then end \n"; - KieSession ks = getSessionFromString( drl ); - TraitFactoryImpl.setMode(mode, ks.getKieBase() ); + KieSession ks = getSessionFromString(drl); + TraitFactoryImpl.setMode(mode, ks.getKieBase()); - List list = new ArrayList(); - ks.setGlobal( "list", list ); + List list = new ArrayList<>(); + ks.setGlobal("list", list); ks.fireAllRules(); - ks.insert( "go" ); + ks.insert("go"); ks.fireAllRules(); - ks.insert( "go2" ); + ks.insert("go2"); ks.fireAllRules(); - LOGGER.debug( "---------------------------------------" ); + LOGGER.debug("---------------------------------------"); ks.dispose(); @@ -4241,39 +4014,39 @@ public void testTraitLogicalTMS() { "declare trait A @propertyReactive end\n" + "declare trait B @propertyReactive end\n" + "" + - "rule Init when then X x = new X(); insert( x ); end \n"+ - "rule Go when String( this == \"go\" ) $x : X() then don( $x, A.class, true ); don( $x, B.class, true ); end \n" + - "rule Go2 when String( this == \"go2\" ) $x : X() then don( $x, A.class ); end \n" + - "rule Go3 when String( this == \"go3\" ) $x : A() not B() then list.add( 100 ); end \n" + + "rule Init when then X x = new X(); insert(x); end \n"+ + "rule Go when String(this == \"go\") $x : X() then don($x, A.class, true); don($x, B.class, true); end \n" + + "rule Go2 when String(this == \"go2\") $x : X() then don($x, A.class); end \n" + + "rule Go3 when String(this == \"go3\") $x : A() not B() then list.add(100); end \n" + ""; - KieSession ks = getSessionFromString( drl ); - TraitFactoryImpl.setMode(mode, ks.getKieBase() ); + KieSession ks = getSessionFromString(drl); + TraitFactoryImpl.setMode(mode, ks.getKieBase()); - List list = new ArrayList(); - ks.setGlobal( "list", list ); + List list = new ArrayList<>(); + ks.setGlobal("list", list); ks.fireAllRules(); - FactHandle handle = ks.insert( "go" ); + FactHandle handle = ks.insert("go"); ks.fireAllRules(); - ks.insert( "go2" ); + ks.insert("go2"); ks.fireAllRules(); - ks.delete( handle ); + ks.delete(handle); ks.fireAllRules(); - LOGGER.debug( "---------------------------------------" ); + LOGGER.debug("---------------------------------------"); - for ( Object o : ks.getObjects() ) { - LOGGER.debug( o.toString() ); + for (Object o : ks.getObjects()) { + LOGGER.debug(o.toString()); } - ks.insert( "go3" ); + ks.insert("go3"); ks.fireAllRules(); - assertThat(list).isEqualTo(List.of(100)); + assertThat(list).containsExactly(100); ks.dispose(); } @@ -4294,7 +4067,7 @@ public void testTraitNoType() { "\n" + "\n" + "declare Parent\n" + - "@Traitable( logical = true )" + + "@Traitable(logical = true)" + "@propertyReactive\n" + "end\n" + "\n" + @@ -4310,15 +4083,15 @@ public void testTraitNoType() { "then\n" + " Parent p = new Parent();" + " insert(p);\n" + - " ChildTrait ct = don( p , ChildTrait.class );\n" + + " ChildTrait ct = don(p , ChildTrait.class);\n" + " list.add(\"correct1\");\n" + "end\n" + "\n" + "rule \"check\"\n" + "no-loop\n" + "when\n" + - " $c : ChildTrait($n : naam == \"kudak\", id == 1020 )\n" + - " $p : Thing( core == $c.core, fields[\"naam\"] == $n )\n" + + " $c : ChildTrait($n : naam == \"kudak\", id == 1020)\n" + + " $p : Thing(core == $c.core, fields[\"naam\"] == $n)\n" + "then\n" + " list.add(\"correct2\");\n" + "end"; @@ -4326,12 +4099,11 @@ public void testTraitNoType() { KieSession ksession = loadKnowledgeBaseFromString(drl).newKieSession(); TraitFactoryImpl.setMode(mode, ksession.getKieBase()); - List list = new ArrayList(); + List list = new ArrayList<>(); ksession.setGlobal("list",list); ksession.fireAllRules(); - assertThat(list.contains("correct1")).isTrue(); - assertThat(list.contains("correct2")).isTrue(); + assertThat(list).contains("correct1", "correct2"); } @@ -4354,37 +4126,37 @@ public void testTraitdeleteOrder() { "when \n" + " $e : Entity() \n" + "then\n" + - " don( $e, A.class ); \n" + - " don( $e, C.class ); \n" + - " don( $e, B.class ); \n" + + " don($e, A.class); \n" + + " don($e, C.class); \n" + + " don($e, B.class); \n" + "end\n" + ""; KieSession ksession = loadKnowledgeBaseFromString(drl).newKieSession(); - TraitFactoryImpl.setMode(mode, ksession.getKieBase() ); + TraitFactoryImpl.setMode(mode, ksession.getKieBase()); - FactHandle handle = ksession.insert( new Entity( ) ); + FactHandle handle = ksession.insert(new Entity()); ksession.fireAllRules(); - final ArrayList list = new ArrayList(); + final List list = new ArrayList<>(); - ksession.addEventListener( new RuleRuntimeEventListener() { - public void objectInserted( org.kie.api.event.rule.ObjectInsertedEvent objectInsertedEvent ) { } - public void objectUpdated( org.kie.api.event.rule.ObjectUpdatedEvent objectUpdatedEvent ) { } - public void objectDeleted( org.kie.api.event.rule.ObjectDeletedEvent objectRetractedEvent ) { + ksession.addEventListener(new RuleRuntimeEventListener() { + public void objectInserted(org.kie.api.event.rule.ObjectInsertedEvent objectInsertedEvent) { } + public void objectUpdated(org.kie.api.event.rule.ObjectUpdatedEvent objectUpdatedEvent) { } + public void objectDeleted(org.kie.api.event.rule.ObjectDeletedEvent objectRetractedEvent) { Object o = objectRetractedEvent.getOldObject(); - if ( o instanceof TraitProxyImpl) { - String traitName = ( (TraitProxyImpl) o )._getTraitName(); - list.add( traitName.substring( traitName.lastIndexOf( "." ) + 1 ) ); + if (o instanceof TraitProxyImpl) { + String traitName = ((TraitProxyImpl) o)._getTraitName(); + list.add(traitName.substring(traitName.lastIndexOf(".") + 1)); } } - } ); + }); - ksession.delete( handle ); + ksession.delete(handle); ksession.fireAllRules(); - LOGGER.debug( list.toString() ); - assertThat(list).isEqualTo(Arrays.asList("B", "C", "A")); + LOGGER.debug(list.toString()); + assertThat(list).containsExactly("B", "C", "A"); } @@ -4399,7 +4171,7 @@ public void testTraitWithManySoftFields() { "\n" + "declare trait Tx \n"; - for ( int j = 0; j < 150; j ++ ) { + for (int j = 0; j < 150; j ++) { drl += " fld" + j + " : String \n"; } @@ -4411,17 +4183,17 @@ public void testTraitWithManySoftFields() { "rule \"don\"\n" + "when \n" + "then\n" + - " don( new TBean(), Tx.class ); \n" + + " don(new TBean(), Tx.class); \n" + "end\n" + "" + ""; KieSession ksession = loadKnowledgeBaseFromString(drl).newKieSession(); - TraitFactoryImpl.setMode(mode, ksession.getKieBase() ); + TraitFactoryImpl.setMode(mode, ksession.getKieBase()); ksession.fireAllRules(); - assertThat(ksession.getObjects().size()).isEqualTo(2); + assertThat(ksession.getObjects()).hasSize(2); } @@ -4446,21 +4218,21 @@ public int getdeletes() { } @Override - public void objectInserted( org.kie.api.event.rule.ObjectInsertedEvent event ) { - if ( ! ( event.getObject() instanceof String ) ) { + public void objectInserted(org.kie.api.event.rule.ObjectInsertedEvent event) { + if (! (event.getObject() instanceof String)) { inserts++; } } @Override - public void objectUpdated( org.kie.api.event.rule.ObjectUpdatedEvent event ) { - if ( ! ( event.getObject() instanceof String ) ) { + public void objectUpdated(org.kie.api.event.rule.ObjectUpdatedEvent event) { + if (! (event.getObject() instanceof String)) { updates++; } } - public void objectDeleted( org.kie.api.event.rule.ObjectDeletedEvent objectdeleteedEvent ) { - if ( ! ( objectdeleteedEvent.getOldObject() instanceof String ) ) { + public void objectDeleted(org.kie.api.event.rule.ObjectDeletedEvent objectdeleteedEvent) { + if (! (objectdeleteedEvent.getOldObject() instanceof String)) { deletes++; } } @@ -4497,54 +4269,54 @@ public void testDonManyTraitsAtOnce() { "when \n" + "then\n" + " TBean t = new TBean(); \n" + - " don( t, A.class ); \n" + - " don( t, B.class ); \n" + + " don(t, A.class); \n" + + " don(t, B.class); \n" + "end\n" + "" + "rule \"Don 2\" " + "when \n" + - " $s : String( this == \"go\" ) \n" + + " $s : String(this == \"go\") \n" + " $t : TBean() \n" + "then \n" + - " list.add( 0 ); \n" + - " don( $t, Arrays.asList( C.class, D.class, E.class, F.class ), true ); \n" + + " list.add(0); \n" + + " don($t, Arrays.asList(C.class, D.class, E.class, F.class), true); \n" + "end \n" + "" + "rule Clear \n" + "when \n" + - " $s : String( this == \"undo\" ) \n" + + " $s : String(this == \"undo\") \n" + " $t : TBean() \n" + "then \n" + - " delete( $s ); \n" + - " delete( $t ); \n" + + " delete($s); \n" + + " delete($t); \n" + "end \n" + "" + "rule C \n" + "when\n" + - " B( this isA C ) \n" + + " B(this isA C) \n" + "then \n" + - " list.add( 1 ); \n" + + " list.add(1); \n" + "end \n" + "rule D \n" + "when\n" + - " D( this isA A, this isA C ) \n" + + " D(this isA A, this isA C) \n" + "then \n" + - " list.add( 2 ); \n" + + " list.add(2); \n" + "end \n"+ "rule E \n" + "when\n" + - " D( this isA A, this isA E ) \n" + + " D(this isA A, this isA E) \n" + "then \n" + - " list.add( 3 ); \n" + + " list.add(3); \n" + "end \n"; KieSession ksession = loadKnowledgeBaseFromString(drl).newKieSession(); - TraitFactoryImpl.setMode(mode, ksession.getKieBase() ); - ArrayList list = new ArrayList(); - ksession.setGlobal( "list", list ); + TraitFactoryImpl.setMode(mode, ksession.getKieBase()); + List list = new ArrayList<>(); + ksession.setGlobal("list", list); CountingWorkingMemoryEventListener cwm = new CountingWorkingMemoryEventListener(); - ksession.addEventListener( cwm ); + ksession.addEventListener(cwm); ksession.fireAllRules(); @@ -4555,7 +4327,7 @@ public void testDonManyTraitsAtOnce() { assertThat(cwm.getUpdates()).isEqualTo(1); cwm.reset(); - FactHandle handle = ksession.insert( "go" ); + FactHandle handle = ksession.insert("go"); ksession.fireAllRules(); // don C, D, E, F at once : 4 inserts @@ -4565,7 +4337,7 @@ public void testDonManyTraitsAtOnce() { assertThat(cwm.getUpdates()).isEqualTo(3); cwm.reset(); - ksession.delete( handle ); + ksession.delete(handle); ksession.fireAllRules(); // logically asserted C, D, E, F are deleteed @@ -4575,11 +4347,11 @@ public void testDonManyTraitsAtOnce() { assertThat(cwm.getUpdates()).isEqualTo(0); cwm.reset(); - for ( Object o : ksession.getObjects() ) { - LOGGER.debug( o.toString() ); + for (Object o : ksession.getObjects()) { + LOGGER.debug(o.toString()); } - ksession.insert( "undo" ); + ksession.insert("undo"); ksession.fireAllRules(); // deleteing the core bean @@ -4590,8 +4362,8 @@ public void testDonManyTraitsAtOnce() { cwm.reset(); - assertThat(list.size()).isEqualTo(4); - assertThat(list.containsAll(Arrays.asList(0, 1, 2, 3))).isTrue(); + assertThat(list).hasSize(4); + assertThat(list).contains(0, 1, 2, 3); } @Test @@ -4614,28 +4386,28 @@ public void testDonManyTraitsAtOnce2() { "when \n" + "then\n" + " TBean t = new TBean(); \n" + - " don( t, A.class ); \n" + - " don( t, B.class ); \n" + + " don(t, A.class); \n" + + " don(t, B.class); \n" + "end\n" + "" + "rule \"Test Don A,B\" " + "when \n" + " A(this isA B) \n" + "then \n" + - " list.add( 0 ); \n" + + " list.add(0); \n" + "end \n"; KieSession ksession = loadKnowledgeBaseFromString(drl).newKieSession(); - TraitFactoryImpl.setMode(mode, ksession.getKieBase() ); - ArrayList list = new ArrayList(); - ksession.setGlobal( "list", list ); + TraitFactoryImpl.setMode(mode, ksession.getKieBase()); + List list = new ArrayList<>(); + ksession.setGlobal("list", list); CountingWorkingMemoryEventListener cwm = new CountingWorkingMemoryEventListener(); - ksession.addEventListener( cwm ); + ksession.addEventListener(cwm); ksession.fireAllRules(); - assertThat(list).isEqualTo(List.of(0)); + assertThat(list).containsExactly(0); assertThat(cwm.getdeletes()).isEqualTo(0); assertThat(cwm.getInserts()).isEqualTo(3); @@ -4693,14 +4465,14 @@ public void testMultithreadingTraits() throws InterruptedException { " no-loop true\n" + " when\n" + " $p : Item ()\n" + - " not ItemStyle ( id == $p.id )\n" + + " not ItemStyle (id == $p.id)\n" + " then\n" + " don($p, ItemStyle.class);\n" + "end\n" + "rule \"Item Style - Adjustable\"" + " no-loop true" + " when" + - " $style : ItemStyle ( !adjustable )" + + " $style : ItemStyle (!adjustable)" + " Item (" + " id == $style.id " + " )" + @@ -4710,14 +4482,14 @@ public void testMultithreadingTraits() throws InterruptedException { " };" + "end"; KieBase kbase = getKieBaseFromString(s1); - TraitFactoryImpl.setMode(mode, kbase ); + TraitFactoryImpl.setMode(mode, kbase); // might need to tweak these numbers. often works with 7-10,100,60, but often fails 15-20,100,60 int MAX_THREADS = 20; int MAX_REPETITIONS = 100; int MAX_WAIT_SECONDS = 60; - final ExecutorService executorService = Executors.newFixedThreadPool( MAX_THREADS ); + final ExecutorService executorService = Executors.newFixedThreadPool(MAX_THREADS); try { for (int threadIndex = 0; threadIndex < MAX_THREADS; threadIndex++) { executorService.execute(new TraitRulesThread(threadIndex, MAX_REPETITIONS, kbase.newKieSession())); @@ -4727,7 +4499,7 @@ public void testMultithreadingTraits() throws InterruptedException { executorService.awaitTermination(MAX_WAIT_SECONDS, TimeUnit.SECONDS); final List queuedTasks = executorService.shutdownNow(); - assertThat(queuedTasks.size()).isEqualTo(0); + assertThat(queuedTasks).isEmpty(); assertThat(executorService.isTerminated()).isEqualTo(true); } } @@ -4747,7 +4519,7 @@ public void testShedOneLastTrait() throws InterruptedException { "rule \"Don ItemStyle\"\n" + " when\n" + " then\n" + - " don( new Core(), Mask.class );\n" + + " don(new Core(), Mask.class);\n" + "end\n" + "" + "rule \"React\" \n" + @@ -4755,34 +4527,34 @@ public void testShedOneLastTrait() throws InterruptedException { " $s : String() \n" + " $m : Mask() \n" + "then \n" + - " delete( $s ); \n" + - " shed( $m, Mask.class ); \n" + + " delete($s); \n" + + " shed($m, Mask.class); \n" + "end\n" + "" + "rule Log \n" + "when \n" + " $t : Thing() \n" + "then \n" + - " list.add( $t.getClass().getName() ); \n" + + " list.add($t.getClass().getName()); \n" + "end \n"; KieBase kbase = getKieBaseFromString(s1); - TraitFactoryImpl.setMode(mode, kbase ); - ArrayList list = new ArrayList(); + TraitFactoryImpl.setMode(mode, kbase); + List list = new ArrayList<>(); KieSession knowledgeSession = kbase.newKieSession(); - knowledgeSession.setGlobal( "list", list ); + knowledgeSession.setGlobal("list", list); knowledgeSession.fireAllRules(); - assertThat(list.size()).isEqualTo(1); - assertThat(list).isEqualTo(List.of("test.Mask.test.Core_Proxy")); + assertThat(list).hasSize(1); + assertThat(list).containsExactly("test.Mask.test.Core_Proxy"); - knowledgeSession.insert( "shed" ); + knowledgeSession.insert("shed"); knowledgeSession.fireAllRules(); - assertThat(list.size()).isEqualTo(2); - assertThat(list).isEqualTo(Arrays.asList("test.Mask.test.Core_Proxy", "org.drools.base.factmodel.traits.Thing.test.Core_Proxy")); + assertThat(list).hasSize(2); + assertThat(list).containsExactly("test.Mask.test.Core_Proxy", "org.drools.base.factmodel.traits.Thing.test.Core_Proxy"); } @@ -4800,37 +4572,37 @@ public void testShedThingCompletelyThenDonAgain() throws InterruptedException { "" + "rule \"Don ItemStyle\"\n" + " when\n" + - " $s : String( this == \"don1\" ) \n" + + " $s : String(this == \"don1\") \n" + " then\n" + - " delete( $s ); \n" + - " don( new Core(), Mask.class );\n" + + " delete($s); \n" + + " don(new Core(), Mask.class);\n" + "end\n" + "" + "rule \"Clear\" \n" + " when \n" + - " $s : String( this == \"shed1\" ) \n" + + " $s : String(this == \"shed1\") \n" + " $m : Mask() \n" + "then \n" + - " delete( $s ); \n" + - " shed( $m, Thing.class ); \n" + + " delete($s); \n" + + " shed($m, Thing.class); \n" + "end\n" + "" + "rule \"Add\" \n" + " when \n" + - " $s : String( this == \"don2\" ) \n" + + " $s : String(this == \"don2\") \n" + " $c : Core() \n" + "then \n" + - " delete( $s ); \n" + - " don( $c, Mask2.class ); \n" + + " delete($s); \n" + + " don($c, Mask2.class); \n" + "end\n" + "" + "rule \"Clear Again\" \n" + " when \n" + - " $s : String( this == \"shed2\" ) \n" + + " $s : String(this == \"shed2\") \n" + " $m : Mask2() \n" + "then \n" + - " delete( $s ); \n" + - " shed( $m, Mask2.class ); \n" + + " delete($s); \n" + + " shed($m, Mask2.class); \n" + "end\n" + "" + "" + @@ -4838,40 +4610,40 @@ public void testShedThingCompletelyThenDonAgain() throws InterruptedException { "when \n" + " $t : Thing() \n" + "then \n" + - " list.add( $t.getClass().getName() ); \n" + + " list.add($t.getClass().getName()); \n" + "end \n"; KieBase kbase = getKieBaseFromString(s1); - TraitFactoryImpl.setMode(mode, kbase ); - ArrayList list = new ArrayList(); + TraitFactoryImpl.setMode(mode, kbase); + List list = new ArrayList<>(); KieSession knowledgeSession = kbase.newKieSession(); - knowledgeSession.setGlobal( "list", list ); + knowledgeSession.setGlobal("list", list); - knowledgeSession.insert( "don1" ); + knowledgeSession.insert("don1"); knowledgeSession.fireAllRules(); - assertThat(list.size()).isEqualTo(1); - assertThat(list).isEqualTo(List.of("test.Mask.test.Core_Proxy")); + assertThat(list).hasSize(1); + assertThat(list).containsExactly("test.Mask.test.Core_Proxy"); - knowledgeSession.insert( "shed1" ); + knowledgeSession.insert("shed1"); knowledgeSession.fireAllRules(); - assertThat(list.size()).isEqualTo(1); - assertThat(list).isEqualTo(List.of("test.Mask.test.Core_Proxy")); + assertThat(list).hasSize(1); + assertThat(list).containsExactly("test.Mask.test.Core_Proxy"); - knowledgeSession.insert( "don2" ); + knowledgeSession.insert("don2"); knowledgeSession.fireAllRules(); - LOGGER.debug( list.toString() ); - assertThat(list.size()).isEqualTo(2); - assertThat(list).isEqualTo(Arrays.asList("test.Mask.test.Core_Proxy", "test.Mask2.test.Core_Proxy")); + LOGGER.debug(list.toString()); + assertThat(list).hasSize(2); + assertThat(list).containsExactly("test.Mask.test.Core_Proxy", "test.Mask2.test.Core_Proxy"); - knowledgeSession.insert( "shed2" ); + knowledgeSession.insert("shed2"); knowledgeSession.fireAllRules(); - assertThat(list.size()).isEqualTo(3); - assertThat(list).isEqualTo(Arrays.asList("test.Mask.test.Core_Proxy", "test.Mask2.test.Core_Proxy", "org.drools.base.factmodel.traits.Thing.test.Core_Proxy")); + assertThat(list).hasSize(3); + assertThat(list).containsExactly("test.Mask.test.Core_Proxy", "test.Mask2.test.Core_Proxy", "org.drools.base.factmodel.traits.Thing.test.Core_Proxy"); } @@ -4889,23 +4661,23 @@ public void testTraitImplicitInsertionExceptionOnNonTraitable() throws Interrupt "rule \"Don ItemStyle\"\n" + " when\n" + " then\n" + - " don( new Core(), Mask.class );\n" + + " don(new Core(), Mask.class);\n" + "end\n" + "" + ""; KieBase kbase = getKieBaseFromString(s1); - TraitFactoryImpl.setMode(mode, kbase ); + TraitFactoryImpl.setMode(mode, kbase); ArrayList list = new ArrayList(); KieSession knowledgeSession = kbase.newKieSession(); - knowledgeSession.setGlobal( "list", list ); + knowledgeSession.setGlobal("list", list); try { knowledgeSession.fireAllRules(); - fail( "Core is not declared @Traitable, this test should have thrown an exception" ); - } catch ( Exception csq ) { - assertThat(csq.getCause() instanceof IllegalStateException).isTrue(); + fail("Core is not declared @Traitable, this test should have thrown an exception"); + } catch (Exception csq) { + assertThat(csq.getCause()).isInstanceOf(IllegalStateException.class); } } @@ -4914,7 +4686,7 @@ public void testTraitImplicitInsertionExceptionOnNonTraitable() throws Interrupt @Trait public static interface SomeTrait extends Thing { public String getFoo(); - public void setFoo( String foo ); + public void setFoo(String foo); } @Test @@ -4929,19 +4701,19 @@ public void testTraitLegacyTraitableWithLegacyTrait() { "rule \"Don ItemStyle\"\n" + " when\n" + " then\n" + - " don( new StudentImpl(), SomeTrait.class );\n" + + " don(new StudentImpl(), SomeTrait.class);\n" + "end\n"; KieBase kbase = getKieBaseFromString(s1); - TraitFactoryImpl.setMode(mode, kbase ); + TraitFactoryImpl.setMode(mode, kbase); ArrayList list = new ArrayList(); KieSession knowledgeSession = kbase.newKieSession(); - knowledgeSession.setGlobal( "list", list ); + knowledgeSession.setGlobal("list", list); knowledgeSession.fireAllRules(); - assertThat(knowledgeSession.getObjects().size()).isEqualTo(2); + assertThat(knowledgeSession.getObjects()).hasSize(2); } @Test @@ -4958,28 +4730,28 @@ public void testIsALegacyTrait() { "rule \"Don ItemStyle\"\n" + " when\n" + " then\n" + - " insert( new StudentImpl() );\n" + - " don( new Entity(), IStudent.class );\n" + + " insert(new StudentImpl());\n" + + " don(new Entity(), IStudent.class);\n" + "end\n" + "" + "rule Check " + " when " + " $s : StudentImpl() " + - " $e : Entity( this isA $s ) " + + " $e : Entity(this isA $s) " + " then " + - " list.add( 1 ); " + + " list.add(1); " + " end "; KieBase kbase = getKieBaseFromString(s1); - TraitFactoryImpl.setMode(mode, kbase ); - ArrayList list = new ArrayList(); + TraitFactoryImpl.setMode(mode, kbase); + List list = new ArrayList<>(); KieSession knowledgeSession = kbase.newKieSession(); - knowledgeSession.setGlobal( "list", list ); + knowledgeSession.setGlobal("list", list); knowledgeSession.fireAllRules(); - assertThat(list).isEqualTo(List.of(1)); + assertThat(list).containsExactly(1); } @Category(ReviseTraitTestWithPRAlwaysCategory.class) @@ -5001,43 +4773,43 @@ public void testClassLiteralsWithOr() { "when " + "then " + " Foo f = new Foo(); " + - " insert( f ); " + + " insert(f); " + "end " + "rule One " + "when " + - " $f : Foo( this not isA A ) " + + " $f : Foo(this not isA A) " + "then " + - " don( $f, A.class ); " + + " don($f, A.class); " + "end " + "rule Two " + "when " + - " $f : Foo( this not isA B ) " + + " $f : Foo(this not isA B) " + "then " + - " don( $f, B.class ); " + + " don($f, B.class); " + "end " + "rule Check " + "when " + - " $f : Foo( this isA B || this isA A ) " + + " $f : Foo(this isA B || this isA A) " + "then " + - " list.add( 1 ); " + + " list.add(1); " + "end " + ""; - KieBase kbase = new KieHelper(PropertySpecificOption.ALLOWED).addContent( drl, ResourceType.DRL ).build(); - TraitFactoryImpl.setMode(mode, kbase ); - ArrayList list = new ArrayList(); + KieBase kbase = new KieHelper(PropertySpecificOption.ALLOWED).addContent(drl, ResourceType.DRL).build(); + TraitFactoryImpl.setMode(mode, kbase); + List list = new ArrayList<>(); KieSession ksession = kbase.newKieSession(); - ksession.setGlobal( "list", list ); + ksession.setGlobal("list", list); ksession.fireAllRules(); - assertThat(list).isEqualTo(List.of(1)); + assertThat(list).containsExactly(1); } @@ -5067,41 +4839,40 @@ public void testIsASwappedArg() { "rule Init " + "when " + "then " + - " Foo f = new Foo( new StudentImpl() ); " + - " don( f, IStudent.class ); " + + " Foo f = new Foo(new StudentImpl()); " + + " don(f, IStudent.class); " + "end " + "rule Match1 " + "when " + - " $f : Foo( $x : object ) " + - " $p : StudentImpl( this isA $f ) from $x " + + " $f : Foo($x : object) " + + " $p : StudentImpl(this isA $f) from $x " + "then " + - " list.add( 1 ); " + + " list.add(1); " + "end " + "rule Match2 " + "when " + - " $f : Foo( $x : object ) " + - " $p : StudentImpl( $f isA this ) from $x " + + " $f : Foo($x : object) " + + " $p : StudentImpl($f isA this) from $x " + "then " + - " list.add( 2 ); " + + " list.add(2); " + "end " + ""; - KieBase kbase = loadKnowledgeBaseFromString( drl ); - TraitFactoryImpl.setMode(mode, kbase ); - ArrayList list = new ArrayList(); + KieBase kbase = loadKnowledgeBaseFromString(drl); + TraitFactoryImpl.setMode(mode, kbase); + List list = new ArrayList<>(); KieSession ksession = kbase.newKieSession(); - ksession.setGlobal( "list", list ); + ksession.setGlobal("list", list); ksession.fireAllRules(); - assertThat(list.size()).isEqualTo(2); - assertThat(list.contains(1)).isTrue(); - assertThat(list.contains(2)).isTrue(); + assertThat(list).hasSize(2); + assertThat(list).contains(1, 2); } @@ -5126,23 +4897,23 @@ public void testHierarchyEncodeOnPackageMerge() { TraitFactoryImpl.setMode(mode, (InternalRuleBase) knowledgeBase); KnowledgeBuilder kb = KnowledgeBuilderFactory.newKnowledgeBuilder(); - kb.add( new ByteArrayResource( drl0.getBytes() ), ResourceType.DRL ); + kb.add(new ByteArrayResource(drl0.getBytes()), ResourceType.DRL); assertThat(kb.hasErrors()).isFalse(); - knowledgeBase.addPackages( kb.getKnowledgePackages() ); + knowledgeBase.addPackages(kb.getKnowledgePackages()); KnowledgeBuilder kb2 = KnowledgeBuilderFactory.newKnowledgeBuilder(); - kb2.add( new ByteArrayResource( drl1.getBytes() ), ResourceType.DRL ); - LOGGER.debug( kb2.getErrors().toString() ); + kb2.add(new ByteArrayResource(drl1.getBytes()), ResourceType.DRL); + LOGGER.debug(kb2.getErrors().toString()); assertThat(kb2.hasErrors()).isFalse(); - knowledgeBase.addPackages( kb2.getKnowledgePackages() ); + knowledgeBase.addPackages(kb2.getKnowledgePackages()); HierarchyEncoder hier = ((TraitRuntimeComponentFactory) RuntimeComponentFactory.get()).getTraitRegistry(knowledgeBase).getHierarchy(); - BitSet b = (BitSet) hier.getCode( "org.drools.test.B" ).clone(); - BitSet c = (BitSet) hier.getCode( "org.drools.test.C" ).clone(); + BitSet b = (BitSet) hier.getCode("org.drools.test.B").clone(); + BitSet c = (BitSet) hier.getCode("org.drools.test.C").clone(); - c.and( b ); + c.and(b); assertThat(c).isEqualTo(b); } @@ -5168,9 +4939,9 @@ public void testDonThenReinsert() throws InterruptedException { "" + "rule 'Don ItemStyle' " + " when\n" + - " $e : TBean( ) " + + " $e : TBean() " + " then " + - " don( $e, Mask.class );\n" + + " don($e, Mask.class);\n" + "end\n" + "" + "rule \"React\" \n" + @@ -5183,29 +4954,29 @@ public void testDonThenReinsert() throws InterruptedException { KieBase kbase = getKieBaseFromString(s1, EqualityBehaviorOption.IDENTITY); - TraitFactoryImpl.setMode(mode, kbase ); + TraitFactoryImpl.setMode(mode, kbase); ArrayList list = new ArrayList(); KieSession knowledgeSession = kbase.newKieSession(); - knowledgeSession.setGlobal( "list", list ); - TBean e = new TBean( "aaa" ); + knowledgeSession.setGlobal("list", list); + TBean e = new TBean("aaa"); int n = knowledgeSession.fireAllRules(); assertThat(n).isEqualTo(1); - knowledgeSession.insert( e ); + knowledgeSession.insert(e); n = knowledgeSession.fireAllRules(); assertThat(n).isEqualTo(2); - knowledgeSession.insert( e ); + knowledgeSession.insert(e); n = knowledgeSession.fireAllRules(); assertThat(n).isEqualTo(0); - knowledgeSession.delete( knowledgeSession.getFactHandle( e ) ); + knowledgeSession.delete(knowledgeSession.getFactHandle(e)); n = knowledgeSession.fireAllRules(); assertThat(n).isEqualTo(1); - assertThat(knowledgeSession.getObjects().size()).isEqualTo(0); + assertThat(knowledgeSession.getObjects()).isEmpty(); } @@ -5236,30 +5007,30 @@ public void testCastOnTheFly() throws InterruptedException { " dialect 'mvel' " + " when " + " then " + - " Foo o = insert( new Foo( 42 ) ).as( Foo.class ); " + - " list.add( o.getId() ); " + + " Foo o = insert(new Foo(42)).as(Foo.class); " + + " list.add(o.getId()); " + "end " + "rule Don " + " when " + " $f : Foo() " + " then " + - " Lower l = don( $f, Lower.class ); " + - " Upper u = bolster( $f ).as( Upper.class ); " + - " list.add( u.getId() + 1 ); " + + " Lower l = don($f, Lower.class); " + + " Upper u = bolster($f).as(Upper.class); " + + " list.add(u.getId() + 1); " + " end "; KieBase kbase = getKieBaseFromString(s1); - TraitFactoryImpl.setMode(mode, kbase ); - ArrayList list = new ArrayList(); + TraitFactoryImpl.setMode(mode, kbase); + List list = new ArrayList<>(); KieSession knowledgeSession = kbase.newKieSession(); - knowledgeSession.setGlobal( "list", list ); + knowledgeSession.setGlobal("list", list); knowledgeSession.fireAllRules(); - assertThat(list).isEqualTo(Arrays.asList(42, 43)); + assertThat(list).containsExactly(42, 43); } @@ -5283,24 +5054,24 @@ public void testDonModify() { "when\n" + "then\n" + " Entity core = new Entity();\n" + - " insert( core );\n" + + " insert(core);\n" + "end\n" + "rule Trait when\n" + - " $core: Entity( )\n" + + " $core: Entity()\n" + "then\n" + - " IPerson x = don( $core, IPerson.class, true );\n" + - " IStudent s = don( $core, IStudent.class, true );\n" + - " Person p = don( $core, Person.class, true );\n" + + " IPerson x = don($core, IPerson.class, true);\n" + + " IStudent s = don($core, IStudent.class, true);\n" + + " Person p = don($core, Person.class, true);\n" + "end\n" + "rule R2 when\n" + - " $p: IPerson( name == null )\n" + + " $p: IPerson(name == null)\n" + "then\n" + "end\n"; - KieBase kbase = getKieBaseFromString( drl ); - TraitFactoryImpl.setMode(mode, kbase ); + KieBase kbase = getKieBaseFromString(drl); + TraitFactoryImpl.setMode(mode, kbase); KieSession kSession = kbase.newKieSession(); assertThat(kSession.fireAllRules()).isEqualTo(3); @@ -5319,28 +5090,28 @@ public void testAlphaNodeSharing() { "rule Init " + "when " + "then " + - " don( new Entity(), Person.class ); " + + " don(new Entity(), Person.class); " + "end\n" + "rule One when" + - " $core: Entity( this isA Person ) " + + " $core: Entity(this isA Person) " + "then " + "end " + "rule Two when" + - " $core: Entity( this isA Person ) " + + " $core: Entity(this isA Person) " + "then " + "end " + "\n"; - final KieBase kbase = getKieBaseFromString( drl ); - TraitFactoryImpl.setMode(mode, kbase ); + final KieBase kbase = getKieBaseFromString(drl); + TraitFactoryImpl.setMode(mode, kbase); KieSession kSession = kbase.newKieSession(); assertThat(kSession.fireAllRules()).isEqualTo(3); - NamedEntryPoint nep = ( (NamedEntryPoint) kSession.getEntryPoint( EntryPointId.DEFAULT.getEntryPointId() ) ); - ObjectTypeNode otn = nep.getEntryPointNode().getObjectTypeNodes().get( new ClassObjectType( Entity.class ) ); + NamedEntryPoint nep = ((NamedEntryPoint) kSession.getEntryPoint(EntryPointId.DEFAULT.getEntryPointId())); + ObjectTypeNode otn = nep.getEntryPointNode().getObjectTypeNodes().get(new ClassObjectType(Entity.class)); assertThat(otn).isNotNull(); assertThat(otn.getObjectSinkPropagator().getSinks().length).isEqualTo(1); } @@ -5356,45 +5127,45 @@ public void testPartitionWithSiblingsOnDelete() { "declare trait C extends A @propertyReactive end " + "rule Trait when " + - " $core: Entity( ) " + + " $core: Entity() " + "then " + - " don( $core, A.class ); " + - " don( $core, B.class ); " + - " don( $core, C.class ); " + + " don($core, A.class); " + + " don($core, B.class); " + + " don($core, C.class); " + "end " + "rule Shed when " + " $s: String() " + " $core : Entity() " + "then " + - " shed( $core, C.class ); " + + " shed($core, C.class); " + "end " + - "rule RA when A() then list.add( 'A' ); end " + - "rule RB when B() then list.add( 'B' ); end " + - "rule RC when C() then list.add( 'C' ); end " + + "rule RA when A() then list.add('A'); end " + + "rule RB when B() then list.add('B'); end " + + "rule RC when C() then list.add('C'); end " + " "; - KieBase kbase = new KieHelper().addContent( drl, ResourceType.DRL ).build(); - TraitFactoryImpl.setMode(mode, kbase ); + KieBase kbase = new KieHelper().addContent(drl, ResourceType.DRL).build(); + TraitFactoryImpl.setMode(mode, kbase); KieSession ksession = kbase.newKieSession(); - List list = new ArrayList(); - ksession.setGlobal( "list", list ); + List list = new ArrayList<>(); + ksession.setGlobal("list", list); Entity e = new Entity(); - ksession.insert( e ); + ksession.insert(e); ksession.fireAllRules(); - assertThat(list).isEqualTo(Arrays.asList('A', 'B', 'C')); + assertThat(list).containsExactly('A', 'B', 'C'); - ksession.insert( "go" ); + ksession.insert("go"); ksession.fireAllRules(); - Set s = checkOTNPartitioning( e, ksession ); - assertThat(s.size()).isEqualTo(2); + Set s = checkOTNPartitioning(e, ksession); + assertThat(s).hasSize(2); - assertThat(list).isEqualTo(Arrays.asList('A', 'B', 'C')); + assertThat(list).containsExactly('A', 'B', 'C'); } @@ -5407,46 +5178,46 @@ public void testTupleIntegrityOnModification() { "declare trait A @propertyReactive value : int end " + "rule Trait when " + - " $core: Entity( ) " + + " $core: Entity() " + "then " + - " A o = don( $core, A.class ); " + + " A o = don($core, A.class); " + "end " + "rule Test when " + - " $x: A( value == 0 ) " + + " $x: A(value == 0) " + "then " + - " list.add( 0 ); " + + " list.add(0); " + "end " + "rule Check when " + - " $x: A( value == 42 ) " + + " $x: A(value == 42) " + "then " + - " list.add( 42 ); " + + " list.add(42); " + "end " + "rule Mood when " + - " $x : A( value != 42 ) " + + " $x : A(value != 42) " + "then " + - " modify ( $x ) { setValue( 42 ); } " + + " modify ($x) { setValue(42); } " + "end "; - KieBase kbase = getKieBaseFromString( drl ); - TraitFactoryImpl.setMode(mode, kbase ); + KieBase kbase = getKieBaseFromString(drl); + TraitFactoryImpl.setMode(mode, kbase); KieSession ksession = kbase.newKieSession(); - List list = new ArrayList(); - ksession.setGlobal( "list", list ); + List list = new ArrayList<>(); + ksession.setGlobal("list", list); - ksession.insert( new Entity() ); + ksession.insert(new Entity()); ksession.fireAllRules(); - for ( final Object o : ksession.getObjects(object -> object.getClass().getName().contains( "test.A" )) ) { - InternalFactHandle handle = (InternalFactHandle) ksession.getFactHandle( o ); + for (final Object o : ksession.getObjects(object -> object.getClass().getName().contains("test.A"))) { + InternalFactHandle handle = (InternalFactHandle) ksession.getFactHandle(o); TupleImpl first = handle.getFirstLeftTuple(); - assertThat(first instanceof RuleTerminalNodeLeftTuple).isTrue(); + assertThat(first).isInstanceOf(RuleTerminalNodeLeftTuple.class); assertThat(((RuleTerminalNodeLeftTuple) first).getRule().getName()).isEqualTo("Check"); } - assertThat(list).isEqualTo(Arrays.asList(0, 42)); + assertThat(list).containsExactly(0, 42); } @Test @@ -5462,9 +5233,9 @@ public void testShedVacancy() { "rule Trait when " + "then " + - " Entity e = new Entity( 'x1' ); " + - " don( e, C.class ); " + - " don( e, D.class ); " + + " Entity e = new Entity('x1'); " + + " don(e, C.class); " + + " don(e, D.class); " + "end " + "rule Mood when " + @@ -5476,63 +5247,63 @@ public void testShedVacancy() { " $s : String() " + " $x : Entity() " + "then " + - " delete( $s ); " + - " shed( $x, A.class ); " + + " delete($s); " + + " shed($x, A.class); " + "end " + ""; - KieBase kbase = getKieBaseFromString( drl ); - TraitFactoryImpl.setMode(mode, kbase ); + KieBase kbase = getKieBaseFromString(drl); + TraitFactoryImpl.setMode(mode, kbase); KieSession ksession = kbase.newKieSession(); List list = new ArrayList(); - ksession.setGlobal( "list", list ); + ksession.setGlobal("list", list); HierarchyEncoder hier = ((TraitRuntimeComponentFactory) RuntimeComponentFactory.get()).getTraitRegistry(((InternalKnowledgeBase) kbase)).getHierarchy(); - BitSet a = (BitSet) hier.getCode( "org.drools.test.A" ).clone(); - BitSet b = (BitSet) hier.getCode( "org.drools.test.B" ).clone(); - BitSet c = (BitSet) hier.getCode( "org.drools.test.C" ).clone(); - BitSet d = (BitSet) hier.getCode( "org.drools.test.D" ).clone(); + BitSet a = (BitSet) hier.getCode("org.drools.test.A").clone(); + BitSet b = (BitSet) hier.getCode("org.drools.test.B").clone(); + BitSet c = (BitSet) hier.getCode("org.drools.test.C").clone(); + BitSet d = (BitSet) hier.getCode("org.drools.test.D").clone(); int n = ksession.fireAllRules(); assertThat(n).isEqualTo(2); - LOGGER.debug( "---------------------------------------------------------------\n\n\n " ); + LOGGER.debug("---------------------------------------------------------------\n\n\n "); int counter = 0; - for ( Object o : ksession.getObjects() ) { - if ( o instanceof TraitProxyImpl) { + for (Object o : ksession.getObjects()) { + if (o instanceof TraitProxyImpl) { TraitProxyImpl tp = (TraitProxyImpl) o; - if ( tp._getTypeCode().equals( c ) ) { - assertThat(tp.listAssignedOtnTypeCodes().size()).isEqualTo(1); - assertThat(tp.listAssignedOtnTypeCodes().contains(b)).isTrue(); + if (tp._getTypeCode().equals(c)) { + assertThat(tp.listAssignedOtnTypeCodes()).hasSize(1); + assertThat(tp.listAssignedOtnTypeCodes()).contains(b); counter++; - } else if ( tp._getTypeCode().equals( d ) ) { - assertThat(tp.listAssignedOtnTypeCodes().isEmpty()).isTrue(); + } else if (tp._getTypeCode().equals(d)) { + assertThat(tp.listAssignedOtnTypeCodes()).isEmpty(); counter++; } - } else if ( o instanceof TraitableBean ) { + } else if (o instanceof TraitableBean) { TraitableBean tb = (TraitableBean) o; - LOGGER.debug( tb.getCurrentTypeCode().toString() ); + LOGGER.debug(tb.getCurrentTypeCode().toString()); counter++; } } assertThat(counter).isEqualTo(3); - ksession.insert( "go" ); + ksession.insert("go"); ksession.fireAllRules(); - LOGGER.debug( "---------------------------------------------------------------\n\n\n " ); + LOGGER.debug("---------------------------------------------------------------\n\n\n "); int counter2 = 0; - for ( Object o : ksession.getObjects() ) { - if ( o instanceof TraitProxyImpl) { + for (Object o : ksession.getObjects()) { + if (o instanceof TraitProxyImpl) { TraitProxyImpl tp = (TraitProxyImpl) o; assertThat(tp._getTypeCode()).isEqualTo(d); - assertThat(tp.listAssignedOtnTypeCodes().size()).isEqualTo(1); - assertThat(tp.listAssignedOtnTypeCodes().contains(b)).isTrue(); + assertThat(tp.listAssignedOtnTypeCodes()).hasSize(1); + assertThat(tp.listAssignedOtnTypeCodes()).contains(b); counter2++; - } else if ( o instanceof TraitableBean ) { + } else if (o instanceof TraitableBean) { TraitableBean tb = (TraitableBean) o; assertThat(tb.getCurrentTypeCode()).isEqualTo(d); counter2++; @@ -5554,32 +5325,32 @@ public void testExternalUpdateWithProxyRefreshInEqualityMode() { "end " + "rule Don when " + - " $x : ExtEntity( $id : id ) " + + " $x : ExtEntity($id : id) " + "then " + - " list.add( $id ); " + - " don( $x, Mask.class ); " + + " list.add($id); " + + " don($x, Mask.class); " + "end " + "rule Test when " + - " Mask( $n : num ) " + + " Mask($n : num) " + "then " + - " list.add( $n ); " + + " list.add($n); " + "end "; - KieBase kbase = getKieBaseFromString( drl, EqualityBehaviorOption.EQUALITY ); - TraitFactoryImpl.setMode(mode, kbase ); + KieBase kbase = getKieBaseFromString(drl, EqualityBehaviorOption.EQUALITY); + TraitFactoryImpl.setMode(mode, kbase); KieSession ksession = kbase.newKieSession(); - List list = new ArrayList(); - ksession.setGlobal( "list", list ); + List list = new ArrayList<>(); + ksession.setGlobal("list", list); - FactHandle handle = ksession.insert( new ExtEntity( "x1", 42 ) ); + FactHandle handle = ksession.insert(new ExtEntity("x1", 42)); ksession.fireAllRules(); - ksession.update( handle, new ExtEntity( "x1", 35 ) ); + ksession.update(handle, new ExtEntity("x1", 35)); ksession.fireAllRules(); - assertThat(list).isEqualTo(Arrays.asList("x1", 42, "x1", 42)); + assertThat(list).containsExactly("x1", 42, "x1", 42); } @@ -5593,26 +5364,26 @@ public void testIsAInstanceOf() { "rule Test1 " + "when " + - " StudentImpl( this isA IStudent.class ) " + - "then list.add( 1 ); end " + + " StudentImpl(this isA IStudent.class) " + + "then list.add(1); end " + "rule Test2 " + "when " + - " IStudent( this isA StudentImpl.class ) " + - "then list.add( 2 ); end " + + " IStudent(this isA StudentImpl.class) " + + "then list.add(2); end " + ""; - KieBase kbase = getKieBaseFromString( drl ); - List list = new ArrayList( ); - TraitFactoryImpl.setMode(mode, kbase ); + KieBase kbase = getKieBaseFromString(drl); + List list = new ArrayList<>(); + TraitFactoryImpl.setMode(mode, kbase); KieSession knowledgeSession = kbase.newKieSession(); - knowledgeSession.setGlobal( "list", list ); - knowledgeSession.insert( new StudentImpl( ) ); + knowledgeSession.setGlobal("list", list); + knowledgeSession.insert(new StudentImpl()); assertThat(knowledgeSession.fireAllRules()).isEqualTo(2); - assertThat(list).isEqualTo(Arrays.asList(1, 2)); + assertThat(list).containsExactly(1, 2); } @@ -5624,21 +5395,21 @@ public void testIsAInstanceOfNonTraitable() { "rule Test1 " + "when " + - " Object( this isA String.class ) " + - "then list.add( 1 ); end " + + " Object(this isA String.class) " + + "then list.add(1); end " + ""; - KieBase kbase = getKieBaseFromString( drl ); - List list = new ArrayList( ); - TraitFactoryImpl.setMode(mode, kbase ); + KieBase kbase = getKieBaseFromString(drl); + List list = new ArrayList<>(); + TraitFactoryImpl.setMode(mode, kbase); KieSession knowledgeSession = kbase.newKieSession(); - knowledgeSession.setGlobal( "list", list ); - knowledgeSession.insert( "hello" ); + knowledgeSession.setGlobal("list", list); + knowledgeSession.insert("hello"); assertThat(knowledgeSession.fireAllRules()).isEqualTo(1); - assertThat(list).isEqualTo(List.of(1)); + assertThat(list).containsExactly(1); } @@ -5652,26 +5423,26 @@ public int getNum() { return num; } - public void setNum( int num ) { + public void setNum(int num) { this.num = num; } - public ExtEntity( String id, int num ) { - super( id ); + public ExtEntity(String id, int num) { + super(id); this.num = num; } } - protected Set checkOTNPartitioning( TraitableBean core, KieSession wm ) { + protected Set checkOTNPartitioning(TraitableBean core, KieSession wm) { Set otns = new HashSet(); - for ( Object o : core._getTraitMap().values() ) { + for (Object o : core._getTraitMap().values()) { TraitProxyImpl tp = (TraitProxyImpl) o; Set localNodes = tp.listAssignedOtnTypeCodes(); - for ( BitSet code : localNodes ) { - assertThat(otns.contains(code)).isFalse(); - otns.add( code ); + for (BitSet code : localNodes) { + assertThat(otns).doesNotContain(code); + otns.add(code); } } @@ -5688,27 +5459,27 @@ public void testSerializeKieBaseWithTraits() { "rule Test1 " + "when " + - " StudentImpl( this isA IStudent.class ) " + - "then list.add( 1 ); end " + + " StudentImpl(this isA IStudent.class) " + + "then list.add(1); end " + "rule Test2 " + "when " + - " IStudent( this isA StudentImpl.class ) " + - "then list.add( 2 ); end " + + " IStudent(this isA StudentImpl.class) " + + "then list.add(2); end " + ""; - KieBase kbase = getKieBaseFromString( drl ); + KieBase kbase = getKieBaseFromString(drl); - List list = new ArrayList( ); - TraitFactoryImpl.setMode(mode, kbase ); + List list = new ArrayList<>(); + TraitFactoryImpl.setMode(mode, kbase); KieSession knowledgeSession = kbase.newKieSession(); - knowledgeSession.setGlobal( "list", list ); - knowledgeSession.insert( new StudentImpl( ) ); + knowledgeSession.setGlobal("list", list); + knowledgeSession.insert(new StudentImpl()); assertThat(knowledgeSession.fireAllRules()).isEqualTo(2); - assertThat(list).isEqualTo(Arrays.asList(1, 2)); + assertThat(list).containsExactly(1, 2); } @Test @@ -5739,27 +5510,27 @@ public void testMixin2() { "rule \"Zero\"\n" + "when\n" + "then\n" + - " insert( new Person() );\n" + + " insert(new Person());\n" + "end\n" + "\n" + "\n" + "rule \"Student\"\n" + "no-loop\n" + "when\n" + - " $p : Person( $name : name, $age : age < 25, $weight : weight )\n" + + " $p : Person($name : name, $age : age < 25, $weight : weight)\n" + "then\n" + - " Student s = don( $p, Student.class );\n" + - " s.setSchool( \"SomeSchool\" );\n" + - " s.learn( \" AI \" );\n" + + " Student s = don($p, Student.class);\n" + + " s.setSchool(\"SomeSchool\");\n" + + " s.learn(\" AI \");\n" + "end\n"; - KieSession ks = getSessionFromString( drl ); - TraitFactoryImpl.setMode(mode, ks.getKieBase() ); + KieSession ks = getSessionFromString(drl); + TraitFactoryImpl.setMode(mode, ks.getKieBase()); ks.fireAllRules(); } - @Trait( impl = ScholarImpl.class ) + @Trait(impl = ScholarImpl.class) public interface Scholar { void learn(String subject); } @@ -5772,16 +5543,16 @@ public static class ScholarImpl implements Scholar { public ScholarImpl() { } - public ScholarImpl( Thing arg ) { + public ScholarImpl(Thing arg) { this.core = arg; } - public void learn( String subject ) { - LOGGER.debug( "I " + core.getFields().get( "name" ) + ", now know everything about " + subject ); + public void learn(String subject) { + LOGGER.debug("I " + core.getFields().get("name") + ", now know everything about " + subject); } } - @Trait( impl = YImpl.class ) + @Trait(impl = YImpl.class) public interface Y { String getShared(); String getYValue(); @@ -5800,7 +5571,7 @@ public String getYValue() { } } - @Trait( impl = ZImpl.class ) + @Trait(impl = ZImpl.class) public interface Z { String getShared(); String getZValue(); @@ -5839,27 +5610,27 @@ private void checkMixinResolutionUsesOrder(String interfaces, String first) { "end\n" + "\n" + "\n" + - "declare X extends " + interfaces + " @Trait( mixinSolveConflicts = Trait.MixinConflictResolutionStrategy.DECLARATION_ORDER ) end\n" + + "declare X extends " + interfaces + " @Trait(mixinSolveConflicts = Trait.MixinConflictResolutionStrategy.DECLARATION_ORDER) end\n" + "\n" + "rule Init when\n" + "then\n" + - " insert( new Bean() );\n" + + " insert(new Bean());\n" + "end\n" + "\n" + "rule Exec no-loop when\n" + " $b : Bean()\n" + "then\n" + - " X x = don( $b, X.class );\n" + - " list.add( x.getYValue() );\n" + - " list.add( x.getZValue() );\n" + - " list.add( x.getShared() );\n" + + " X x = don($b, X.class);\n" + + " list.add(x.getYValue());\n" + + " list.add(x.getZValue());\n" + + " list.add(x.getShared());\n" + "end\n"; - KieSession ks = getSessionFromString( drl ); - TraitFactoryImpl.setMode(mode, ks.getKieBase() ); + KieSession ks = getSessionFromString(drl); + TraitFactoryImpl.setMode(mode, ks.getKieBase()); List list = new ArrayList(); - ks.setGlobal( "list", list ); + ks.setGlobal("list", list); ks.fireAllRules(); @@ -5884,32 +5655,29 @@ public void testMixinWithConflictsThrowingError() { "end\n" + "\n" + "\n" + - "declare X extends Y,Z @Trait( mixinSolveConflicts = Trait.MixinConflictResolutionStrategy.ERROR_ON_CONFLICT ) end\n" + + "declare X extends Y,Z @Trait(mixinSolveConflicts = Trait.MixinConflictResolutionStrategy.ERROR_ON_CONFLICT) end\n" + "\n" + "rule Init when\n" + "then\n" + - " insert( new Bean() );\n" + + " insert(new Bean());\n" + "end\n" + "\n" + "rule Exec no-loop when\n" + " $b : Bean()\n" + "then\n" + - " X x = don( $b, X.class );\n" + - " list.add( x.getYValue() );\n" + - " list.add( x.getZValue() );\n" + - " list.add( x.getShared() );\n" + + " X x = don($b, X.class);\n" + + " list.add(x.getYValue());\n" + + " list.add(x.getZValue());\n" + + " list.add(x.getShared());\n" + "end\n"; - KieSession ks = getSessionFromString( drl ); - TraitFactoryImpl.setMode(mode, ks.getKieBase() ); + KieSession ks = getSessionFromString(drl); + TraitFactoryImpl.setMode(mode, ks.getKieBase()); List list = new ArrayList(); - ks.setGlobal( "list", list ); + ks.setGlobal("list", list); - try { - ks.fireAllRules(); - fail("don should fail due to the conflict in getShared() method"); - } catch (Exception e) { } + assertThatException().as("don should fail due to the conflict in getShared() method").isThrownBy(() -> ks.fireAllRules()); } @Test @@ -5934,58 +5702,58 @@ public void testPreserveAllSetBitMask() { "" + "rule Init when\n" + "then " + - " Entity e1 = new Entity( \"X\" ); " + - " insert( e1 ); " + - " Entity e2 = new Entity( \"Y\" ); " + - " insert( e2 ); " + + " Entity e1 = new Entity(\"X\"); " + + " insert(e1); " + + " Entity e2 = new Entity(\"Y\"); " + + " insert(e2); " + " " + - " D d1 = don( e1, D.class, true ); " + - " F f2 = don( e2, F.class, true ); " + + " D d1 = don(e1, D.class, true); " + + " F f2 = don(e2, F.class, true); " + " " + - " modify ( d1 ) { getObjProp().add( f2.getCore() ); } " + - " modify ( f2.getCore() ) {} " + + " modify (d1) { getObjProp().add(f2.getCore()); } " + + " modify (f2.getCore()) {} " + "end " + "" + "rule Rec no-loop when\n" + - " MyThing( $x_0 := core, this isA D.class, $p : this#RootThing.objProp ) " + - " exists MyThing( $x_1 := core , core memberOf $p, this isA F.class ) " + + " MyThing($x_0 := core, this isA D.class, $p : this#RootThing.objProp) " + + " exists MyThing($x_1 := core , core memberOf $p, this isA F.class) " + "then " + - " don( $x_0, E.class, true ); " + + " don($x_0, E.class, true); " + "end " + "" + "rule Shed_2 when\n" + - " $s : String( this == \"go2\") " + - " $x : E( $objs : objProp ) " + - " $y : F( $z : core memberOf $objs ) " + + " $s : String(this == \"go2\") " + + " $x : E($objs : objProp) " + + " $y : F($z : core memberOf $objs) " + "then " + - " retract( $s ); " + - " modify ( $x ) { getObjProp().remove( $z ); } " + - " modify ( $y ) {} " + + " retract($s); " + + " modify ($x) { getObjProp().remove($z); } " + + " modify ($y) {} " + "end "; KieHelper helper = new KieHelper(); - KieBase kieBase = helper.addContent( drl, ResourceType.DRL ).getKieContainer().getKieBase(); - TraitFactoryImpl.setMode(mode, kieBase ); + KieBase kieBase = helper.addContent(drl, ResourceType.DRL).getKieContainer().getKieBase(); + TraitFactoryImpl.setMode(mode, kieBase); KieSession kSession = kieBase.newKieSession(); kSession.fireAllRules(); - kSession.insert( "go2" ); + kSession.insert("go2"); kSession.fireAllRules(); - for ( Object o : kSession.getObjects( new ClassObjectFilter( Entity.class ) ) ) { + for (Object o : kSession.getObjects(new ClassObjectFilter(Entity.class))) { Entity e = (Entity) o; - if ( e.getId().equals( "X" ) ) { + if (e.getId().equals("X")) { assertThat(e.hasTrait("t.x.D")).isTrue(); assertThat(e.hasTrait("t.x.E")).isFalse(); assertThat(e.hasTrait("t.x.F")).isFalse(); - assertThat(((List) e._getDynamicProperties().get("objProp")).size()).isEqualTo(0); - } else if ( e.getId().equals( "Y" ) ) { + assertThat(((List) e._getDynamicProperties().get("objProp"))).isEmpty(); + } else if (e.getId().equals("Y")) { assertThat(e.hasTrait("t.x.F")).isTrue(); assertThat(e.hasTrait("t.x.D")).isFalse(); assertThat(e.hasTrait("t.x.E")).isFalse(); } else { - fail( "Unrecognized entity in WM" ); + fail("Unrecognized entity in WM"); } } } diff --git a/drools-traits/src/test/java/org/drools/traits/compiler/integrationtests/TraitTypeGenerationTest.java b/drools-traits/src/test/java/org/drools/traits/compiler/integrationtests/TraitTypeGenerationTest.java index b4f647b526c..51d42a2f5c4 100644 --- a/drools-traits/src/test/java/org/drools/traits/compiler/integrationtests/TraitTypeGenerationTest.java +++ b/drools-traits/src/test/java/org/drools/traits/compiler/integrationtests/TraitTypeGenerationTest.java @@ -30,7 +30,7 @@ import org.drools.traits.compiler.CommonTraitTest; import org.drools.traits.compiler.Person; import org.drools.traits.core.factmodel.Entity; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.kie.api.KieBase; import org.kie.api.KieServices; import org.kie.api.builder.KieBuilder; @@ -82,7 +82,7 @@ public void setB(final int b) { } } - @Test(timeout=10000) + @Test public void testWithDeclaredTypeAndTraitInDifferentPackages() { // DROOLS-91 final String str1 = @@ -194,7 +194,7 @@ public void testIsAWith2KContainers() { KieBuilder kbuilder = ks.newKieBuilder(kfs ); kbuilder.buildAll(); - assertThat(kbuilder.getResults().getMessages().size()).isEqualTo(0); + assertThat(kbuilder.getResults().getMessages()).isEmpty(); ks.newKieContainer( kbuilder.getKieModule().getReleaseId() ).getKieBase(); @@ -205,7 +205,7 @@ public void testIsAWith2KContainers() { ksession.setGlobal( "students", students ); ksession.insert( new Person("tom", 20 ) ); ksession.fireAllRules(); - assertThat(students.size()).isEqualTo(1); + assertThat(students).hasSize(1); } public static interface FooIntf { @@ -347,7 +347,7 @@ public void testRedeclareClassAsTrait() { KieHelper kh = new KieHelper(); kh.addContent( s1, ResourceType.DRL ); - assertThat(kh.verify().getMessages(Message.Level.ERROR).size()).isEqualTo(1); + assertThat(kh.verify().getMessages(Message.Level.ERROR)).hasSize(1); } public static class SomeClass {} @@ -381,7 +381,7 @@ public void testMultipleInheritanceWithPosition1() throws Exception { knowledgeBase.addPackages(kBuilder.getKnowledgePackages()); FactType sw = knowledgeBase.getFactType("org.drools.test", "MultiInhPosTrait"); - assertThat(sw.getFields().size()).isEqualTo(5); + assertThat(sw.getFields()).hasSize(5); assertThat(sw.getFields().get(0).getName()).isEqualTo("field0"); assertThat(sw.getFields().get(1).getName()).isEqualTo("field1"); assertThat(sw.getFields().get(2).getName()).isEqualTo("mfield1"); @@ -417,7 +417,7 @@ public void testMultipleInheritanceWithPosition2() throws Exception { knowledgeBase.addPackages(kBuilder.getKnowledgePackages()); FactType sw = knowledgeBase.getFactType("org.drools.test", "MultiInhPosTrait"); - assertThat(sw.getFields().size()).isEqualTo(5); + assertThat(sw.getFields()).hasSize(5); assertThat(sw.getFields().get(0).getName()).isEqualTo("mfield0"); assertThat(sw.getFields().get(1).getName()).isEqualTo("field0"); assertThat(sw.getFields().get(2).getName()).isEqualTo("mfield1"); @@ -453,7 +453,7 @@ public void testMultipleInheritanceWithPosition3() throws Exception { knowledgeBase.addPackages(kBuilder.getKnowledgePackages()); FactType sw = knowledgeBase.getFactType("org.drools.test", "MultiInhPosTrait"); - assertThat(sw.getFields().size()).isEqualTo(5); + assertThat(sw.getFields()).hasSize(5); assertThat(sw.getFields().get(0).getName()).isEqualTo("field0"); assertThat(sw.getFields().get(1).getName()).isEqualTo("field2"); assertThat(sw.getFields().get(2).getName()).isEqualTo("field1"); @@ -489,7 +489,7 @@ public void testMultipleInheritanceWithPosition4() throws Exception { knowledgeBase.addPackages(kBuilder.getKnowledgePackages()); FactType sw = knowledgeBase.getFactType("org.drools.test", "MultiInhPosTrait"); - assertThat(sw.getFields().size()).isEqualTo(5); + assertThat(sw.getFields()).hasSize(5); assertThat(sw.getFields().get(0).getName()).isEqualTo("field1"); assertThat(sw.getFields().get(1).getName()).isEqualTo("field2"); assertThat(sw.getFields().get(2).getName()).isEqualTo("mfield0"); @@ -525,7 +525,7 @@ public void testMultipleInheritanceWithPosition5() throws Exception { knowledgeBase.addPackages(kBuilder.getKnowledgePackages()); FactType sw = knowledgeBase.getFactType("org.drools.test", "MultiInhPosTrait"); - assertThat(sw.getFields().size()).isEqualTo(5); + assertThat(sw.getFields()).hasSize(5); assertThat(sw.getFields().get(0).getName()).isEqualTo("field1"); assertThat(sw.getFields().get(1).getName()).isEqualTo("field0"); assertThat(sw.getFields().get(2).getName()).isEqualTo("mfield1"); @@ -567,7 +567,7 @@ public void testMultipleInheritanceWithPosition6() throws Exception { knowledgeBase.addPackages(kBuilder.getKnowledgePackages()); FactType sw = knowledgeBase.getFactType("org.drools.test", "MultiInhPosTrait"); - assertThat(sw.getFields().size()).isEqualTo(6); + assertThat(sw.getFields()).hasSize(6); assertThat(sw.getFields().get(0).getName()).isEqualTo("field0"); assertThat(sw.getFields().get(1).getName()).isEqualTo("field1"); assertThat(sw.getFields().get(2).getName()).isEqualTo("field2"); @@ -610,7 +610,7 @@ public void testMultipleInheritanceWithPosition7() throws Exception { knowledgeBase.addPackages(kBuilder.getKnowledgePackages()); FactType sw = knowledgeBase.getFactType("org.drools.test", "MultiInhPosTrait"); - assertThat(sw.getFields().size()).isEqualTo(6); + assertThat(sw.getFields()).hasSize(6); assertThat(sw.getFields().get(0).getName()).isEqualTo("field0"); assertThat(sw.getFields().get(1).getName()).isEqualTo("field2"); assertThat(sw.getFields().get(2).getName()).isEqualTo("mfield0"); diff --git a/drools-traits/src/test/java/org/drools/traits/core/factmodel/ClassBuilderTest.java b/drools-traits/src/test/java/org/drools/traits/core/factmodel/ClassBuilderTest.java index 1440cdd373b..10f6dffe16f 100755 --- a/drools-traits/src/test/java/org/drools/traits/core/factmodel/ClassBuilderTest.java +++ b/drools-traits/src/test/java/org/drools/traits/core/factmodel/ClassBuilderTest.java @@ -9,8 +9,7 @@ * * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an + * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations @@ -34,9 +33,9 @@ import org.drools.base.factmodel.FieldDefinition; import org.drools.core.rule.JavaDialectRuntimeData; import org.drools.wiring.dynamic.PackageClassLoader; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.drools.wiring.api.classloader.ProjectClassLoader; -import org.junit.Before; -import org.junit.Test; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.fail; @@ -48,7 +47,7 @@ public class ClassBuilderTest { ClassLoader classLoader; JavaDialectRuntimeData data; - @Before + @BeforeEach public void setUp() throws Exception { data = new JavaDialectRuntimeData(); } @@ -75,54 +74,40 @@ private Class build(ClassBuilder builder, ClassDefinition classDef) throws Excep * Test method for 'org.drools.core.common.asm.ClassBuilder.buildClass(ClassDefinition)' */ @Test - public void testBuildClass() { - try { - ClassBuilder builder = new TraitClassBuilderFactory().getBeanClassBuilder(); - - ClassDefinition classDef = new ClassDefinition( "org.drools.TestClass1", - null, - new String[]{"java.io.Serializable"} ); - FieldDefinition intDef = new FieldDefinition("intAttr", - "int" ); - - FieldDefinition stringDef = new FieldDefinition( "stringAttr", - "java.lang.String" );//"java.lang.String" ); - classDef.addField( intDef ); - classDef.addField( stringDef ); - - Class clazz = build(builder, classDef); - - - - intDef.setReadWriteAccessor( store.getAccessor( clazz, - intDef.getName() ) ); - stringDef.setReadWriteAccessor( store.getAccessor( clazz, - stringDef.getName() ) ); - - byte[] d = builder.buildClass( classDef, classLoader ); - - assertThat(clazz).as("Returned class should be the same").isSameAs(classDef.getDefinedClass()); - assertThat(clazz.getName()).as("Class name should be equal").isEqualTo(classDef.getClassName()); - - Serializable instance = (Serializable) clazz.newInstance(); - - String stringValue = "Atributo String ok"; - stringDef.setValue( instance, - stringValue ); - assertThat(stringDef.getValue(instance)).as("Attribute should have been correctly set").isEqualTo(stringValue); - - int intValue = 50; - intDef.setValue( instance, - new Integer( intValue ) ); - assertThat(((Integer) intDef.getValue(instance)).intValue()).as("Attribute should have been correctly set").isEqualTo(intValue); - - // testing class rebuilding - clazz = build(builder, classDef); - - } catch ( Exception e ) { - e.printStackTrace(); - fail( "Error creating class" ); - } + public void testBuildClass() throws Exception { + ClassBuilder builder = new TraitClassBuilderFactory().getBeanClassBuilder(); + + ClassDefinition classDef = new ClassDefinition( "org.drools.TestClass1", null, new String[]{"java.io.Serializable"} ); + FieldDefinition intDef = new FieldDefinition("intAttr", "int" ); + + FieldDefinition stringDef = new FieldDefinition( "stringAttr", "java.lang.String" );//"java.lang.String" ); + classDef.addField( intDef ); + classDef.addField( stringDef ); + + Class clazz = build(builder, classDef); + + + + intDef.setReadWriteAccessor( store.getAccessor( clazz, intDef.getName() ) ); + stringDef.setReadWriteAccessor( store.getAccessor( clazz, stringDef.getName() ) ); + + byte[] d = builder.buildClass( classDef, classLoader ); + + assertThat(clazz).as("Returned class should be the same").isSameAs(classDef.getDefinedClass()); + assertThat(clazz.getName()).as("Class name should be equal").isEqualTo(classDef.getClassName()); + + Serializable instance = (Serializable) clazz.newInstance(); + + String stringValue = "Atributo String ok"; + stringDef.setValue( instance, stringValue ); + assertThat(stringDef.getValue(instance)).as("Attribute should have been correctly set").isEqualTo(stringValue); + + int intValue = 50; + intDef.setValue( instance, new Integer( intValue ) ); + assertThat(((Integer) intDef.getValue(instance)).intValue()).as("Attribute should have been correctly set").isEqualTo(intValue); + + // testing class rebuilding + clazz = build(builder, classDef); } /** @@ -131,8 +116,7 @@ public void testBuildClass() { * @throws FileNotFoundException * @throws IOException */ - private void writeJar(byte[] data) throws FileNotFoundException, - IOException { + private void writeJar(byte[] data) throws FileNotFoundException, IOException { FileOutputStream out = new FileOutputStream("/Users/michaelneale/edson.jar"); JarOutputStream jout = new JarOutputStream( out ); JarEntry je = new JarEntry( "br/com/auster/TestClass1.class" ); @@ -143,363 +127,236 @@ private void writeJar(byte[] data) throws FileNotFoundException, } @Test - public void testEquals() { - try { - ClassBuilder builder = new TraitClassBuilderFactory().getBeanClassBuilder(); - - ClassDefinition classDef = new ClassDefinition( "org.drools.TestClass2", - null, - new String[]{} ); - FieldDefinition long1Def = new FieldDefinition( "longAttr1", - "long", - true ); - FieldDefinition long2Def = new FieldDefinition( "longAttr2", - "long", - true ); - FieldDefinition doubleDef = new FieldDefinition( "doubleAttr", - "double", - true ); - FieldDefinition intDef = new FieldDefinition( "intAttr", - "int", - true ); - FieldDefinition strDef = new FieldDefinition( "stringAttr", - "java.lang.String", - true ); - FieldDefinition dateDef = new FieldDefinition( "dateAttr", - "java.util.Date", - true ); - FieldDefinition str2Def = new FieldDefinition( "stringAttr2", - "java.lang.String" ); - classDef.addField( long1Def ); - classDef.addField( long2Def ); - classDef.addField( doubleDef ); - classDef.addField( intDef ); - classDef.addField( strDef ); - classDef.addField( dateDef ); - classDef.addField( str2Def ); - - Class clazz = build(builder, classDef); - long1Def.setReadWriteAccessor( store.getAccessor( clazz, - long1Def.getName() ) ); - long2Def.setReadWriteAccessor( store.getAccessor( clazz, - long2Def.getName() ) ); - doubleDef.setReadWriteAccessor( store.getAccessor( clazz, - doubleDef.getName() ) ); - intDef.setReadWriteAccessor( store.getAccessor( clazz, - intDef.getName() ) ); - strDef.setReadWriteAccessor( store.getAccessor( clazz, - strDef.getName( ) ) ); - dateDef.setReadWriteAccessor( store.getAccessor( clazz, - dateDef.getName() ) ); - str2Def.setReadWriteAccessor( store.getAccessor( clazz, - str2Def.getName() ) ); - - Object x = clazz.newInstance(); - Object y = clazz.newInstance(); - - long1Def.setValue( x, - Long.valueOf( 20 ) ); - long2Def.setValue( x, - Long.valueOf( 30 ) ); - doubleDef.setValue( x, - Double.valueOf( 50.0 ) ); - intDef.setValue( x, - Integer.valueOf( 10 ) ); - strDef.setValue( x, - "abc" ); - dateDef.setValue( x, - new Date( 1000 ) ); - str2Def.setValue( x, - "instance1" ); - - long1Def.setValue( y, - Long.valueOf( 20 ) ); - long2Def.setValue( y, - Long.valueOf( 30 ) ); - doubleDef.setValue( y, - Double.valueOf( 50.0 ) ); - intDef.setValue( y, - Integer.valueOf( 10 ) ); - strDef.setValue( y, - "abc" ); - dateDef.setValue( y, - new Date( 1000 ) ); - str2Def.setValue( y, - "instance2" ); - - Object o = new Object(); - - assertThat(x.equals(x)).isTrue(); - - assertThat(x.equals(o)).isFalse(); - - assertThat(x.equals(y)).isTrue(); - - intDef.setValue( y, - Integer.valueOf( 1 ) ); - assertThat(x.equals(y)).isFalse(); - - intDef.setValue( y, - Integer.valueOf( 10 ) ); - strDef.setValue( y, - "xyz" ); - assertThat(x.equals(y)).isFalse(); - - strDef.setValue( y, - null ); - assertThat(x.equals(y)).isFalse(); - - strDef.setValue( y, - "abc" ); - dateDef.setValue( y, - new Date( 1 ) ); - assertThat(x.equals(y)).isFalse(); - - dateDef.setValue( y, - null ); - assertThat(x.equals(y)).isFalse(); - - } catch ( Exception e ) { - e.printStackTrace(); - fail( "Exception not expected" ); - } + public void testEquals() throws Exception { + ClassBuilder builder = new TraitClassBuilderFactory().getBeanClassBuilder(); + + ClassDefinition classDef = new ClassDefinition( "org.drools.TestClass2", null, new String[]{} ); + FieldDefinition long1Def = new FieldDefinition( "longAttr1", "long", true ); + FieldDefinition long2Def = new FieldDefinition( "longAttr2", "long", true ); + FieldDefinition doubleDef = new FieldDefinition( "doubleAttr", "double", true ); + FieldDefinition intDef = new FieldDefinition( "intAttr", "int", true ); + FieldDefinition strDef = new FieldDefinition( "stringAttr", "java.lang.String", true ); + FieldDefinition dateDef = new FieldDefinition( "dateAttr", "java.util.Date", true ); + FieldDefinition str2Def = new FieldDefinition( "stringAttr2", "java.lang.String" ); + classDef.addField( long1Def ); + classDef.addField( long2Def ); + classDef.addField( doubleDef ); + classDef.addField( intDef ); + classDef.addField( strDef ); + classDef.addField( dateDef ); + classDef.addField( str2Def ); + + Class clazz = build(builder, classDef); + long1Def.setReadWriteAccessor( store.getAccessor( clazz, long1Def.getName() ) ); + long2Def.setReadWriteAccessor( store.getAccessor( clazz, long2Def.getName() ) ); + doubleDef.setReadWriteAccessor( store.getAccessor( clazz, doubleDef.getName() ) ); + intDef.setReadWriteAccessor( store.getAccessor( clazz, intDef.getName() ) ); + strDef.setReadWriteAccessor( store.getAccessor( clazz, strDef.getName( ) ) ); + dateDef.setReadWriteAccessor( store.getAccessor( clazz, dateDef.getName() ) ); + str2Def.setReadWriteAccessor( store.getAccessor( clazz, str2Def.getName() ) ); + + Object x = clazz.newInstance(); + Object y = clazz.newInstance(); + + long1Def.setValue( x, Long.valueOf( 20 ) ); + long2Def.setValue( x, Long.valueOf( 30 ) ); + doubleDef.setValue( x, Double.valueOf( 50.0 ) ); + intDef.setValue( x, Integer.valueOf( 10 ) ); + strDef.setValue( x, "abc" ); + dateDef.setValue( x, new Date( 1000 ) ); + str2Def.setValue( x, "instance1" ); + + long1Def.setValue( y, Long.valueOf( 20 ) ); + long2Def.setValue( y, Long.valueOf( 30 ) ); + doubleDef.setValue( y, Double.valueOf( 50.0 ) ); + intDef.setValue( y, Integer.valueOf( 10 ) ); + strDef.setValue( y, "abc" ); + dateDef.setValue( y, new Date( 1000 ) ); + str2Def.setValue( y, "instance2" ); + + Object o = new Object(); + + assertThat(x).isEqualTo(x);; + + assertThat(x).isNotEqualTo(o); + + assertThat(x).isEqualTo(y);; + + intDef.setValue( y, Integer.valueOf( 1 ) ); + assertThat(x).isNotEqualTo(y); + + intDef.setValue( y, Integer.valueOf( 10 ) ); + strDef.setValue( y, "xyz" ); + assertThat(x).isNotEqualTo(y); + + strDef.setValue( y, null ); + assertThat(x).isNotEqualTo(y); + + strDef.setValue( y, "abc" ); + dateDef.setValue( y, new Date( 1 ) ); + assertThat(x).isNotEqualTo(y); + + dateDef.setValue( y, null ); + assertThat(x).isNotEqualTo(y); } @Test - public void testHashCode() { - try { - ClassBuilder builder = new TraitClassBuilderFactory().getBeanClassBuilder(); - - ClassDefinition classDef = new ClassDefinition( "org.drools.TestClass3", - null, - new String[]{} ); - FieldDefinition intDef = new FieldDefinition( "intAttr", - "int", - true ); - FieldDefinition strDef = new FieldDefinition( "stringAttr", - "java.lang.String", - false ); - classDef.addField( intDef ); - classDef.addField( strDef ); - - Class clazz = build(builder, classDef); - intDef.setReadWriteAccessor( store.getAccessor( clazz, - intDef.getName() ) ); - strDef.setReadWriteAccessor( store.getAccessor( clazz, - strDef.getName() ) ); - - Object x = clazz.newInstance(); - - intDef.setValue( x, - new Integer( 10 ) ); - strDef.setValue( x, - "abc" ); - - assertThat(x.hashCode()).as("Wrong hashcode calculation").isEqualTo(31 + 10); - assertThat(x.hashCode()).as("Wrong hashcode calculation").isEqualTo(x.hashCode()); - - } catch ( Exception e ) { - e.printStackTrace(); - fail( "Exception not expected" ); - } + public void testHashCode() throws Exception { + ClassBuilder builder = new TraitClassBuilderFactory().getBeanClassBuilder(); + + ClassDefinition classDef = new ClassDefinition( "org.drools.TestClass3", null, new String[]{} ); + FieldDefinition intDef = new FieldDefinition( "intAttr", "int", true ); + FieldDefinition strDef = new FieldDefinition( "stringAttr", "java.lang.String", false ); + classDef.addField( intDef ); + classDef.addField( strDef ); + + Class clazz = build(builder, classDef); + intDef.setReadWriteAccessor( store.getAccessor( clazz, intDef.getName() ) ); + strDef.setReadWriteAccessor( store.getAccessor( clazz, strDef.getName() ) ); + + Object x = clazz.newInstance(); + + intDef.setValue( x, new Integer( 10 ) ); + strDef.setValue( x, "abc" ); + + assertThat(x.hashCode()).as("Wrong hashcode calculation").isEqualTo(31 + 10); + assertThat(x.hashCode()).as("Wrong hashcode calculation").isEqualTo(x.hashCode()); } @Test - public void testToString() { - try { - ClassBuilder builder = new TraitClassBuilderFactory().getBeanClassBuilder(); - - ClassDefinition classDef = new ClassDefinition( "org.drools.TestClass4", - null, - new String[]{} ); - FieldDefinition long1Def = new FieldDefinition( "longAttr1", - "long", - true ); - FieldDefinition long2Def = new FieldDefinition( "longAttr2", - "long", - true ); - FieldDefinition doubleDef = new FieldDefinition( "doubleAttr", - "double", - true ); - FieldDefinition intDef = new FieldDefinition( "intAttr", - "int", - true ); - FieldDefinition strDef = new FieldDefinition( "stringAttr", - "java.lang.String", - true ); - FieldDefinition dateDef = new FieldDefinition( "dateAttr", - "java.util.Date", - true ); - FieldDefinition str2Def = new FieldDefinition( "stringAttr2", - "java.lang.String" ); - classDef.addField( long1Def ); - classDef.addField( long2Def ); - classDef.addField( doubleDef ); - classDef.addField( intDef ); - classDef.addField( strDef ); - classDef.addField( dateDef ); - classDef.addField( str2Def ); - - Class clazz = build(builder, classDef); - long1Def.setReadWriteAccessor( store.getAccessor( clazz, - long1Def.getName() ) ); - long2Def.setReadWriteAccessor( store.getAccessor( clazz, - long2Def.getName() ) ); - doubleDef.setReadWriteAccessor( store.getAccessor( clazz, - doubleDef.getName() ) ); - intDef.setReadWriteAccessor( store.getAccessor( clazz, - intDef.getName() ) ); - strDef.setReadWriteAccessor( store.getAccessor( clazz, - strDef.getName() ) ); - dateDef.setReadWriteAccessor( store.getAccessor( clazz, - dateDef.getName() ) ); - str2Def.setReadWriteAccessor( store.getAccessor( clazz, - str2Def.getName() ) ); - - Object x = clazz.newInstance(); - - long1Def.setValue( x, - new Long( 20 ) ); - long2Def.setValue( x, - new Long( 30 ) ); - doubleDef.setValue( x, - new Double( 50.0 ) ); - intDef.setValue( x, - new Integer( 10 ) ); - strDef.setValue( x, - "abc" ); - dateDef.setValue( x, - new Date( 1000 ) ); - str2Def.setValue( x, - "instance1" ); - - String result = x.toString(); - - assertThat(result.contains(long1Def.getName())).isTrue(); - assertThat(result.contains(long2Def.getName())).isTrue(); - assertThat(result.contains(doubleDef.getName())).isTrue(); - assertThat(result.contains(intDef.getName())).isTrue(); - assertThat(result.contains(strDef.getName())).isTrue(); - assertThat(result.contains(dateDef.getName())).isTrue(); - assertThat(result.contains(str2Def.getName())).isTrue(); - - } catch ( Exception e ) { - e.printStackTrace(); - fail( "Exception not expected" ); - } + public void testToString() throws Exception { + ClassBuilder builder = new TraitClassBuilderFactory().getBeanClassBuilder(); + + ClassDefinition classDef = new ClassDefinition( "org.drools.TestClass4", null, new String[]{} ); + FieldDefinition long1Def = new FieldDefinition( "longAttr1", "long", true ); + FieldDefinition long2Def = new FieldDefinition( "longAttr2", "long", true ); + FieldDefinition doubleDef = new FieldDefinition( "doubleAttr", "double", true ); + FieldDefinition intDef = new FieldDefinition( "intAttr", "int", true ); + FieldDefinition strDef = new FieldDefinition( "stringAttr", "java.lang.String", true ); + FieldDefinition dateDef = new FieldDefinition( "dateAttr", "java.util.Date", true ); + FieldDefinition str2Def = new FieldDefinition( "stringAttr2", "java.lang.String" ); + classDef.addField( long1Def ); + classDef.addField( long2Def ); + classDef.addField( doubleDef ); + classDef.addField( intDef ); + classDef.addField( strDef ); + classDef.addField( dateDef ); + classDef.addField( str2Def ); + + Class clazz = build(builder, classDef); + long1Def.setReadWriteAccessor( store.getAccessor( clazz, long1Def.getName() ) ); + long2Def.setReadWriteAccessor( store.getAccessor( clazz, long2Def.getName() ) ); + doubleDef.setReadWriteAccessor( store.getAccessor( clazz, doubleDef.getName() ) ); + intDef.setReadWriteAccessor( store.getAccessor( clazz, intDef.getName() ) ); + strDef.setReadWriteAccessor( store.getAccessor( clazz, strDef.getName() ) ); + dateDef.setReadWriteAccessor( store.getAccessor( clazz, dateDef.getName() ) ); + str2Def.setReadWriteAccessor( store.getAccessor( clazz, str2Def.getName() ) ); + + Object x = clazz.newInstance(); + + long1Def.setValue( x, new Long( 20 ) ); + long2Def.setValue( x, new Long( 30 ) ); + doubleDef.setValue( x, new Double( 50.0 ) ); + intDef.setValue( x, new Integer( 10 ) ); + strDef.setValue( x, "abc" ); + dateDef.setValue( x, new Date( 1000 ) ); + str2Def.setValue( x, "instance1" ); + + String result = x.toString(); + + assertThat(result).contains(long1Def.getName()); + assertThat(result).contains(long2Def.getName()); + assertThat(result).contains(doubleDef.getName()); + assertThat(result).contains(intDef.getName()); + assertThat(result).contains(strDef.getName()); + assertThat(result).contains(dateDef.getName()); + assertThat(result).contains(str2Def.getName()); } @Test - public void testConstructorWithFields() { - try { - ClassBuilder builder = new TraitClassBuilderFactory().getBeanClassBuilder(); - - ClassDefinition classDef = new ClassDefinition( "org.drools.TestClass5", - null, - new String[]{} ); - - String[] types = new String[]{"byte", "short", "int", "long", "float", "double", "char", "java.lang.String", "boolean"}; - FieldDefinition[] fields = new FieldDefinition[types.length]; - for ( int i = 0; i < types.length; i++ ) { - String attrName = types[i].substring( types[i].lastIndexOf( '.' ) + 1 ); - attrName = attrName.substring( 0, - 1 ).toLowerCase() + attrName.substring( 1 ) + "Attr"; - fields[i] = new FieldDefinition( attrName, // attr name - types[i], // attr type - i % 2 == 0 ); // half of them are key - classDef.addField( fields[i] ); - } - - Class clazz = build(builder, classDef); - - for ( FieldDefinition field : fields ) { - field.setReadWriteAccessor( store.getAccessor( clazz, - field.getName() ) ); - } - - Constructor< ? >[] cons = clazz.getConstructors(); - - assertThat(cons.length).isEqualTo(3); - for ( Constructor< ? > c : cons ) { - Class< ? >[] ptypes = c.getParameterTypes(); - if ( ptypes.length == 0 ) { - // default constructor - } else if ( ptypes.length == fields.length ) { - // constructor with fields - for ( int i = 0; i < ptypes.length; i++ ) { - if ( !ptypes[i].equals( fields[i].getType() ) ) { - fail( "Wrong parameter in constructor. index=" + i + " expected=" + fields[i].getType() + " found=" + ptypes[i] ); - } - } - - // test actual invocation - Object instance = c.newInstance( (byte) 1, - (short) 2, - 3, - 4l, - 5.0f, - 6.0d, - 'a', - "xyz", - true ); - - assertThat(fields[0].getValue(instance)).isEqualTo((byte) 1); - assertThat(fields[1].getValue(instance)).isEqualTo((short) 2); - assertThat(fields[2].getValue(instance)).isEqualTo(3); - assertThat(fields[3].getValue(instance)).isEqualTo(4l); - assertThat(fields[4].getValue(instance)).isEqualTo(5.0f); - assertThat(fields[5].getValue(instance)).isEqualTo(6.0d); - assertThat(fields[6].getValue(instance)).isEqualTo('a'); - assertThat(fields[7].getValue(instance)).isEqualTo("xyz"); - assertThat(fields[8].getValue(instance)).isEqualTo(true); - } else if ( ptypes.length == ( fields.length / 2 +1 ) ) { // as defined in the beginning of the test - // constructor with key fields - int i = 0; - for ( FieldDefinition field : fields ) { - if ( field.isKey() && !ptypes[i++].equals( field.getType() ) ) { - fail( "Wrong parameter in constructor. index=" + i + " expected=" + field.getType() + " found=" + ptypes[i] ); - } - } - // test actual invocation - Object instance = c.newInstance( (byte) 1, - 3, - 5.0f, - 'a', - true ); - - assertThat(fields[0].getValue(instance)).isEqualTo((byte) 1); - assertThat(fields[2].getValue(instance)).isEqualTo(3); - assertThat(fields[4].getValue(instance)).isEqualTo(5.0f); - assertThat(fields[6].getValue(instance)).isEqualTo('a'); - assertThat(fields[8].getValue(instance)).isEqualTo(true); - - } else { - fail( "Unexpected constructor: " + c.toString() ); - } - } - - } catch ( Exception e ) { - e.printStackTrace(); - fail( "Unexpected Exception: " + e.getMessage() ); - } + public void testConstructorWithFields() throws Exception { + ClassBuilder builder = new TraitClassBuilderFactory().getBeanClassBuilder(); + + ClassDefinition classDef = new ClassDefinition( "org.drools.TestClass5", null, new String[]{} ); + + String[] types = new String[]{"byte", "short", "int", "long", "float", "double", "char", "java.lang.String", "boolean"}; + FieldDefinition[] fields = new FieldDefinition[types.length]; + for ( int i = 0; i < types.length; i++ ) { + String attrName = types[i].substring( types[i].lastIndexOf( '.' ) + 1 ); + attrName = attrName.substring( 0, 1 ).toLowerCase() + attrName.substring( 1 ) + "Attr"; + fields[i] = new FieldDefinition( attrName, // attr name + types[i], // attr type + i % 2 == 0 ); // half of them are key + classDef.addField( fields[i] ); + } + + Class clazz = build(builder, classDef); + + for ( FieldDefinition field : fields ) { + field.setReadWriteAccessor( store.getAccessor( clazz, field.getName() ) ); + } + + Constructor< ? >[] cons = clazz.getConstructors(); + + assertThat(cons.length).isEqualTo(3); + for ( Constructor< ? > c : cons ) { + Class< ? >[] ptypes = c.getParameterTypes(); + if ( ptypes.length == 0 ) { + // default constructor + } else if ( ptypes.length == fields.length ) { + // constructor with fields + for ( int i = 0; i < ptypes.length; i++ ) { + if ( !ptypes[i].equals( fields[i].getType() ) ) { + fail( "Wrong parameter in constructor. index=" + i + " expected=" + fields[i].getType() + " found=" + ptypes[i] ); + } + } + + // test actual invocation + Object instance = c.newInstance( (byte) 1, (short) 2, 3, 4l, 5.0f, 6.0d, 'a', "xyz", true ); + + assertThat(fields[0].getValue(instance)).isEqualTo((byte) 1); + assertThat(fields[1].getValue(instance)).isEqualTo((short) 2); + assertThat(fields[2].getValue(instance)).isEqualTo(3); + assertThat(fields[3].getValue(instance)).isEqualTo(4l); + assertThat(fields[4].getValue(instance)).isEqualTo(5.0f); + assertThat(fields[5].getValue(instance)).isEqualTo(6.0d); + assertThat(fields[6].getValue(instance)).isEqualTo('a'); + assertThat(fields[7].getValue(instance)).isEqualTo("xyz"); + assertThat(fields[8].getValue(instance)).isEqualTo(true); + } else if ( ptypes.length == ( fields.length / 2 +1 ) ) { // as defined in the beginning of the test + // constructor with key fields + int i = 0; + for ( FieldDefinition field : fields ) { + if ( field.isKey() && !ptypes[i++].equals( field.getType() ) ) { + fail( "Wrong parameter in constructor. index=" + i + " expected=" + field.getType() + " found=" + ptypes[i] ); + } + } + // test actual invocation + Object instance = c.newInstance( (byte) 1, 3, 5.0f, 'a', true ); + + assertThat(fields[0].getValue(instance)).isEqualTo((byte) 1); + assertThat(fields[2].getValue(instance)).isEqualTo(3); + assertThat(fields[4].getValue(instance)).isEqualTo(5.0f); + assertThat(fields[6].getValue(instance)).isEqualTo('a'); + assertThat(fields[8].getValue(instance)).isEqualTo(true); + + } else { + fail( "Unexpected constructor: " + c.toString() ); + } + } } @Test - public void testGetResourcesJBRULES3122() { - try { - ClassBuilder builder = new TraitClassBuilderFactory().getBeanClassBuilder(); - - ClassDefinition classDef = new ClassDefinition("org.drools.TestClass4", null, new String[] {}); - Class clazz = build(builder, classDef); - ClassLoader cl = clazz.getClassLoader(); - - // We expect normal classloader stuff to work - assertThat(cl.getResources("not-there.txt").hasMoreElements()).isFalse(); - } catch (Exception e) { - e.printStackTrace(); - fail("Exception not expected: " + e.getMessage()); - } + public void testGetResourcesJBRULES3122() throws Exception { + ClassBuilder builder = new TraitClassBuilderFactory().getBeanClassBuilder(); + + ClassDefinition classDef = new ClassDefinition("org.drools.TestClass4", null, new String[] {}); + Class clazz = build(builder, classDef); + ClassLoader cl = clazz.getClassLoader(); + + // We expect normal classloader stuff to work + assertThat(cl.getResources("not-there.txt").hasMoreElements()).isFalse(); } } diff --git a/drools-traits/src/test/java/org/drools/traits/core/factmodel/InstancesHashcodedTest.java b/drools-traits/src/test/java/org/drools/traits/core/factmodel/InstancesHashcodedTest.java index 7e04e9e46a4..c33ad8e600c 100755 --- a/drools-traits/src/test/java/org/drools/traits/core/factmodel/InstancesHashcodedTest.java +++ b/drools-traits/src/test/java/org/drools/traits/core/factmodel/InstancesHashcodedTest.java @@ -28,8 +28,8 @@ import org.drools.base.factmodel.FieldDefinition; import org.drools.core.rule.JavaDialectRuntimeData; import org.drools.wiring.dynamic.PackageClassLoader; +import org.junit.jupiter.api.Test; import org.drools.wiring.api.classloader.ProjectClassLoader; -import org.junit.Test; import static org.drools.util.ClassUtils.convertClassToResourcePath; diff --git a/drools-traits/src/test/java/org/drools/traits/core/factmodel/JeneratorTest.java b/drools-traits/src/test/java/org/drools/traits/core/factmodel/JeneratorTest.java index fd656cfb569..134ad78c190 100644 --- a/drools-traits/src/test/java/org/drools/traits/core/factmodel/JeneratorTest.java +++ b/drools-traits/src/test/java/org/drools/traits/core/factmodel/JeneratorTest.java @@ -22,7 +22,7 @@ import java.util.jar.JarEntry; import java.util.jar.JarInputStream; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; diff --git a/drools-traits/src/test/java/org/drools/traits/core/factmodel/TripleStoreTest.java b/drools-traits/src/test/java/org/drools/traits/core/factmodel/TripleStoreTest.java index 6626e0771f6..288f463b008 100644 --- a/drools-traits/src/test/java/org/drools/traits/core/factmodel/TripleStoreTest.java +++ b/drools-traits/src/test/java/org/drools/traits/core/factmodel/TripleStoreTest.java @@ -23,7 +23,7 @@ import java.util.Collection; import java.util.List; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.kie.api.runtime.rule.Variable; import static org.assertj.core.api.Assertions.assertThat; @@ -183,31 +183,30 @@ public void testQueryVariable() { tKey = new TripleImpl( V, "hasCity", V ); coll = store.getAll(tKey); - assertThat(coll.containsAll(Arrays.asList(t3, t4))).isTrue(); - assertThat(coll.size()).isEqualTo(2); - + assertThat(coll).hasSize(2); + assertThat(coll).containsExactlyInAnyOrder(t3, t4); tKey = new TripleImpl( ind, V, V ); coll = store.getAll(tKey); - assertThat(coll.containsAll(Arrays.asList(t1, t2, t3))).isTrue(); - assertThat(coll.size()).isEqualTo(3); + assertThat(coll).hasSize(3); + assertThat(coll).containsExactlyInAnyOrder(t1, t2, t3); tKey = new TripleImpl( ind2, V, "lancia" ); coll = store.getAll(tKey); - assertThat(coll.containsAll(Arrays.asList(t5, t6))).isTrue(); - assertThat(coll.size()).isEqualTo(2); + assertThat(coll).hasSize(2); + assertThat(coll).containsExactlyInAnyOrder(t5, t6); tKey = new TripleImpl( V, V, "lancia" ); coll = store.getAll(tKey); - assertThat(coll.containsAll(Arrays.asList(t5, t6))).isTrue(); - assertThat(coll.size()).isEqualTo(2); + assertThat(coll).hasSize(2); + assertThat(coll).containsExactlyInAnyOrder(t5, t6); tKey = new TripleImpl( V, V, V ); coll = store.getAll(tKey); - assertThat(coll.containsAll(Arrays.asList(t1, t2, t3, t4, t5, t6))).isTrue(); - assertThat(coll.size()).isEqualTo(6); + assertThat(coll).hasSize(6); + assertThat(coll).containsExactlyInAnyOrder(t1, t2, t3, t4, t5, t6); } @@ -245,14 +244,13 @@ public void testAddNary() { Triple tKey; - Triple t; Collection coll; tKey = new TripleImpl( ind, "hasName", V ); coll = store.getAll(tKey); - assertThat(coll.containsAll(Arrays.asList(new TripleImpl(ind, "hasName", "oscar"), + assertThat(coll).containsExactlyInAnyOrder(new TripleImpl(ind, "hasName", "oscar"), new TripleImpl(ind, "hasName", "mark"), - new TripleImpl(ind, "hasName", "daniel")))).isTrue(); + new TripleImpl(ind, "hasName", "daniel")); assertThat(store.contains(new TripleImpl(ind, "hasName", "marc"))).isFalse(); assertThat(store.contains(new TripleImpl(ind, "hasName", "mark"))).isTrue(); @@ -265,20 +263,20 @@ public void testAddNary() { tKey = new TripleImpl( ind, "hasCar", V ); coll = store.getAll(tKey); - assertThat(coll.containsAll(Arrays.asList(new TripleImpl(ind, "hasCar", "mini"), - new TripleImpl(ind, "hasCar", "ferrari")))).isTrue(); + assertThat(coll).containsExactlyInAnyOrder(new TripleImpl(ind, "hasCar", "mini"), + new TripleImpl(ind, "hasCar", "ferrari")); store.remove( new TripleImpl(ind, "hasCar", "mini") ); tKey = new TripleImpl( ind, "hasCar", V ); coll = store.getAll(tKey); - assertThat(coll.size()).isEqualTo(1); + assertThat(coll).hasSize(1); store.remove( new TripleImpl(ind, "hasCar", "ferrari") ); tKey = new TripleImpl( ind, "hasCar", V ); coll = store.getAll(tKey); - assertThat(coll.size()).isEqualTo(0); + assertThat(coll).isEmpty(); } diff --git a/drools-traits/src/test/java/org/drools/traits/core/meta/org/MetadataTest.java b/drools-traits/src/test/java/org/drools/traits/core/meta/org/MetadataTest.java index 6a40cc460c5..4f454dd3283 100644 --- a/drools-traits/src/test/java/org/drools/traits/core/meta/org/MetadataTest.java +++ b/drools-traits/src/test/java/org/drools/traits/core/meta/org/MetadataTest.java @@ -40,7 +40,7 @@ import org.drools.traits.core.metadata.Lit; import org.drools.traits.core.metadata.MetadataContainer; import org.drools.traits.core.metadata.With; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -103,7 +103,7 @@ public void testKlassAndSubKlassWithInterfaces() { assertThat(sk.prop.get(ski)).isEqualTo("bye"); LOGGER.debug( ski.map.toString()); - Map tgt = new HashMap(); + Map tgt = new HashMap<>(); tgt.put( "prop", "bye" ); tgt.put( "subProp", -99 ); assertThat(ski.map).isEqualTo(tgt); @@ -183,7 +183,7 @@ public void testURIs() { assertThat(AnotherKlass_.modify(aki).num(33).getUri()).isEqualTo(URI.create(uri.toString() + "/modify?num")); - assertThat(uri.toString().startsWith(aki.get_().getMetaClassInfo().getUri().toString())).isTrue(); + assertThat(uri.toString()).startsWith(aki.get_().getMetaClassInfo().getUri().toString()); assertThat(SubKlass_.newSubKlass(URI.create("http://www.test.org#SubKlass/123")).getUri()).isEqualTo(URI.create("http://www.test.org#SubKlass/123?create")); @@ -195,7 +195,7 @@ public void testURIs() { public void testNewInstance() { Klass klass = Klass_.newKlass( URI.create( "test" ) ).call(); assertThat(klass).isNotNull(); - assertThat(klass instanceof KlassImpl).isTrue(); + assertThat(klass).isInstanceOf(KlassImpl.class); SubKlass klass2 = SubKlass_.newSubKlass( URI.create( "test2" ) ).subProp( 42 ).prop( "hello" ).call(); @@ -215,7 +215,7 @@ public void testURIsOnLegacyClasses() { @Test public void testDon() { Entity entity = new Entity( "123" ); - entity._setDynamicProperties( new HashMap( ) ); + entity._setDynamicProperties( new HashMap<>( ) ); entity._getDynamicProperties().put( "prop", "hello" ); Klass klass = Klass_.donKlass( entity ) @@ -229,7 +229,7 @@ public void testDon() { @Test public void testDonWithAttributes() { Entity entity = new Entity( "123" ); - entity._setDynamicProperties( new HashMap() ); + entity._setDynamicProperties( new HashMap<>() ); SubKlass klass = SubKlass_.donSubKlass(entity ) .setTraitFactory(createStandaloneTraitFactory()) @@ -259,7 +259,7 @@ public void testCollectionOrientedProperties() { AnotherKlass aki3 = AnotherKlass_.newAnotherKlass( "003" ).call(); AnotherKlass aki4 = AnotherKlass_.newAnotherKlass( "004" ).call(); - ArrayList initial = new ArrayList( Arrays.asList( aki0, aki1 ) ); + List initial = new ArrayList<>( List.of( aki0, aki1 ) ); SubKlass ski = SubKlass_.newSubKlass( URI.create( "123" ) ) .links( initial, Lit.SET ) .links( aki1, Lit.REMOVE ) @@ -311,14 +311,13 @@ public void testOneToManyProperty() { assertThat(klass1.getOneAnother()).isSameAs(aki2); assertThat(klass2.getOneAnother()).isSameAs(aki); - assertThat(aki.getManyKlasses().contains(klass1)).isFalse(); - assertThat(aki2.getManyKlasses().contains(klass1)).isTrue(); - assertThat(aki.getManyKlasses().contains(klass2)).isTrue(); + assertThat(aki.getManyKlasses()).doesNotContain(klass1); + assertThat(aki2.getManyKlasses()).contains(klass1).doesNotContain(klass2); AnotherKlass_.modify( aki2 ).manyKlasses( klass1, Lit.REMOVE ).call(); assertThat(klass1.getOneAnother()).isNull(); - assertThat(aki2.getManyKlasses().contains(klass1)).isFalse(); + assertThat(aki2.getManyKlasses()).doesNotContain(klass1); } @@ -362,51 +361,35 @@ public void testManyToManyProperty() { AnotherKlass_.modify( aki2 ).manyMoreKlasses( klass2, Lit.ADD ).call(); AnotherKlass_.modify( aki1 ).manyMoreKlasses( klass2, Lit.ADD ).call(); - assertThat(klass1.getManyAnothers().contains(aki1)).isTrue(); - assertThat(klass1.getManyAnothers().contains(aki2)).isTrue(); - assertThat(klass2.getManyAnothers().contains(aki1)).isTrue(); - assertThat(klass2.getManyAnothers().contains(aki2)).isTrue(); + assertThat(klass1.getManyAnothers()).contains(aki1, aki2); + assertThat(klass2.getManyAnothers()).contains(aki1, aki2); - assertThat(aki1.getManyMoreKlasses().contains(klass1)).isTrue(); - assertThat(aki1.getManyMoreKlasses().contains(klass2)).isTrue(); - assertThat(aki2.getManyMoreKlasses().contains(klass1)).isTrue(); - assertThat(aki2.getManyMoreKlasses().contains(klass2)).isTrue(); + assertThat(aki1.getManyMoreKlasses()).contains(klass1, klass2); + assertThat(aki2.getManyMoreKlasses()).contains(klass1, klass2); AnotherKlass_.modify( aki2 ).manyMoreKlasses( klass2, Lit.REMOVE ).call(); - assertThat(klass1.getManyAnothers().contains(aki1)).isTrue(); - assertThat(klass1.getManyAnothers().contains(aki2)).isTrue(); - assertThat(klass2.getManyAnothers().contains(aki1)).isTrue(); - assertThat(klass2.getManyAnothers().contains(aki2)).isFalse(); + assertThat(klass1.getManyAnothers()).contains(aki1, aki2); + assertThat(klass2.getManyAnothers()).contains(aki1).doesNotContain(aki2); - assertThat(aki1.getManyMoreKlasses().contains(klass1)).isTrue(); - assertThat(aki1.getManyMoreKlasses().contains(klass2)).isTrue(); - assertThat(aki2.getManyMoreKlasses().contains(klass1)).isTrue(); - assertThat(aki2.getManyMoreKlasses().contains(klass2)).isFalse(); + assertThat(aki1.getManyMoreKlasses()).contains(klass1, klass2); + assertThat(aki2.getManyMoreKlasses()).contains(klass1).doesNotContain(klass2); AnotherKlass_.modify( aki2 ).manyMoreKlasses( klass2, Lit.ADD ).call(); - assertThat(klass1.getManyAnothers().contains(aki1)).isTrue(); - assertThat(klass1.getManyAnothers().contains(aki2)).isTrue(); - assertThat(klass2.getManyAnothers().contains(aki1)).isTrue(); - assertThat(klass2.getManyAnothers().contains(aki2)).isTrue(); + assertThat(klass1.getManyAnothers()).contains(aki1, aki2); + assertThat(klass2.getManyAnothers()).contains(aki1, aki2); - assertThat(aki1.getManyMoreKlasses().contains(klass1)).isTrue(); - assertThat(aki1.getManyMoreKlasses().contains(klass2)).isTrue(); - assertThat(aki2.getManyMoreKlasses().contains(klass1)).isTrue(); - assertThat(aki2.getManyMoreKlasses().contains(klass2)).isTrue(); + assertThat(aki1.getManyMoreKlasses()).contains(klass1, klass2); + assertThat(aki2.getManyMoreKlasses()).contains(klass1, klass2); AnotherKlass_.modify( aki2 ).manyMoreKlasses( klass2, Lit.SET ).call(); - assertThat(klass1.getManyAnothers().contains(aki1)).isTrue(); - assertThat(klass1.getManyAnothers().contains(aki2)).isFalse(); - assertThat(klass2.getManyAnothers().contains(aki1)).isTrue(); - assertThat(klass2.getManyAnothers().contains(aki2)).isTrue(); + assertThat(klass1.getManyAnothers()).contains(aki1).doesNotContain(aki2); + assertThat(klass2.getManyAnothers()).contains(aki1, aki2); - assertThat(aki1.getManyMoreKlasses().contains(klass1)).isTrue(); - assertThat(aki1.getManyMoreKlasses().contains(klass2)).isTrue(); - assertThat(aki2.getManyMoreKlasses().contains(klass1)).isFalse(); - assertThat(aki2.getManyMoreKlasses().contains(klass2)).isTrue(); + assertThat(aki1.getManyMoreKlasses()).contains(klass1, klass2); + assertThat(aki2.getManyMoreKlasses()).doesNotContain(klass1).contains(klass2); } diff --git a/drools-traits/src/test/java/org/drools/traits/core/util/HierarchyTest.java b/drools-traits/src/test/java/org/drools/traits/core/util/HierarchyTest.java index d460cfd45d5..94c7d520aea 100644 --- a/drools-traits/src/test/java/org/drools/traits/core/util/HierarchyTest.java +++ b/drools-traits/src/test/java/org/drools/traits/core/util/HierarchyTest.java @@ -21,7 +21,7 @@ import org.drools.traits.core.factmodel.CodedHierarchy; import org.drools.traits.core.factmodel.HierarchyEncoder; import org.drools.traits.core.factmodel.IndexedTypeHierarchy; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -41,9 +41,9 @@ public class HierarchyTest { @Test public void testHierEncoderTrivial() { - HierarchyEncoder encoder = new HierarchyEncoderImpl(); + HierarchyEncoder encoder = new HierarchyEncoderImpl<>(); - encoder.encode( "A", Collections.EMPTY_LIST ); + encoder.encode( "A", Collections.emptyList()); encoder.encode("B", List.of("A")); encoder.encode("C", List.of("B")); encoder.encode( "D", Arrays.asList( "B", "C" ) ); @@ -58,13 +58,13 @@ public void testHierEncoderTrivial() { @Test public void testHierManyRoots() { - HierarchyEncoder encoder = new HierarchyEncoderImpl(); + HierarchyEncoder encoder = new HierarchyEncoderImpl<>(); - encoder.encode( "A", Collections.EMPTY_LIST ); - encoder.encode( "B", Collections.EMPTY_LIST ); - encoder.encode( "C", Collections.EMPTY_LIST ); - encoder.encode( "D", Collections.EMPTY_LIST ); - encoder.encode( "E", Collections.EMPTY_LIST ); + encoder.encode( "A", Collections.emptyList()); + encoder.encode( "B", Collections.emptyList()); + encoder.encode( "C", Collections.emptyList()); + encoder.encode( "D", Collections.emptyList()); + encoder.encode( "E", Collections.emptyList()); LOGGER.debug( encoder.toString() ); @@ -75,21 +75,21 @@ public void testHierManyRoots() { assertThat(encoder.getCode("E")).isEqualTo(parseBitSet("10000")); assertThat(encoder.size()).isEqualTo(5); - assertThat(encoder.getSortedMembers().size()).isEqualTo(5); - assertThat(encoder.getSortedMap().size()).isEqualTo(5); + assertThat(encoder.getSortedMembers()).hasSize(5); + assertThat(encoder.getSortedMap()).hasSize(5); } @Test public void testHierManyRootsPropagation() { - HierarchyEncoderImpl encoder = new HierarchyEncoderImpl(); + HierarchyEncoderImpl encoder = new HierarchyEncoderImpl<>(); - encoder.encode( "A", Collections.EMPTY_LIST ); + encoder.encode( "A", Collections.emptyList()); encoder.encode("B", List.of("A")); encoder.encode("C", List.of("A")); encoder.encode( "D", Arrays.asList( "B", "C" ) ); - encoder.encode( "E", Collections.EMPTY_LIST ); + encoder.encode( "E", Collections.emptyList()); LOGGER.debug( encoder.toString() ); @@ -99,27 +99,27 @@ public void testHierManyRootsPropagation() { BitSet d = encoder.getCode( "D" ); BitSet e = encoder.getCode( "E" ); - assertThat(encoder.superset(b, a) > 0).isTrue(); - assertThat(encoder.superset(c, a) > 0).isTrue(); - assertThat(encoder.superset(d, a) > 0).isTrue(); - assertThat(encoder.superset(d, b) > 0).isTrue(); - assertThat(encoder.superset(d, c) > 0).isTrue(); + assertThat(encoder.superset(b, a)).isGreaterThan(0); + assertThat(encoder.superset(c, a)).isGreaterThan(0); + assertThat(encoder.superset(d, a)).isGreaterThan(0); + assertThat(encoder.superset(d, b)).isGreaterThan(0); + assertThat(encoder.superset(d, c)).isGreaterThan(0); - assertThat(encoder.superset(e, a) < 0).isTrue(); - assertThat(encoder.superset(e, b) < 0).isTrue(); - assertThat(encoder.superset(e, c) < 0).isTrue(); - assertThat(encoder.superset(e, d) < 0).isTrue(); - assertThat(encoder.superset(e, e) == 0).isTrue(); + assertThat(encoder.superset(e, a)).isLessThan(0); + assertThat(encoder.superset(e, b)).isLessThan(0); + assertThat(encoder.superset(e, c)).isLessThan(0); + assertThat(encoder.superset(e, d)).isLessThan(0); + assertThat(encoder.superset(e, e)).isEqualTo(0); } @Test public void testHierALotOfClasses() { - HierarchyEncoder encoder = new HierarchyEncoderImpl(); + HierarchyEncoder encoder = new HierarchyEncoderImpl<>(); int N = 1194; - encoder.encode( "A", Collections.EMPTY_LIST ); + encoder.encode( "A", Collections.emptyList()); for ( int j = 1; j < N; j++ ) { encoder.encode( "X" + j, List.of("A")); } @@ -134,9 +134,9 @@ public void testHierALotOfClasses() { @Test public void testHierEncoderSimpleInheritance() { - HierarchyEncoder encoder = new HierarchyEncoderImpl(); + HierarchyEncoder encoder = new HierarchyEncoderImpl<>(); - encoder.encode( "A", Collections.EMPTY_LIST ); + encoder.encode( "A", Collections.emptyList()); encoder.encode("B", List.of("A")); encoder.encode("C", List.of("A")); encoder.encode("D", List.of("B")); @@ -160,9 +160,9 @@ public void testHierEncoderSimpleInheritance() { @Test public void testHierEncoderAnotherSimpleInheritance() { - HierarchyEncoder encoder = new HierarchyEncoderImpl(); + HierarchyEncoder encoder = new HierarchyEncoderImpl<>(); - encoder.encode( "R", Collections.EMPTY_LIST ); + encoder.encode( "R", Collections.emptyList()); encoder.encode("A1", List.of("R")); encoder.encode("A2", List.of("R")); encoder.encode("A3", List.of("R")); @@ -193,9 +193,9 @@ public void testHierEncoderAnotherSimpleInheritance() { @Test public void testHierEncoderAnotherSimpleInheritanceChangeOrder() { - HierarchyEncoder encoder = new HierarchyEncoderImpl(); + HierarchyEncoder encoder = new HierarchyEncoderImpl<>(); - encoder.encode( "R", Collections.EMPTY_LIST ); + encoder.encode( "R", Collections.emptyList()); encoder.encode("B1", List.of("R")); encoder.encode("B2", List.of("R")); @@ -233,9 +233,9 @@ public void testHierEncoderAnotherSimpleInheritanceChangeOrder() { @Test public void testHierEncoderBipartiteInheritance() { - HierarchyEncoder encoder = new HierarchyEncoderImpl(); + HierarchyEncoder encoder = new HierarchyEncoderImpl<>(); - encoder.encode( "R", Collections.EMPTY_LIST ); + encoder.encode( "R", Collections.emptyList()); encoder.encode("A1", List.of("R")); encoder.encode("A2", List.of("R")); encoder.encode("A3", List.of("R")); @@ -263,9 +263,9 @@ public void testHierEncoderBipartiteInheritance() { @Test public void testHierEncoderBipartiteInheritanceDiffOrder() { - HierarchyEncoder encoder = new HierarchyEncoderImpl(); + HierarchyEncoder encoder = new HierarchyEncoderImpl<>(); - encoder.encode( "R", Collections.EMPTY_LIST ); + encoder.encode( "R", Collections.emptyList()); encoder.encode("B1", List.of("R")); encoder.encode("B2", List.of("R")); @@ -296,9 +296,9 @@ public void testHierEncoderBipartiteInheritanceDiffOrder() { @Test public void testSquare() { - HierarchyEncoder encoder = new HierarchyEncoderImpl(); + HierarchyEncoder encoder = new HierarchyEncoderImpl<>(); - encoder.encode( "T", Collections.EMPTY_LIST ); + encoder.encode( "T", Collections.emptyList()); encoder.encode("A", List.of("T")); encoder.encode("B", List.of("T")); encoder.encode( "C", Arrays.asList( "A", "B" ) ); @@ -319,9 +319,9 @@ public void testSquare() { @Test public void testConflictArising() { - HierarchyEncoder encoder = new HierarchyEncoderImpl(); + HierarchyEncoder encoder = new HierarchyEncoderImpl<>(); - encoder.encode( "A", Collections.EMPTY_LIST ); + encoder.encode( "A", Collections.emptyList()); encoder.encode("B", List.of("A")); encoder.encode("C", List.of("A")); encoder.encode("D", List.of("B")); @@ -362,9 +362,9 @@ public void testConflictArising() { @Test public void testConflictArising2() { - HierarchyEncoder encoder = new HierarchyEncoderImpl(); + HierarchyEncoder encoder = new HierarchyEncoderImpl<>(); - encoder.encode( "A", Collections.EMPTY_LIST ); + encoder.encode( "A", Collections.emptyList()); encoder.encode("B", List.of("A")); encoder.encode("C", List.of("A")); encoder.encode("D", List.of("B")); @@ -391,9 +391,9 @@ public void testConflictArising2() { @Test public void testHierEncoderBipartiteStarInheritance() { - HierarchyEncoder encoder = new HierarchyEncoderImpl(); + HierarchyEncoder encoder = new HierarchyEncoderImpl<>(); - encoder.encode( "R", Collections.EMPTY_LIST ); + encoder.encode( "R", Collections.emptyList()); encoder.encode("B1", List.of("R")); encoder.encode("B2", List.of("R")); @@ -434,9 +434,9 @@ public void testHierEncoderBipartiteStarInheritance() { @Test public void testHierEncoderBipartiteStarInheritanceDiffOrder() { - HierarchyEncoder encoder = new HierarchyEncoderImpl(); + HierarchyEncoder encoder = new HierarchyEncoderImpl<>(); - encoder.encode( "R", Collections.EMPTY_LIST ); + encoder.encode( "R", Collections.emptyList()); encoder.encode("A1", List.of("R")); encoder.encode("A2", List.of("R")); @@ -491,9 +491,9 @@ private BitSet parseBitSet( String s ) { @Test public void testHierEncoderComplexInheritance() { - HierarchyEncoder encoder = new HierarchyEncoderImpl(); + HierarchyEncoder encoder = new HierarchyEncoderImpl<>(); - encoder.encode( "A", Collections.EMPTY_LIST ); + encoder.encode( "A", Collections.emptyList()); checkHier( encoder, 'A' ); encoder.encode("B", List.of("A")); @@ -547,7 +547,7 @@ public void testHierEncoderComplexInheritance() { BitSet ns = iter.next(); Long next = toLong( ns ); LOGGER.debug( next.toString() ); - assertThat(next > last).isTrue(); + assertThat(next).isGreaterThan(last); last = next; } } @@ -562,12 +562,12 @@ private Long toLong( BitSet ns ) { return l; } - private void checkHier( HierarchyEncoder encoder, char fin ) { + private void checkHier( HierarchyEncoder encoder, char fin ) { List[] sups = new ArrayList[ fin - 'A' + 1 ]; for ( int j = 'A'; j <= fin; j++ ) { - sups[ j - 'A' ] = ((HierarchyEncoderImpl) encoder).ancestorValues( "" + (char) j ); + sups[ j - 'A' ] = ((HierarchyEncoderImpl) encoder).ancestorValues( "" + (char) j ); }; for ( int j = 'A' ; j < 'A' + sups.length ; j++ ) { @@ -577,7 +577,7 @@ private void checkHier( HierarchyEncoder encoder, char fin ) { BitSet xcode = encoder.getCode( x ); BitSet ycode = encoder.getCode( y ); - int subOf = ((HierarchyEncoderImpl) encoder).superset(xcode, ycode); + int subOf = ((HierarchyEncoderImpl) encoder).superset(xcode, ycode); if ( x.equals( y ) ) { assertThat(subOf).as(x + " vs " + y).isEqualTo(0); @@ -600,9 +600,9 @@ private void checkHier( HierarchyEncoder encoder, char fin ) { @Test public void testHierEncoderMoreInheritance() { - HierarchyEncoderImpl encoder = new HierarchyEncoderImpl(); + HierarchyEncoderImpl encoder = new HierarchyEncoderImpl<>(); - encoder.encode( "A", Collections.EMPTY_LIST ); + encoder.encode( "A", Collections.emptyList()); encoder.encode("B", List.of("A")); encoder.encode("C", List.of("A")); encoder.encode("D", List.of("A")); @@ -656,9 +656,9 @@ public void testHierEncoderMoreInheritance() { @Test public void testSecondOrderInheritance() { - HierarchyEncoder encoder = new HierarchyEncoderImpl(); + HierarchyEncoder encoder = new HierarchyEncoderImpl<>(); - encoder.encode( "T", Collections.EMPTY_LIST ); + encoder.encode( "T", Collections.emptyList()); encoder.encode("A", List.of("T")); encoder.encode("B", List.of("T")); encoder.encode("C", List.of("T")); @@ -672,8 +672,8 @@ public void testSecondOrderInheritance() { LOGGER.debug( encoder.toString() ); - assertThat(((HierarchyEncoderImpl) encoder).superset(encoder.getCode("Z"), encoder.getCode("F")) < 0).isTrue() ; - assertThat(((HierarchyEncoderImpl) encoder).superset(encoder.getCode("F"), encoder.getCode("Z")) < 0).isTrue() ; + assertThat(((HierarchyEncoderImpl) encoder).superset(encoder.getCode("Z"), encoder.getCode("F"))).isLessThan(0); + assertThat(((HierarchyEncoderImpl) encoder).superset(encoder.getCode("F"), encoder.getCode("Z"))).isLessThan(0); } @@ -682,9 +682,9 @@ public void testSecondOrderInheritance() { @Test public void testDecoderAncestors() { - HierarchyEncoder encoder = new HierarchyEncoderImpl(); + HierarchyEncoder encoder = new HierarchyEncoderImpl<>(); - encoder.encode( "Thing", Collections.EMPTY_LIST ); + encoder.encode( "Thing", Collections.emptyList()); encoder.encode("A", List.of("Thing")); encoder.encode("Z", List.of("Thing")); encoder.encode( "B", Arrays.asList( "A", "Z" ) ); @@ -701,96 +701,96 @@ public void testDecoderAncestors() { LOGGER.debug( encoder.toString() ); BitSet b; - Collection x; + Collection x; b = parseBitSet( "1100111" ); x = encoder.upperAncestors(b); LOGGER.debug( "ANC " + x ); - assertThat(x.contains("A")).isTrue(); - assertThat(x.contains("Z")).isTrue(); - assertThat(x.contains("C")).isTrue(); - assertThat(x.contains("Q")).isTrue(); - assertThat(x.contains("T")).isTrue(); - assertThat(x.contains("R")).isTrue(); - assertThat(x.contains("S")).isTrue(); - assertThat(x.contains("M")).isTrue(); - assertThat(x.contains("Thing")).isTrue(); - assertThat(x.size()).isEqualTo(9); + assertThat(x).contains("A"); + assertThat(x).contains("Z"); + assertThat(x).contains("C"); + assertThat(x).contains("Q"); + assertThat(x).contains("T"); + assertThat(x).contains("R"); + assertThat(x).contains("S"); + assertThat(x).contains("M"); + assertThat(x).contains("Thing"); + assertThat(x).hasSize(9); b = parseBitSet( "100000" ); x = encoder.upperAncestors(b); LOGGER.debug( "ANC " + x ); - assertThat(x.size()).isEqualTo(2); - assertThat(x.contains("Q")).isTrue(); - assertThat(x.contains("Thing")).isTrue(); + assertThat(x).hasSize(2); + assertThat(x).contains("Q"); + assertThat(x).contains("Thing"); b = parseBitSet( "1111" ); x = encoder.upperAncestors(b); LOGGER.debug( "ANC " + x ); - assertThat(x.size()).isEqualTo(6); - assertThat(x.contains("A")).isTrue(); - assertThat(x.contains("Z")).isTrue(); - assertThat(x.contains("B")).isTrue(); - assertThat(x.contains("C")).isTrue(); - assertThat(x.contains("N")).isTrue(); - assertThat(x.contains("Thing")).isTrue(); + assertThat(x).hasSize(6); + assertThat(x).contains("A"); + assertThat(x).contains("Z"); + assertThat(x).contains("B"); + assertThat(x).contains("C"); + assertThat(x).contains("N"); + assertThat(x).contains("Thing"); b = parseBitSet( "111" ); x = encoder.upperAncestors(b); LOGGER.debug( "ANC " + x ); - assertThat(x.size()).isEqualTo(4); - assertThat(x.contains("A")).isTrue(); - assertThat(x.contains("Z")).isTrue(); - assertThat(x.contains("C")).isTrue(); - assertThat(x.contains("Thing")).isTrue(); + assertThat(x).hasSize(4); + assertThat(x).contains("A"); + assertThat(x).contains("Z"); + assertThat(x).contains("C"); + assertThat(x).contains("Thing"); b = parseBitSet( "1" ); x = encoder.upperAncestors(b); LOGGER.debug( "ANC " + x ); - assertThat(x.size()).isEqualTo(2); - assertThat(x.contains("A")).isTrue(); - assertThat(x.contains("Thing")).isTrue(); + assertThat(x).hasSize(2); + assertThat(x).contains("A"); + assertThat(x).contains("Thing"); b = parseBitSet( "10" ); x = encoder.upperAncestors(b); LOGGER.debug( "ANC " + x ); - assertThat(x.size()).isEqualTo(2); - assertThat(x.contains("Z")).isTrue(); - assertThat(x.contains("Thing")).isTrue(); + assertThat(x).hasSize(2); + assertThat(x).contains("Z"); + assertThat(x).contains("Thing"); b = parseBitSet( "0" ); x = encoder.upperAncestors(b); LOGGER.debug( "ANC " + x ); - assertThat(x.size()).isEqualTo(1); - assertThat(x.contains("Thing")).isTrue(); + assertThat(x).hasSize(1); + assertThat(x).contains("Thing"); b = parseBitSet( "1011" ); x = encoder.upperAncestors(b); LOGGER.debug( "ANC " + x ); - assertThat(x.size()).isEqualTo(4); - assertThat(x.contains("Thing")).isTrue(); - assertThat(x.contains("A")).isTrue(); - assertThat(x.contains("B")).isTrue(); - assertThat(x.contains("Z")).isTrue(); + assertThat(x).hasSize(4); + assertThat(x).contains("Thing"); + assertThat(x).contains("A"); + assertThat(x).contains("B"); + assertThat(x).contains("Z"); } @Test public void testDecoderDescendants() { - HierarchyEncoder encoder = new HierarchyEncoderImpl(); + HierarchyEncoder encoder = new HierarchyEncoderImpl<>(); - encoder.encode( "Thing", Collections.EMPTY_LIST ); + encoder.encode( "Thing", Collections.emptyList()); encoder.encode("A", List.of("Thing")); encoder.encode("Z", List.of("Thing")); encoder.encode( "B", Arrays.asList( "A", "Z" ) ); @@ -806,40 +806,37 @@ public void testDecoderDescendants() { LOGGER.debug( encoder.toString() ); - BitSet b; - Collection x; - - b = parseBitSet( "111" ); - x = encoder.lowerDescendants(b); + BitSet b = parseBitSet( "111" ); + Collection x = encoder.lowerDescendants(b); LOGGER.debug( "DESC " + x ); - assertThat(x.size()).isEqualTo(3); - assertThat(x.contains("C")).isTrue(); - assertThat(x.contains("N")).isTrue(); - assertThat(x.contains("T")).isTrue(); + assertThat(x).hasSize(3); + assertThat(x).contains("C"); + assertThat(x).contains("N"); + assertThat(x).contains("T"); b = parseBitSet( "10" ); x = encoder.lowerDescendants(b); LOGGER.debug( "DESC " + x ); - assertThat(x.size()).isEqualTo(5); - assertThat(x.contains("C")).isTrue(); - assertThat(x.contains("N")).isTrue(); - assertThat(x.contains("T")).isTrue(); - assertThat(x.contains("Z")).isTrue(); - assertThat(x.contains("B")).isTrue(); + assertThat(x).hasSize(5); + assertThat(x).contains("C"); + assertThat(x).contains("N"); + assertThat(x).contains("T"); + assertThat(x).contains("Z"); + assertThat(x).contains("B"); b = parseBitSet( "100000" ); x = encoder.lowerDescendants(b); LOGGER.debug( "DESC " + x ); - assertThat(x.size()).isEqualTo(4); - assertThat(x.contains("Q")).isTrue(); - assertThat(x.contains("T")).isTrue(); - assertThat(x.contains("M")).isTrue(); - assertThat(x.contains("O")).isTrue(); + assertThat(x).hasSize(4); + assertThat(x).contains("Q"); + assertThat(x).contains("T"); + assertThat(x).contains("M"); + assertThat(x).contains("O"); @@ -848,45 +845,45 @@ public void testDecoderDescendants() { x = encoder.lowerDescendants(b); LOGGER.debug( "DESC " + x ); - assertThat(x.size()).isEqualTo(1); - assertThat(x.contains("T")).isTrue(); + assertThat(x).hasSize(1); + assertThat(x).contains("T"); b = parseBitSet( "1111" ); x = encoder.lowerDescendants(b); LOGGER.debug( "DESC " + x ); - assertThat(x.size()).isEqualTo(1); - assertThat(x.contains("N")).isTrue(); + assertThat(x).hasSize(1); + assertThat(x).contains("N"); b = parseBitSet( "1" ); x = encoder.lowerDescendants(b); LOGGER.debug( "DESC " + x ); - assertThat(x.size()).isEqualTo(5); - assertThat(x.contains("A")).isTrue(); - assertThat(x.contains("B")).isTrue(); - assertThat(x.contains("C")).isTrue(); - assertThat(x.contains("N")).isTrue(); - assertThat(x.contains("T")).isTrue(); + assertThat(x).hasSize(5); + assertThat(x).contains("A"); + assertThat(x).contains("B"); + assertThat(x).contains("C"); + assertThat(x).contains("N"); + assertThat(x).contains("T"); LOGGER.debug(" +*******************************+ "); x = encoder.lowerDescendants(new BitSet()); LOGGER.debug( "DESC " + x ); - assertThat(x.size()).isEqualTo(13); - assertThat(x.contains("Z")).isTrue(); - assertThat(x.contains("Thing")).isTrue(); + assertThat(x).hasSize(13); + assertThat(x).contains("Z"); + assertThat(x).contains("Thing"); } @Test public void testHierEncoderDecoderLower() { - HierarchyEncoder encoder = new HierarchyEncoderImpl(); + HierarchyEncoder encoder = new HierarchyEncoderImpl<>(); - encoder.encode( "Thing", Collections.EMPTY_LIST ); + encoder.encode( "Thing", Collections.emptyList()); encoder.encode("A", List.of("Thing")); encoder.encode("Z", List.of("Thing")); encoder.encode( "B", Arrays.asList( "A", "Z" ) ); @@ -902,31 +899,31 @@ public void testHierEncoderDecoderLower() { LOGGER.debug( encoder.toString() ); - Collection x; + Collection x; x = encoder.lowerBorder( encoder.metMembersCode(List.of("B"))); LOGGER.debug( "GCS " + x ); - assertThat(x.size()).isEqualTo(1); - assertThat(x.contains("B")).isTrue(); + assertThat(x).hasSize(1); + assertThat(x).contains("B"); x = encoder.immediateChildren( encoder.metMembersCode(List.of("B"))); LOGGER.debug( "GCS " + x ); - assertThat(x.size()).isEqualTo(1); - assertThat(x.contains("N")).isTrue(); + assertThat(x).hasSize(1); + assertThat(x).contains("N"); x = encoder.lowerBorder( encoder.metMembersCode( Arrays.asList( "Z", "Q" ) ) ); LOGGER.debug( "GCS " + x ); - assertThat(x.size()).isEqualTo(1); - assertThat(x.contains("T")).isTrue(); + assertThat(x).hasSize(1); + assertThat(x).contains("T"); x = encoder.immediateChildren( encoder.metMembersCode( Arrays.asList( "Z", "Q" ) ) ); LOGGER.debug( "GCS " + x ); - assertThat(x.size()).isEqualTo(1); - assertThat(x.contains("T")).isTrue(); + assertThat(x).hasSize(1); + assertThat(x).contains("T"); @@ -934,16 +931,16 @@ public void testHierEncoderDecoderLower() { x = encoder.lowerBorder( encoder.metMembersCode( Arrays.asList( "A", "Z" ) ) ); LOGGER.debug( "GCS " + x ); - assertThat(x.size()).isEqualTo(2); - assertThat(x.contains("B")).isTrue(); - assertThat(x.contains("C")).isTrue(); + assertThat(x).hasSize(2); + assertThat(x).contains("B"); + assertThat(x).contains("C"); x = encoder.immediateChildren( encoder.metMembersCode( Arrays.asList( "A", "Z" ) ) ); LOGGER.debug( "GCS " + x ); - assertThat(x.size()).isEqualTo(2); - assertThat(x.contains("B")).isTrue(); - assertThat(x.contains("C")).isTrue(); + assertThat(x).hasSize(2); + assertThat(x).contains("B"); + assertThat(x).contains("C"); @@ -951,18 +948,18 @@ public void testHierEncoderDecoderLower() { x = encoder.lowerBorder( encoder.metMembersCode(List.of("Thing"))); LOGGER.debug( "GCS " + x ); - assertThat(x.size()).isEqualTo(1); - assertThat(x.contains("Thing")).isTrue(); + assertThat(x).hasSize(1); + assertThat(x).contains("Thing"); x = encoder.immediateChildren( encoder.metMembersCode(List.of("Thing"))); LOGGER.debug( "GCS " + x ); - assertThat(x.size()).isEqualTo(5); - assertThat(x.contains("A")).isTrue(); - assertThat(x.contains("Z")).isTrue(); - assertThat(x.contains("P")).isTrue(); - assertThat(x.contains("Q")).isTrue(); - assertThat(x.contains("R")).isTrue(); + assertThat(x).hasSize(5); + assertThat(x).contains("A"); + assertThat(x).contains("Z"); + assertThat(x).contains("P"); + assertThat(x).contains("Q"); + assertThat(x).contains("R"); } @@ -970,9 +967,9 @@ public void testHierEncoderDecoderLower() { @Test public void testHierEncoderDecoderUpper() { - HierarchyEncoder encoder = new HierarchyEncoderImpl(); + HierarchyEncoder encoder = new HierarchyEncoderImpl<>(); - encoder.encode( "Thing", Collections.EMPTY_LIST ); + encoder.encode( "Thing", Collections.emptyList()); encoder.encode("A", List.of("Thing")); encoder.encode("Z", List.of("Thing")); encoder.encode( "B", Arrays.asList( "A", "Z" ) ); @@ -988,62 +985,60 @@ public void testHierEncoderDecoderUpper() { LOGGER.debug( encoder.toString() ); - Collection x; - - x = encoder.upperBorder( encoder.metMembersCode(List.of("B"))); + Collection x = encoder.upperBorder( encoder.metMembersCode(List.of("B"))); LOGGER.debug( "LCS " + x ); - assertThat(x.size()).isEqualTo(1); - assertThat(x.contains("B")).isTrue(); + assertThat(x).hasSize(1); + assertThat(x).contains("B"); x = encoder.immediateParents( encoder.metMembersCode(List.of("B"))); LOGGER.debug( "LCS " + x ); - assertThat(x.size()).isEqualTo(2); - assertThat(x.contains("A")).isTrue(); - assertThat(x.contains("Z")).isTrue(); + assertThat(x).hasSize(2); + assertThat(x).contains("A"); + assertThat(x).contains("Z"); x = encoder.upperBorder( encoder.jointMembersCode( Arrays.asList( "Z", "Q" ) ) ); LOGGER.debug( "LCS " + x ); - assertThat(x.size()).isEqualTo(1); - assertThat(x.contains("Thing")).isTrue(); + assertThat(x).hasSize(1); + assertThat(x).contains("Thing"); x = encoder.immediateParents( encoder.jointMembersCode( Arrays.asList( "Z", "Q" ) ) ); LOGGER.debug( "LCS " + x ); - assertThat(x.size()).isEqualTo(1); - assertThat(x.contains("Thing")).isTrue(); + assertThat(x).hasSize(1); + assertThat(x).contains("Thing"); x = encoder.upperBorder( encoder.jointMembersCode( Arrays.asList( "B", "C" ) ) ); LOGGER.debug( "LCS " + x ); - assertThat(x.size()).isEqualTo(2); - assertThat(x.contains("A")).isTrue(); - assertThat(x.contains("Z")).isTrue(); + assertThat(x).hasSize(2); + assertThat(x).contains("A"); + assertThat(x).contains("Z"); x = encoder.immediateParents( encoder.jointMembersCode( Arrays.asList( "B", "C" ) ) ); LOGGER.debug( "LCS " + x ); - assertThat(x.size()).isEqualTo(2); - assertThat(x.contains("A")).isTrue(); - assertThat(x.contains("Z")).isTrue(); + assertThat(x).hasSize(2); + assertThat(x).contains("A"); + assertThat(x).contains("Z"); x = encoder.upperBorder( encoder.jointMembersCode(List.of("T"))); LOGGER.debug( "LCS " + x ); - assertThat(x.size()).isEqualTo(1); - assertThat(x.contains("T")).isTrue(); + assertThat(x).hasSize(1); + assertThat(x).contains("T"); x = encoder.immediateParents( encoder.jointMembersCode(List.of("T"))); LOGGER.debug( "LCS " + x ); - assertThat(x.size()).isEqualTo(2); - assertThat(x.contains("C")).isTrue(); - assertThat(x.contains("Q")).isTrue(); + assertThat(x).hasSize(2); + assertThat(x).contains("C"); + assertThat(x).contains("Q"); } @@ -1057,7 +1052,7 @@ public void testHierEncoderDecoderUpper() { public void testClassInstanceHierarchies() { HierarchyEncoder encoder = new HierarchyEncoderImpl(); - BitSet ak = encoder.encode( "A", Collections.EMPTY_LIST ); + BitSet ak = encoder.encode( "A", Collections.emptyList()); BitSet bk = encoder.encode("B", List.of("A")); BitSet ck = encoder.encode("C", List.of("A")); BitSet dk = encoder.encode("D", List.of("B")); @@ -1139,7 +1134,7 @@ public void testClassInstanceHierarchies() { public void testUnwantedCodeOverriding() { HierarchyEncoder encoder = new HierarchyEncoderImpl(); - BitSet ak = encoder.encode( "A", Collections.EMPTY_LIST ); + BitSet ak = encoder.encode( "A", Collections.emptyList()); BitSet ck = encoder.encode("C", List.of("A")); BitSet dk = encoder.encode("D", List.of("A")); BitSet gk = encoder.encode( "G", Arrays.asList( "C", "D" ) ); @@ -1186,7 +1181,7 @@ public void testUnwantedCodeOverriding() { public void testDeepTree() { HierarchyEncoder encoder = new HierarchyEncoderImpl(); - encoder.encode( "A", Collections.EMPTY_LIST ); + encoder.encode( "A", Collections.emptyList()); encoder.encode("B", List.of("A")); @@ -1219,7 +1214,7 @@ public void testDeepTree() { public void testNestedTree() { HierarchyEncoder encoder = new HierarchyEncoderImpl(); - encoder.encode( "A", Collections.EMPTY_LIST ); + encoder.encode( "A", Collections.emptyList()); encoder.encode("B", List.of("A")); encoder.encode("C", List.of("B")); encoder.encode("D", List.of("B")); diff --git a/drools-verifier/drools-verifier-drl/src/main/java/org/drools/verifier/visitor/ExprConstraintDescrVisitor.java b/drools-verifier/drools-verifier-drl/src/main/java/org/drools/verifier/visitor/ExprConstraintDescrVisitor.java index ba67c653c3e..89b05be9f93 100644 --- a/drools-verifier/drools-verifier-drl/src/main/java/org/drools/verifier/visitor/ExprConstraintDescrVisitor.java +++ b/drools-verifier/drools-verifier-drl/src/main/java/org/drools/verifier/visitor/ExprConstraintDescrVisitor.java @@ -20,6 +20,7 @@ import java.util.List; +import org.drools.drl.parser.DrlExprParserFactory; import org.drools.drl.parser.impl.Operator; import org.drools.drl.parser.DrlExprParser; import org.drools.drl.ast.descr.AtomicExprDescr; @@ -57,7 +58,7 @@ public ExprConstraintDescrVisitor(Pattern pattern, VerifierData data, OrderNumbe public void visit(ExprConstraintDescr descr) { - DrlExprParser drlExprParser = new DrlExprParser(LanguageLevelOption.DRL5); + DrlExprParser drlExprParser = DrlExprParserFactory.getDrlExprParser(LanguageLevelOption.DRL5); ConstraintConnectiveDescr constraintConnectiveDescr = drlExprParser.parse(descr.getExpression()); visit(constraintConnectiveDescr.getDescrs()); diff --git a/drools-verifier/drools-verifier-drl/src/main/java/org/drools/verifier/visitor/RuleDescrVisitor.java b/drools-verifier/drools-verifier-drl/src/main/java/org/drools/verifier/visitor/RuleDescrVisitor.java index 9a614cda74c..ca6f99b68c2 100644 --- a/drools-verifier/drools-verifier-drl/src/main/java/org/drools/verifier/visitor/RuleDescrVisitor.java +++ b/drools-verifier/drools-verifier-drl/src/main/java/org/drools/verifier/visitor/RuleDescrVisitor.java @@ -200,6 +200,10 @@ private Consequence visitConsequence(VerifierComponent parent, * Strip all comments out of the code. */ StringBuilder buffer = new StringBuilder(text); + + // Make sure there is a '\n' at the end of a comment even if it's the last line of the consequence. + buffer.append('\n'); + int commentIndex = buffer.indexOf("//"); while (commentIndex != -1) { diff --git a/kie-api/src/main/java/org/kie/api/runtime/process/NodeInstanceContainer.java b/kie-api/src/main/java/org/kie/api/runtime/process/NodeInstanceContainer.java index f8a749bc758..c8915cc1e34 100644 --- a/kie-api/src/main/java/org/kie/api/runtime/process/NodeInstanceContainer.java +++ b/kie-api/src/main/java/org/kie/api/runtime/process/NodeInstanceContainer.java @@ -34,6 +34,16 @@ public interface NodeInstanceContainer { */ Collection getNodeInstances(); + /** + * Returns all node instances that are currently active + * within this container and are serializable + * + * @return the list of serializable node instances currently active + */ + default Collection getSerializableNodeInstances() { + return getNodeInstances(); // defaulting to getNodeInstances to avoid breaking + } + /** * Returns the node instance with the given id, or null * if the node instance cannot be found. diff --git a/kie-dmn/kie-dmn-core/src/main/java/org/kie/dmn/core/api/EvaluatorResult.java b/kie-dmn/kie-dmn-api/src/main/java/org/kie/dmn/api/core/EvaluatorResult.java similarity index 96% rename from kie-dmn/kie-dmn-core/src/main/java/org/kie/dmn/core/api/EvaluatorResult.java rename to kie-dmn/kie-dmn-api/src/main/java/org/kie/dmn/api/core/EvaluatorResult.java index 7ef00e8ac0b..078bac9ce08 100644 --- a/kie-dmn/kie-dmn-core/src/main/java/org/kie/dmn/core/api/EvaluatorResult.java +++ b/kie-dmn/kie-dmn-api/src/main/java/org/kie/dmn/api/core/EvaluatorResult.java @@ -16,7 +16,7 @@ * specific language governing permissions and limitations * under the License. */ -package org.kie.dmn.core.api; +package org.kie.dmn.api.core; public interface EvaluatorResult { diff --git a/kie-dmn/kie-dmn-api/src/main/java/org/kie/dmn/api/core/event/AfterConditionalEvaluationEvent.java b/kie-dmn/kie-dmn-api/src/main/java/org/kie/dmn/api/core/event/AfterConditionalEvaluationEvent.java new file mode 100644 index 00000000000..06b4050772f --- /dev/null +++ b/kie-dmn/kie-dmn-api/src/main/java/org/kie/dmn/api/core/event/AfterConditionalEvaluationEvent.java @@ -0,0 +1,33 @@ +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you 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 + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.kie.dmn.api.core.event; + +import org.kie.dmn.api.core.EvaluatorResult; + +/** + * Event fired after the then/else branches of an if condition are evaluated + * @see AfterEvaluateConditionalEvent + */ +public interface AfterConditionalEvaluationEvent { + + EvaluatorResult getEvaluatorResultResult(); + + String getExecutedId(); + +} diff --git a/kie-dmn/kie-dmn-api/src/main/java/org/kie/dmn/api/core/event/AfterEvaluateConditionalEvent.java b/kie-dmn/kie-dmn-api/src/main/java/org/kie/dmn/api/core/event/AfterEvaluateConditionalEvent.java new file mode 100644 index 00000000000..b0fb5f2c623 --- /dev/null +++ b/kie-dmn/kie-dmn-api/src/main/java/org/kie/dmn/api/core/event/AfterEvaluateConditionalEvent.java @@ -0,0 +1,33 @@ +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you 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 + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.kie.dmn.api.core.event; + +import org.kie.dmn.api.core.EvaluatorResult; + +/** + * Event fired after the if if conditional is evaluated + * + */ +public interface AfterEvaluateConditionalEvent { + + EvaluatorResult getEvaluatorResultResult(); + + String getExecutedId(); + +} diff --git a/kie-dmn/kie-dmn-api/src/main/java/org/kie/dmn/api/core/event/AfterEvaluateDecisionTableEvent.java b/kie-dmn/kie-dmn-api/src/main/java/org/kie/dmn/api/core/event/AfterEvaluateDecisionTableEvent.java index 3fac12be823..6daa2958bd5 100644 --- a/kie-dmn/kie-dmn-api/src/main/java/org/kie/dmn/api/core/event/AfterEvaluateDecisionTableEvent.java +++ b/kie-dmn/kie-dmn-api/src/main/java/org/kie/dmn/api/core/event/AfterEvaluateDecisionTableEvent.java @@ -33,4 +33,8 @@ default String getDecisionTableId() { List getMatches(); List getSelected(); + + List getMatchesIds(); + + List getSelectedIds(); } diff --git a/kie-dmn/kie-dmn-api/src/main/java/org/kie/dmn/api/core/event/DMNRuntimeEventListener.java b/kie-dmn/kie-dmn-api/src/main/java/org/kie/dmn/api/core/event/DMNRuntimeEventListener.java index ddb6e890938..258d3f8b6b8 100644 --- a/kie-dmn/kie-dmn-api/src/main/java/org/kie/dmn/api/core/event/DMNRuntimeEventListener.java +++ b/kie-dmn/kie-dmn-api/src/main/java/org/kie/dmn/api/core/event/DMNRuntimeEventListener.java @@ -47,4 +47,16 @@ default void afterInvokeBKM(AfterInvokeBKMEvent event) {} default void beforeEvaluateAll(BeforeEvaluateAllEvent event) {} default void afterEvaluateAll(AfterEvaluateAllEvent event) {} + + /** + * Fired after the if if conditional is evaluated + * + */ + default void afterEvaluateConditional(AfterEvaluateConditionalEvent event) {} + + /** + * Fired after the then/else branches of an if condition are evaluated + * + */ + default void afterConditionalEvaluation(AfterConditionalEvaluationEvent event) {} } diff --git a/kie-dmn/kie-dmn-core-jsr223/src/main/java/org/kie/dmn/core/jsr223/JSR223DTExpressionEvaluator.java b/kie-dmn/kie-dmn-core-jsr223/src/main/java/org/kie/dmn/core/jsr223/JSR223DTExpressionEvaluator.java index ff114e2eb44..93fe8a412e9 100644 --- a/kie-dmn/kie-dmn-core-jsr223/src/main/java/org/kie/dmn/core/jsr223/JSR223DTExpressionEvaluator.java +++ b/kie-dmn/kie-dmn-core-jsr223/src/main/java/org/kie/dmn/core/jsr223/JSR223DTExpressionEvaluator.java @@ -35,8 +35,8 @@ import org.kie.dmn.api.feel.runtime.events.FEELEvent; import org.kie.dmn.api.feel.runtime.events.FEELEventListener; import org.kie.dmn.core.api.DMNExpressionEvaluator; -import org.kie.dmn.core.api.EvaluatorResult; -import org.kie.dmn.core.api.EvaluatorResult.ResultType; +import org.kie.dmn.api.core.EvaluatorResult; +import org.kie.dmn.api.core.EvaluatorResult.ResultType; import org.kie.dmn.core.ast.DMNDTExpressionEvaluator; import org.kie.dmn.core.ast.DMNDTExpressionEvaluator.EventResults; import org.kie.dmn.core.ast.EvaluatorResultImpl; @@ -106,7 +106,11 @@ public EvaluatorResult evaluate(DMNRuntimeEventManager dmrem, DMNResult dmnr) { LOG.debug("failed evaluate", e); throw new RuntimeException(e); } finally { - DMNRuntimeEventManagerUtils.fireAfterEvaluateDecisionTable( dmrem, node.getName(), node.getName(), dt.getId(), result, (r != null ? r.matchedRules : null), (r != null ? r.fired : null) ); + DMNRuntimeEventManagerUtils.fireAfterEvaluateDecisionTable( dmrem, node.getName(), node.getName(), dt.getId(), result, + (r != null ? r.matchedRules : null), + (r != null ? r.fired : null), + (r != null ? r.matchedIds : null), + (r != null ? r.firedIds : null)); } } diff --git a/kie-dmn/kie-dmn-core-jsr223/src/main/java/org/kie/dmn/core/jsr223/JSR223LiteralExpressionEvaluator.java b/kie-dmn/kie-dmn-core-jsr223/src/main/java/org/kie/dmn/core/jsr223/JSR223LiteralExpressionEvaluator.java index 5b3a5302298..48630c6459e 100644 --- a/kie-dmn/kie-dmn-core-jsr223/src/main/java/org/kie/dmn/core/jsr223/JSR223LiteralExpressionEvaluator.java +++ b/kie-dmn/kie-dmn-core-jsr223/src/main/java/org/kie/dmn/core/jsr223/JSR223LiteralExpressionEvaluator.java @@ -21,8 +21,8 @@ import org.kie.dmn.api.core.DMNResult; import org.kie.dmn.api.core.event.DMNRuntimeEventManager; import org.kie.dmn.core.api.DMNExpressionEvaluator; -import org.kie.dmn.core.api.EvaluatorResult; -import org.kie.dmn.core.api.EvaluatorResult.ResultType; +import org.kie.dmn.api.core.EvaluatorResult; +import org.kie.dmn.api.core.EvaluatorResult.ResultType; import org.kie.dmn.core.ast.EvaluatorResultImpl; import org.kie.dmn.core.impl.DMNResultImpl; import org.slf4j.Logger; diff --git a/kie-dmn/kie-dmn-core/src/main/java/org/kie/dmn/core/api/DMNExpressionEvaluator.java b/kie-dmn/kie-dmn-core/src/main/java/org/kie/dmn/core/api/DMNExpressionEvaluator.java index c40ebcb323d..c6237641674 100644 --- a/kie-dmn/kie-dmn-core/src/main/java/org/kie/dmn/core/api/DMNExpressionEvaluator.java +++ b/kie-dmn/kie-dmn-core/src/main/java/org/kie/dmn/core/api/DMNExpressionEvaluator.java @@ -19,6 +19,7 @@ package org.kie.dmn.core.api; import org.kie.dmn.api.core.DMNResult; +import org.kie.dmn.api.core.EvaluatorResult; import org.kie.dmn.api.core.event.DMNRuntimeEventManager; /** diff --git a/kie-dmn/kie-dmn-core/src/main/java/org/kie/dmn/core/ast/DMNConditionalEvaluator.java b/kie-dmn/kie-dmn-core/src/main/java/org/kie/dmn/core/ast/DMNConditionalEvaluator.java index 7da9445a81a..8f89bb1fcbb 100644 --- a/kie-dmn/kie-dmn-core/src/main/java/org/kie/dmn/core/ast/DMNConditionalEvaluator.java +++ b/kie-dmn/kie-dmn-core/src/main/java/org/kie/dmn/core/ast/DMNConditionalEvaluator.java @@ -18,15 +18,20 @@ */ package org.kie.dmn.core.ast; +import java.util.HashMap; +import java.util.Map; + import org.kie.dmn.api.core.DMNMessage; import org.kie.dmn.api.core.DMNResult; import org.kie.dmn.api.core.event.DMNRuntimeEventManager; import org.kie.dmn.core.api.DMNExpressionEvaluator; -import org.kie.dmn.core.api.EvaluatorResult; -import org.kie.dmn.core.api.EvaluatorResult.ResultType; +import org.kie.dmn.api.core.EvaluatorResult; +import org.kie.dmn.api.core.EvaluatorResult.ResultType; import org.kie.dmn.core.impl.DMNResultImpl; +import org.kie.dmn.core.impl.DMNRuntimeEventManagerUtils; import org.kie.dmn.core.util.Msg; import org.kie.dmn.core.util.MsgUtil; +import org.kie.dmn.model.api.Conditional; import org.kie.dmn.model.api.DMNElement; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -40,6 +45,7 @@ public class DMNConditionalEvaluator implements DMNExpressionEvaluator { private DMNExpressionEvaluator elseEvaluator; private DMNElement node; private String name; + private final Map evaluatorIdMap = new HashMap<>(); public DMNConditionalEvaluator(String name, DMNElement node, DMNExpressionEvaluator ifEvaluator, DMNExpressionEvaluator thenEvaluator, DMNExpressionEvaluator elseEvaluator) { this.name = name; @@ -47,6 +53,14 @@ public DMNConditionalEvaluator(String name, DMNElement node, DMNExpressionEvalua this.ifEvaluator = ifEvaluator; this.thenEvaluator = thenEvaluator; this.elseEvaluator = elseEvaluator; + Conditional conditional = node.getChildren().stream() + .filter(c -> c instanceof Conditional) + .map(c -> (Conditional) c) + .findFirst() + .orElseThrow(() -> new RuntimeException("Missing Conditional element inside " + node)); + evaluatorIdMap.put(ifEvaluator, conditional.getIf().getId()); + evaluatorIdMap.put(thenEvaluator, conditional.getThen().getId()); + evaluatorIdMap.put(elseEvaluator, conditional.getElse().getId()); } @Override @@ -54,16 +68,12 @@ public EvaluatorResult evaluate(DMNRuntimeEventManager eventManager, DMNResult d DMNResultImpl result = (DMNResultImpl) dmnr; EvaluatorResult ifEvaluation = ifEvaluator.evaluate(eventManager, result); + String executedId = evaluatorIdMap.get(ifEvaluator); + DMNRuntimeEventManagerUtils.fireAfterEvaluateConditional(eventManager, ifEvaluation, executedId); if (ifEvaluation.getResultType().equals(ResultType.SUCCESS)) { Object ifResult = ifEvaluation.getResult(); - if (ifResult instanceof Boolean) { - if (((Boolean) ifResult).booleanValue()) { - return thenEvaluator.evaluate(eventManager, result); - } else { - return elseEvaluator.evaluate(eventManager, result); - } - } else if (ifResult == null) { - return elseEvaluator.evaluate(eventManager, result); + if (ifResult == null || ifResult instanceof Boolean) { + return manageBooleanOrNullIfResult((Boolean) ifResult, eventManager, result); } else { MsgUtil.reportMessage(logger, DMNMessage.Severity.ERROR, @@ -80,4 +90,13 @@ public EvaluatorResult evaluate(DMNRuntimeEventManager eventManager, DMNResult d return new EvaluatorResultImpl(null, ResultType.FAILURE); } + protected EvaluatorResult manageBooleanOrNullIfResult(Boolean booleanResult, DMNRuntimeEventManager eventManager, DMNResultImpl result) { + DMNExpressionEvaluator evaluatorToUse = booleanResult != null && booleanResult ? thenEvaluator : elseEvaluator; + + EvaluatorResult toReturn = evaluatorToUse.evaluate(eventManager, result); + String executedId = evaluatorIdMap.get(evaluatorToUse); + DMNRuntimeEventManagerUtils.fireAfterConditionalEvaluation(eventManager, toReturn, executedId); + return toReturn; + } + } diff --git a/kie-dmn/kie-dmn-core/src/main/java/org/kie/dmn/core/ast/DMNContextEvaluator.java b/kie-dmn/kie-dmn-core/src/main/java/org/kie/dmn/core/ast/DMNContextEvaluator.java index 4fbb5c0c649..cedf3e309a3 100644 --- a/kie-dmn/kie-dmn-core/src/main/java/org/kie/dmn/core/ast/DMNContextEvaluator.java +++ b/kie-dmn/kie-dmn-core/src/main/java/org/kie/dmn/core/ast/DMNContextEvaluator.java @@ -31,8 +31,8 @@ import org.kie.dmn.api.core.DMNType; import org.kie.dmn.api.core.event.DMNRuntimeEventManager; import org.kie.dmn.core.api.DMNExpressionEvaluator; -import org.kie.dmn.core.api.EvaluatorResult; -import org.kie.dmn.core.api.EvaluatorResult.ResultType; +import org.kie.dmn.api.core.EvaluatorResult; +import org.kie.dmn.api.core.EvaluatorResult.ResultType; import org.kie.dmn.core.impl.DMNResultImpl; import org.kie.dmn.core.impl.DMNRuntimeEventManagerUtils; import org.kie.dmn.core.impl.DMNRuntimeImpl; diff --git a/kie-dmn/kie-dmn-core/src/main/java/org/kie/dmn/core/ast/DMNDTExpressionEvaluator.java b/kie-dmn/kie-dmn-core/src/main/java/org/kie/dmn/core/ast/DMNDTExpressionEvaluator.java index 7432b3114c6..4b1cc02daf3 100644 --- a/kie-dmn/kie-dmn-core/src/main/java/org/kie/dmn/core/ast/DMNDTExpressionEvaluator.java +++ b/kie-dmn/kie-dmn-core/src/main/java/org/kie/dmn/core/ast/DMNDTExpressionEvaluator.java @@ -19,7 +19,6 @@ package org.kie.dmn.core.ast; import java.util.ArrayList; -import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.Map; @@ -32,8 +31,8 @@ import org.kie.dmn.api.core.event.DMNRuntimeEventManager; import org.kie.dmn.api.feel.runtime.events.FEELEvent; import org.kie.dmn.core.api.DMNExpressionEvaluator; -import org.kie.dmn.core.api.EvaluatorResult; -import org.kie.dmn.core.api.EvaluatorResult.ResultType; +import org.kie.dmn.api.core.EvaluatorResult; +import org.kie.dmn.api.core.EvaluatorResult.ResultType; import org.kie.dmn.core.impl.DMNResultImpl; import org.kie.dmn.core.impl.DMNRuntimeEventManagerUtils; import org.kie.dmn.core.impl.DMNRuntimeImpl; @@ -104,7 +103,11 @@ public EvaluatorResult evaluate(DMNRuntimeEventManager dmrem, DMNResult dmnr) { r = processEvents( events, dmrem, result, node ); return new EvaluatorResultImpl( dtr, r.hasErrors ? ResultType.FAILURE : ResultType.SUCCESS ); } finally { - DMNRuntimeEventManagerUtils.fireAfterEvaluateDecisionTable( dmrem, node.getName(), dt.getName(), dtNodeId, result, (r != null ? r.matchedRules : null), (r != null ? r.fired : null) ); + DMNRuntimeEventManagerUtils.fireAfterEvaluateDecisionTable( dmrem, node.getName(), dt.getName(), dtNodeId, result, + (r != null ? r.matchedRules : null), + (r != null ? r.fired : null), + (r != null ? r.matchedIds : null), + (r != null ? r.firedIds : null)); } } @@ -113,8 +116,10 @@ public static EventResults processEvents(List events, DMNRuntimeEvent for ( FEELEvent e : events ) { if ( e instanceof DecisionTableRulesMatchedEvent ) { r.matchedRules = ((DecisionTableRulesMatchedEvent) e).getMatches(); + r.matchedIds = ((DecisionTableRulesMatchedEvent) e).getMatchesIds(); } else if ( e instanceof DecisionTableRulesSelectedEvent ) { r.fired = ((DecisionTableRulesSelectedEvent) e).getFired(); + r.firedIds = ((DecisionTableRulesSelectedEvent) e).getFiredIds(); } else if ( e.getSeverity() == FEELEvent.Severity.ERROR ) { MsgUtil.reportMessage( logger, DMNMessage.Severity.ERROR, @@ -144,6 +149,8 @@ public static class EventResults { public boolean hasErrors = false; public List matchedRules; public List fired; + public List matchedIds; + public List firedIds; } diff --git a/kie-dmn/kie-dmn-core/src/main/java/org/kie/dmn/core/ast/DMNDecisionServiceEvaluator.java b/kie-dmn/kie-dmn-core/src/main/java/org/kie/dmn/core/ast/DMNDecisionServiceEvaluator.java index 63a6faf1a74..328ee461b02 100644 --- a/kie-dmn/kie-dmn-core/src/main/java/org/kie/dmn/core/ast/DMNDecisionServiceEvaluator.java +++ b/kie-dmn/kie-dmn-core/src/main/java/org/kie/dmn/core/ast/DMNDecisionServiceEvaluator.java @@ -33,8 +33,8 @@ import org.kie.dmn.api.core.ast.DecisionServiceNode; import org.kie.dmn.api.core.event.DMNRuntimeEventManager; import org.kie.dmn.core.api.DMNExpressionEvaluator; -import org.kie.dmn.core.api.EvaluatorResult; -import org.kie.dmn.core.api.EvaluatorResult.ResultType; +import org.kie.dmn.api.core.EvaluatorResult; +import org.kie.dmn.api.core.EvaluatorResult.ResultType; import org.kie.dmn.core.compiler.DMNCompilerImpl; import org.kie.dmn.core.impl.DMNDecisionResultImpl; import org.kie.dmn.core.impl.DMNResultImpl; diff --git a/kie-dmn/kie-dmn-core/src/main/java/org/kie/dmn/core/ast/DMNDecisionServiceFunctionDefinitionEvaluator.java b/kie-dmn/kie-dmn-core/src/main/java/org/kie/dmn/core/ast/DMNDecisionServiceFunctionDefinitionEvaluator.java index 21ee7e0af6a..99700adc603 100644 --- a/kie-dmn/kie-dmn-core/src/main/java/org/kie/dmn/core/ast/DMNDecisionServiceFunctionDefinitionEvaluator.java +++ b/kie-dmn/kie-dmn-core/src/main/java/org/kie/dmn/core/ast/DMNDecisionServiceFunctionDefinitionEvaluator.java @@ -31,8 +31,8 @@ import org.kie.dmn.api.core.ast.DecisionServiceNode; import org.kie.dmn.api.core.event.DMNRuntimeEventManager; import org.kie.dmn.core.api.DMNExpressionEvaluator; -import org.kie.dmn.core.api.EvaluatorResult; -import org.kie.dmn.core.api.EvaluatorResult.ResultType; +import org.kie.dmn.api.core.EvaluatorResult; +import org.kie.dmn.api.core.EvaluatorResult.ResultType; import org.kie.dmn.core.ast.DMNFunctionDefinitionEvaluator.FormalParameter; import org.kie.dmn.core.impl.DMNResultImpl; import org.kie.dmn.core.impl.DMNRuntimeImpl; @@ -160,7 +160,7 @@ private Object performTypeCheckIfNeeded(Object param, int paramIndex) { dsFormalParameter.type, typeCheck, (rx, tx) -> MsgUtil.reportMessage(LOG, - DMNMessage.Severity.WARN, + DMNMessage.Severity.ERROR, null, resultContext, null, @@ -169,7 +169,11 @@ private Object performTypeCheckIfNeeded(Object param, int paramIndex) { dsFormalParameter.name, tx, MsgUtil.clipString(rx.toString(), 50))); - return result; + if (param != null && result == null) { + throw new IllegalArgumentException("Parameter " + param + " cannot be assigned to parameter of type " + dsFormalParameter.type + "!"); + } else { + return result; + } } @Override diff --git a/kie-dmn/kie-dmn-core/src/main/java/org/kie/dmn/core/ast/DMNFilterEvaluator.java b/kie-dmn/kie-dmn-core/src/main/java/org/kie/dmn/core/ast/DMNFilterEvaluator.java index ccaddaac570..b0120fd57e5 100644 --- a/kie-dmn/kie-dmn-core/src/main/java/org/kie/dmn/core/ast/DMNFilterEvaluator.java +++ b/kie-dmn/kie-dmn-core/src/main/java/org/kie/dmn/core/ast/DMNFilterEvaluator.java @@ -28,8 +28,8 @@ import org.kie.dmn.api.core.DMNResult; import org.kie.dmn.api.core.event.DMNRuntimeEventManager; import org.kie.dmn.core.api.DMNExpressionEvaluator; -import org.kie.dmn.core.api.EvaluatorResult; -import org.kie.dmn.core.api.EvaluatorResult.ResultType; +import org.kie.dmn.api.core.EvaluatorResult; +import org.kie.dmn.api.core.EvaluatorResult.ResultType; import org.kie.dmn.core.impl.DMNResultImpl; import org.kie.dmn.core.util.IterableRange; import org.kie.dmn.core.util.Msg; diff --git a/kie-dmn/kie-dmn-core/src/main/java/org/kie/dmn/core/ast/DMNFunctionDefinitionEvaluator.java b/kie-dmn/kie-dmn-core/src/main/java/org/kie/dmn/core/ast/DMNFunctionDefinitionEvaluator.java index c7d6469aaca..902ff74556c 100644 --- a/kie-dmn/kie-dmn-core/src/main/java/org/kie/dmn/core/ast/DMNFunctionDefinitionEvaluator.java +++ b/kie-dmn/kie-dmn-core/src/main/java/org/kie/dmn/core/ast/DMNFunctionDefinitionEvaluator.java @@ -32,8 +32,8 @@ import org.kie.dmn.api.core.ast.DMNNode; import org.kie.dmn.api.core.event.DMNRuntimeEventManager; import org.kie.dmn.core.api.DMNExpressionEvaluator; -import org.kie.dmn.core.api.EvaluatorResult; -import org.kie.dmn.core.api.EvaluatorResult.ResultType; +import org.kie.dmn.api.core.EvaluatorResult; +import org.kie.dmn.api.core.EvaluatorResult.ResultType; import org.kie.dmn.core.impl.BaseDMNTypeImpl; import org.kie.dmn.core.impl.DMNContextFEELCtxWrapper; import org.kie.dmn.core.impl.DMNResultImpl; diff --git a/kie-dmn/kie-dmn-core/src/main/java/org/kie/dmn/core/ast/DMNInvocationEvaluator.java b/kie-dmn/kie-dmn-core/src/main/java/org/kie/dmn/core/ast/DMNInvocationEvaluator.java index ec42aa0f1ec..44e166bb221 100644 --- a/kie-dmn/kie-dmn-core/src/main/java/org/kie/dmn/core/ast/DMNInvocationEvaluator.java +++ b/kie-dmn/kie-dmn-core/src/main/java/org/kie/dmn/core/ast/DMNInvocationEvaluator.java @@ -32,8 +32,8 @@ import org.kie.dmn.api.core.event.DMNRuntimeEventManager; import org.kie.dmn.api.feel.runtime.events.FEELEvent; import org.kie.dmn.core.api.DMNExpressionEvaluator; -import org.kie.dmn.core.api.EvaluatorResult; -import org.kie.dmn.core.api.EvaluatorResult.ResultType; +import org.kie.dmn.api.core.EvaluatorResult; +import org.kie.dmn.api.core.EvaluatorResult.ResultType; import org.kie.dmn.core.impl.DMNModelImpl; import org.kie.dmn.core.impl.DMNResultImpl; import org.kie.dmn.core.util.Msg; diff --git a/kie-dmn/kie-dmn-core/src/main/java/org/kie/dmn/core/ast/DMNIteratorEvaluator.java b/kie-dmn/kie-dmn-core/src/main/java/org/kie/dmn/core/ast/DMNIteratorEvaluator.java index 1abbe18e518..1d73315edee 100644 --- a/kie-dmn/kie-dmn-core/src/main/java/org/kie/dmn/core/ast/DMNIteratorEvaluator.java +++ b/kie-dmn/kie-dmn-core/src/main/java/org/kie/dmn/core/ast/DMNIteratorEvaluator.java @@ -27,8 +27,8 @@ import org.kie.dmn.api.core.DMNResult; import org.kie.dmn.api.core.event.DMNRuntimeEventManager; import org.kie.dmn.core.api.DMNExpressionEvaluator; -import org.kie.dmn.core.api.EvaluatorResult; -import org.kie.dmn.core.api.EvaluatorResult.ResultType; +import org.kie.dmn.api.core.EvaluatorResult; +import org.kie.dmn.api.core.EvaluatorResult.ResultType; import org.kie.dmn.core.impl.DMNResultImpl; import org.kie.dmn.core.util.IterableRange; import org.kie.dmn.core.util.Msg; diff --git a/kie-dmn/kie-dmn-core/src/main/java/org/kie/dmn/core/ast/DMNListEvaluator.java b/kie-dmn/kie-dmn-core/src/main/java/org/kie/dmn/core/ast/DMNListEvaluator.java index f0156ddfa9c..0a85a479073 100644 --- a/kie-dmn/kie-dmn-core/src/main/java/org/kie/dmn/core/ast/DMNListEvaluator.java +++ b/kie-dmn/kie-dmn-core/src/main/java/org/kie/dmn/core/ast/DMNListEvaluator.java @@ -26,8 +26,8 @@ import org.kie.dmn.api.core.DMNResult; import org.kie.dmn.api.core.event.DMNRuntimeEventManager; import org.kie.dmn.core.api.DMNExpressionEvaluator; -import org.kie.dmn.core.api.EvaluatorResult; -import org.kie.dmn.core.api.EvaluatorResult.ResultType; +import org.kie.dmn.api.core.EvaluatorResult; +import org.kie.dmn.api.core.EvaluatorResult.ResultType; import org.kie.dmn.core.impl.DMNResultImpl; import org.kie.dmn.core.util.Msg; import org.kie.dmn.core.util.MsgUtil; diff --git a/kie-dmn/kie-dmn-core/src/main/java/org/kie/dmn/core/ast/DMNLiteralExpressionEvaluator.java b/kie-dmn/kie-dmn-core/src/main/java/org/kie/dmn/core/ast/DMNLiteralExpressionEvaluator.java index 5e42fbc420d..07d1f69390b 100644 --- a/kie-dmn/kie-dmn-core/src/main/java/org/kie/dmn/core/ast/DMNLiteralExpressionEvaluator.java +++ b/kie-dmn/kie-dmn-core/src/main/java/org/kie/dmn/core/ast/DMNLiteralExpressionEvaluator.java @@ -19,7 +19,6 @@ package org.kie.dmn.core.ast; import java.util.ArrayList; -import java.util.Arrays; import java.util.List; import org.kie.dmn.api.core.DMNMessage; @@ -29,8 +28,8 @@ import org.kie.dmn.api.feel.runtime.events.FEELEvent.Severity; import org.kie.dmn.api.feel.runtime.events.FEELEventListener; import org.kie.dmn.core.api.DMNExpressionEvaluator; -import org.kie.dmn.core.api.EvaluatorResult; -import org.kie.dmn.core.api.EvaluatorResult.ResultType; +import org.kie.dmn.api.core.EvaluatorResult; +import org.kie.dmn.api.core.EvaluatorResult.ResultType; import org.kie.dmn.core.impl.DMNResultImpl; import org.kie.dmn.core.util.Msg; import org.kie.dmn.core.util.MsgUtil; diff --git a/kie-dmn/kie-dmn-core/src/main/java/org/kie/dmn/core/ast/DMNRelationEvaluator.java b/kie-dmn/kie-dmn-core/src/main/java/org/kie/dmn/core/ast/DMNRelationEvaluator.java index 1bb21d824b7..6a971ffba15 100644 --- a/kie-dmn/kie-dmn-core/src/main/java/org/kie/dmn/core/ast/DMNRelationEvaluator.java +++ b/kie-dmn/kie-dmn-core/src/main/java/org/kie/dmn/core/ast/DMNRelationEvaluator.java @@ -28,8 +28,8 @@ import org.kie.dmn.api.core.DMNResult; import org.kie.dmn.api.core.event.DMNRuntimeEventManager; import org.kie.dmn.core.api.DMNExpressionEvaluator; -import org.kie.dmn.core.api.EvaluatorResult; -import org.kie.dmn.core.api.EvaluatorResult.ResultType; +import org.kie.dmn.api.core.EvaluatorResult; +import org.kie.dmn.api.core.EvaluatorResult.ResultType; import org.kie.dmn.core.impl.DMNResultImpl; import org.kie.dmn.core.util.Msg; import org.kie.dmn.core.util.MsgUtil; diff --git a/kie-dmn/kie-dmn-core/src/main/java/org/kie/dmn/core/ast/EvaluatorResultImpl.java b/kie-dmn/kie-dmn-core/src/main/java/org/kie/dmn/core/ast/EvaluatorResultImpl.java index 73b25ca012b..ed8eb063996 100644 --- a/kie-dmn/kie-dmn-core/src/main/java/org/kie/dmn/core/ast/EvaluatorResultImpl.java +++ b/kie-dmn/kie-dmn-core/src/main/java/org/kie/dmn/core/ast/EvaluatorResultImpl.java @@ -18,7 +18,7 @@ */ package org.kie.dmn.core.ast; -import org.kie.dmn.core.api.EvaluatorResult; +import org.kie.dmn.api.core.EvaluatorResult; public class EvaluatorResultImpl implements EvaluatorResult { private final Object result; diff --git a/kie-dmn/kie-dmn-core/src/main/java/org/kie/dmn/core/compiler/DMNEvaluatorCompiler.java b/kie-dmn/kie-dmn-core/src/main/java/org/kie/dmn/core/compiler/DMNEvaluatorCompiler.java index 9e4ad9d59e9..a4e384da787 100644 --- a/kie-dmn/kie-dmn-core/src/main/java/org/kie/dmn/core/compiler/DMNEvaluatorCompiler.java +++ b/kie-dmn/kie-dmn-core/src/main/java/org/kie/dmn/core/compiler/DMNEvaluatorCompiler.java @@ -38,7 +38,7 @@ import org.kie.dmn.api.core.ast.DMNNode; import org.kie.dmn.api.core.ast.DecisionNode; import org.kie.dmn.core.api.DMNExpressionEvaluator; -import org.kie.dmn.core.api.EvaluatorResult; +import org.kie.dmn.api.core.EvaluatorResult; import org.kie.dmn.core.ast.DMNBaseNode; import org.kie.dmn.core.ast.DMNConditionalEvaluator; import org.kie.dmn.core.ast.DMNContextEvaluator; @@ -678,7 +678,7 @@ protected DMNExpressionEvaluator compileDecisionTable(DMNCompilerContext ctx, DM java.util.List rules = new ArrayList<>(); index = 0; for ( DecisionRule dr : dt.getRule() ) { - DTDecisionRule rule = new DTDecisionRule( index ); + DTDecisionRule rule = new DTDecisionRule( index, dr.getId() ); for ( int i = 0; i < dr.getInputEntry().size(); i++ ) { UnaryTests ut = dr.getInputEntry().get(i); final java.util.List tests; diff --git a/kie-dmn/kie-dmn-core/src/main/java/org/kie/dmn/core/compiler/alphanetbased/DMNAlphaNetworkEvaluatorImpl.java b/kie-dmn/kie-dmn-core/src/main/java/org/kie/dmn/core/compiler/alphanetbased/DMNAlphaNetworkEvaluatorImpl.java index 522eb377438..33342770490 100644 --- a/kie-dmn/kie-dmn-core/src/main/java/org/kie/dmn/core/compiler/alphanetbased/DMNAlphaNetworkEvaluatorImpl.java +++ b/kie-dmn/kie-dmn-core/src/main/java/org/kie/dmn/core/compiler/alphanetbased/DMNAlphaNetworkEvaluatorImpl.java @@ -27,7 +27,7 @@ import org.kie.dmn.api.core.event.DMNRuntimeEventManager; import org.kie.dmn.api.feel.runtime.events.FEELEvent; import org.kie.dmn.core.api.DMNExpressionEvaluator; -import org.kie.dmn.core.api.EvaluatorResult; +import org.kie.dmn.api.core.EvaluatorResult; import org.kie.dmn.core.ast.DMNBaseNode; import org.kie.dmn.core.ast.DMNDTExpressionEvaluator; import org.kie.dmn.core.ast.EvaluatorResultImpl; @@ -111,7 +111,10 @@ public EvaluatorResult evaluate(DMNRuntimeEventManager eventManager, DMNResult d } finally { evalCtx.exitFrame(); DMNRuntimeEventManagerUtils.fireAfterEvaluateDecisionTable(eventManager, node.getName(), decisionTableName, decisionTableId, dmnResult, - (eventResults != null ? eventResults.matchedRules : null), (eventResults != null ? eventResults.fired : null)); + (eventResults != null ? eventResults.matchedRules : null), + (eventResults != null ? eventResults.fired : null), + (eventResults != null ? eventResults.matchedIds : null), + (eventResults != null ? eventResults.firedIds : null)); } } diff --git a/kie-dmn/kie-dmn-core/src/main/java/org/kie/dmn/core/compiler/alphanetbased/Results.java b/kie-dmn/kie-dmn-core/src/main/java/org/kie/dmn/core/compiler/alphanetbased/Results.java index ec7de3836cc..ca42e119aec 100644 --- a/kie-dmn/kie-dmn-core/src/main/java/org/kie/dmn/core/compiler/alphanetbased/Results.java +++ b/kie-dmn/kie-dmn-core/src/main/java/org/kie/dmn/core/compiler/alphanetbased/Results.java @@ -7,7 +7,7 @@ * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an @@ -29,9 +29,9 @@ import org.drools.model.functions.Function1; import org.kie.dmn.api.feel.runtime.events.FEELEvent; import org.kie.dmn.feel.lang.EvaluationContext; +import org.kie.dmn.feel.runtime.decisiontables.DTDecisionRule; import org.kie.dmn.feel.runtime.decisiontables.DecisionTable; import org.kie.dmn.feel.runtime.decisiontables.HitPolicy; -import org.kie.dmn.feel.runtime.decisiontables.Indexed; import org.kie.dmn.feel.runtime.events.DecisionTableRulesMatchedEvent; import org.kie.dmn.feel.runtime.events.HitPolicyViolationEvent; @@ -49,7 +49,8 @@ static class Items { public void addResult(ResultObject resultObject) { resultGroupedByRow - .computeIfAbsent(resultObject.row, i -> new ArrayList<>(1)) // 10 (the default for Java) columns output are not that usual + .computeIfAbsent(resultObject.row, i -> new ArrayList<>(1)) // 10 (the default for Java) columns + // output are not that usual .add(resultObject); } @@ -57,8 +58,8 @@ public void clearResults() { resultGroupedByRow.clear(); } - List matches() { - return indexes().map(i -> (Indexed) () -> i).collect(toList()); + List matches() { + return indexes().map(i -> new DTDecisionRule(i, null)).collect(toList()); } private Stream indexes() { @@ -147,25 +148,39 @@ public Object applyHitPolicy(EvaluationContext evaluationContext, } events.add(new HitPolicyViolationEvent( FEELEvent.Severity.WARN, - String.format("No rule matched for decision table '%s' and no default values were defined. Setting result to null.", decisionTable.getName()), + String.format("No rule matched for decision table '%s' and no default values were defined. " + + "Setting result to null.", decisionTable.getName()), decisionTable.getName(), Collections.emptyList())); } - List matchIndexes = items.matches(); - evaluationContext.notifyEvt( () -> { - List matchedIndexes = matchIndexes.stream().map( dr -> dr.getIndex() + 1 ).collect(Collectors.toList() ); - return new DecisionTableRulesMatchedEvent(FEELEvent.Severity.INFO, - String.format("Rules matched for decision table '%s': %s", decisionTable.getName(), matchIndexes), - decisionTable.getName(), - decisionTable.getName(), - matchedIndexes ); - } + List matchingDecisionRules = items.matches(); + evaluationContext.notifyEvt(() -> { + List matches = new ArrayList<>(); + List matchesId = new ArrayList<>(); + matchingDecisionRules.forEach(dr -> { + matches.add(dr.getIndex() + 1); + if (dr.getId() != null && !dr.getId().isEmpty()) { + matchesId.add(dr.getId()); + } + }); + return new DecisionTableRulesMatchedEvent(FEELEvent.Severity.INFO, + String.format("Rules matched for " + + "decision " + + "table '%s': " + + "%s", + decisionTable.getName(), matchingDecisionRules), + decisionTable.getName(), + decisionTable.getName(), + matches, + matchesId); + } ); List resultObjects = items.evaluateResults(evaluationContext); - Map errorMessages = checkResults(decisionTable.getOutputs(), evaluationContext, matchIndexes, resultObjects ); + Map errorMessages = checkResults(decisionTable.getOutputs(), evaluationContext, matchingDecisionRules + , resultObjects); if (!errorMessages.isEmpty()) { List offending = new ArrayList<>(errorMessages.keySet()); events.add(new HitPolicyViolationEvent( @@ -178,6 +193,6 @@ public Object applyHitPolicy(EvaluationContext evaluationContext, return null; } - return hitPolicy.getDti().dti(evaluationContext, decisionTable, matchIndexes, resultObjects); + return hitPolicy.getDti().dti(evaluationContext, decisionTable, matchingDecisionRules, resultObjects); } } diff --git a/kie-dmn/kie-dmn-core/src/main/java/org/kie/dmn/core/impl/AfterConditionalEvaluationEventImpl.java b/kie-dmn/kie-dmn-core/src/main/java/org/kie/dmn/core/impl/AfterConditionalEvaluationEventImpl.java new file mode 100644 index 00000000000..5d3c8eb2464 --- /dev/null +++ b/kie-dmn/kie-dmn-core/src/main/java/org/kie/dmn/core/impl/AfterConditionalEvaluationEventImpl.java @@ -0,0 +1,43 @@ +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you 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 + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.kie.dmn.core.impl; + +import org.kie.dmn.api.core.EvaluatorResult; +import org.kie.dmn.api.core.event.AfterConditionalEvaluationEvent; + +public class AfterConditionalEvaluationEventImpl implements AfterConditionalEvaluationEvent { + + private final EvaluatorResult evaluatorResult; + private final String executedId; + + public AfterConditionalEvaluationEventImpl(EvaluatorResult evaluatorResult, String executedId) { + this.evaluatorResult = evaluatorResult; + this.executedId = executedId; + } + + @Override + public EvaluatorResult getEvaluatorResultResult() { + return evaluatorResult; + } + + @Override + public String getExecutedId() { + return executedId; + } +} diff --git a/kie-dmn/kie-dmn-core/src/main/java/org/kie/dmn/core/impl/AfterEvaluateConditionalEventImpl.java b/kie-dmn/kie-dmn-core/src/main/java/org/kie/dmn/core/impl/AfterEvaluateConditionalEventImpl.java new file mode 100644 index 00000000000..4aa97cec111 --- /dev/null +++ b/kie-dmn/kie-dmn-core/src/main/java/org/kie/dmn/core/impl/AfterEvaluateConditionalEventImpl.java @@ -0,0 +1,43 @@ +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you 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 + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.kie.dmn.core.impl; + +import org.kie.dmn.api.core.event.AfterEvaluateConditionalEvent; +import org.kie.dmn.api.core.EvaluatorResult; + +public class AfterEvaluateConditionalEventImpl implements AfterEvaluateConditionalEvent { + + private final EvaluatorResult evaluatorResult; + private final String executedId; + + public AfterEvaluateConditionalEventImpl(EvaluatorResult evaluatorResult, String executedId) { + this.evaluatorResult = evaluatorResult; + this.executedId = executedId; + } + + @Override + public EvaluatorResult getEvaluatorResultResult() { + return evaluatorResult; + } + + @Override + public String getExecutedId() { + return executedId; + } +} diff --git a/kie-dmn/kie-dmn-core/src/main/java/org/kie/dmn/core/impl/AfterEvaluateDecisionTableEventImpl.java b/kie-dmn/kie-dmn-core/src/main/java/org/kie/dmn/core/impl/AfterEvaluateDecisionTableEventImpl.java index edfb392bc06..76d80fccfbe 100644 --- a/kie-dmn/kie-dmn-core/src/main/java/org/kie/dmn/core/impl/AfterEvaluateDecisionTableEventImpl.java +++ b/kie-dmn/kie-dmn-core/src/main/java/org/kie/dmn/core/impl/AfterEvaluateDecisionTableEventImpl.java @@ -33,14 +33,18 @@ public class AfterEvaluateDecisionTableEventImpl private final DMNResult result; private final List matches; private final List fired; + private final List matchesIds; + private final List firedIds; - public AfterEvaluateDecisionTableEventImpl(String nodeName, String dtName, String dtId, DMNResult result, List matches, List fired) { + public AfterEvaluateDecisionTableEventImpl(String nodeName, String dtName, String dtId, DMNResult result, List matches, List fired, List matchesIds, List firedIds) { this.nodeName = nodeName; this.dtName = dtName; this.dtId = dtId; this.result = result; this.matches = matches; this.fired = fired; + this.matchesIds = matchesIds; + this.firedIds = firedIds; } @Override @@ -73,9 +77,18 @@ public List getSelected() { return fired == null ? Collections.emptyList() : fired; } + @Override + public List getMatchesIds() { + return matchesIds == null ? Collections.emptyList() : matchesIds; + } + + @Override + public List getSelectedIds() {return firedIds == null ? Collections.emptyList() : firedIds; + } + @Override public String toString() { - return "AfterEvaluateDecisionTableEvent{ nodeName='"+nodeName+"' decisionTableName='" + dtName + "' matches=" + getMatches() + " fired=" + getSelected() + " }"; + return "AfterEvaluateDecisionTableEvent{ nodeName='"+nodeName+"' decisionTableName='" + dtName + "' matches=" + getMatches() + " fired=" + getSelected() + "' matchesIds=" + getMatchesIds() + " firedIds=" + getSelectedIds() + " }"; } } diff --git a/kie-dmn/kie-dmn-core/src/main/java/org/kie/dmn/core/impl/DMNRuntimeEventManagerUtils.java b/kie-dmn/kie-dmn-core/src/main/java/org/kie/dmn/core/impl/DMNRuntimeEventManagerUtils.java index 23879b1c7af..6469590ca80 100644 --- a/kie-dmn/kie-dmn-core/src/main/java/org/kie/dmn/core/impl/DMNRuntimeEventManagerUtils.java +++ b/kie-dmn/kie-dmn-core/src/main/java/org/kie/dmn/core/impl/DMNRuntimeEventManagerUtils.java @@ -26,8 +26,10 @@ import org.kie.dmn.api.core.ast.BusinessKnowledgeModelNode; import org.kie.dmn.api.core.ast.DecisionNode; import org.kie.dmn.api.core.ast.DecisionServiceNode; +import org.kie.dmn.api.core.event.AfterConditionalEvaluationEvent; import org.kie.dmn.api.core.event.AfterEvaluateAllEvent; import org.kie.dmn.api.core.event.AfterEvaluateBKMEvent; +import org.kie.dmn.api.core.event.AfterEvaluateConditionalEvent; import org.kie.dmn.api.core.event.AfterEvaluateContextEntryEvent; import org.kie.dmn.api.core.event.AfterEvaluateDecisionEvent; import org.kie.dmn.api.core.event.AfterEvaluateDecisionServiceEvent; @@ -42,6 +44,7 @@ import org.kie.dmn.api.core.event.BeforeInvokeBKMEvent; import org.kie.dmn.api.core.event.DMNRuntimeEventListener; import org.kie.dmn.api.core.event.DMNRuntimeEventManager; +import org.kie.dmn.api.core.EvaluatorResult; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -100,9 +103,9 @@ public static void fireBeforeEvaluateDecisionTable( DMNRuntimeEventManager event } } - public static void fireAfterEvaluateDecisionTable( DMNRuntimeEventManager eventManager, String nodeName, String dtName, String dtId, DMNResult result, List matches, List fired ) { + public static void fireAfterEvaluateDecisionTable( DMNRuntimeEventManager eventManager, String nodeName, String dtName, String dtId, DMNResult result, List matches, List fired, List matchedIds, List firedIds ) { if( eventManager.hasListeners() ) { - AfterEvaluateDecisionTableEvent event = new AfterEvaluateDecisionTableEventImpl(nodeName, dtName, dtId, result, matches, fired); + AfterEvaluateDecisionTableEvent event = new AfterEvaluateDecisionTableEventImpl(nodeName, dtName, dtId, result, matches, fired, matchedIds, firedIds); notifyListeners(eventManager, l -> l.afterEvaluateDecisionTable(event)); } } @@ -149,6 +152,20 @@ public static void fireAfterEvaluateAll(DMNRuntimeEventManagerImpl eventManager, } } + public static void fireAfterEvaluateConditional(DMNRuntimeEventManager eventManager, EvaluatorResult evaluatorResult, String executedId) { + if( eventManager.hasListeners() ) { + AfterEvaluateConditionalEvent event = new AfterEvaluateConditionalEventImpl(evaluatorResult, executedId); + notifyListeners(eventManager, l -> l.afterEvaluateConditional(event)); + } + } + + public static void fireAfterConditionalEvaluation(DMNRuntimeEventManager eventManager, EvaluatorResult evaluatorResult, String idExecuted) { + if( eventManager.hasListeners() ) { + AfterConditionalEvaluationEvent event = new AfterConditionalEvaluationEventImpl(evaluatorResult, idExecuted); + notifyListeners(eventManager, l -> l.afterConditionalEvaluation(event)); + } + } + private static void notifyListeners(DMNRuntimeEventManager eventManager, Consumer consumer) { for( DMNRuntimeEventListener listener : eventManager.getListeners() ) { try { @@ -159,6 +176,7 @@ private static void notifyListeners(DMNRuntimeEventManager eventManager, Consume } } + private DMNRuntimeEventManagerUtils() { // Constructing instances is not allowed for this class } diff --git a/kie-dmn/kie-dmn-core/src/main/java/org/kie/dmn/core/impl/DMNRuntimeImpl.java b/kie-dmn/kie-dmn-core/src/main/java/org/kie/dmn/core/impl/DMNRuntimeImpl.java index 12a3eebea54..203c44f32af 100644 --- a/kie-dmn/kie-dmn-core/src/main/java/org/kie/dmn/core/impl/DMNRuntimeImpl.java +++ b/kie-dmn/kie-dmn-core/src/main/java/org/kie/dmn/core/impl/DMNRuntimeImpl.java @@ -45,7 +45,7 @@ import org.kie.dmn.api.core.event.BeforeEvaluateDecisionEvent; import org.kie.dmn.api.core.event.DMNRuntimeEventListener; import org.kie.dmn.core.api.DMNFactory; -import org.kie.dmn.core.api.EvaluatorResult; +import org.kie.dmn.api.core.EvaluatorResult; import org.kie.dmn.core.ast.BusinessKnowledgeModelNodeImpl; import org.kie.dmn.core.ast.DMNBaseNode; import org.kie.dmn.core.ast.DMNDecisionServiceEvaluator; diff --git a/kie-dmn/kie-dmn-core/src/main/java/org/kie/dmn/core/pmml/AbstractDMNKiePMMLInvocationEvaluator.java b/kie-dmn/kie-dmn-core/src/main/java/org/kie/dmn/core/pmml/AbstractDMNKiePMMLInvocationEvaluator.java index 584005239ce..414d1efbc4b 100644 --- a/kie-dmn/kie-dmn-core/src/main/java/org/kie/dmn/core/pmml/AbstractDMNKiePMMLInvocationEvaluator.java +++ b/kie-dmn/kie-dmn-core/src/main/java/org/kie/dmn/core/pmml/AbstractDMNKiePMMLInvocationEvaluator.java @@ -28,8 +28,8 @@ import org.kie.dmn.api.core.DMNResult; import org.kie.dmn.api.core.DMNType; import org.kie.dmn.api.core.event.DMNRuntimeEventManager; -import org.kie.dmn.core.api.EvaluatorResult; -import org.kie.dmn.core.api.EvaluatorResult.ResultType; +import org.kie.dmn.api.core.EvaluatorResult; +import org.kie.dmn.api.core.EvaluatorResult.ResultType; import org.kie.dmn.core.ast.EvaluatorResultImpl; import org.kie.dmn.core.impl.CompositeTypeImpl; import org.kie.dmn.core.impl.DMNResultImpl; diff --git a/kie-dmn/kie-dmn-core/src/main/java/org/kie/dmn/core/pmml/AbstractPMMLInvocationEvaluator.java b/kie-dmn/kie-dmn-core/src/main/java/org/kie/dmn/core/pmml/AbstractPMMLInvocationEvaluator.java index 25f6b18a963..fb07f4708ad 100644 --- a/kie-dmn/kie-dmn-core/src/main/java/org/kie/dmn/core/pmml/AbstractPMMLInvocationEvaluator.java +++ b/kie-dmn/kie-dmn-core/src/main/java/org/kie/dmn/core/pmml/AbstractPMMLInvocationEvaluator.java @@ -30,8 +30,8 @@ import org.kie.dmn.api.core.DMNType; import org.kie.dmn.api.core.event.DMNRuntimeEventManager; import org.kie.dmn.core.api.DMNExpressionEvaluator; -import org.kie.dmn.core.api.EvaluatorResult; -import org.kie.dmn.core.api.EvaluatorResult.ResultType; +import org.kie.dmn.api.core.EvaluatorResult; +import org.kie.dmn.api.core.EvaluatorResult.ResultType; import org.kie.dmn.core.ast.DMNFunctionDefinitionEvaluator.FormalParameter; import org.kie.dmn.core.ast.EvaluatorResultImpl; import org.kie.dmn.core.impl.DMNModelImpl; diff --git a/kie-dmn/kie-dmn-core/src/main/java/org/kie/dmn/core/util/Msg.java b/kie-dmn/kie-dmn-core/src/main/java/org/kie/dmn/core/util/Msg.java index 2f65e3e2639..d099f5b0131 100644 --- a/kie-dmn/kie-dmn-core/src/main/java/org/kie/dmn/core/util/Msg.java +++ b/kie-dmn/kie-dmn-core/src/main/java/org/kie/dmn/core/util/Msg.java @@ -112,8 +112,8 @@ public final class Msg { public static final Message2 ERR_COMPILING_ALLOWED_VALUES_LIST_ON_ITEM_DEF = new Message2( DMNMessageType.ERR_COMPILING_FEEL, "Error compiling allowed values list '%s' on item definition '%s'" ); public static final Message2 ERR_COMPILING_TYPE_CONSTRAINT_LIST_ON_ITEM_DEF = new Message2( DMNMessageType.ERR_COMPILING_FEEL, "Error compiling type constraint list '%s' on item definition '%s'" ); public static final Message4 ERR_COMPILING_FEEL_EXPR_FOR_NAME_ON_NODE = new Message4( DMNMessageType.ERR_COMPILING_FEEL, "Error compiling FEEL expression '%s' for name '%s' on node '%s': %s" ); - public static final Message2 ERR_EVAL_CTX_ENTRY_ON_CTX = new Message2( DMNMessageType.ERR_EVAL_CTX, "Error evaluating context extry '%s' on context '%s'" ); - public static final Message3 ERR_EVAL_CTX_ENTRY_ON_CTX_MSG = new Message3( DMNMessageType.ERR_EVAL_CTX, "Unrecoverable error evaluating context extry '%s' on context '%s': %s" ); + public static final Message2 ERR_EVAL_CTX_ENTRY_ON_CTX = new Message2( DMNMessageType.ERR_EVAL_CTX, "Error evaluating context entry '%s' on context '%s'" ); + public static final Message3 ERR_EVAL_CTX_ENTRY_ON_CTX_MSG = new Message3( DMNMessageType.ERR_EVAL_CTX, "Unrecoverable error evaluating context entry '%s' on context '%s': %s" ); public static final Message1 DECISION_NOT_FOUND_FOR_NAME = new Message1( DMNMessageType.DECISION_NOT_FOUND, "Decision not found for name '%s'" ); public static final Message1 DECISION_NOT_FOUND_FOR_ID = new Message1( DMNMessageType.DECISION_NOT_FOUND, "Decision not found for type '%s'" ); public static final Message1 DECISION_SERVICE_NOT_FOUND_FOR_NAME = new Message1( DMNMessageType.DECISION_NOT_FOUND, "Decision Service not found for name '%s'"); diff --git a/kie-dmn/kie-dmn-core/src/test/java/org/kie/dmn/core/DMNCompilerTest.java b/kie-dmn/kie-dmn-core/src/test/java/org/kie/dmn/core/DMNCompilerTest.java index 7e9874ef7da..18d96e5ef71 100644 --- a/kie-dmn/kie-dmn-core/src/test/java/org/kie/dmn/core/DMNCompilerTest.java +++ b/kie-dmn/kie-dmn-core/src/test/java/org/kie/dmn/core/DMNCompilerTest.java @@ -56,7 +56,7 @@ import static org.kie.dmn.core.util.DynamicTypeUtils.entry; import static org.kie.dmn.core.util.DynamicTypeUtils.mapOf; import static org.kie.dmn.core.util.DynamicTypeUtils.prototype; -import static org.kie.dmn.feel.codegen.feel11.CodegenTestUtil.newEmptyEvaluationContext; +import static org.kie.dmn.feel.util.EvaluationContextTestUtil.newEmptyEvaluationContext; public class DMNCompilerTest extends BaseVariantTest { diff --git a/kie-dmn/kie-dmn-core/src/test/java/org/kie/dmn/core/DMNInputRuntimeTest.java b/kie-dmn/kie-dmn-core/src/test/java/org/kie/dmn/core/DMNInputRuntimeTest.java index 4feaac9d57a..5f245869683 100644 --- a/kie-dmn/kie-dmn-core/src/test/java/org/kie/dmn/core/DMNInputRuntimeTest.java +++ b/kie-dmn/kie-dmn-core/src/test/java/org/kie/dmn/core/DMNInputRuntimeTest.java @@ -19,6 +19,7 @@ package org.kie.dmn.core; import java.math.BigDecimal; +import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.List; @@ -39,7 +40,12 @@ import org.kie.dmn.api.core.ast.DecisionServiceNode; import org.kie.dmn.api.core.ast.InputDataNode; import org.kie.dmn.api.core.ast.ItemDefNode; +import org.kie.dmn.api.core.event.AfterConditionalEvaluationEvent; +import org.kie.dmn.api.core.event.AfterEvaluateConditionalEvent; +import org.kie.dmn.api.core.event.AfterEvaluateDecisionTableEvent; +import org.kie.dmn.api.core.event.DMNRuntimeEventListener; import org.kie.dmn.core.api.DMNFactory; +import org.kie.dmn.core.api.event.DefaultDMNRuntimeEventListener; import org.kie.dmn.core.util.DMNRuntimeUtil; import static org.assertj.core.api.Assertions.assertThat; @@ -377,6 +383,72 @@ void typeConstraintsChecks(boolean useExecModelCompiler) { assertThat(dmnResult3.getMessages().stream().anyMatch(m -> m.getMessageType().equals(DMNMessageType.ERROR_EVAL_NODE))).isTrue(); } + @ParameterizedTest + @MethodSource("params") + void evaluationHitIdsCheck(boolean useExecModelCompiler) { + init(useExecModelCompiler); + final String ifElementId = "_3C702CE4-E5A0-4B6F-905D-C2621FFFA387"; + final String thenElementId = "_6481FF12-61B5-451C-B775-4143D9B6CD6B"; + final String elseElementId = "_2CD02CB2-6B56-45C4-B461-405E89D45633"; + final String ruleId0 = "_1578BD9E-2BF9-4BFC-8956-1A736959C937"; + final String ruleId1 = "_31CD7AA3-A806-4E7E-B512-821F82043620"; + final String ruleId3 = "_2545E1A8-93D3-4C8A-A0ED-8AD8B10A58F9"; + final String ruleId4 = "_510A50DA-D5A4-4F06-B0BE-7F8F2AA83740"; + final DMNRuntime runtime = DMNRuntimeUtil.createRuntime("valid_models/DMNv1_5/RiskScore_Simple.dmn", this.getClass() ); + + + final List evaluateConditionalIds = new ArrayList<>(); + final List conditionalEvaluationIds = new ArrayList<>(); + final List executedRuleIds = new ArrayList<>(); + runtime.addListener(new DefaultDMNRuntimeEventListener() { + + @Override + public void afterConditionalEvaluation(AfterConditionalEvaluationEvent event) { + conditionalEvaluationIds.add(event.getExecutedId()); + } + + @Override + public void afterEvaluateConditional(AfterEvaluateConditionalEvent event) { + evaluateConditionalIds.add(event.getExecutedId()); + } + + @Override + public void afterEvaluateDecisionTable(AfterEvaluateDecisionTableEvent event) { + executedRuleIds.addAll(event.getSelectedIds()); + } + + }); + final DMNModel dmnModel = runtime.getModel( + "https://kie.org/dmn/_A3317FB1-7BF8-4904-A5F4-2CD63AF3AEC9", + "DMN_A77074C1-21FE-4F7E-9753-F84661569AFC" ); + assertThat(dmnModel).isNotNull(); + assertThat(dmnModel.hasErrors()).as(DMNRuntimeUtil.formatMessages(dmnModel.getMessages())).isFalse(); + + final DMNContext ctx1 = runtime.newContext(); + ctx1.set("Credit Score", "Poor"); + ctx1.set("DTI", 33); + final DMNResult dmnResult1 = runtime.evaluateAll( dmnModel, ctx1 ); + assertThat(dmnResult1.hasErrors()).as(DMNRuntimeUtil.formatMessages(dmnResult1.getMessages())).isFalse(); + assertThat( dmnResult1.getContext().get( "Risk Score" )).isEqualTo(BigDecimal.valueOf(50)); + assertThat(evaluateConditionalIds).hasSize(1).allMatch(id -> id.equals(ifElementId)); + assertThat(conditionalEvaluationIds).hasSize(1).allMatch(id -> id.equals(elseElementId)); + assertThat(executedRuleIds).hasSize(2).contains(ruleId0, ruleId3); + + // + evaluateConditionalIds.clear(); + conditionalEvaluationIds.clear(); + executedRuleIds.clear(); + final DMNContext ctx2 = runtime.newContext(); + ctx2.set("Credit Score", "Excellent"); + ctx2.set("DTI", 10); + final DMNResult dmnResult2 = runtime.evaluateAll( dmnModel, ctx2 ); + assertThat(dmnResult2.hasErrors()).as(DMNRuntimeUtil.formatMessages(dmnResult1.getMessages())).isFalse(); + assertThat( dmnResult2.getContext().get( "Risk Score" )).isEqualTo(BigDecimal.valueOf(20)); + assertThat(evaluateConditionalIds).hasSize(1).allMatch(id -> id.equals(ifElementId)); + assertThat(conditionalEvaluationIds).hasSize(1).allMatch(id -> id.equals(thenElementId)); + assertThat(executedRuleIds).hasSize(2).contains(ruleId1, ruleId4); + } + @ParameterizedTest @MethodSource("params") void dmnInputDataNodeTypeTest(boolean useExecModelCompiler) { diff --git a/kie-dmn/kie-dmn-core/src/test/java/org/kie/dmn/core/DMNRuntimeTest.java b/kie-dmn/kie-dmn-core/src/test/java/org/kie/dmn/core/DMNRuntimeTest.java index 89e261436f7..13a044a6576 100644 --- a/kie-dmn/kie-dmn-core/src/test/java/org/kie/dmn/core/DMNRuntimeTest.java +++ b/kie-dmn/kie-dmn-core/src/test/java/org/kie/dmn/core/DMNRuntimeTest.java @@ -63,7 +63,7 @@ import org.kie.dmn.api.core.event.BeforeEvaluateDecisionTableEvent; import org.kie.dmn.api.core.event.DMNRuntimeEventListener; import org.kie.dmn.core.api.DMNFactory; -import org.kie.dmn.core.api.EvaluatorResult; +import org.kie.dmn.api.core.EvaluatorResult; import org.kie.dmn.core.ast.DMNContextEvaluator; import org.kie.dmn.core.ast.DecisionNodeImpl; import org.kie.dmn.core.ast.EvaluatorResultImpl; diff --git a/kie-dmn/kie-dmn-core/src/test/java/org/kie/dmn/core/ast/DMNConditionalEvaluatorTest.java b/kie-dmn/kie-dmn-core/src/test/java/org/kie/dmn/core/ast/DMNConditionalEvaluatorTest.java new file mode 100644 index 00000000000..4514ce77ce6 --- /dev/null +++ b/kie-dmn/kie-dmn-core/src/test/java/org/kie/dmn/core/ast/DMNConditionalEvaluatorTest.java @@ -0,0 +1,175 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you 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 + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.kie.dmn.core.ast; + +import java.util.Collections; +import java.util.List; +import java.util.Set; + +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.kie.dmn.api.core.EvaluatorResult; +import org.kie.dmn.api.core.event.AfterConditionalEvaluationEvent; +import org.kie.dmn.api.core.event.AfterEvaluateConditionalEvent; +import org.kie.dmn.api.core.event.DMNRuntimeEventListener; +import org.kie.dmn.api.core.event.DMNRuntimeEventManager; +import org.kie.dmn.core.api.DMNExpressionEvaluator; +import org.kie.dmn.core.impl.DMNResultImpl; +import org.kie.dmn.model.api.ChildExpression; +import org.kie.dmn.model.api.Conditional; +import org.kie.dmn.model.api.DMNElement; +import org.kie.dmn.model.api.DMNModelInstrumentedBase; +import org.kie.dmn.model.api.Expression; +import org.mockito.ArgumentCaptor; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.reset; +import static org.mockito.Mockito.spy; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +class DMNConditionalEvaluatorTest { + + private static final String ID_ELEMENT_ID = "ID_ELEMENT_ID"; + private static final String THEN_ELEMENT_ID = "THEN_ELEMENT_ID"; + private static final String ELSE_ELEMENT_ID = "ELSE_ELEMENT_ID"; + private static DMNRuntimeEventManager eventManagerMock; + private static DMNRuntimeEventListener spiedListener; + private static EvaluatorResult ifEvaluationMock; + private static EvaluatorResult thenEvaluationMock; + private static EvaluatorResult elseEvaluationMock; + private static DMNResultImpl dmnResultMock; + private static DMNConditionalEvaluator dmnConditionalEvaluator; + + @BeforeAll + static void setUp() { + spiedListener = spy(DMNRuntimeEventListener.class); + Set listeners = Collections.singleton(spiedListener); + eventManagerMock = mock(DMNRuntimeEventManager.class); + when(eventManagerMock.hasListeners()).thenReturn(true); + when(eventManagerMock.getListeners()).thenReturn(listeners); + ifEvaluationMock = mock(EvaluatorResult.class); + thenEvaluationMock = mock(EvaluatorResult.class); + elseEvaluationMock = mock(EvaluatorResult.class); + + dmnResultMock = mock(DMNResultImpl.class); + DMNExpressionEvaluator ifEvaluatorMock = mock(DMNExpressionEvaluator.class); + DMNExpressionEvaluator thenEvaluatorMock = mock(DMNExpressionEvaluator.class); + DMNExpressionEvaluator elseEvaluatorMock = mock(DMNExpressionEvaluator.class); + + when(ifEvaluatorMock.evaluate(eventManagerMock, dmnResultMock)).thenReturn(ifEvaluationMock); + when(thenEvaluatorMock.evaluate(eventManagerMock, dmnResultMock)).thenReturn(thenEvaluationMock); + when(elseEvaluatorMock.evaluate(eventManagerMock, dmnResultMock)).thenReturn(elseEvaluationMock); + + ChildExpression ifMock = mock(ChildExpression.class); + when(ifMock.getId()).thenReturn(ID_ELEMENT_ID); + + ChildExpression thenMock = mock(ChildExpression.class); + when(thenMock.getId()).thenReturn(THEN_ELEMENT_ID); + + ChildExpression elseMock = mock(ChildExpression.class); + when(elseMock.getId()).thenReturn(ELSE_ELEMENT_ID); + + Conditional conditionalMock = mock(Conditional.class); + when(conditionalMock.getIf()).thenReturn(ifMock); + when(conditionalMock.getThen()).thenReturn(thenMock); + when(conditionalMock.getElse()).thenReturn(elseMock); + + List nodeChildren = Collections.singletonList(conditionalMock); + DMNElement nodeMock = mock(DMNElement.class); + when(nodeMock.getChildren()).thenReturn(nodeChildren); + + dmnConditionalEvaluator = new DMNConditionalEvaluator("name", + nodeMock, + ifEvaluatorMock, + thenEvaluatorMock, + elseEvaluatorMock); + } + + @BeforeEach + void setup() { + reset(spiedListener); + } + + @Test + void evaluateListenerInvocation() { + when(ifEvaluationMock.getResultType()).thenReturn(EvaluatorResult.ResultType.FAILURE); // not interested in + // nested execution + + dmnConditionalEvaluator.evaluate(eventManagerMock, dmnResultMock); + ArgumentCaptor evaluateConditionalEventArgumentCaptor = + ArgumentCaptor.forClass(AfterEvaluateConditionalEvent.class); + verify(spiedListener).afterEvaluateConditional(evaluateConditionalEventArgumentCaptor.capture()); + AfterEvaluateConditionalEvent evaluateConditionalEvent = evaluateConditionalEventArgumentCaptor.getValue(); + assertThat(evaluateConditionalEvent).isNotNull(); + assertThat(evaluateConditionalEvent.getEvaluatorResultResult()).isEqualTo(ifEvaluationMock); + assertThat(evaluateConditionalEvent.getExecutedId()).isEqualTo(ID_ELEMENT_ID); + } + + @Test + void evaluateManageBooleanOrNullIfResultInvocation() { + when(ifEvaluationMock.getResultType()).thenReturn(EvaluatorResult.ResultType.SUCCESS); + when(ifEvaluationMock.getResult()).thenReturn(true); + + DMNConditionalEvaluator spiedDmnConditionalEvaluator = spy(dmnConditionalEvaluator); + spiedDmnConditionalEvaluator.evaluate(eventManagerMock, dmnResultMock); + verify(spiedDmnConditionalEvaluator).manageBooleanOrNullIfResult(true, eventManagerMock, dmnResultMock); + } + + @Test + void manageBooleanOrNullIfResultWithTrue() { + dmnConditionalEvaluator.manageBooleanOrNullIfResult(true, eventManagerMock, dmnResultMock); + ArgumentCaptor afterConditionalEvaluationEventArgumentCaptor = + ArgumentCaptor.forClass(AfterConditionalEvaluationEvent.class); + verify(spiedListener).afterConditionalEvaluation(afterConditionalEvaluationEventArgumentCaptor.capture()); + AfterConditionalEvaluationEvent conditionalEvaluationEvent = + afterConditionalEvaluationEventArgumentCaptor.getValue(); + assertThat(conditionalEvaluationEvent).isNotNull(); + assertThat(conditionalEvaluationEvent.getEvaluatorResultResult()).isEqualTo(thenEvaluationMock); + assertThat(conditionalEvaluationEvent.getExecutedId()).isEqualTo(THEN_ELEMENT_ID); + } + + @Test + void manageBooleanOrNullIfResultWithFalse() { + dmnConditionalEvaluator.manageBooleanOrNullIfResult(false, eventManagerMock, dmnResultMock); + ArgumentCaptor afterConditionalEvaluationEventArgumentCaptor = + ArgumentCaptor.forClass(AfterConditionalEvaluationEvent.class); + verify(spiedListener).afterConditionalEvaluation(afterConditionalEvaluationEventArgumentCaptor.capture()); + AfterConditionalEvaluationEvent conditionalEvaluationEvent = + afterConditionalEvaluationEventArgumentCaptor.getValue(); + assertThat(conditionalEvaluationEvent).isNotNull(); + assertThat(conditionalEvaluationEvent.getEvaluatorResultResult()).isEqualTo(elseEvaluationMock); + assertThat(conditionalEvaluationEvent.getExecutedId()).isEqualTo(ELSE_ELEMENT_ID); + } + + @Test + void manageBooleanOrNullIfResultWithNull() { + dmnConditionalEvaluator.manageBooleanOrNullIfResult(null, eventManagerMock, dmnResultMock); + ArgumentCaptor afterConditionalEvaluationEventArgumentCaptor = + ArgumentCaptor.forClass(AfterConditionalEvaluationEvent.class); + verify(spiedListener).afterConditionalEvaluation(afterConditionalEvaluationEventArgumentCaptor.capture()); + AfterConditionalEvaluationEvent conditionalEvaluationEvent = + afterConditionalEvaluationEventArgumentCaptor.getValue(); + assertThat(conditionalEvaluationEvent).isNotNull(); + assertThat(conditionalEvaluationEvent.getEvaluatorResultResult()).isEqualTo(elseEvaluationMock); + assertThat(conditionalEvaluationEvent.getExecutedId()).isEqualTo(ELSE_ELEMENT_ID); + } +} \ No newline at end of file diff --git a/kie-dmn/kie-dmn-core/src/test/java/org/kie/dmn/core/ast/DMNContextEvaluatorTest.java b/kie-dmn/kie-dmn-core/src/test/java/org/kie/dmn/core/ast/DMNContextEvaluatorTest.java index 066c5439439..ab1f01394f0 100644 --- a/kie-dmn/kie-dmn-core/src/test/java/org/kie/dmn/core/ast/DMNContextEvaluatorTest.java +++ b/kie-dmn/kie-dmn-core/src/test/java/org/kie/dmn/core/ast/DMNContextEvaluatorTest.java @@ -31,7 +31,7 @@ import org.kie.dmn.api.core.ast.DecisionNode; import org.kie.dmn.core.api.DMNExpressionEvaluator; import org.kie.dmn.core.api.DMNFactory; -import org.kie.dmn.core.api.EvaluatorResult; +import org.kie.dmn.api.core.EvaluatorResult; import org.kie.dmn.core.impl.DMNDecisionResultImpl; import org.kie.dmn.core.impl.DMNResultImpl; import org.kie.dmn.core.impl.DMNResultImplFactory; diff --git a/kie-dmn/kie-dmn-core/src/test/java/org/kie/dmn/core/decisionservices/DMNDecisionServicesTest.java b/kie-dmn/kie-dmn-core/src/test/java/org/kie/dmn/core/decisionservices/DMNDecisionServicesTest.java index 69be0798dd9..a98a5d1ea97 100644 --- a/kie-dmn/kie-dmn-core/src/test/java/org/kie/dmn/core/decisionservices/DMNDecisionServicesTest.java +++ b/kie-dmn/kie-dmn-core/src/test/java/org/kie/dmn/core/decisionservices/DMNDecisionServicesTest.java @@ -633,8 +633,8 @@ void test20190520(boolean useExecModelCompiler) { final DMNResult dmnResult = runtime.evaluateAll(dmnModel, emptyContext); LOG.debug("{}", dmnResult); dmnResult.getDecisionResults().forEach(x -> LOG.debug("{}", x)); - assertThat(dmnResult.hasErrors()).as(DMNRuntimeUtil.formatMessages(dmnResult.getMessages())).isFalse(); - assertThat((Map) dmnResult.getDecisionResultByName("my invoke DS1").getResult()).containsEntry("outDS1", true); + assertThat(dmnResult.hasErrors()).as(DMNRuntimeUtil.formatMessages(dmnResult.getMessages())).isTrue(); + assertThat((Map) dmnResult.getDecisionResultByName("my invoke DS1").getResult()).isNull(); } @ParameterizedTest diff --git a/kie-dmn/kie-dmn-core/src/test/java/org/kie/dmn/core/impl/DMNRuntimeEventManagerUtilsTest.java b/kie-dmn/kie-dmn-core/src/test/java/org/kie/dmn/core/impl/DMNRuntimeEventManagerUtilsTest.java new file mode 100644 index 00000000000..1a78b34fe8c --- /dev/null +++ b/kie-dmn/kie-dmn-core/src/test/java/org/kie/dmn/core/impl/DMNRuntimeEventManagerUtilsTest.java @@ -0,0 +1,78 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you 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 + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.kie.dmn.core.impl; + +import java.util.Collections; +import java.util.Set; + +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; +import org.kie.dmn.api.core.EvaluatorResult; +import org.kie.dmn.api.core.event.AfterConditionalEvaluationEvent; +import org.kie.dmn.api.core.event.AfterEvaluateConditionalEvent; +import org.kie.dmn.api.core.event.DMNRuntimeEventListener; +import org.kie.dmn.api.core.event.DMNRuntimeEventManager; +import org.mockito.ArgumentCaptor; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.spy; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +class DMNRuntimeEventManagerUtilsTest { + + private static DMNRuntimeEventManager eventManagerMock; + private static DMNRuntimeEventListener spiedListener; + + @BeforeAll + static void setUp() { + spiedListener = spy(DMNRuntimeEventListener.class); + Set listeners = Collections.singleton(spiedListener); + eventManagerMock = mock(DMNRuntimeEventManager.class); + when(eventManagerMock.hasListeners()).thenReturn(true); + when(eventManagerMock.getListeners()).thenReturn(listeners); + } + + @Test + void fireAfterEvaluateConditional() { + EvaluatorResult evaluatorResult = mock(EvaluatorResult.class); + String executedId = "EXECUTED_ID"; + DMNRuntimeEventManagerUtils.fireAfterEvaluateConditional(eventManagerMock, evaluatorResult, executedId); + ArgumentCaptor evaluateConditionalEventArgumentCaptor = ArgumentCaptor.forClass(AfterEvaluateConditionalEvent.class); + verify(spiedListener).afterEvaluateConditional (evaluateConditionalEventArgumentCaptor.capture()); + AfterEvaluateConditionalEvent evaluateConditionalEvent = evaluateConditionalEventArgumentCaptor.getValue(); + assertThat(evaluateConditionalEvent).isNotNull(); + assertThat(evaluateConditionalEvent.getEvaluatorResultResult()).isEqualTo(evaluatorResult); + assertThat(evaluateConditionalEvent.getExecutedId()).isEqualTo(executedId); + } + + @Test + void fireAfterConditionalEvaluation() { + EvaluatorResult evaluatorResult = mock(EvaluatorResult.class); + String executedId = "EXECUTED_ID"; + DMNRuntimeEventManagerUtils.fireAfterConditionalEvaluation(eventManagerMock, evaluatorResult, executedId); + ArgumentCaptor conditionalEvaluationEventArgumentCaptor = ArgumentCaptor.forClass(AfterConditionalEvaluationEvent.class); + verify(spiedListener).afterConditionalEvaluation (conditionalEvaluationEventArgumentCaptor.capture()); + AfterConditionalEvaluationEvent evaluateConditionalEvent = conditionalEvaluationEventArgumentCaptor.getValue(); + assertThat(evaluateConditionalEvent).isNotNull(); + assertThat(evaluateConditionalEvent.getEvaluatorResultResult()).isEqualTo(evaluatorResult); + assertThat(evaluateConditionalEvent.getExecutedId()).isEqualTo(executedId); + } +} \ No newline at end of file diff --git a/kie-dmn/kie-dmn-feel/src/main/antlr4/org/kie/dmn/feel/parser/feel11/FEEL_1_1.g4 b/kie-dmn/kie-dmn-feel/src/main/antlr4/org/kie/dmn/feel/parser/feel11/FEEL_1_1.g4 index 4760125e128..09eb8cb081a 100644 --- a/kie-dmn/kie-dmn-feel/src/main/antlr4/org/kie/dmn/feel/parser/feel11/FEEL_1_1.g4 +++ b/kie-dmn/kie-dmn-feel/src/main/antlr4/org/kie/dmn/feel/parser/feel11/FEEL_1_1.g4 @@ -135,6 +135,7 @@ type helper.popScope(); } : {_input.LT(1).getText().equals("list")}? sk=Identifier LT type GT #listType + | {_input.LT(1).getText().equals("range")}? sk=Identifier LT type GT #rangeType | {_input.LT(1).getText().equals("context")}? sk=Identifier LT Identifier COLON type ( COMMA Identifier COLON type )* GT #contextType | FUNCTION #qnType | FUNCTION LT (type ( COMMA type )*)? GT RARROW type #functionType @@ -323,7 +324,8 @@ literal | BooleanLiteral #boolLiteral | atLiteral #atLiteralLabel | StringLiteral #stringLiteral - | NULL #nullLiteral + | NULL #nullLiteral + | UNDEFINEDVALUE #undefined ; atLiteral @@ -339,6 +341,7 @@ BooleanLiteral | FALSE ; + /************************** * OTHER CONSTRUCTS **************************/ @@ -462,6 +465,7 @@ reusableKeywords | BETWEEN | NOT | NULL + | UNDEFINEDVALUE | TRUE | FALSE ; @@ -535,6 +539,10 @@ NULL : 'null' ; +UNDEFINEDVALUE + : 'undefined' + ; + TRUE : 'true' ; diff --git a/kie-dmn/kie-dmn-feel/src/main/java/org/kie/dmn/feel/codegen/feel11/ASTCompilerHelper.java b/kie-dmn/kie-dmn-feel/src/main/java/org/kie/dmn/feel/codegen/feel11/ASTCompilerHelper.java index 30930577189..b2b5f1bf59d 100644 --- a/kie-dmn/kie-dmn-feel/src/main/java/org/kie/dmn/feel/codegen/feel11/ASTCompilerHelper.java +++ b/kie-dmn/kie-dmn-feel/src/main/java/org/kie/dmn/feel/codegen/feel11/ASTCompilerHelper.java @@ -72,12 +72,14 @@ import org.kie.dmn.feel.lang.ast.QualifiedNameNode; import org.kie.dmn.feel.lang.ast.QuantifiedExpressionNode; import org.kie.dmn.feel.lang.ast.RangeNode; +import org.kie.dmn.feel.lang.ast.RangeTypeNode; import org.kie.dmn.feel.lang.ast.SignedUnaryNode; import org.kie.dmn.feel.lang.ast.StringNode; import org.kie.dmn.feel.lang.ast.TemporalConstantNode; import org.kie.dmn.feel.lang.ast.TypeNode; import org.kie.dmn.feel.lang.ast.UnaryTestListNode; import org.kie.dmn.feel.lang.ast.UnaryTestNode; +import org.kie.dmn.feel.lang.ast.UndefinedValueNode; import org.kie.dmn.feel.lang.impl.JavaBackedType; import org.kie.dmn.feel.lang.impl.MapBackedType; import org.kie.dmn.feel.lang.types.AliasFEELType; @@ -136,12 +138,14 @@ import static org.kie.dmn.feel.codegen.feel11.DMNCodegenConstants.QUALIFIEDNAMENODE_CT; import static org.kie.dmn.feel.codegen.feel11.DMNCodegenConstants.QUANTIFIEDEXPRESSIONNODE_CT; import static org.kie.dmn.feel.codegen.feel11.DMNCodegenConstants.RANGENODE_CT; +import static org.kie.dmn.feel.codegen.feel11.DMNCodegenConstants.RANGETYPENODE_CT; import static org.kie.dmn.feel.codegen.feel11.DMNCodegenConstants.SIGNEDUNARYNODE_CT; import static org.kie.dmn.feel.codegen.feel11.DMNCodegenConstants.STRINGNODE_CT; import static org.kie.dmn.feel.codegen.feel11.DMNCodegenConstants.TEMPORALCONSTANTNODE_CT; import static org.kie.dmn.feel.codegen.feel11.DMNCodegenConstants.TYPE_CT; import static org.kie.dmn.feel.codegen.feel11.DMNCodegenConstants.UNARYTESTLISTNODE_CT; import static org.kie.dmn.feel.codegen.feel11.DMNCodegenConstants.UNARYTESTNODE_CT; +import static org.kie.dmn.feel.codegen.feel11.DMNCodegenConstants.UNDEFINEDVALUENODE_CT; import static org.kie.dmn.feel.util.CodegenUtils.getEnumExpression; import static org.kie.dmn.feel.util.CodegenUtils.getListExpression; import static org.kie.dmn.feel.util.CodegenUtils.getStringLiteralExpr; @@ -431,6 +435,12 @@ public BlockStmt add(RangeNode n) { endExpression), n.getText()); } + public BlockStmt add(RangeTypeNode n) { + Expression genTypeNodeExpression = getNodeExpression(n.getGenericTypeNode()); + return addVariableDeclaratorWithObjectCreation(RANGETYPENODE_CT, NodeList.nodeList(genTypeNodeExpression), + n.getText()); + } + public BlockStmt add(SignedUnaryNode n) { Expression signExpression = getEnumExpression(n.getSign()); Expression expressionExpression = getNodeExpression(n.getExpression()); @@ -480,6 +490,10 @@ public BlockStmt add(UnaryTestNode n) { n.getText()); } + public BlockStmt add(UndefinedValueNode n) { + return addVariableDeclaratorWithObjectCreation(UNDEFINEDVALUENODE_CT, NodeList.nodeList()); + } + public String getLastVariableName() { return lastVariableName.get(); } diff --git a/kie-dmn/kie-dmn-feel/src/main/java/org/kie/dmn/feel/codegen/feel11/ASTCompilerVisitor.java b/kie-dmn/kie-dmn-feel/src/main/java/org/kie/dmn/feel/codegen/feel11/ASTCompilerVisitor.java index 0a509bca667..ffa86fc0613 100644 --- a/kie-dmn/kie-dmn-feel/src/main/java/org/kie/dmn/feel/codegen/feel11/ASTCompilerVisitor.java +++ b/kie-dmn/kie-dmn-feel/src/main/java/org/kie/dmn/feel/codegen/feel11/ASTCompilerVisitor.java @@ -50,11 +50,13 @@ import org.kie.dmn.feel.lang.ast.QualifiedNameNode; import org.kie.dmn.feel.lang.ast.QuantifiedExpressionNode; import org.kie.dmn.feel.lang.ast.RangeNode; +import org.kie.dmn.feel.lang.ast.RangeTypeNode; import org.kie.dmn.feel.lang.ast.SignedUnaryNode; import org.kie.dmn.feel.lang.ast.StringNode; import org.kie.dmn.feel.lang.ast.TemporalConstantNode; import org.kie.dmn.feel.lang.ast.UnaryTestListNode; import org.kie.dmn.feel.lang.ast.UnaryTestNode; +import org.kie.dmn.feel.lang.ast.UndefinedValueNode; import org.kie.dmn.feel.lang.ast.Visitor; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -253,6 +255,12 @@ public BlockStmt visit(RangeNode n) { return compilerHelper.add(n); } + @Override + public BlockStmt visit(RangeTypeNode n) { + LOGGER.trace("visit {}", n); + return compilerHelper.add(n); + } + @Override public BlockStmt visit(SignedUnaryNode n) { LOGGER.trace("visit {}", n); @@ -283,6 +291,12 @@ public BlockStmt visit(UnaryTestNode n) { return compilerHelper.add(n); } + @Override + public BlockStmt visit(UndefinedValueNode n) { + LOGGER.trace("visit {}", n); + return compilerHelper.add(n); + } + public String getLastVariableName() { LOGGER.trace("getLastVariableName"); return compilerHelper.getLastVariableName(); diff --git a/kie-dmn/kie-dmn-feel/src/main/java/org/kie/dmn/feel/codegen/feel11/ASTUnaryTestTransform.java b/kie-dmn/kie-dmn-feel/src/main/java/org/kie/dmn/feel/codegen/feel11/ASTUnaryTestTransform.java index 133531034e8..3f2ea6e9077 100644 --- a/kie-dmn/kie-dmn-feel/src/main/java/org/kie/dmn/feel/codegen/feel11/ASTUnaryTestTransform.java +++ b/kie-dmn/kie-dmn-feel/src/main/java/org/kie/dmn/feel/codegen/feel11/ASTUnaryTestTransform.java @@ -37,6 +37,7 @@ import org.kie.dmn.feel.lang.ast.StringNode; import org.kie.dmn.feel.lang.ast.UnaryTestListNode; import org.kie.dmn.feel.lang.ast.UnaryTestNode; +import org.kie.dmn.feel.lang.ast.UndefinedValueNode; import org.kie.dmn.feel.lang.ast.visitor.DefaultedVisitor; public class ASTUnaryTestTransform extends DefaultedVisitor { @@ -136,6 +137,11 @@ public UnaryTestSubexpr visit(QualifiedNameNode n) { } } + @Override + public UnaryTestSubexpr visit(UndefinedValueNode n) { + return new SimpleUnaryExpression(n); + } + private UnaryTestSubexpr propagateWildcard(ASTNode n) { return Arrays.stream(n.getChildrenNode()).map(e -> e.accept(this)).anyMatch(UnaryTestSubexpr::isWildcard) ? new WildCardUnaryExpression((BaseNode) n) : new SimpleUnaryExpression((BaseNode) n); diff --git a/kie-dmn/kie-dmn-feel/src/main/java/org/kie/dmn/feel/codegen/feel11/DMNCodegenConstants.java b/kie-dmn/kie-dmn-feel/src/main/java/org/kie/dmn/feel/codegen/feel11/DMNCodegenConstants.java index 96520d8689c..4b214951b05 100644 --- a/kie-dmn/kie-dmn-feel/src/main/java/org/kie/dmn/feel/codegen/feel11/DMNCodegenConstants.java +++ b/kie-dmn/kie-dmn-feel/src/main/java/org/kie/dmn/feel/codegen/feel11/DMNCodegenConstants.java @@ -51,11 +51,13 @@ import org.kie.dmn.feel.lang.ast.QualifiedNameNode; import org.kie.dmn.feel.lang.ast.QuantifiedExpressionNode; import org.kie.dmn.feel.lang.ast.RangeNode; +import org.kie.dmn.feel.lang.ast.RangeTypeNode; import org.kie.dmn.feel.lang.ast.SignedUnaryNode; import org.kie.dmn.feel.lang.ast.StringNode; import org.kie.dmn.feel.lang.ast.TemporalConstantNode; import org.kie.dmn.feel.lang.ast.UnaryTestListNode; import org.kie.dmn.feel.lang.ast.UnaryTestNode; +import org.kie.dmn.feel.lang.ast.UndefinedValueNode; import org.kie.dmn.feel.lang.impl.JavaBackedType; import org.kie.dmn.feel.lang.impl.MapBackedType; import org.kie.dmn.feel.lang.types.AliasFEELType; @@ -142,6 +144,8 @@ public class DMNCodegenConstants { public static final ClassOrInterfaceType LISTNODE_CT = parseClassOrInterfaceType(ListNode.class.getCanonicalName()); public static final ClassOrInterfaceType LISTTYPENODE_CT = parseClassOrInterfaceType(ListTypeNode.class.getCanonicalName()); + public static final ClassOrInterfaceType RANGETYPENODE_CT = + parseClassOrInterfaceType(RangeTypeNode.class.getCanonicalName()); public static final ClassOrInterfaceType NAMEDEFNODE_CT = parseClassOrInterfaceType(NameDefNode.class.getCanonicalName()); public static final ClassOrInterfaceType NAMEDPARAMETERNODE_CT = @@ -169,6 +173,7 @@ public class DMNCodegenConstants { parseClassOrInterfaceType(UnaryTestListNode.class.getCanonicalName()); public static final ClassOrInterfaceType UNARYTESTNODE_CT = parseClassOrInterfaceType(UnaryTestNode.class.getCanonicalName()); + public static final ClassOrInterfaceType UNDEFINEDVALUENODE_CT = parseClassOrInterfaceType(UndefinedValueNode.class.getCanonicalName()); private DMNCodegenConstants() { } diff --git a/kie-dmn/kie-dmn-feel/src/main/java/org/kie/dmn/feel/lang/ast/ASTBuilderFactory.java b/kie-dmn/kie-dmn-feel/src/main/java/org/kie/dmn/feel/lang/ast/ASTBuilderFactory.java index 95a1f5c54a3..8908a3a9dde 100644 --- a/kie-dmn/kie-dmn-feel/src/main/java/org/kie/dmn/feel/lang/ast/ASTBuilderFactory.java +++ b/kie-dmn/kie-dmn-feel/src/main/java/org/kie/dmn/feel/lang/ast/ASTBuilderFactory.java @@ -43,6 +43,10 @@ public static NullNode newNullNode(ParserRuleContext ctx) { return new NullNode( ctx ); } + public static UndefinedValueNode newUndefinedValueNode() { + return new UndefinedValueNode(); + } + public static StringNode newStringNode(ParserRuleContext ctx) { return new StringNode( ctx ); } diff --git a/kie-dmn/kie-dmn-feel/src/main/java/org/kie/dmn/feel/lang/ast/RangeNode.java b/kie-dmn/kie-dmn-feel/src/main/java/org/kie/dmn/feel/lang/ast/RangeNode.java index c64317ad43d..0d44d025d79 100644 --- a/kie-dmn/kie-dmn-feel/src/main/java/org/kie/dmn/feel/lang/ast/RangeNode.java +++ b/kie-dmn/kie-dmn-feel/src/main/java/org/kie/dmn/feel/lang/ast/RangeNode.java @@ -28,6 +28,7 @@ import org.kie.dmn.feel.lang.types.impl.ComparablePeriod; import org.kie.dmn.feel.runtime.Range; import org.kie.dmn.feel.runtime.impl.RangeImpl; +import org.kie.dmn.feel.runtime.impl.UndefinedValueComparable; import org.kie.dmn.feel.util.Msg; public class RangeNode @@ -113,13 +114,17 @@ public Range evaluate(EvaluationContext ctx) { Type sType = BuiltInType.determineTypeFromInstance(s); Type eType = BuiltInType.determineTypeFromInstance(e); - if (s != null && e != null && sType != eType && !s.getClass().isAssignableFrom(e.getClass())) { + boolean withUndefined = s instanceof UndefinedValueComparable || e instanceof UndefinedValueComparable; + if (s != null && e != null && + !withUndefined && + sType != eType && + !s.getClass().isAssignableFrom(e.getClass())) { ctx.notifyEvt( astEvent(Severity.ERROR, Msg.createMessage(Msg.X_TYPE_INCOMPATIBLE_WITH_Y_TYPE, "Start", "End"))); return null; } - Comparable start = convertToComparable( ctx, s ); - Comparable end = convertToComparable( ctx, e ); + Comparable start = s instanceof UndefinedValueComparable ? (Comparable) s : convertToComparable(ctx, s ); + Comparable end = e instanceof UndefinedValueComparable ? (Comparable) e : convertToComparable( ctx, e ); return new RangeImpl( lowerBound==IntervalBoundary.OPEN ? Range.RangeBoundary.OPEN : Range.RangeBoundary.CLOSED, start, diff --git a/kie-dmn/kie-dmn-feel/src/main/java/org/kie/dmn/feel/lang/ast/RangeTypeNode.java b/kie-dmn/kie-dmn-feel/src/main/java/org/kie/dmn/feel/lang/ast/RangeTypeNode.java new file mode 100644 index 00000000000..87771e9ac0c --- /dev/null +++ b/kie-dmn/kie-dmn-feel/src/main/java/org/kie/dmn/feel/lang/ast/RangeTypeNode.java @@ -0,0 +1,48 @@ +/** + * Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you 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 + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + * implied. See the License for the specific language governing permissions and limitations under the License. + */ + +package org.kie.dmn.feel.lang.ast; + +import org.antlr.v4.runtime.ParserRuleContext; +import org.kie.dmn.feel.lang.EvaluationContext; +import org.kie.dmn.feel.lang.Type; +import org.kie.dmn.feel.lang.types.GenRangeType; + +public class RangeTypeNode extends TypeNode { + + private final TypeNode genericTypeNode; + + public RangeTypeNode(ParserRuleContext ctx, TypeNode gen) { + super(ctx); + this.genericTypeNode = gen; + } + + public RangeTypeNode(TypeNode genericTypeNode, String text) { + this.genericTypeNode = genericTypeNode; + this.setText(text); + } + + @Override + public Type evaluate(EvaluationContext ctx) { + Type gen = genericTypeNode.evaluate(ctx); + return new GenRangeType(gen); + } + + @Override + public T accept(Visitor v) { + return v.visit(this); + } + + public TypeNode getGenericTypeNode() { + return genericTypeNode; + } + +} diff --git a/kie-dmn/kie-dmn-feel/src/main/java/org/kie/dmn/feel/lang/ast/UndefinedValueNode.java b/kie-dmn/kie-dmn-feel/src/main/java/org/kie/dmn/feel/lang/ast/UndefinedValueNode.java new file mode 100644 index 00000000000..dd423acdb56 --- /dev/null +++ b/kie-dmn/kie-dmn-feel/src/main/java/org/kie/dmn/feel/lang/ast/UndefinedValueNode.java @@ -0,0 +1,39 @@ +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you 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 + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.kie.dmn.feel.lang.ast; + +import org.kie.dmn.feel.lang.EvaluationContext; +import org.kie.dmn.feel.runtime.impl.UndefinedValueComparable; + +public class UndefinedValueNode + extends BaseNode { + + public UndefinedValueNode() { } + + @Override + public Object evaluate(EvaluationContext ctx) { + return new UndefinedValueComparable(); + } + + @Override + public T accept(Visitor v) { + return v.visit(this); + } + +} diff --git a/kie-dmn/kie-dmn-feel/src/main/java/org/kie/dmn/feel/lang/ast/Visitor.java b/kie-dmn/kie-dmn-feel/src/main/java/org/kie/dmn/feel/lang/ast/Visitor.java index 6904d03b2d5..1158d134b07 100644 --- a/kie-dmn/kie-dmn-feel/src/main/java/org/kie/dmn/feel/lang/ast/Visitor.java +++ b/kie-dmn/kie-dmn-feel/src/main/java/org/kie/dmn/feel/lang/ast/Visitor.java @@ -50,6 +50,7 @@ public interface Visitor { T visit(QualifiedNameNode n); T visit(QuantifiedExpressionNode n); T visit(RangeNode n); + T visit(RangeTypeNode n); T visit(SignedUnaryNode n); T visit(StringNode n); @@ -59,4 +60,5 @@ default T visit(TemporalConstantNode n) { T visit(UnaryTestListNode n); T visit(UnaryTestNode n); + T visit(UndefinedValueNode n); } \ No newline at end of file diff --git a/kie-dmn/kie-dmn-feel/src/main/java/org/kie/dmn/feel/lang/ast/visitor/ASTHeuristicCheckerVisitor.java b/kie-dmn/kie-dmn-feel/src/main/java/org/kie/dmn/feel/lang/ast/visitor/ASTHeuristicCheckerVisitor.java index 2d39b7d19da..5927d3e0c0d 100644 --- a/kie-dmn/kie-dmn-feel/src/main/java/org/kie/dmn/feel/lang/ast/visitor/ASTHeuristicCheckerVisitor.java +++ b/kie-dmn/kie-dmn-feel/src/main/java/org/kie/dmn/feel/lang/ast/visitor/ASTHeuristicCheckerVisitor.java @@ -19,16 +19,15 @@ package org.kie.dmn.feel.lang.ast.visitor; import java.util.ArrayList; -import java.util.Arrays; import java.util.List; import org.kie.dmn.api.feel.runtime.events.FEELEvent; import org.kie.dmn.api.feel.runtime.events.FEELEvent.Severity; import org.kie.dmn.feel.lang.ast.ASTNode; import org.kie.dmn.feel.lang.ast.InfixOpNode; -import org.kie.dmn.feel.lang.ast.NullNode; import org.kie.dmn.feel.lang.ast.RangeNode; import org.kie.dmn.feel.lang.ast.UnaryTestNode; +import org.kie.dmn.feel.lang.ast.UndefinedValueNode; import org.kie.dmn.feel.runtime.events.ASTHeuristicCheckEvent; import org.kie.dmn.feel.util.Msg; @@ -63,8 +62,8 @@ public List visit(UnaryTestNode n) { @Override public List visit(RangeNode n) { - if ((n.getStart() instanceof NullNode && n.getEnd() instanceof RangeNode) - || (n.getStart() instanceof RangeNode && n.getEnd() instanceof NullNode)) { + if ((n.getStart() instanceof UndefinedValueNode && n.getEnd() instanceof RangeNode) + || (n.getStart() instanceof RangeNode && n.getEnd() instanceof UndefinedValueNode)) { return List.of(new ASTHeuristicCheckEvent(Severity.WARN, Msg.createMessage(Msg.UT_OF_UT, n.getText()), n)); } return defaultVisit(n); diff --git a/kie-dmn/kie-dmn-feel/src/main/java/org/kie/dmn/feel/lang/ast/visitor/DefaultedVisitor.java b/kie-dmn/kie-dmn-feel/src/main/java/org/kie/dmn/feel/lang/ast/visitor/DefaultedVisitor.java index 68d5baaa16a..1b55497e2f9 100644 --- a/kie-dmn/kie-dmn-feel/src/main/java/org/kie/dmn/feel/lang/ast/visitor/DefaultedVisitor.java +++ b/kie-dmn/kie-dmn-feel/src/main/java/org/kie/dmn/feel/lang/ast/visitor/DefaultedVisitor.java @@ -49,10 +49,12 @@ import org.kie.dmn.feel.lang.ast.QualifiedNameNode; import org.kie.dmn.feel.lang.ast.QuantifiedExpressionNode; import org.kie.dmn.feel.lang.ast.RangeNode; +import org.kie.dmn.feel.lang.ast.RangeTypeNode; import org.kie.dmn.feel.lang.ast.SignedUnaryNode; import org.kie.dmn.feel.lang.ast.StringNode; import org.kie.dmn.feel.lang.ast.UnaryTestListNode; import org.kie.dmn.feel.lang.ast.UnaryTestNode; +import org.kie.dmn.feel.lang.ast.UndefinedValueNode; import org.kie.dmn.feel.lang.ast.Visitor; public abstract class DefaultedVisitor implements Visitor { @@ -194,6 +196,11 @@ public T visit(RangeNode n) { return defaultVisit(n); } + @Override + public T visit(RangeTypeNode n) { + return defaultVisit(n); + } + @Override public T visit(SignedUnaryNode n) { return defaultVisit(n); @@ -234,4 +241,9 @@ public T visit(FunctionTypeNode n) { return defaultVisit(n); } + @Override + public T visit(UndefinedValueNode n) { + return defaultVisit(n); + } + } diff --git a/kie-dmn/kie-dmn-feel/src/main/java/org/kie/dmn/feel/lang/types/GenRangeType.java b/kie-dmn/kie-dmn-feel/src/main/java/org/kie/dmn/feel/lang/types/GenRangeType.java new file mode 100644 index 00000000000..4386040ba0d --- /dev/null +++ b/kie-dmn/kie-dmn-feel/src/main/java/org/kie/dmn/feel/lang/types/GenRangeType.java @@ -0,0 +1,64 @@ +/** + * Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you 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 + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + * implied. See the License for the specific language governing permissions and limitations under the License. + */ + +package org.kie.dmn.feel.lang.types; + +import org.kie.dmn.feel.lang.SimpleType; +import org.kie.dmn.feel.lang.Type; +import org.kie.dmn.feel.runtime.impl.RangeImpl; + +public class GenRangeType implements SimpleType { + + /** + * Represents the "generic" type of the current list + */ + private final Type gen; + + + public GenRangeType(Type gen) { + this.gen = gen; + } + + @Override + public boolean isInstanceOf(Object o) { + if (o instanceof RangeImpl rangeImpl) { + return gen.isInstanceOf(rangeImpl.getLowEndPoint()) && gen.isInstanceOf(rangeImpl.getHighEndPoint()); + } else { + return false; + } + } + + @Override + public boolean isAssignableValue(Object value) { + if ( value == null ) { + return true; // a null-value can be assigned to any type. + } + if (!(value instanceof RangeImpl)) { + return gen.isAssignableValue(value); + } + return isInstanceOf(value); + } + + @Override + public String getName() { + return "[anonymous]"; + } + + public Type getGen() { + return gen; + } + + @Override + public boolean conformsTo(Type t) { + return (t instanceof GenRangeType && this.gen.conformsTo(((GenRangeType) t).gen)) || t == BuiltInType.RANGE; + } + +} diff --git a/kie-dmn/kie-dmn-feel/src/main/java/org/kie/dmn/feel/parser/feel11/ASTBuilderVisitor.java b/kie-dmn/kie-dmn-feel/src/main/java/org/kie/dmn/feel/parser/feel11/ASTBuilderVisitor.java index 62ce7781a5a..64465e00d0e 100644 --- a/kie-dmn/kie-dmn-feel/src/main/java/org/kie/dmn/feel/parser/feel11/ASTBuilderVisitor.java +++ b/kie-dmn/kie-dmn-feel/src/main/java/org/kie/dmn/feel/parser/feel11/ASTBuilderVisitor.java @@ -49,6 +49,7 @@ import org.kie.dmn.feel.lang.ast.QualifiedNameNode; import org.kie.dmn.feel.lang.ast.QuantifiedExpressionNode; import org.kie.dmn.feel.lang.ast.RangeNode; +import org.kie.dmn.feel.lang.ast.RangeTypeNode; import org.kie.dmn.feel.lang.ast.StringNode; import org.kie.dmn.feel.lang.ast.TypeNode; import org.kie.dmn.feel.lang.ast.UnaryTestListNode; @@ -112,6 +113,11 @@ public BaseNode visitNullLiteral(FEEL_1_1Parser.NullLiteralContext ctx) { return ASTBuilderFactory.newNullNode( ctx ); } + @Override + public BaseNode visitUndefined(FEEL_1_1Parser.UndefinedContext ctx) { + return ASTBuilderFactory.newUndefinedValueNode(); + } + @Override public BaseNode visitStringLiteral(FEEL_1_1Parser.StringLiteralContext ctx) { return ASTBuilderFactory.newStringNode( ctx ); @@ -187,13 +193,13 @@ public BaseNode visitPositiveUnaryTestIneqInterval(FEEL_1_1Parser.PositiveUnaryT String op = ctx.op.getText(); switch (UnaryOperator.determineOperator(op)) { case GT: - return ASTBuilderFactory.newIntervalNode(ctx, RangeNode.IntervalBoundary.OPEN, value, ASTBuilderFactory.newNullNode(ctx), RangeNode.IntervalBoundary.OPEN); + return ASTBuilderFactory.newIntervalNode(ctx, RangeNode.IntervalBoundary.OPEN, value, ASTBuilderFactory.newUndefinedValueNode(), RangeNode.IntervalBoundary.OPEN); case GTE: - return ASTBuilderFactory.newIntervalNode(ctx, RangeNode.IntervalBoundary.CLOSED, value, ASTBuilderFactory.newNullNode(ctx), RangeNode.IntervalBoundary.OPEN); + return ASTBuilderFactory.newIntervalNode(ctx, RangeNode.IntervalBoundary.CLOSED, value, ASTBuilderFactory.newUndefinedValueNode(), RangeNode.IntervalBoundary.OPEN); case LT: - return ASTBuilderFactory.newIntervalNode(ctx, RangeNode.IntervalBoundary.OPEN, ASTBuilderFactory.newNullNode(ctx), value, RangeNode.IntervalBoundary.OPEN); + return ASTBuilderFactory.newIntervalNode(ctx, RangeNode.IntervalBoundary.OPEN, ASTBuilderFactory.newUndefinedValueNode(), value, RangeNode.IntervalBoundary.OPEN); case LTE: - return ASTBuilderFactory.newIntervalNode(ctx, RangeNode.IntervalBoundary.OPEN, ASTBuilderFactory.newNullNode(ctx), value, RangeNode.IntervalBoundary.CLOSED); + return ASTBuilderFactory.newIntervalNode(ctx, RangeNode.IntervalBoundary.OPEN, ASTBuilderFactory.newUndefinedValueNode(), value, RangeNode.IntervalBoundary.CLOSED); default: throw new UnsupportedOperationException("by the parser rule FEEL grammar rule 7.a for range syntax should not have determined the operator " + op); } @@ -586,6 +592,12 @@ public BaseNode visitListType(FEEL_1_1Parser.ListTypeContext ctx) { return new ListTypeNode(ctx, type); } + @Override + public BaseNode visitRangeType(FEEL_1_1Parser.RangeTypeContext ctx) { + TypeNode type = (TypeNode) visit(ctx.type()); + return new RangeTypeNode(ctx, type); + } + @Override public BaseNode visitContextType(FEEL_1_1Parser.ContextTypeContext ctx) { List pNames = new ArrayList<>(); diff --git a/kie-dmn/kie-dmn-feel/src/main/java/org/kie/dmn/feel/parser/feel11/ParserHelper.java b/kie-dmn/kie-dmn-feel/src/main/java/org/kie/dmn/feel/parser/feel11/ParserHelper.java index 3ac1ca33150..4308519335a 100644 --- a/kie-dmn/kie-dmn-feel/src/main/java/org/kie/dmn/feel/parser/feel11/ParserHelper.java +++ b/kie-dmn/kie-dmn-feel/src/main/java/org/kie/dmn/feel/parser/feel11/ParserHelper.java @@ -42,6 +42,7 @@ import org.kie.dmn.feel.lang.types.DefaultBuiltinFEELTypeRegistry; import org.kie.dmn.feel.lang.types.FEELTypeRegistry; import org.kie.dmn.feel.lang.types.GenListType; +import org.kie.dmn.feel.lang.types.GenRangeType; import org.kie.dmn.feel.lang.types.ScopeImpl; import org.kie.dmn.feel.lang.types.SymbolTable; import org.kie.dmn.feel.lang.types.VariableSymbol; @@ -144,6 +145,10 @@ public void recoverScope( String name ) { scopeType = ((GenListType) scopeType).getGen(); } + if (scopeType instanceof GenRangeType) { + scopeType = ((GenRangeType) scopeType).getGen(); + } + if (resolved != null && scopeType instanceof CompositeType) { pushScope(scopeType); CompositeType type = (CompositeType) scopeType; diff --git a/kie-dmn/kie-dmn-feel/src/main/java/org/kie/dmn/feel/runtime/Range.java b/kie-dmn/kie-dmn-feel/src/main/java/org/kie/dmn/feel/runtime/Range.java index 39666b6c858..3ca1ec857b7 100644 --- a/kie-dmn/kie-dmn-feel/src/main/java/org/kie/dmn/feel/runtime/Range.java +++ b/kie-dmn/kie-dmn-feel/src/main/java/org/kie/dmn/feel/runtime/Range.java @@ -34,4 +34,6 @@ enum RangeBoundary { Boolean includes(Object param); + boolean isWithUndefined(); + } diff --git a/kie-dmn/kie-dmn-feel/src/main/java/org/kie/dmn/feel/runtime/decisiontables/DTDecisionRule.java b/kie-dmn/kie-dmn-feel/src/main/java/org/kie/dmn/feel/runtime/decisiontables/DTDecisionRule.java index dd08d9f8314..1576c789153 100644 --- a/kie-dmn/kie-dmn-feel/src/main/java/org/kie/dmn/feel/runtime/decisiontables/DTDecisionRule.java +++ b/kie-dmn/kie-dmn-feel/src/main/java/org/kie/dmn/feel/runtime/decisiontables/DTDecisionRule.java @@ -52,11 +52,13 @@ The class DecisionRule is used to model the rules in a decision table (see 8.2 N */ public class DTDecisionRule implements Indexed { private int index; + private String id; private List inputEntry; private List outputEntry; - public DTDecisionRule(int index) { + public DTDecisionRule(int index, String id) { this.index = index; + this.id = id; } /** @@ -86,4 +88,8 @@ public List getOutputEntry() { public int getIndex() { return index; } + + public String getId() { + return id; + } } diff --git a/kie-dmn/kie-dmn-feel/src/main/java/org/kie/dmn/feel/runtime/decisiontables/DecisionTableImpl.java b/kie-dmn/kie-dmn-feel/src/main/java/org/kie/dmn/feel/runtime/decisiontables/DecisionTableImpl.java index 362e1100873..27374bcb428 100644 --- a/kie-dmn/kie-dmn-feel/src/main/java/org/kie/dmn/feel/runtime/decisiontables/DecisionTableImpl.java +++ b/kie-dmn/kie-dmn-feel/src/main/java/org/kie/dmn/feel/runtime/decisiontables/DecisionTableImpl.java @@ -257,12 +257,20 @@ private List findMatches(EvaluationContext ctx, Object[] params) } } ctx.notifyEvt( () -> { - List matches = matchingDecisionRules.stream().map( dr -> dr.getIndex() + 1 ).collect( Collectors.toList() ); + List matches = new ArrayList<>(); + List matchesId = new ArrayList<>(); + matchingDecisionRules.forEach(dr -> { + matches.add( dr.getIndex() + 1 ); + if (dr.getId() != null && !dr.getId().isEmpty()) { + matchesId.add(dr.getId()); + } + }); return new DecisionTableRulesMatchedEvent(FEELEvent.Severity.INFO, - "Rules matched for decision table '" + getName() + "': " + matches.toString(), + "Rules matched for decision table '" + getName() + "': " + matches, getName(), getName(), - matches ); + matches, + matchesId); } ); return matchingDecisionRules; diff --git a/kie-dmn/kie-dmn-feel/src/main/java/org/kie/dmn/feel/runtime/decisiontables/HitPolicy.java b/kie-dmn/kie-dmn-feel/src/main/java/org/kie/dmn/feel/runtime/decisiontables/HitPolicy.java index 21acca05f1c..53e5f92c0f3 100644 --- a/kie-dmn/kie-dmn-feel/src/main/java/org/kie/dmn/feel/runtime/decisiontables/HitPolicy.java +++ b/kie-dmn/kie-dmn-feel/src/main/java/org/kie/dmn/feel/runtime/decisiontables/HitPolicy.java @@ -7,7 +7,7 @@ * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an @@ -43,28 +43,29 @@ import static java.util.stream.IntStream.range; public enum HitPolicy { - UNIQUE( "U", "UNIQUE", HitPolicy::unique, null ), - FIRST( "F", "FIRST", HitPolicy::first, null ), - PRIORITY( "P", "PRIORITY", HitPolicy::priority, null ), - ANY( "A", "ANY", HitPolicy::any, null ), - COLLECT( "C", "COLLECT", HitPolicy::ruleOrder, Collections.EMPTY_LIST ), // Collect – return a list of the outputs in arbitrary order - COLLECT_SUM( "C+", "COLLECT SUM", HitPolicy::sumCollect, null ), - COLLECT_COUNT( "C#", "COLLECT COUNT", HitPolicy::countCollect, BigDecimal.ZERO ), - COLLECT_MIN( "C<", "COLLECT MIN", HitPolicy::minCollect, null ), - COLLECT_MAX( "C>", "COLLECT MAX", HitPolicy::maxCollect, null ), - RULE_ORDER( "R", "RULE ORDER", HitPolicy::ruleOrder, null ), - OUTPUT_ORDER( "O", "OUTPUT ORDER", HitPolicy::outputOrder, null ); - - private final String shortName; - private final String longName; + UNIQUE("U", "UNIQUE", HitPolicy::unique, null), + FIRST("F", "FIRST", HitPolicy::first, null), + PRIORITY("P", "PRIORITY", HitPolicy::priority, null), + ANY("A", "ANY", HitPolicy::any, null), + COLLECT("C", "COLLECT", HitPolicy::ruleOrder, Collections.EMPTY_LIST), // Collect – return a list of the + // outputs in arbitrary order + COLLECT_SUM("C+", "COLLECT SUM", HitPolicy::sumCollect, null), + COLLECT_COUNT("C#", "COLLECT COUNT", HitPolicy::countCollect, BigDecimal.ZERO), + COLLECT_MIN("C<", "COLLECT MIN", HitPolicy::minCollect, null), + COLLECT_MAX("C>", "COLLECT MAX", HitPolicy::maxCollect, null), + RULE_ORDER("R", "RULE ORDER", HitPolicy::ruleOrder, null), + OUTPUT_ORDER("O", "OUTPUT ORDER", HitPolicy::outputOrder, null); + + private final String shortName; + private final String longName; private final HitPolicyDTI dti; - private final Object defaultValue; + private final Object defaultValue; HitPolicy(final String shortName, final String longName) { - this( shortName, longName, HitPolicy::notImplemented, null ); + this(shortName, longName, HitPolicy::notImplemented, null); } - HitPolicy(final String shortName, final String longName, final HitPolicyDTI dti, Object defaultValue ) { + HitPolicy(final String shortName, final String longName, final HitPolicyDTI dti, Object defaultValue) { this.shortName = shortName; this.longName = longName; this.dti = dti; @@ -83,16 +84,18 @@ public HitPolicyDTI getDti() { return dti; } - public Object getDefaultValue() { return defaultValue; } + public Object getDefaultValue() { + return defaultValue; + } public static HitPolicy fromString(String policy) { policy = policy.toUpperCase(); - for ( HitPolicy c : HitPolicy.values() ) { - if ( c.shortName.equals( policy ) || c.longName.equals( policy ) ) { + for (HitPolicy c : HitPolicy.values()) { + if (c.shortName.equals(policy) || c.longName.equals(policy)) { return c; } } - throw new IllegalArgumentException( "Unknown hit policy: " + policy ); + throw new IllegalArgumentException("Unknown hit policy: " + policy); } /* --------------------------------------- @@ -100,19 +103,20 @@ public static HitPolicy fromString(String policy) { --------------------------------------- */ @FunctionalInterface public interface HitPolicyDTI { + Object dti( EvaluationContext ctx, DecisionTable dt, - List matches, + List matches, List results); } public static Object notImplemented( EvaluationContext ctx, DecisionTable dt, - List matches, + List matches, List results) { - throw new RuntimeException( "Not implemented" ); + throw new RuntimeException("Not implemented"); } /** @@ -121,57 +125,40 @@ public static Object notImplemented( public static Object unique( EvaluationContext ctx, DecisionTable dt, - List matches, + List matches, List results) { - if ( matches.size() > 1 ) { - ctx.notifyEvt( () -> { - List ruleMatches = matches.stream().map( m -> m.getIndex() + 1 ).collect( toList() ); - return new HitPolicyViolationEvent( - FEELEvent.Severity.ERROR, - "UNIQUE hit policy decision tables can only have one matching rule. " + - "Multiple matches found for decision table '" + dt.getName() + "'. Matched rules: " + ruleMatches, - dt.getName(), - ruleMatches ); - } + if (matches.size() > 1) { + ctx.notifyEvt(() -> { + List ruleMatches = matches.stream().map(m -> m.getIndex() + 1).collect(toList()); + return new HitPolicyViolationEvent( + FEELEvent.Severity.ERROR, + "UNIQUE hit policy decision tables can only have one matching rule. " + + "Multiple matches found for decision table '" + dt.getName() + "'. " + + "Matched rules: " + ruleMatches, + dt.getName(), + ruleMatches); + } ); return null; } - if ( matches.size() == 1 ) { - ctx.notifyEvt( () -> { - int index = matches.get( 0 ).getIndex() + 1; - return new DecisionTableRulesSelectedEvent( - FEELEvent.Severity.INFO, - "Rule fired for decision table '" + dt.getName() + "': " + index, - dt.getName(), - dt.getName(), - Collections.singletonList( index ) ); - } - ); - return results.get( 0 ); + if (matches.size() == 1) { + notifyDecisionTableRulesSelectedEvent(ctx, dt, matches); + return results.get(0); } return null; } /** - * First – return the first match in rule order + * First – return the first match in rule order */ public static Object first( EvaluationContext ctx, DecisionTable dt, - List matches, + List matches, List results) { - if ( matches.size() >= 1 ) { - ctx.notifyEvt( () -> { - int index = matches.get( 0 ).getIndex() + 1; - return new DecisionTableRulesSelectedEvent( - FEELEvent.Severity.INFO, - "Rule fired for decision table '" + dt.getName() + "': " + index, - dt.getName(), - dt.getName(), - Collections.singletonList( index ) ); - } - ); - return results.get( 0 ); + if (!matches.isEmpty()) { + notifyDecisionTableRulesSelectedEvent(ctx, dt, matches); + return results.get(0); } return null; } @@ -182,174 +169,87 @@ public static Object first( public static Object any( EvaluationContext ctx, DecisionTable dt, - List matches, + List matches, List results) { - if ( matches.size() >= 1 ) { + if (!matches.isEmpty()) { long distinctOutputEntry = results.stream() .distinct() .count(); - if ( distinctOutputEntry > 1 ) { - ctx.notifyEvt( () -> { - List ruleMatches = matches.stream().map( m -> m.getIndex() + 1 ).collect( toList() ); - return new HitPolicyViolationEvent( - FEELEvent.Severity.ERROR, - "'Multiple rules can match, but they [must] all have the same output '" + dt.getName() + "'. Matched rules: " + ruleMatches, - dt.getName(), - ruleMatches ); - } + if (distinctOutputEntry > 1) { + ctx.notifyEvt(() -> { + List ruleMatches = + matches.stream().map(m -> m.getIndex() + 1).collect(toList()); + return new HitPolicyViolationEvent( + FEELEvent.Severity.ERROR, + "'Multiple rules can match, but they [must] all have the same output '" + dt.getName() + "'. Matched rules: " + ruleMatches, + dt.getName(), + ruleMatches); + } ); return null; } - - ctx.notifyEvt( () -> { - int index = matches.get( 0 ).getIndex() + 1; - return new DecisionTableRulesSelectedEvent( - FEELEvent.Severity.INFO, - "Rule fired for decision table '" + dt.getName() + "': " + index, - dt.getName(), - dt.getName(), - Collections.singletonList( index ) ); - } - ); - return results.get( 0 ); + notifyDecisionTableRulesSelectedEvent(ctx, dt, matches); + return results.get(0); } return null; } /** - * Priority – multiple rules can match, with different outputs. The output that comes first in the supplied output values list is returned + * Priority – multiple rules can match, with different outputs. The output that comes first in the supplied + * output values list is returned */ public static Object priority( EvaluationContext ctx, DecisionTable dt, - List matches, + List matches, List results) { - if ( matches.isEmpty() ) { + if (matches.isEmpty()) { return null; } - List> pairs = sortPairs( ctx, dt, matches, results ); - ctx.notifyEvt( () -> { - List indexes = Collections.singletonList( pairs.get( 0 ).getLeft().getIndex() + 1 ); - return new DecisionTableRulesSelectedEvent( - FEELEvent.Severity.INFO, - "Rules fired for decision table '" + dt.getName() + "': " + indexes, - dt.getName(), - dt.getName(), - indexes ); - } - ); - - return pairs.get( 0 ).getRight(); + List> pairs = sortPairs(ctx, dt, matches, results); + int index = pairs.get(0).getLeft().getIndex() + 1; + String id = pairs.get(0).getLeft().getId(); + notifyDecisionTableRulesSelectedEvent(ctx, dt, index, id); + return pairs.get(0).getRight(); } /** - * Output order – return a list of outputs in the order of the output values list + * Output order – return a list of outputs in the order of the output values list */ public static Object outputOrder( EvaluationContext ctx, DecisionTable dt, - List matches, - List results ) { - if ( matches.isEmpty() ) { + List matches, + List results) { + if (matches.isEmpty()) { return null; } - List> pairs = sortPairs( ctx, dt, matches, results ); - ctx.notifyEvt( () -> { - List indexes = pairs.stream().map( p -> p.getLeft().getIndex() + 1 ).collect( toList() ); - return new DecisionTableRulesSelectedEvent( - FEELEvent.Severity.INFO, - "Rules fired for decision table '" + dt.getName() + "': " + indexes, - dt.getName(), - dt.getName(), - indexes ); - } - ); - - return pairs.stream().map( p -> p.getRight() ).collect( Collectors.toList() ); - } - - private static List> sortPairs( EvaluationContext ctx, DecisionTable dt, List matches, List results) { - List> pairs = new ArrayList<>( ); - for( int i = 0; i < matches.size(); i++ ) { - pairs.add( new Pair<>( matches.get( i ), results.get( i ) ) ); - } - - if ( dt.getOutputs().size() == 1 && !dt.getOutputs().get( 0 ).getOutputValues().isEmpty() ) { - // single output, just sort the results - List outs = dt.getOutputs().get( 0 ).getOutputValues(); - pairs.sort( (r1, r2) -> { - return sortByOutputsOrder( ctx, outs, r1.getRight(), r2.getRight() ); - } ); - } else if ( dt.getOutputs().size() > 1 ) { - // multiple outputs, collect the ones that have values listed - List priorities = dt.getOutputs().stream().filter( o -> !o.getOutputValues().isEmpty() ).collect( toList() ); - pairs.sort( (r1, r2) -> { - Map m1 = (Map) r1.getRight(); - Map m2 = (Map) r2.getRight(); - for ( DecisionTable.OutputClause oc : priorities ) { - int o = sortByOutputsOrder( ctx, oc.getOutputValues(), m1.get( oc.getName() ), m2.get( oc.getName() ) ); - if ( o != 0 ) { - return o; - } - } - // unable to sort, so keep order - return 0; - } ); - } - return pairs; - } - - private static int sortByOutputsOrder(EvaluationContext ctx, List outs, Object r1, Object r2) { - boolean r1found = false; - boolean r2found = false; - for( int index = 0; index < outs.size() && !r1found && !r2found; index++ ) { - UnaryTest ut = outs.get( index ); - if( ut.apply( ctx, r1 ) ) { - r1found = true; - } - if( ut.apply( ctx, r2 ) ) { - r2found = true; - } + List> pairs = sortPairs(ctx, dt, matches, results); + int index = pairs.get(0).getLeft().getIndex() + 1; + String id = pairs.get(0).getLeft().getId(); + notifyDecisionTableRulesSelectedEvent(ctx, dt, index, id); - } - if ( r1found && r2found ) { - return 0; - } else if ( r1found ) { - return -1; - } else if ( r2found ) { - return 1; - } else { - return 0; - } + return pairs.stream().map(Pair::getRight).collect(Collectors.toList()); } /** * Rule order – return a list of outputs in rule order - * Collect – return a list of the outputs in arbitrary order + * Collect – return a list of the outputs in arbitrary order */ public static Object ruleOrder( EvaluationContext ctx, DecisionTable dt, - List matches, + List matches, List results) { - if ( matches.isEmpty() ) { + if (matches.isEmpty()) { return null; } - ctx.notifyEvt( () -> { - List indexes = matches.stream().map( m -> m.getIndex() + 1 ).collect( toList() ); - return new DecisionTableRulesSelectedEvent( - FEELEvent.Severity.INFO, - "Rules fired for decision table '" + dt.getName() + "': " + indexes, - dt.getName(), - dt.getName(), - indexes ); - } - ); + notifyDecisionTableRulesSelectedEventWithList(ctx, dt, matches); return results; } public static Collector singleValueOrContext(List outputs) { - return new SingleValueOrContextCollector<>( outputs.stream().map( DecisionTable.OutputClause::getName ).collect( toList() ) ); + return new SingleValueOrContextCollector<>(outputs.stream().map(DecisionTable.OutputClause::getName).collect(toList())); } public static Object generalizedCollect( @@ -358,16 +258,17 @@ public static Object generalizedCollect( List results, Function, Object> resultCollector) { final List> raw; - final List names = dt.getOutputs().stream().map( o -> o.getName() != null ? o.getName() : dt.getName() ).collect( toList() ); - if ( names.size() > 1 ) { + final List names = + dt.getOutputs().stream().map(o -> o.getName() != null ? o.getName() : dt.getName()).collect(toList()); + if (names.size() > 1) { raw = (List>) results; } else { - raw = results.stream().map( (Object r) -> Collections.singletonMap( names.get( 0 ), r ) ).collect( toList() ); + raw = results.stream().map((Object r) -> Collections.singletonMap(names.get(0), r)).collect(toList()); } - return range( 0, names.size() ) - .mapToObj( index -> names.get( index ) ) - .map( name -> resultCollector.apply( raw.stream().map( r -> r.get( name ) ) ) ) - .collect( singleValueOrContext( dt.getOutputs() ) ); + return range(0, names.size()) + .mapToObj(index -> names.get(index)) + .map(name -> resultCollector.apply(raw.stream().map(r -> r.get(name)))) + .collect(singleValueOrContext(dt.getOutputs())); } /** @@ -376,23 +277,14 @@ public static Object generalizedCollect( public static Object countCollect( EvaluationContext ctx, DecisionTable dt, - List matches, + List matches, List results) { - ctx.notifyEvt( () -> { - List indexes = matches.stream().map( m -> m.getIndex() + 1 ).collect( toList() ); - return new DecisionTableRulesSelectedEvent( - FEELEvent.Severity.INFO, - "Rules fired for decision table '" + dt.getName() + "': " + indexes, - dt.getName(), - dt.getName(), - indexes ); - } - ); + notifyDecisionTableRulesSelectedEventWithList(ctx, dt, matches); return generalizedCollect( ctx, dt, results, - x -> new BigDecimal( x.collect( toSet() ).size() ) ); + x -> new BigDecimal(x.collect(toSet()).size())); } /** @@ -401,24 +293,14 @@ public static Object countCollect( public static Object minCollect( EvaluationContext ctx, DecisionTable dt, - List matches, + List matches, List results) { Object result = generalizedCollect( ctx, dt, results, - x -> x.map( y -> (Comparable) y ).collect( minBy( Comparator.naturalOrder() ) ).orElse( null ) ); - ctx.notifyEvt( () -> { - int resultIdx = results.indexOf( result ); - List indexes = resultIdx >= 0 ? Collections.singletonList( matches.get( resultIdx ).getIndex() + 1 ) : Collections.emptyList(); - return new DecisionTableRulesSelectedEvent( - FEELEvent.Severity.INFO, - "Rules fired for decision table '" + dt.getName() + "': " + indexes, - dt.getName(), - dt.getName(), - indexes ); - } - ); + x -> x.map(y -> (Comparable) y).collect(minBy(Comparator.naturalOrder())).orElse(null)); + notifyDecisionTableRulesSelectedEventByResultIdx(ctx, dt, matches, results, result); return result; } @@ -428,57 +310,159 @@ public static Object minCollect( public static Object maxCollect( EvaluationContext ctx, DecisionTable dt, - List matches, + List matches, List results) { Object result = generalizedCollect( ctx, dt, results, - x -> x.map( y -> (Comparable) y ).collect( maxBy( Comparator.naturalOrder() ) ).orElse( null ) ); - ctx.notifyEvt( () -> { - int resultIdx = results.indexOf( result ); - List indexes = resultIdx >= 0 ? Collections.singletonList( matches.get( resultIdx ).getIndex() + 1 ) : Collections.emptyList(); - return new DecisionTableRulesSelectedEvent( - FEELEvent.Severity.INFO, - "Rules fired for decision table '" + dt.getName() + "': " + indexes, - dt.getName(), - dt.getName(), - indexes ); - } - ); + x -> x.map(y -> (Comparable) y).collect(maxBy(Comparator.naturalOrder())).orElse(null)); + notifyDecisionTableRulesSelectedEventByResultIdx(ctx, dt, matches, results, result); return result; } /** - * C+ – return the sum of the outputs + * C+ – return the sum of the outputs */ public static Object sumCollect( EvaluationContext ctx, DecisionTable dt, - List matches, + List matches, List results) { - ctx.notifyEvt( () -> { - List indexes = matches.stream().map( m -> m.getIndex() + 1 ).collect( toList() ); - return new DecisionTableRulesSelectedEvent( - FEELEvent.Severity.INFO, - "Rules fired for decision table '" + dt.getName() + "': " + indexes, - dt.getName(), - dt.getName(), - indexes ); - } - ); + notifyDecisionTableRulesSelectedEventWithList(ctx, dt, matches); return generalizedCollect( ctx, dt, results, - x -> x.reduce( BigDecimal.ZERO, (a, b) -> { - if ( !(a instanceof Number && b instanceof Number) ) { + x -> x.reduce(BigDecimal.ZERO, (a, b) -> { + if (!(a instanceof Number && b instanceof Number)) { return null; } else { - BigDecimal aB = new BigDecimal( a.toString() ); - BigDecimal bB = new BigDecimal( b.toString() ); - return aB.add( bB ); + BigDecimal aB = new BigDecimal(a.toString()); + BigDecimal bB = new BigDecimal(b.toString()); + return aB.add(bB); } - } ) ); + })); + } + + private static void notifyDecisionTableRulesSelectedEventByResultIdx(EvaluationContext ctx, + DecisionTable dt, + List matches, + List results, + Object result) { + int resultIdx = results.indexOf(result); + List indexes = resultIdx >= 0 ? + Collections.singletonList(matches.get(resultIdx).getIndex() + 1) : + Collections.emptyList(); + List matchesId = resultIdx >= 0 ? + Collections.singletonList(matches.get(resultIdx).getId() + 1) : + Collections.emptyList(); + notifyDecisionTableRulesSelectedEvent(ctx, dt, indexes, matchesId); + } + + private static void notifyDecisionTableRulesSelectedEventWithList(EvaluationContext ctx, + DecisionTable dt, + List matches) { + List indexes = new ArrayList<>(); + List matchesId = new ArrayList<>(); + matches.forEach(dr -> { + indexes.add(dr.getIndex() + 1); + if (dr.getId() != null && !dr.getId().isEmpty()) { + matchesId.add(dr.getId()); + } + }); + notifyDecisionTableRulesSelectedEvent(ctx, dt, indexes, matchesId); + } + + private static void notifyDecisionTableRulesSelectedEvent(EvaluationContext ctx, + DecisionTable dt, + List matches) { + int index = matches.get(0).getIndex() + 1; + String id = matches.get(0).getId(); + notifyDecisionTableRulesSelectedEvent(ctx, dt, index, id); + } + + private static void notifyDecisionTableRulesSelectedEvent(EvaluationContext ctx, + DecisionTable dt, + int index, + String id) { + ctx.notifyEvt(() -> new DecisionTableRulesSelectedEvent( + FEELEvent.Severity.INFO, + "Rule fired for decision table '" + dt.getName() + "': " + index, + dt.getName(), + dt.getName(), + Collections.singletonList(index), + Collections.singletonList(id)) + ); + } + + private static void notifyDecisionTableRulesSelectedEvent(EvaluationContext ctx, + DecisionTable dt, + List indexes, + List matchesId) { + ctx.notifyEvt(() -> new DecisionTableRulesSelectedEvent( + FEELEvent.Severity.INFO, + "Rules fired for decision table '" + dt.getName() + "': " + indexes, + dt.getName(), + dt.getName(), + indexes, + matchesId) + ); + } + + private static List> sortPairs(EvaluationContext ctx, DecisionTable dt, + List matches, List results) { + List> pairs = new ArrayList<>(); + for (int i = 0; i < matches.size(); i++) { + pairs.add(new Pair<>(matches.get(i), results.get(i))); + } + + if (dt.getOutputs().size() == 1 && !dt.getOutputs().get(0).getOutputValues().isEmpty()) { + // single output, just sort the results + List outs = dt.getOutputs().get(0).getOutputValues(); + pairs.sort((r1, r2) -> { + return sortByOutputsOrder(ctx, outs, r1.getRight(), r2.getRight()); + }); + } else if (dt.getOutputs().size() > 1) { + // multiple outputs, collect the ones that have values listed + List priorities = + dt.getOutputs().stream().filter(o -> !o.getOutputValues().isEmpty()).collect(toList()); + pairs.sort((r1, r2) -> { + Map m1 = (Map) r1.getRight(); + Map m2 = (Map) r2.getRight(); + for (DecisionTable.OutputClause oc : priorities) { + int o = sortByOutputsOrder(ctx, oc.getOutputValues(), m1.get(oc.getName()), m2.get(oc.getName())); + if (o != 0) { + return o; + } + } + // unable to sort, so keep order + return 0; + }); + } + return pairs; + } + + private static int sortByOutputsOrder(EvaluationContext ctx, List outs, Object r1, Object r2) { + boolean r1found = false; + boolean r2found = false; + for (int index = 0; index < outs.size() && !r1found && !r2found; index++) { + UnaryTest ut = outs.get(index); + if (ut.apply(ctx, r1)) { + r1found = true; + } + if (ut.apply(ctx, r2)) { + r2found = true; + } + } + if (r1found && r2found) { + return 0; + } else if (r1found) { + return -1; + } else if (r2found) { + return 1; + } else { + return 0; + } } } diff --git a/kie-dmn/kie-dmn-feel/src/main/java/org/kie/dmn/feel/runtime/events/DecisionTableRulesMatchedEvent.java b/kie-dmn/kie-dmn-feel/src/main/java/org/kie/dmn/feel/runtime/events/DecisionTableRulesMatchedEvent.java index 60d4ee04f02..45d1dad350f 100644 --- a/kie-dmn/kie-dmn-feel/src/main/java/org/kie/dmn/feel/runtime/events/DecisionTableRulesMatchedEvent.java +++ b/kie-dmn/kie-dmn-feel/src/main/java/org/kie/dmn/feel/runtime/events/DecisionTableRulesMatchedEvent.java @@ -32,12 +32,14 @@ public class DecisionTableRulesMatchedEvent private final String nodeName; private final String dtName; private final List matches; + private final List matchesIds; - public DecisionTableRulesMatchedEvent(Severity severity, String msg, String nodeName, String dtName, List matches) { + public DecisionTableRulesMatchedEvent(Severity severity, String msg, String nodeName, String dtName, List matches, List matchesIds) { super( severity, msg, null ); this.nodeName = nodeName; this.dtName = dtName; this.matches = matches; + this.matchesIds = matchesIds; } public String getNodeName() { @@ -52,6 +54,10 @@ public List getMatches() { return matches; } + public List getMatchesIds() { + return matchesIds; + } + @Override public String toString() { return "DecisionTableRulesMatchedEvent{" + @@ -60,6 +66,7 @@ public String toString() { ", nodeName='" + nodeName + '\'' + ", dtName='" + dtName + '\'' + ", matches='" + matches + '\'' + + ", matchesIds='" + matchesIds + '\'' + '}'; } } diff --git a/kie-dmn/kie-dmn-feel/src/main/java/org/kie/dmn/feel/runtime/events/DecisionTableRulesSelectedEvent.java b/kie-dmn/kie-dmn-feel/src/main/java/org/kie/dmn/feel/runtime/events/DecisionTableRulesSelectedEvent.java index 4adb80d220a..c1569419833 100644 --- a/kie-dmn/kie-dmn-feel/src/main/java/org/kie/dmn/feel/runtime/events/DecisionTableRulesSelectedEvent.java +++ b/kie-dmn/kie-dmn-feel/src/main/java/org/kie/dmn/feel/runtime/events/DecisionTableRulesSelectedEvent.java @@ -40,12 +40,14 @@ public class DecisionTableRulesSelectedEvent private final String nodeName; private final String dtName; private final List fired; + private final List firedIds; - public DecisionTableRulesSelectedEvent(Severity severity, String msg, String nodeName, String dtName, List fired) { + public DecisionTableRulesSelectedEvent(Severity severity, String msg, String nodeName, String dtName, List fired, List firedIds) { super( severity, msg, null ); this.nodeName = nodeName; this.dtName = dtName; this.fired = fired; + this.firedIds = firedIds; } public String getNodeName() { @@ -58,6 +60,10 @@ public List getFired() { return fired; } + public List getFiredIds() { + return firedIds; + } + @Override public String toString() { return "DecisionTableRulesMatchedEvent{" + @@ -66,6 +72,7 @@ public String toString() { ", nodeName='" + nodeName + '\'' + ", dtName='" + dtName + '\'' + ", fired='" + fired + '\'' + + ", firedIds='" + firedIds + '\'' + '}'; } } diff --git a/kie-dmn/kie-dmn-feel/src/main/java/org/kie/dmn/feel/runtime/functions/DecisionTableFunction.java b/kie-dmn/kie-dmn-feel/src/main/java/org/kie/dmn/feel/runtime/functions/DecisionTableFunction.java index 80437477ada..651f334edaa 100644 --- a/kie-dmn/kie-dmn-feel/src/main/java/org/kie/dmn/feel/runtime/functions/DecisionTableFunction.java +++ b/kie-dmn/kie-dmn-feel/src/main/java/org/kie/dmn/feel/runtime/functions/DecisionTableFunction.java @@ -153,7 +153,7 @@ protected List> objectToUnaryTestList(EvaluationContext ctx, Lis */ private static DTDecisionRule toDecisionRule(EvaluationContext mainCtx, FEEL embeddedFEEL, int index, List rule, int inputSize) { // TODO should be check indeed block of inputSize n inputs, followed by block of outputs. - DTDecisionRule dr = new DTDecisionRule( index ); + DTDecisionRule dr = new DTDecisionRule( index, null ); for ( int i = 0; i < rule.size(); i++ ) { Object o = rule.get( i ); if ( i < inputSize ) { diff --git a/kie-dmn/kie-dmn-feel/src/main/java/org/kie/dmn/feel/runtime/functions/RangeFunction.java b/kie-dmn/kie-dmn-feel/src/main/java/org/kie/dmn/feel/runtime/functions/RangeFunction.java index 9dab904aca7..5e37b769bca 100644 --- a/kie-dmn/kie-dmn-feel/src/main/java/org/kie/dmn/feel/runtime/functions/RangeFunction.java +++ b/kie-dmn/kie-dmn-feel/src/main/java/org/kie/dmn/feel/runtime/functions/RangeFunction.java @@ -134,6 +134,7 @@ public FEELFnResult invoke(@ParameterName("from") String from) { return FEELFnResult.ofError(new InvalidParametersEvent(FEELEvent.Severity.ERROR, "from", "endpoints must be of equivalent types")); } + // Boundary values need to be always defined in range string. They can be undefined only in unary test, that represents range, e.g. (<10). return FEELFnResult.ofResult(new RangeImpl(startBoundary, (Comparable) left, (Comparable) right, endBoundary)); } diff --git a/kie-dmn/kie-dmn-feel/src/main/java/org/kie/dmn/feel/runtime/impl/RangeImpl.java b/kie-dmn/kie-dmn-feel/src/main/java/org/kie/dmn/feel/runtime/impl/RangeImpl.java index f16ee87dd3a..51893062d91 100644 --- a/kie-dmn/kie-dmn-feel/src/main/java/org/kie/dmn/feel/runtime/impl/RangeImpl.java +++ b/kie-dmn/kie-dmn-feel/src/main/java/org/kie/dmn/feel/runtime/impl/RangeImpl.java @@ -23,6 +23,11 @@ import org.kie.dmn.feel.runtime.Range; import org.kie.dmn.feel.util.BooleanEvalHelper; +import static org.kie.dmn.feel.lang.ast.UnaryTestNode.UnaryOperator.GT; +import static org.kie.dmn.feel.lang.ast.UnaryTestNode.UnaryOperator.GTE; +import static org.kie.dmn.feel.lang.ast.UnaryTestNode.UnaryOperator.LT; +import static org.kie.dmn.feel.lang.ast.UnaryTestNode.UnaryOperator.LTE; + public class RangeImpl implements Range { @@ -30,7 +35,7 @@ public class RangeImpl private RangeBoundary highBoundary; private Comparable lowEndPoint; private Comparable highEndPoint; - + private boolean withUndefined = false; public RangeImpl() { } @@ -40,6 +45,7 @@ public RangeImpl(RangeBoundary lowBoundary, Comparable lowEndPoint, Comparable h this.highBoundary = highBoundary; this.lowEndPoint = lowEndPoint; this.highEndPoint = highEndPoint; + withUndefined = lowEndPoint instanceof UndefinedValueComparable || highEndPoint instanceof UndefinedValueComparable; } @Override @@ -67,21 +73,30 @@ public Boolean includes(Object param) { if (param == null) { return null; } - if (lowEndPoint == null) { - if (highEndPoint == null) { + if (lowEndPoint == null || lowEndPoint instanceof UndefinedValueComparable) { + if (highEndPoint == null || highEndPoint instanceof UndefinedValueComparable) { return null; - } else { + } else if (lowEndPoint != null) { // it means it is UndefinedValueComparable return negInfRangeIncludes(param); + } else { + return false; } } else { - if (highEndPoint == null) { + if (highEndPoint instanceof UndefinedValueComparable) { return posInfRangeIncludes(param); - } else { + } else if (highEndPoint != null) { return finiteRangeIncludes(param); + } else { + return false; } } } + @Override + public boolean isWithUndefined() { + return withUndefined; + } + private Boolean finiteRangeIncludes(Object param) { if (lowBoundary == RangeBoundary.OPEN && highBoundary == RangeBoundary.OPEN) { return bothOrThrow(compare(lowEndPoint, param, (l, r) -> l.compareTo(r) < 0) , compare(highEndPoint, param, (l, r) -> l.compareTo(r) > 0), param); @@ -154,9 +169,36 @@ public int hashCode() { @Override public String toString() { + return withUndefined ? withUndefinedtoString() : withoutUndefinedtoString(); + } + + private String withoutUndefinedtoString() { return (lowBoundary == RangeBoundary.OPEN ? "(" : "[") + - " " + lowEndPoint + - " .. " + highEndPoint + - " " + ( highBoundary == RangeBoundary.OPEN ? ")" : "]" ); + " " + lowEndPoint + + " .. " + highEndPoint + + " " + ( highBoundary == RangeBoundary.OPEN ? ")" : "]" ); + } + + private String withUndefinedtoString() { + StringBuilder sb = new StringBuilder("( "); + if (lowEndPoint instanceof UndefinedValueComparable) { + if (highBoundary == RangeBoundary.OPEN) { + sb.append(LT.symbol); + } else { + sb.append(LTE.symbol); + } + sb.append(" "); + sb.append(highEndPoint); + } else if (highEndPoint instanceof UndefinedValueComparable) { + if (lowBoundary == RangeBoundary.OPEN) { + sb.append(GT.symbol); + } else { + sb.append(GTE.symbol); + } + sb.append(" "); + sb.append(lowEndPoint); + } + sb.append(" )"); + return sb.toString(); } } diff --git a/kie-dmn/kie-dmn-feel/src/main/java/org/kie/dmn/feel/runtime/impl/UndefinedValueComparable.java b/kie-dmn/kie-dmn-feel/src/main/java/org/kie/dmn/feel/runtime/impl/UndefinedValueComparable.java new file mode 100644 index 00000000000..240f7c98dae --- /dev/null +++ b/kie-dmn/kie-dmn-feel/src/main/java/org/kie/dmn/feel/runtime/impl/UndefinedValueComparable.java @@ -0,0 +1,43 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you 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 + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.kie.dmn.feel.runtime.impl; + +public class UndefinedValueComparable implements Comparable { + + + @Override + public int compareTo(UndefinedValueComparable o) { + return 0; + } + + @Override + public String toString() { + return "undefined"; + } + + @Override + public int hashCode() { + return 0; + } + + @Override + public boolean equals(Object obj) { + return obj instanceof UndefinedValueComparable; + } +} \ No newline at end of file diff --git a/kie-dmn/kie-dmn-feel/src/main/java/org/kie/dmn/feel/util/EvalHelper.java b/kie-dmn/kie-dmn-feel/src/main/java/org/kie/dmn/feel/util/EvalHelper.java index ddd788b19d1..346712fe935 100644 --- a/kie-dmn/kie-dmn-feel/src/main/java/org/kie/dmn/feel/util/EvalHelper.java +++ b/kie-dmn/kie-dmn-feel/src/main/java/org/kie/dmn/feel/util/EvalHelper.java @@ -38,6 +38,7 @@ import org.kie.dmn.feel.lang.FEELProperty; import org.kie.dmn.feel.runtime.Range; import org.kie.dmn.feel.runtime.Range.RangeBoundary; +import org.kie.dmn.feel.runtime.impl.UndefinedValueComparable; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -186,6 +187,9 @@ public static PropertyValueResult getDefinedValue(final Object current, final St default: return PropertyValueResult.notDefined(); } + if (result instanceof UndefinedValueComparable) { + result = null; + } } else { Method getter = getGenericAccessor( current.getClass(), property ); if ( getter != null ) { diff --git a/kie-dmn/kie-dmn-feel/src/main/java/org/kie/dmn/feel/util/TypeUtil.java b/kie-dmn/kie-dmn-feel/src/main/java/org/kie/dmn/feel/util/TypeUtil.java index 7af8ad5d7af..339f1dbf141 100644 --- a/kie-dmn/kie-dmn-feel/src/main/java/org/kie/dmn/feel/util/TypeUtil.java +++ b/kie-dmn/kie-dmn-feel/src/main/java/org/kie/dmn/feel/util/TypeUtil.java @@ -41,6 +41,12 @@ import org.kie.dmn.feel.runtime.functions.DateAndTimeFunction; import org.kie.dmn.feel.runtime.functions.DateFunction; import org.kie.dmn.feel.runtime.functions.TimeFunction; +import org.kie.dmn.feel.runtime.impl.UndefinedValueComparable; + +import static org.kie.dmn.feel.lang.ast.UnaryTestNode.UnaryOperator.GT; +import static org.kie.dmn.feel.lang.ast.UnaryTestNode.UnaryOperator.GTE; +import static org.kie.dmn.feel.lang.ast.UnaryTestNode.UnaryOperator.LT; +import static org.kie.dmn.feel.lang.ast.UnaryTestNode.UnaryOperator.LTE; public final class TypeUtil { @@ -78,7 +84,8 @@ public static String formatValue(final Object val, final boolean wrapForCodeUsag } else if (val instanceof ZoneTime zoneTime) { return formatTimeString(zoneTime.format(), wrapForCodeUsage); } else if (val instanceof LocalDateTime || val instanceof OffsetDateTime) { - return formatDateTimeString(DateAndTimeFunction.FEEL_DATE_TIME.format((TemporalAccessor) val), wrapForCodeUsage); + return formatDateTimeString(DateAndTimeFunction.FEEL_DATE_TIME.format((TemporalAccessor) val), + wrapForCodeUsage); } else if (val instanceof ZonedDateTime) { TemporalAccessor ta = (TemporalAccessor) val; ZoneId zone = ta.query(TemporalQueries.zone()); @@ -86,7 +93,8 @@ public static String formatValue(final Object val, final boolean wrapForCodeUsag // it is a ZoneRegion return formatDateTimeString(DateAndTimeFunction.REGION_DATETIME_FORMATTER.format((TemporalAccessor) val), wrapForCodeUsage); } else { - return formatDateTimeString(DateAndTimeFunction.FEEL_DATE_TIME.format((TemporalAccessor) val), wrapForCodeUsage); + return formatDateTimeString(DateAndTimeFunction.FEEL_DATE_TIME.format((TemporalAccessor) val), + wrapForCodeUsage); } } else if (val instanceof Duration) { return formatDuration((Duration) val, wrapForCodeUsage); @@ -183,11 +191,33 @@ public static String formatContext(final Map context, final boolean wrapDateTime public static String formatRange(final Range val, final boolean wrapDateTimeValuesInFunctions) { final StringBuilder sb = new StringBuilder(); - sb.append(val.getLowBoundary() == Range.RangeBoundary.OPEN ? "( " : "[ "); - sb.append(formatValue(val.getLowEndPoint(), wrapDateTimeValuesInFunctions)); - sb.append(" .. "); - sb.append(formatValue(val.getHighEndPoint(), wrapDateTimeValuesInFunctions)); - sb.append(val.getHighBoundary() == Range.RangeBoundary.OPEN ? " )" : " ]"); + if (val.isWithUndefined()) { + sb.append("( "); + if (val.getLowEndPoint() instanceof UndefinedValueComparable) { + if (val.getHighBoundary() == Range.RangeBoundary.OPEN) { + sb.append(LT.symbol); + } else { + sb.append(LTE.symbol); + } + sb.append(" "); + sb.append(formatValue(val.getHighEndPoint(), wrapDateTimeValuesInFunctions)); + } else if (val.getHighEndPoint() instanceof UndefinedValueComparable) { + if (val.getLowBoundary() == Range.RangeBoundary.OPEN) { + sb.append(GT.symbol); + } else { + sb.append(GTE.symbol); + } + sb.append(" "); + sb.append(formatValue(val.getLowEndPoint(), wrapDateTimeValuesInFunctions)); + } + sb.append(" )"); + } else { + sb.append(val.getLowBoundary() == Range.RangeBoundary.OPEN ? "( " : "[ "); + sb.append(formatValue(val.getLowEndPoint(), wrapDateTimeValuesInFunctions)); + sb.append(" .. "); + sb.append(formatValue(val.getHighEndPoint(), wrapDateTimeValuesInFunctions)); + sb.append(val.getHighBoundary() == Range.RangeBoundary.OPEN ? " )" : " ]"); + } return sb.toString(); } @@ -274,7 +304,8 @@ private static void appendToDurationString(final StringBuilder sb, final long da sb.append(timeSegmentChar); } - private static void appendSecondsToDurationString(final StringBuilder sb, final long seconds, final long nanoseconds) { + private static void appendSecondsToDurationString(final StringBuilder sb, final long seconds, + final long nanoseconds) { if (seconds < 0 && nanoseconds > 0) { if (seconds == -1) { sb.append("0"); diff --git a/kie-dmn/kie-dmn-feel/src/test/java/org/kie/dmn/feel/codegen/feel11/CodegenFEELUnaryTestsTest.java b/kie-dmn/kie-dmn-feel/src/test/java/org/kie/dmn/feel/codegen/feel11/CodegenFEELUnaryTestsTest.java index ff42ea47a6d..c598d4f9df5 100644 --- a/kie-dmn/kie-dmn-feel/src/test/java/org/kie/dmn/feel/codegen/feel11/CodegenFEELUnaryTestsTest.java +++ b/kie-dmn/kie-dmn-feel/src/test/java/org/kie/dmn/feel/codegen/feel11/CodegenFEELUnaryTestsTest.java @@ -34,6 +34,7 @@ import org.kie.dmn.feel.parser.feel11.ASTBuilderVisitor; import org.kie.dmn.feel.parser.feel11.FEELParser; import org.kie.dmn.feel.parser.feel11.FEEL_1_1Parser; +import org.kie.dmn.feel.util.EvaluationContextTestUtil; import org.kie.dmn.feel.util.NumberEvalHelper; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -98,7 +99,7 @@ private List parseCompileEvaluate(String feelLiteralExpression, Object FEELEventListenersManager mgr = new FEELEventListenersManager(); SyntaxErrorListener listener = new SyntaxErrorListener(); mgr.addListener(listener); - EvaluationContext emptyContext = CodegenTestUtil.newEmptyEvaluationContext(mgr); + EvaluationContext emptyContext = EvaluationContextTestUtil.newEmptyEvaluationContext(mgr); CompiledFEELUnaryTests compiledUnaryTests = parse(feelLiteralExpression, mgr, listener); LOG.debug("{}", compiledUnaryTests); List result = compiledUnaryTests.getUnaryTests() diff --git a/kie-dmn/kie-dmn-feel/src/test/java/org/kie/dmn/feel/codegen/feel11/DirectCompilerTest.java b/kie-dmn/kie-dmn-feel/src/test/java/org/kie/dmn/feel/codegen/feel11/DirectCompilerTest.java index 9231a8b1d5d..5a8f00660d7 100644 --- a/kie-dmn/kie-dmn-feel/src/test/java/org/kie/dmn/feel/codegen/feel11/DirectCompilerTest.java +++ b/kie-dmn/kie-dmn-feel/src/test/java/org/kie/dmn/feel/codegen/feel11/DirectCompilerTest.java @@ -36,6 +36,7 @@ import org.kie.dmn.feel.runtime.FEELTernaryLogicTest; import org.kie.dmn.feel.runtime.functions.CustomFEELFunction; import org.kie.dmn.feel.util.CompilerUtils; +import org.kie.dmn.feel.util.EvaluationContextTestUtil; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -226,7 +227,7 @@ void filter_path_tricky1() { CompiledFEELExpression nameRef = CompilerUtils.parseCodegen("[ {x:1, y:2}, {x:2, y:3} ][x]"); LOG.debug("{}", nameRef); - EvaluationContext context = CodegenTestUtil.newEmptyEvaluationContext(); + EvaluationContext context = EvaluationContextTestUtil.newEmptyEvaluationContext(); context.setValue("x", 2); Object result = nameRef.apply(context); LOG.debug("{}", result); @@ -239,7 +240,7 @@ void filter_path_tricky2() { CompiledFEELExpression nameRef = CompilerUtils.parseCodegen("[ {x:1, y:2}, {x:2, y:3} ][x]"); LOG.debug("{}", nameRef); - EvaluationContext context = CodegenTestUtil.newEmptyEvaluationContext(); + EvaluationContext context = EvaluationContextTestUtil.newEmptyEvaluationContext(); context.setValue("x", false); Object result = nameRef.apply(context); LOG.debug("{}", result); @@ -410,7 +411,7 @@ void nameReference() { CompiledFEELExpression nameRef = parseCodegen(inputExpression, mapOf(entry("someSimpleName", BuiltInType.STRING) ) ); LOG.debug("{}", nameRef); - EvaluationContext context = CodegenTestUtil.newEmptyEvaluationContext(); + EvaluationContext context = EvaluationContextTestUtil.newEmptyEvaluationContext(); context.setValue("someSimpleName", 123L); Object result = nameRef.apply(context); LOG.debug("{}", result); @@ -425,7 +426,7 @@ void qualifiedName() { CompiledFEELExpression qualRef = parseCodegen(inputExpression, mapOf(entry("My Person", personType) ) ); LOG.debug("{}", qualRef); - EvaluationContext context = CodegenTestUtil.newEmptyEvaluationContext(); + EvaluationContext context = EvaluationContextTestUtil.newEmptyEvaluationContext(); context.setValue("My Person", mapOf( entry("Full Name", "John Doe"), entry("Age", 47) )); Object result = qualRef.apply(context); LOG.debug("{}", result); @@ -456,7 +457,7 @@ void qualifiedName2() { CompiledFEELExpression qualRef = parseCodegen(inputExpression, mapOf(entry("My Person", personType) ) ); LOG.debug("{}", qualRef); - EvaluationContext context = CodegenTestUtil.newEmptyEvaluationContext(); + EvaluationContext context = EvaluationContextTestUtil.newEmptyEvaluationContext(); context.setValue("My Person", new MyPerson()); Object result = qualRef.apply(context); LOG.debug("{}", result); @@ -471,7 +472,7 @@ void qualifiedName3() { CompiledFEELExpression qualRef = parseCodegen(inputExpression, mapOf(entry("a date", dateType))); LOG.debug("{}", qualRef); - EvaluationContext context = CodegenTestUtil.newEmptyEvaluationContext(); + EvaluationContext context = EvaluationContextTestUtil.newEmptyEvaluationContext(); context.setValue("a date", LocalDate.of(2016, 8, 2)); Object result = qualRef.apply(context); LOG.debug("{}", result); diff --git a/kie-dmn/kie-dmn-feel/src/test/java/org/kie/dmn/feel/lang/ast/ForExpressionNodeTest.java b/kie-dmn/kie-dmn-feel/src/test/java/org/kie/dmn/feel/lang/ast/ForExpressionNodeTest.java index 290abe5132f..f09f03caa66 100644 --- a/kie-dmn/kie-dmn-feel/src/test/java/org/kie/dmn/feel/lang/ast/ForExpressionNodeTest.java +++ b/kie-dmn/kie-dmn-feel/src/test/java/org/kie/dmn/feel/lang/ast/ForExpressionNodeTest.java @@ -26,7 +26,7 @@ import java.util.Map; import org.junit.jupiter.api.Test; -import org.kie.dmn.feel.codegen.feel11.CodegenTestUtil; +import org.kie.dmn.feel.util.EvaluationContextTestUtil; import org.kie.dmn.feel.lang.Type; import org.kie.dmn.feel.lang.types.BuiltInType; @@ -39,7 +39,7 @@ void evaluateSimpleArray() { IterationContextNode x = getIterationContextNode("x", getListNode("[ 1, 2, 3, 4 ]", Arrays.asList("1", "2", "3", "4")), "x in [ 1, 2, 3, 4 ]"); IterationContextNode y = getIterationContextNode("y", getNameRefNode(BuiltInType.UNKNOWN, "x"), "y in x"); ForExpressionNode forExpressionNode = new ForExpressionNode(Arrays.asList(x, y), getNameRefNode(BuiltInType.UNKNOWN, "y"), "for x in [ 1, 2, 3, 4 ], y in x return y"); - Object retrieved = forExpressionNode.evaluate(CodegenTestUtil.newEmptyEvaluationContext()); + Object retrieved = forExpressionNode.evaluate(EvaluationContextTestUtil.newEmptyEvaluationContext()); assertThat(retrieved).isInstanceOf(List.class).asList(). containsExactly(BigDecimal.ONE, BigDecimal.valueOf(2), BigDecimal.valueOf(3), BigDecimal.valueOf(4)); } @@ -52,7 +52,7 @@ void evaluateNestedArray() { IterationContextNode x = getIterationContextNode("x", getNestedListNode("[ [1, 2], [3, 4] ]", firstIterationContext), "x in [ [1, 2], [3, 4] ]"); IterationContextNode y = getIterationContextNode("y", getNameRefNode(BuiltInType.UNKNOWN, "x"), "y in x"); ForExpressionNode forExpressionNode = new ForExpressionNode(Arrays.asList(x, y), getNameRefNode(BuiltInType.UNKNOWN, "y"), "for x in [ [1, 2], [3, 4] ], y in x return y"); - Object retrieved = forExpressionNode.evaluate(CodegenTestUtil.newEmptyEvaluationContext()); + Object retrieved = forExpressionNode.evaluate(EvaluationContextTestUtil.newEmptyEvaluationContext()); assertThat(retrieved).isInstanceOf(List.class).asList(). containsExactly(BigDecimal.ONE, BigDecimal.valueOf(2), BigDecimal.valueOf(3), BigDecimal.valueOf(4)); diff --git a/kie-dmn/kie-dmn-feel/src/test/java/org/kie/dmn/feel/lang/ast/RangeTypeNodeTest.java b/kie-dmn/kie-dmn-feel/src/test/java/org/kie/dmn/feel/lang/ast/RangeTypeNodeTest.java new file mode 100644 index 00000000000..aaa5a3caa02 --- /dev/null +++ b/kie-dmn/kie-dmn-feel/src/test/java/org/kie/dmn/feel/lang/ast/RangeTypeNodeTest.java @@ -0,0 +1,52 @@ +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you 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 + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.kie.dmn.feel.lang.ast; + +import org.assertj.core.api.Assertions; +import org.junit.jupiter.api.Test; +import org.kie.dmn.feel.lang.types.GenRangeType; +import org.kie.dmn.feel.util.EvaluationContextTestUtil; +import org.kie.dmn.feel.lang.types.BuiltInType; +import org.mockito.Mockito; + +class RangeTypeNodeTest { + + @Test + void evaluate() { + final CTypeNode typeNode = new CTypeNode(BuiltInType.BOOLEAN); + final RangeTypeNode rangeTypeNode = new RangeTypeNode(typeNode, "sometext"); + Assertions.assertThat(rangeTypeNode.evaluate(EvaluationContextTestUtil.newEmptyEvaluationContext())).isInstanceOf(GenRangeType.class); + } + + @Test + void accept() { + final Visitor visitor = Mockito.spy(Visitor.class); + final RangeTypeNode rangeTypeNode = new RangeTypeNode(null, "sometext"); + rangeTypeNode.accept(visitor); + Mockito.verify(visitor).visit(rangeTypeNode); + } + + @Test + void getGenTypeNode() { + final CTypeNode typeNode = new CTypeNode(BuiltInType.BOOLEAN); + final RangeTypeNode rangeTypeNode = new RangeTypeNode(typeNode, "sometext"); + Assertions.assertThat(rangeTypeNode.getGenericTypeNode()).isSameAs(typeNode); + } +} \ No newline at end of file diff --git a/kie-dmn/kie-dmn-feel/src/test/java/org/kie/dmn/feel/lang/ast/forexpressioniterators/ForIterationUtilsTest.java b/kie-dmn/kie-dmn-feel/src/test/java/org/kie/dmn/feel/lang/ast/forexpressioniterators/ForIterationUtilsTest.java index 226d2e1797d..852ed9e2057 100644 --- a/kie-dmn/kie-dmn-feel/src/test/java/org/kie/dmn/feel/lang/ast/forexpressioniterators/ForIterationUtilsTest.java +++ b/kie-dmn/kie-dmn-feel/src/test/java/org/kie/dmn/feel/lang/ast/forexpressioniterators/ForIterationUtilsTest.java @@ -6,9 +6,9 @@ * to you 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 - *

+ * * http://www.apache.org/licenses/LICENSE-2.0 - *

+ * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY @@ -32,7 +32,7 @@ import org.mockito.ArgumentCaptor; import static org.assertj.core.api.Assertions.assertThat; -import static org.kie.dmn.feel.codegen.feel11.CodegenTestUtil.newEmptyEvaluationContext; +import static org.kie.dmn.feel.util.EvaluationContextTestUtil.newEmptyEvaluationContext; import static org.kie.dmn.feel.lang.ast.forexpressioniterators.ForIterationUtils.getForIteration; import static org.kie.dmn.feel.lang.ast.forexpressioniterators.ForIterationUtils.validateValues; import static org.kie.dmn.feel.lang.ast.forexpressioniterators.ForIterationUtils.valueMustBeValid; diff --git a/kie-dmn/kie-dmn-feel/src/test/java/org/kie/dmn/feel/marshaller/FEELCodeMarshallerTest.java b/kie-dmn/kie-dmn-feel/src/test/java/org/kie/dmn/feel/marshaller/FEELCodeMarshallerTest.java index 8b2adc20b4d..b79ad9ab479 100644 --- a/kie-dmn/kie-dmn-feel/src/test/java/org/kie/dmn/feel/marshaller/FEELCodeMarshallerTest.java +++ b/kie-dmn/kie-dmn-feel/src/test/java/org/kie/dmn/feel/marshaller/FEELCodeMarshallerTest.java @@ -36,6 +36,7 @@ import org.kie.dmn.feel.lang.types.impl.ComparablePeriod; import org.kie.dmn.feel.runtime.Range; import org.kie.dmn.feel.runtime.impl.RangeImpl; +import org.kie.dmn.feel.runtime.impl.UndefinedValueComparable; import static org.assertj.core.api.Assertions.assertThat; @@ -96,13 +97,18 @@ private static Collection data() { { Arrays.asList( Duration.ofDays( 4 ), Duration.ofDays( 2 ), Duration.ofHours( 25 ) ), "[ duration( \"P4D\" ), duration( \"P2D\" ), duration( \"P1DT1H\" ) ]" }, { Arrays.asList( Arrays.asList( 1, 2 ), Arrays.asList( 3, 4 ) ), "[ [ 1, 2 ], [ 3, 4 ] ]" }, // ranges - { new RangeImpl( Range.RangeBoundary.CLOSED, "a", "z", Range.RangeBoundary.OPEN ), "[ \"a\" .. \"z\" )" }, - { new RangeImpl( Range.RangeBoundary.CLOSED, Duration.ofHours( 30 ), Duration.ofHours( 50 ), Range.RangeBoundary.OPEN ), "[ duration( \"P1DT6H\" ) .. duration( \"P2DT2H\" ) )" }, + { new RangeImpl( Range.RangeBoundary.CLOSED, "a", "z", Range.RangeBoundary.OPEN), "[ \"a\" .. \"z\" )" }, + { new RangeImpl( Range.RangeBoundary.CLOSED, Duration.ofHours( 30 ), Duration.ofHours( 50 ), Range.RangeBoundary.OPEN), "[ duration( \"P1DT6H\" ) .. duration( \"P2DT2H\" ) )" }, + { new RangeImpl(Range.RangeBoundary.OPEN, BigDecimal.ONE, new UndefinedValueComparable(), Range.RangeBoundary.OPEN), "( > 1 )" }, + { new RangeImpl(Range.RangeBoundary.CLOSED, BigDecimal.ONE, new UndefinedValueComparable(), Range.RangeBoundary.OPEN), "( >= 1 )" }, + { new RangeImpl(Range.RangeBoundary.OPEN, new UndefinedValueComparable(), BigDecimal.ONE, Range.RangeBoundary.OPEN), "( < 1 )" }, + { new RangeImpl(Range.RangeBoundary.OPEN, new UndefinedValueComparable(), BigDecimal.ONE, Range.RangeBoundary.CLOSED), "( <= 1 )" }, // context { new LinkedHashMap() {{ put( "Full Name", "John Doe"); put( "Age", 35 ); put( "Date of Birth", LocalDate.of( 1982, 6, 9 ) ); }}, "{ Full Name : \"John Doe\", Age : 35, Date of Birth : date( \"1982-06-09\" ) }" }, // null - { null, "null" } + { null, "null" }, + { new UndefinedValueComparable(), "undefined"} }; return Arrays.asList( cases ); } diff --git a/kie-dmn/kie-dmn-feel/src/test/java/org/kie/dmn/feel/marshaller/FEELCodeMarshallerUnmarshallTest.java b/kie-dmn/kie-dmn-feel/src/test/java/org/kie/dmn/feel/marshaller/FEELCodeMarshallerUnmarshallTest.java index aa2457b8362..0635ac36400 100644 --- a/kie-dmn/kie-dmn-feel/src/test/java/org/kie/dmn/feel/marshaller/FEELCodeMarshallerUnmarshallTest.java +++ b/kie-dmn/kie-dmn-feel/src/test/java/org/kie/dmn/feel/marshaller/FEELCodeMarshallerUnmarshallTest.java @@ -37,6 +37,7 @@ import org.kie.dmn.feel.lang.types.impl.ComparablePeriod; import org.kie.dmn.feel.runtime.Range; import org.kie.dmn.feel.runtime.impl.RangeImpl; +import org.kie.dmn.feel.runtime.impl.UndefinedValueComparable; import static org.assertj.core.api.Assertions.assertThat; @@ -91,13 +92,20 @@ private static Collection data() { { BuiltInType.UNKNOWN, "[ duration( \"P4D\" ), duration( \"P2D\" ), duration( \"P1DT1H\" ) ]", Arrays.asList( Duration.ofDays( 4 ), Duration.ofDays( 2 ), Duration.ofHours( 25 ) ) }, { BuiltInType.UNKNOWN, "[ [ 1, 2 ], [ 3, 4 ] ]", Arrays.asList( Arrays.asList( BigDecimal.valueOf( 1 ), BigDecimal.valueOf( 2 ) ), Arrays.asList( BigDecimal.valueOf( 3 ), BigDecimal.valueOf( 4 ) ) ) }, // ranges - { BuiltInType.UNKNOWN, "[ \"a\" .. \"z\" )", new RangeImpl( Range.RangeBoundary.CLOSED, "a", "z", Range.RangeBoundary.OPEN ) }, - { BuiltInType.UNKNOWN, "[ duration( \"P1DT6H\" ) .. duration( \"P2DT2H\" ) )", new RangeImpl( Range.RangeBoundary.CLOSED, Duration.ofHours( 30 ), Duration.ofHours( 50 ), Range.RangeBoundary.OPEN ) }, + { BuiltInType.UNKNOWN, "[ \"a\" .. \"z\" )", new RangeImpl( Range.RangeBoundary.CLOSED, "a", "z", Range.RangeBoundary.OPEN) }, + { BuiltInType.UNKNOWN, "[ duration( \"P1DT6H\" ) .. duration( \"P2DT2H\" ) )", new RangeImpl( Range.RangeBoundary.CLOSED, Duration.ofHours( 30 ), Duration.ofHours( 50 ), Range.RangeBoundary.OPEN) }, + + { BuiltInType.UNKNOWN, "( > 1 )", new RangeImpl(Range.RangeBoundary.OPEN, BigDecimal.ONE, new UndefinedValueComparable(), Range.RangeBoundary.OPEN)}, + { BuiltInType.UNKNOWN, "( >= 1 )", new RangeImpl(Range.RangeBoundary.CLOSED, BigDecimal.ONE, new UndefinedValueComparable(), Range.RangeBoundary.OPEN) }, + { BuiltInType.UNKNOWN, "( < 1 )", new RangeImpl(Range.RangeBoundary.OPEN, new UndefinedValueComparable(), BigDecimal.ONE, Range.RangeBoundary.OPEN)}, + { BuiltInType.UNKNOWN, "( <= 1 )", new RangeImpl(Range.RangeBoundary.OPEN, new UndefinedValueComparable(), BigDecimal.ONE, Range.RangeBoundary.CLOSED) }, + // context { BuiltInType.UNKNOWN, "{ Full Name : \"John Doe\", Age : 35, Date of Birth : date( \"1982-06-09\" ) }", new LinkedHashMap() {{ put( "Full Name", "John Doe"); put( "Age", BigDecimal.valueOf( 35 ) ); put( "Date of Birth", LocalDate.of( 1982, 6, 9 ) ); }} }, // null - { BuiltInType.UNKNOWN, "null", null } + { BuiltInType.UNKNOWN, "null", null }, + { BuiltInType.UNKNOWN, "undefined", new UndefinedValueComparable() } }; return Arrays.asList( cases ); } diff --git a/kie-dmn/kie-dmn-feel/src/test/java/org/kie/dmn/feel/parser/feel11/FEELParserSeverityTest.java b/kie-dmn/kie-dmn-feel/src/test/java/org/kie/dmn/feel/parser/feel11/FEELParserSeverityTest.java index 6f499898978..02851b82d29 100644 --- a/kie-dmn/kie-dmn-feel/src/test/java/org/kie/dmn/feel/parser/feel11/FEELParserSeverityTest.java +++ b/kie-dmn/kie-dmn-feel/src/test/java/org/kie/dmn/feel/parser/feel11/FEELParserSeverityTest.java @@ -83,7 +83,7 @@ void unexistentOperatorEQEQ() { @Test void unexistentOperatorInvokeLTLT() { - // RHDM-1119 + // RHDM-1119 String inputExpression = "{ m: <<18 }.m(16)"; ASTNode number = parseSeverity(inputExpression, FEELEvent.Severity.WARN); diff --git a/kie-dmn/kie-dmn-feel/src/test/java/org/kie/dmn/feel/runtime/FEELCompilerTest.java b/kie-dmn/kie-dmn-feel/src/test/java/org/kie/dmn/feel/runtime/FEELCompilerTest.java index 80502839d79..f3b34fef4f9 100644 --- a/kie-dmn/kie-dmn-feel/src/test/java/org/kie/dmn/feel/runtime/FEELCompilerTest.java +++ b/kie-dmn/kie-dmn-feel/src/test/java/org/kie/dmn/feel/runtime/FEELCompilerTest.java @@ -25,7 +25,7 @@ import java.util.List; import org.junit.jupiter.api.Test; -import org.kie.dmn.feel.codegen.feel11.CodegenTestUtil; +import org.kie.dmn.feel.util.EvaluationContextTestUtil; import org.kie.dmn.feel.codegen.feel11.CompiledFEELExpression; import org.kie.dmn.feel.lang.EvaluationContext; import org.kie.dmn.feel.lang.FEELProperty; @@ -226,7 +226,7 @@ void filter_path_tricky1() { CompiledFEELExpression nameRef = CompilerUtils.parseInterpreted("[ {x:1, y:2}, {x:2, y:3} ][x]"); LOG.debug("{}", nameRef); - EvaluationContext context = CodegenTestUtil.newEmptyEvaluationContext(); + EvaluationContext context = EvaluationContextTestUtil.newEmptyEvaluationContext(); context.setValue("x", 2); Object result = nameRef.apply(context); LOG.debug("{}", result); @@ -239,7 +239,7 @@ void filter_path_tricky2() { CompiledFEELExpression nameRef = CompilerUtils.parseInterpreted("[ {x:1, y:2}, {x:2, y:3} ][x]"); LOG.debug("{}", nameRef); - EvaluationContext context = CodegenTestUtil.newEmptyEvaluationContext(); + EvaluationContext context = EvaluationContextTestUtil.newEmptyEvaluationContext(); context.setValue("x", false); Object result = nameRef.apply(context); LOG.debug("{}", result); @@ -410,7 +410,7 @@ void nameReference() { CompiledFEELExpression nameRef = parseInterpreted(inputExpression, mapOf(entry("someSimpleName", BuiltInType.STRING) ) ); LOG.debug("{}", nameRef); - EvaluationContext context = CodegenTestUtil.newEmptyEvaluationContext(); + EvaluationContext context = EvaluationContextTestUtil.newEmptyEvaluationContext(); context.setValue("someSimpleName", 123L); Object result = nameRef.apply(context); LOG.debug("{}", result); @@ -425,7 +425,7 @@ void qualifiedName() { CompiledFEELExpression qualRef = parseInterpreted(inputExpression, mapOf(entry("My Person", personType) ) ); LOG.debug("{}", qualRef); - EvaluationContext context = CodegenTestUtil.newEmptyEvaluationContext(); + EvaluationContext context = EvaluationContextTestUtil.newEmptyEvaluationContext(); context.setValue("My Person", mapOf( entry("Full Name", "John Doe"), entry("Age", 47) )); Object result = qualRef.apply(context); LOG.debug("{}", result); @@ -456,7 +456,7 @@ void qualifiedName2() { CompiledFEELExpression qualRef = parseInterpreted(inputExpression, mapOf(entry("My Person", personType) ) ); LOG.debug("{}", qualRef); - EvaluationContext context = CodegenTestUtil.newEmptyEvaluationContext(); + EvaluationContext context = EvaluationContextTestUtil.newEmptyEvaluationContext(); context.setValue("My Person", new MyPerson()); Object result = qualRef.apply(context); LOG.debug("{}", result); @@ -471,7 +471,7 @@ void qualifiedName3() { CompiledFEELExpression qualRef = parseInterpreted(inputExpression, mapOf(entry("a date", dateType))); LOG.debug("{}", qualRef); - EvaluationContext context = CodegenTestUtil.newEmptyEvaluationContext(); + EvaluationContext context = EvaluationContextTestUtil.newEmptyEvaluationContext(); context.setValue("a date", LocalDate.of(2016, 8, 2)); Object result = qualRef.apply(context); LOG.debug("{}", result); diff --git a/kie-dmn/kie-dmn-feel/src/test/java/org/kie/dmn/feel/runtime/FEELOperatorsTest.java b/kie-dmn/kie-dmn-feel/src/test/java/org/kie/dmn/feel/runtime/FEELOperatorsTest.java index 92258af10bf..5d167665c70 100644 --- a/kie-dmn/kie-dmn-feel/src/test/java/org/kie/dmn/feel/runtime/FEELOperatorsTest.java +++ b/kie-dmn/kie-dmn-feel/src/test/java/org/kie/dmn/feel/runtime/FEELOperatorsTest.java @@ -127,6 +127,8 @@ private static Collection data() { {"(function(a: context) {b: \"b\", c: \"c\"}) instance of function>->context", Boolean.TRUE , null}, {"(function(a: context) \"foo\") instance of function>->string", Boolean.FALSE , null}, {"(function(a: context, b: context) \"foo\") instance of function,context>->string", Boolean.TRUE , null}, + {"range(\"[1..3]\") instance of range", Boolean.TRUE , null}, + {"range(\"[1..3]\") instance of range", Boolean.FALSE , null} }; return addAdditionalParameters(cases, false); } diff --git a/kie-dmn/kie-dmn-feel/src/test/java/org/kie/dmn/feel/runtime/FEELRangesTest.java b/kie-dmn/kie-dmn-feel/src/test/java/org/kie/dmn/feel/runtime/FEELRangesTest.java index 780e31e96dd..b2419f52634 100644 --- a/kie-dmn/kie-dmn-feel/src/test/java/org/kie/dmn/feel/runtime/FEELRangesTest.java +++ b/kie-dmn/kie-dmn-feel/src/test/java/org/kie/dmn/feel/runtime/FEELRangesTest.java @@ -31,6 +31,7 @@ import org.kie.dmn.feel.lang.FEELDialect; import org.kie.dmn.feel.lang.types.impl.ComparablePeriod; import org.kie.dmn.feel.runtime.impl.RangeImpl; +import org.kie.dmn.feel.runtime.impl.UndefinedValueComparable; public class FEELRangesTest extends BaseFEELTest { @@ -42,6 +43,13 @@ protected void instanceTest(String expression, Object result, FEELEvent.Severity private static Collection data() { final Object[][] cases = new Object[][]{ + // when converting from unary tests, boundaries are dictated by comparison + {"(>1)", new RangeImpl(Range.RangeBoundary.OPEN, BigDecimal.ONE, new UndefinedValueComparable(), Range.RangeBoundary.OPEN), null}, + {"(>=1)", new RangeImpl(Range.RangeBoundary.CLOSED, BigDecimal.ONE, new UndefinedValueComparable(), Range.RangeBoundary.OPEN), null}, + {"(<1)", new RangeImpl(Range.RangeBoundary.OPEN, new UndefinedValueComparable(), BigDecimal.ONE, Range.RangeBoundary.OPEN), null}, + {"(<=1)", new RangeImpl(Range.RangeBoundary.OPEN, new UndefinedValueComparable(), BigDecimal.ONE, Range.RangeBoundary.CLOSED), null}, + {"(null..10)", new RangeImpl(Range.RangeBoundary.OPEN, null, BigDecimal.valueOf(10), Range.RangeBoundary.OPEN), null}, + {"[1..2]", new RangeImpl(Range.RangeBoundary.CLOSED, BigDecimal.ONE, BigDecimal.valueOf(2), Range.RangeBoundary.CLOSED), null}, {"[2..1]", new RangeImpl(Range.RangeBoundary.CLOSED, BigDecimal.valueOf(2), BigDecimal.ONE, Range.RangeBoundary.CLOSED), null}, {"[1..2)", new RangeImpl(Range.RangeBoundary.CLOSED, BigDecimal.ONE, BigDecimal.valueOf(2), Range.RangeBoundary.OPEN), null}, @@ -161,7 +169,7 @@ private static Collection data() { put("enddate", LocalDate.of(1978, 10, 13)); put("rangedates", new RangeImpl(Range.RangeBoundary.CLOSED, LocalDate.of(1978, 9, 12), LocalDate.of(1978, 10, 13), Range.RangeBoundary.CLOSED)); }}, null}, - + // Table 42: {"[1..10].start included", Boolean.TRUE, null}, {"[1..10].start", new BigDecimal(1), null}, @@ -172,12 +180,14 @@ private static Collection data() { {"(1..10].end", new BigDecimal(10), null}, {"(1..10].end included", Boolean.TRUE, null}, {"(<=10).start included", Boolean.FALSE, null}, + {"(<10).start", null, null}, {"(<=10).start", null, null}, {"(<=10).end", new BigDecimal(10), null}, {"(<=10).end included", Boolean.TRUE, null}, {"(>1).start included", Boolean.FALSE, null}, {"(>1).start", new BigDecimal(1), null}, {"(>1).end", null, null}, + {"(>=1).end", null, null}, {"(>1).end included", Boolean.FALSE, null}, }; return addAdditionalParameters(cases, false); diff --git a/kie-dmn/kie-dmn-feel/src/test/java/org/kie/dmn/feel/runtime/functions/BaseFEELFunctionHelperTest.java b/kie-dmn/kie-dmn-feel/src/test/java/org/kie/dmn/feel/runtime/functions/BaseFEELFunctionHelperTest.java index 9143712030a..b8d51268fa7 100644 --- a/kie-dmn/kie-dmn-feel/src/test/java/org/kie/dmn/feel/runtime/functions/BaseFEELFunctionHelperTest.java +++ b/kie-dmn/kie-dmn-feel/src/test/java/org/kie/dmn/feel/runtime/functions/BaseFEELFunctionHelperTest.java @@ -30,7 +30,7 @@ import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; -import org.kie.dmn.feel.codegen.feel11.CodegenTestUtil; +import org.kie.dmn.feel.util.EvaluationContextTestUtil; import org.kie.dmn.feel.lang.EvaluationContext; import org.kie.dmn.feel.lang.impl.NamedParameter; import org.kie.dmn.feel.runtime.FEELFunction; @@ -44,7 +44,7 @@ class BaseFEELFunctionHelperTest { @BeforeEach public void setUp() { - ctx = CodegenTestUtil.newEmptyEvaluationContext(); + ctx = EvaluationContextTestUtil.newEmptyEvaluationContext(); } @Test diff --git a/kie-dmn/kie-dmn-feel/src/test/java/org/kie/dmn/feel/runtime/functions/BaseFEELFunctionTest.java b/kie-dmn/kie-dmn-feel/src/test/java/org/kie/dmn/feel/runtime/functions/BaseFEELFunctionTest.java index f5deff2214d..af32bcc9c6a 100644 --- a/kie-dmn/kie-dmn-feel/src/test/java/org/kie/dmn/feel/runtime/functions/BaseFEELFunctionTest.java +++ b/kie-dmn/kie-dmn-feel/src/test/java/org/kie/dmn/feel/runtime/functions/BaseFEELFunctionTest.java @@ -31,7 +31,7 @@ import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; -import org.kie.dmn.feel.codegen.feel11.CodegenTestUtil; +import org.kie.dmn.feel.util.EvaluationContextTestUtil; import org.kie.dmn.feel.lang.EvaluationContext; import org.kie.dmn.feel.lang.ast.BaseNode; import org.kie.dmn.feel.lang.ast.InfixOpNode; @@ -51,7 +51,7 @@ class BaseFEELFunctionTest { @BeforeEach public void setUp() { - ctx = CodegenTestUtil.newEmptyEvaluationContext(); + ctx = EvaluationContextTestUtil.newEmptyEvaluationContext(); } @Test diff --git a/kie-dmn/kie-dmn-feel/src/test/java/org/kie/dmn/feel/runtime/functions/DateFunctionTest.java b/kie-dmn/kie-dmn-feel/src/test/java/org/kie/dmn/feel/runtime/functions/DateFunctionTest.java index db9ece6621b..f1462b8d79d 100644 --- a/kie-dmn/kie-dmn-feel/src/test/java/org/kie/dmn/feel/runtime/functions/DateFunctionTest.java +++ b/kie-dmn/kie-dmn-feel/src/test/java/org/kie/dmn/feel/runtime/functions/DateFunctionTest.java @@ -32,7 +32,7 @@ class DateFunctionTest { @BeforeEach void setUp() { - dateFunction = new DateFunction(); + dateFunction = DateFunction.INSTANCE; } @Test diff --git a/kie-dmn/kie-dmn-feel/src/test/java/org/kie/dmn/feel/runtime/functions/ScorerHelperTest.java b/kie-dmn/kie-dmn-feel/src/test/java/org/kie/dmn/feel/runtime/functions/ScorerHelperTest.java index 71f4bf6934f..9cc4098d8cb 100644 --- a/kie-dmn/kie-dmn-feel/src/test/java/org/kie/dmn/feel/runtime/functions/ScorerHelperTest.java +++ b/kie-dmn/kie-dmn-feel/src/test/java/org/kie/dmn/feel/runtime/functions/ScorerHelperTest.java @@ -24,7 +24,7 @@ import java.util.Random; import org.junit.jupiter.api.Test; -import org.kie.dmn.feel.codegen.feel11.CodegenTestUtil; +import org.kie.dmn.feel.util.EvaluationContextTestUtil; import org.kie.dmn.feel.lang.EvaluationContext; import org.kie.dmn.feel.lang.impl.NamedParameter; @@ -443,7 +443,7 @@ void typeIdentityOfParameters() { retrieved = ScoreHelper.typeIdentityOfParameters.applyAsInt(compares); assertThat(retrieved).isEqualTo(500); - originalInput = new Object[] { CodegenTestUtil.newEmptyEvaluationContext(), "String" }; + originalInput = new Object[] { EvaluationContextTestUtil.newEmptyEvaluationContext(), "String" }; adaptedInput = originalInput; parameterTypes = new Class[] { EvaluationContext.class, String.class }; compares = new ScoreHelper.Compares(originalInput, adaptedInput, parameterTypes); @@ -451,7 +451,7 @@ void typeIdentityOfParameters() { assertThat(retrieved).isEqualTo(1000); originalInput = new Object[] { "String" }; - adaptedInput = new Object[] { CodegenTestUtil.newEmptyEvaluationContext(), "String" }; + adaptedInput = new Object[] { EvaluationContextTestUtil.newEmptyEvaluationContext(), "String" }; parameterTypes = new Class[] { EvaluationContext.class, String.class }; compares = new ScoreHelper.Compares(originalInput, adaptedInput, parameterTypes); retrieved = ScoreHelper.typeIdentityOfParameters.applyAsInt(compares); @@ -465,7 +465,7 @@ void typeIdentityOfParameters() { assertThat(retrieved).isEqualTo(0); originalInput = new Object[] { "String", 34 }; - adaptedInput = new Object[] { CodegenTestUtil.newEmptyEvaluationContext(), "String", 34 }; + adaptedInput = new Object[] { EvaluationContextTestUtil.newEmptyEvaluationContext(), "String", 34 }; parameterTypes = new Class[] { EvaluationContext.class, String.class, Integer.class }; compares = new ScoreHelper.Compares(originalInput, adaptedInput, parameterTypes); retrieved = ScoreHelper.typeIdentityOfParameters.applyAsInt(compares); @@ -491,7 +491,7 @@ void typeIdentityOfParameters() { retrieved = ScoreHelper.typeIdentityOfParameters.applyAsInt(compares); assertThat(retrieved).isEqualTo(0); - originalInput = new Object[] { CodegenTestUtil.newEmptyEvaluationContext(), "String" }; + originalInput = new Object[] { EvaluationContextTestUtil.newEmptyEvaluationContext(), "String" }; parameterTypes = new Class[] { EvaluationContext.class, Integer.class }; compares = new ScoreHelper.Compares(originalInput, null, parameterTypes); retrieved = ScoreHelper.typeIdentityOfParameters.applyAsInt(compares); @@ -531,20 +531,20 @@ void coercedToVarargs() { retrieved = ScoreHelper.coercedToVarargs.applyAsInt(compares); assertThat(retrieved).isEqualTo(coercedToVarargsScore); - originalInput = new Object[] { CodegenTestUtil.newEmptyEvaluationContext(), "String", 34 }; + originalInput = new Object[] { EvaluationContextTestUtil.newEmptyEvaluationContext(), "String", 34 }; adaptedInput = new Object[] { new Object[] {"String", 34} }; compares = new ScoreHelper.Compares(originalInput, adaptedInput, null); retrieved = ScoreHelper.coercedToVarargs.applyAsInt(compares); assertThat(retrieved).isEqualTo(coercedToVarargsScore); originalInput = new Object[] { "String", 34 }; - adaptedInput = new Object[] { CodegenTestUtil.newEmptyEvaluationContext(), new Object[] {"String", 34} }; + adaptedInput = new Object[] { EvaluationContextTestUtil.newEmptyEvaluationContext(), new Object[] {"String", 34} }; compares = new ScoreHelper.Compares(originalInput, adaptedInput, null); retrieved = ScoreHelper.coercedToVarargs.applyAsInt(compares); assertThat(retrieved).isEqualTo(coercedToVarargsScore); - originalInput = new Object[] { CodegenTestUtil.newEmptyEvaluationContext(), "String", 34 }; - adaptedInput = new Object[] { CodegenTestUtil.newEmptyEvaluationContext(), new Object[] {"String", 34} }; + originalInput = new Object[] { EvaluationContextTestUtil.newEmptyEvaluationContext(), "String", 34 }; + adaptedInput = new Object[] { EvaluationContextTestUtil.newEmptyEvaluationContext(), new Object[] {"String", 34} }; compares = new ScoreHelper.Compares(originalInput, adaptedInput, null); retrieved = ScoreHelper.coercedToVarargs.applyAsInt(compares); assertThat(retrieved).isEqualTo(coercedToVarargsScore); diff --git a/kie-dmn/kie-dmn-feel/src/test/java/org/kie/dmn/feel/runtime/impl/RangeImplTest.java b/kie-dmn/kie-dmn-feel/src/test/java/org/kie/dmn/feel/runtime/impl/RangeImplTest.java index 6201fe90b12..521abb12fc7 100644 --- a/kie-dmn/kie-dmn-feel/src/test/java/org/kie/dmn/feel/runtime/impl/RangeImplTest.java +++ b/kie-dmn/kie-dmn-feel/src/test/java/org/kie/dmn/feel/runtime/impl/RangeImplTest.java @@ -25,6 +25,24 @@ class RangeImplTest { + @Test + void isWithUndefined() { + RangeImpl rangeImpl = new RangeImpl(Range.RangeBoundary.CLOSED, null, null, Range.RangeBoundary.OPEN); + assertThat(rangeImpl.isWithUndefined()).isFalse(); + rangeImpl = new RangeImpl(Range.RangeBoundary.CLOSED, 10, null, Range.RangeBoundary.OPEN); + assertThat(rangeImpl.isWithUndefined()).isFalse(); + rangeImpl = new RangeImpl(Range.RangeBoundary.CLOSED, null, 10, Range.RangeBoundary.OPEN); + assertThat(rangeImpl.isWithUndefined()).isFalse(); + rangeImpl = new RangeImpl(Range.RangeBoundary.CLOSED, null, new UndefinedValueComparable(), Range.RangeBoundary.OPEN); + assertThat(rangeImpl.isWithUndefined()).isTrue(); + rangeImpl = new RangeImpl(Range.RangeBoundary.CLOSED, new UndefinedValueComparable(), null, Range.RangeBoundary.OPEN); + assertThat(rangeImpl.isWithUndefined()).isTrue(); + rangeImpl = new RangeImpl(Range.RangeBoundary.CLOSED, 10, new UndefinedValueComparable(), Range.RangeBoundary.OPEN); + assertThat(rangeImpl.isWithUndefined()).isTrue(); + rangeImpl = new RangeImpl(Range.RangeBoundary.CLOSED, new UndefinedValueComparable(), 10, Range.RangeBoundary.OPEN); + assertThat(rangeImpl.isWithUndefined()).isTrue(); + } + @Test void getLowBoundary() { final Range.RangeBoundary lowBoundary = Range.RangeBoundary.CLOSED; @@ -77,6 +95,26 @@ void includes() { assertThat(rangeImpl.includes(10)).isTrue(); assertThat(rangeImpl.includes(12)).isTrue(); assertThat(rangeImpl.includes(15)).isTrue(); + + rangeImpl = new RangeImpl(Range.RangeBoundary.CLOSED, new UndefinedValueComparable(), 15, Range.RangeBoundary.CLOSED); + assertThat(rangeImpl.includes(-1456)).isTrue(); + assertThat(rangeImpl.includes(20)).isFalse(); + assertThat(rangeImpl.includes(null)).isNull(); + + rangeImpl = new RangeImpl(Range.RangeBoundary.CLOSED, 15, new UndefinedValueComparable(), Range.RangeBoundary.CLOSED); + assertThat(rangeImpl.includes(-1456)).isFalse(); + assertThat(rangeImpl.includes(20)).isTrue(); + assertThat(rangeImpl.includes(null)).isNull(); + + rangeImpl = new RangeImpl(Range.RangeBoundary.CLOSED, null, new UndefinedValueComparable(), Range.RangeBoundary.CLOSED); + assertThat(rangeImpl.includes(-1456)).isNull(); + assertThat(rangeImpl.includes(20)).isNull(); + assertThat(rangeImpl.includes(null)).isNull(); + + rangeImpl = new RangeImpl(Range.RangeBoundary.CLOSED, new UndefinedValueComparable(), null, Range.RangeBoundary.CLOSED); + assertThat(rangeImpl.includes(-1456)).isNull(); + assertThat(rangeImpl.includes(20)).isNull(); + assertThat(rangeImpl.includes(null)).isNull(); } @Test diff --git a/kie-dmn/kie-dmn-feel/src/test/java/org/kie/dmn/feel/util/CompilerUtils.java b/kie-dmn/kie-dmn-feel/src/test/java/org/kie/dmn/feel/util/CompilerUtils.java index c201ec39ca3..3c645548ed0 100644 --- a/kie-dmn/kie-dmn-feel/src/test/java/org/kie/dmn/feel/util/CompilerUtils.java +++ b/kie-dmn/kie-dmn-feel/src/test/java/org/kie/dmn/feel/util/CompilerUtils.java @@ -25,7 +25,6 @@ import com.github.javaparser.ast.stmt.BlockStmt; import org.antlr.v4.runtime.tree.ParseTree; import org.kie.dmn.feel.codegen.feel11.ASTCompilerVisitor; -import org.kie.dmn.feel.codegen.feel11.CodegenTestUtil; import org.kie.dmn.feel.codegen.feel11.CompiledFEELExpression; import org.kie.dmn.feel.codegen.feel11.CompilerBytecodeLoader; import org.kie.dmn.feel.lang.EvaluationContext; @@ -100,7 +99,7 @@ public static CompiledFEELExpression parseInterpreted(String input, Map org.apache.maven.plugins maven-scm-plugin - 1.11.1 run-tck-suite diff --git a/kie-dmn/kie-dmn-test-resources/src/test/resources/valid_models/DMNv1_5/MultipleHitRules.dmn b/kie-dmn/kie-dmn-test-resources/src/test/resources/valid_models/DMNv1_5/MultipleHitRules.dmn new file mode 100644 index 00000000000..b01f79264a5 --- /dev/null +++ b/kie-dmn/kie-dmn-test-resources/src/test/resources/valid_models/DMNv1_5/MultipleHitRules.dmn @@ -0,0 +1,94 @@ + + + + + number + + + + + + + + + + + + + Numbers + + + + + + + i + + + + + + + >0 + + + 1 + + + // Your annotations here + + + + + >1 + + + 2 + + + + + + + + >2 + + + 3 + + + + + + + + + + + + + + + 190 + + + 60 + 118 + 118 + 240 + + + + + + + + + + + + + + + + diff --git a/kie-dmn/kie-dmn-test-resources/src/test/resources/valid_models/DMNv1_5/RiskScore_Conditional.dmn b/kie-dmn/kie-dmn-test-resources/src/test/resources/valid_models/DMNv1_5/RiskScore_Conditional.dmn new file mode 100644 index 00000000000..a4816f968de --- /dev/null +++ b/kie-dmn/kie-dmn-test-resources/src/test/resources/valid_models/DMNv1_5/RiskScore_Conditional.dmn @@ -0,0 +1,328 @@ + + + + string + + "Asia", "Europe" + + + + string + + "Poor", "Fair", "Excellent" + + + + string + + "High", "Medium", "Low" + + + + string + + "Qualified", "Not Qualified" + + + + + + + + + + + + + + + + + + + + + + + World Region = "Asia" + + + + + + + Credit Score + + + + + DTI + + + + + + + "Poor" + + + - + + + 30 + + + // Your annotations here + + + + + "Fair" + + + - + + + 20 + + + + + + + + "Excellent" + + + - + + + 10 + + + + + + + + - + + + > 40 + + + 30 + + + + + + + + - + + + [20..40] + + + 20 + + + + + + + + - + + + < 20 + + + 10 + + + + + + + + + + + + Credit Score + + + + + DTI + + + + + + + "Poor" + + + - + + + 35 + + + // Your annotations here + + + + + "Fair" + + + - + + + 25 + + + + + + + + "Excellent" + + + - + + + 15 + + + + + + + + - + + + > 40 + + + 35 + + + + + + + + - + + + [20..40] + + + 25 + + + + + + + + - + + + < 20 + + + 15 + + + + + + + + + + + + + + + + + + + 60 + 145 + 118 + 118 + 240 + + + 120 + + + 60 + 145 + 118 + 118 + 240 + + + 190 + + + 190 + + + 232 + + + 60 + 145 + 118 + 118 + 240 + + + 60 + 145 + 118 + 118 + 240 + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/kie-dmn/kie-dmn-test-resources/src/test/resources/valid_models/DMNv1_5/RiskScore_Simple.dmn b/kie-dmn/kie-dmn-test-resources/src/test/resources/valid_models/DMNv1_5/RiskScore_Simple.dmn new file mode 100644 index 00000000000..ea0d40e36a1 --- /dev/null +++ b/kie-dmn/kie-dmn-test-resources/src/test/resources/valid_models/DMNv1_5/RiskScore_Simple.dmn @@ -0,0 +1,228 @@ + + + + string + + "Poor", "Fair", "Excellent" + + + + string + + "High", "Medium", "Low" + + + + string + + "Qualified", "Not Qualified" + + + + + + + + + + + + + + + + + + + + Credit Score + + + + + DTI + + + + + + + "Poor" + + + - + + + 30 + + + // Your annotations here + + + + + "Fair" + + + - + + + 20 + + + + + + + + "Excellent" + + + - + + + 10 + + + + + + + + - + + + > 40 + + + 30 + + + + + + + + - + + + [20..40] + + + 20 + + + + + + + + - + + + < 20 + + + 10 + + + + + + + + + + + + + + + + Risk Score <= 30 + + + + + "Qualified" + + + + + "Not Qualified" + + + + + + + + + + 60 + 145 + 118 + 118 + 240 + + + 120 + + + 60 + 145 + 118 + 118 + 240 + + + 190 + + + 190 + + + 60 + 145 + 118 + 118 + 240 + + + 232 + + + 232 + + + 190 + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/kie-dmn/kie-dmn-trisotech/src/main/java/org/kie/dmn/trisotech/core/ast/DMNConditionalEvaluator.java b/kie-dmn/kie-dmn-trisotech/src/main/java/org/kie/dmn/trisotech/core/ast/DMNConditionalEvaluator.java index 4a2a1e15586..7821ce36724 100644 --- a/kie-dmn/kie-dmn-trisotech/src/main/java/org/kie/dmn/trisotech/core/ast/DMNConditionalEvaluator.java +++ b/kie-dmn/kie-dmn-trisotech/src/main/java/org/kie/dmn/trisotech/core/ast/DMNConditionalEvaluator.java @@ -22,8 +22,8 @@ import org.kie.dmn.api.core.DMNResult; import org.kie.dmn.api.core.event.DMNRuntimeEventManager; import org.kie.dmn.core.api.DMNExpressionEvaluator; -import org.kie.dmn.core.api.EvaluatorResult; -import org.kie.dmn.core.api.EvaluatorResult.ResultType; +import org.kie.dmn.api.core.EvaluatorResult; +import org.kie.dmn.api.core.EvaluatorResult.ResultType; import org.kie.dmn.core.ast.EvaluatorResultImpl; import org.kie.dmn.core.impl.DMNResultImpl; import org.kie.dmn.core.util.MsgUtil; diff --git a/kie-dmn/kie-dmn-trisotech/src/main/java/org/kie/dmn/trisotech/core/ast/DMNFilterEvaluator.java b/kie-dmn/kie-dmn-trisotech/src/main/java/org/kie/dmn/trisotech/core/ast/DMNFilterEvaluator.java index 167a6bd01ad..f5482b7b7c0 100644 --- a/kie-dmn/kie-dmn-trisotech/src/main/java/org/kie/dmn/trisotech/core/ast/DMNFilterEvaluator.java +++ b/kie-dmn/kie-dmn-trisotech/src/main/java/org/kie/dmn/trisotech/core/ast/DMNFilterEvaluator.java @@ -18,7 +18,6 @@ */ package org.kie.dmn.trisotech.core.ast; -import java.util.Arrays; import java.util.Collections; import java.util.LinkedList; import java.util.List; @@ -29,8 +28,8 @@ import org.kie.dmn.api.core.DMNResult; import org.kie.dmn.api.core.event.DMNRuntimeEventManager; import org.kie.dmn.core.api.DMNExpressionEvaluator; -import org.kie.dmn.core.api.EvaluatorResult; -import org.kie.dmn.core.api.EvaluatorResult.ResultType; +import org.kie.dmn.api.core.EvaluatorResult; +import org.kie.dmn.api.core.EvaluatorResult.ResultType; import org.kie.dmn.core.ast.EvaluatorResultImpl; import org.kie.dmn.core.impl.DMNResultImpl; import org.kie.dmn.core.util.MsgUtil; diff --git a/kie-dmn/kie-dmn-trisotech/src/main/java/org/kie/dmn/trisotech/core/ast/DMNIteratorEvaluator.java b/kie-dmn/kie-dmn-trisotech/src/main/java/org/kie/dmn/trisotech/core/ast/DMNIteratorEvaluator.java index 0c5a30c0eb7..6536b46adbf 100644 --- a/kie-dmn/kie-dmn-trisotech/src/main/java/org/kie/dmn/trisotech/core/ast/DMNIteratorEvaluator.java +++ b/kie-dmn/kie-dmn-trisotech/src/main/java/org/kie/dmn/trisotech/core/ast/DMNIteratorEvaluator.java @@ -26,8 +26,8 @@ import org.kie.dmn.api.core.DMNResult; import org.kie.dmn.api.core.event.DMNRuntimeEventManager; import org.kie.dmn.core.api.DMNExpressionEvaluator; -import org.kie.dmn.core.api.EvaluatorResult; -import org.kie.dmn.core.api.EvaluatorResult.ResultType; +import org.kie.dmn.api.core.EvaluatorResult; +import org.kie.dmn.api.core.EvaluatorResult.ResultType; import org.kie.dmn.core.ast.EvaluatorResultImpl; import org.kie.dmn.core.impl.DMNResultImpl; import org.kie.dmn.core.util.MsgUtil; diff --git a/kie-dmn/kie-dmn-validation/src/main/java/org/kie/dmn/validation/dtanalysis/DMNDTAnalyser.java b/kie-dmn/kie-dmn-validation/src/main/java/org/kie/dmn/validation/dtanalysis/DMNDTAnalyser.java index 84bdbc3683b..e82e068c888 100644 --- a/kie-dmn/kie-dmn-validation/src/main/java/org/kie/dmn/validation/dtanalysis/DMNDTAnalyser.java +++ b/kie-dmn/kie-dmn-validation/src/main/java/org/kie/dmn/validation/dtanalysis/DMNDTAnalyser.java @@ -55,6 +55,7 @@ import org.kie.dmn.feel.lang.ast.UnaryTestListNode; import org.kie.dmn.feel.lang.ast.UnaryTestNode; import org.kie.dmn.feel.lang.ast.UnaryTestNode.UnaryOperator; +import org.kie.dmn.feel.lang.ast.UndefinedValueNode; import org.kie.dmn.feel.lang.ast.Visitor; import org.kie.dmn.feel.lang.impl.FEELBuilder; import org.kie.dmn.feel.lang.impl.InterpretedExecutableExpression; @@ -289,9 +290,9 @@ private void verifyUtln(UnaryTestListNode utln, DecisionTable dt) { } private Optional checkForDiamondRange(RangeNode rangeNode) { - if ((rangeNode.getStart() instanceof NullNode || rangeNode.getStart() == null) && rangeNode.getUpperBound() == IntervalBoundary.OPEN && rangeNode.getEnd() instanceof RangeNode) { + if ((rangeNode.getStart() instanceof NullNode || rangeNode.getStart() instanceof UndefinedValueNode || rangeNode.getStart() == null) && rangeNode.getUpperBound() == IntervalBoundary.OPEN && rangeNode.getEnd() instanceof RangeNode) { return Optional.ofNullable(((RangeNode) rangeNode.getEnd()).getStart()); // <> value - } else if ((rangeNode.getEnd() instanceof NullNode || rangeNode.getEnd() == null) && rangeNode.getLowerBound() == IntervalBoundary.OPEN && rangeNode.getStart() instanceof RangeNode) { + } else if ((rangeNode.getEnd() instanceof NullNode || rangeNode.getEnd() instanceof UndefinedValueNode || rangeNode.getEnd() == null) && rangeNode.getLowerBound() == IntervalBoundary.OPEN && rangeNode.getStart() instanceof RangeNode) { return Optional.ofNullable(((RangeNode) rangeNode.getStart()).getEnd()); // >< value } else { return Optional.empty(); @@ -751,14 +752,15 @@ private Interval utnToInterval(UnaryTestNode ut, Interval minMax, List discreteV return new Interval(RangeBoundary.CLOSED, valueFromNode(ut.getValue()), minMax.getUpperBound().getValue(), minMax.getUpperBound().getBoundaryType(), rule, col); } else if (ut.getValue() instanceof RangeNode) { RangeNode rangeNode = (RangeNode) ut.getValue(); - if (!(rangeNode.getStart() instanceof NullNode || rangeNode.getEnd() instanceof NullNode)) { + if (!(rangeNode.getStart() instanceof NullNode || rangeNode.getStart() instanceof UndefinedValueNode || + rangeNode.getEnd() instanceof NullNode || rangeNode.getEnd() instanceof UndefinedValueNode)) { return new Interval(rangeNode.getLowerBound() == IntervalBoundary.OPEN ? RangeBoundary.OPEN : RangeBoundary.CLOSED, valueFromNode(rangeNode.getStart()), valueFromNode(rangeNode.getEnd()), rangeNode.getUpperBound() == IntervalBoundary.OPEN ? RangeBoundary.OPEN : RangeBoundary.CLOSED, rule, col); - } else if (rangeNode.getStart() instanceof NullNode) { + } else if (rangeNode.getStart() instanceof NullNode || rangeNode.getStart() instanceof UndefinedValueNode) { return new Interval(minMax.getLowerBound().getBoundaryType(), minMax.getLowerBound().getValue(), valueFromNode(rangeNode.getEnd()), diff --git a/kie-dmn/kie-dmn-validation/src/main/java/org/kie/dmn/validation/dtanalysis/model/Interval.java b/kie-dmn/kie-dmn-validation/src/main/java/org/kie/dmn/validation/dtanalysis/model/Interval.java index bb9c9ca09c4..fb4ebccc8a2 100644 --- a/kie-dmn/kie-dmn-validation/src/main/java/org/kie/dmn/validation/dtanalysis/model/Interval.java +++ b/kie-dmn/kie-dmn-validation/src/main/java/org/kie/dmn/validation/dtanalysis/model/Interval.java @@ -30,6 +30,7 @@ import org.kie.dmn.feel.runtime.Range; import org.kie.dmn.feel.runtime.Range.RangeBoundary; import org.kie.dmn.feel.runtime.impl.RangeImpl; +import org.kie.dmn.feel.runtime.impl.UndefinedValueComparable; import org.kie.dmn.feel.util.Generated; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -99,7 +100,7 @@ private static Comparable nullIfInfinity(Comparable input) { if (input != POS_INF && input != NEG_INF) { return input; } else { - return null; + return new UndefinedValueComparable(); } } diff --git a/kie-pmml-trusty/kie-pmml-compiler/kie-pmml-compiler-core/PMMLCompiler.uml b/kie-pmml-trusty/kie-pmml-compiler/kie-pmml-compiler-core/PMMLCompiler.uml index 9a2bea63492..40b89299c9b 100644 --- a/kie-pmml-trusty/kie-pmml-compiler/kie-pmml-compiler-core/PMMLCompiler.uml +++ b/kie-pmml-trusty/kie-pmml-compiler/kie-pmml-compiler-core/PMMLCompiler.uml @@ -1,4 +1,22 @@ + JAVA org.kie.pmml.compiler.executor.PMMLCompilerExecutorImpl diff --git a/pom.xml b/pom.xml index 5fae74ed325..82960af5a91 100644 --- a/pom.xml +++ b/pom.xml @@ -142,6 +142,8 @@ **/branch.yaml **/main.yaml **/mvel.jj + **/JavaLexer.g4 + **/JavaParser.g4 **/*.csv **/*.sdo **/*.sdt @@ -310,6 +312,29 @@ + + + enableNewParser + + + enableNewParser + + + + + + org.apache.maven.plugins + maven-surefire-plugin + + + + true + + + + + +