Hand written SpEL parser. Removed antlr dependency. tests upgraded to JUnit4 - 93% coverage.

This commit is contained in:
Andy Clement
2009-05-27 04:20:18 +00:00
parent e5b553c16a
commit 886739f1d8
105 changed files with 3629 additions and 8643 deletions

View File

@@ -16,6 +16,8 @@
package org.springframework.expression.spel;
import org.junit.Test;
/**
* Tests the evaluation of real boolean expressions, these use AND, OR, NOT, TRUE, FALSE
*
@@ -23,14 +25,17 @@ package org.springframework.expression.spel;
*/
public class BooleanExpressionTests extends ExpressionTestCase {
@Test
public void testBooleanTrue() {
evaluate("true", Boolean.TRUE, Boolean.class);
}
@Test
public void testBooleanFalse() {
evaluate("false", Boolean.FALSE, Boolean.class);
}
@Test
public void testOr() {
evaluate("false or false", Boolean.FALSE, Boolean.class);
evaluate("false or true", Boolean.TRUE, Boolean.class);
@@ -38,6 +43,7 @@ public class BooleanExpressionTests extends ExpressionTestCase {
evaluate("true or true", Boolean.TRUE, Boolean.class);
}
@Test
public void testAnd() {
evaluate("false and false", Boolean.FALSE, Boolean.class);
evaluate("false and true", Boolean.FALSE, Boolean.class);
@@ -45,23 +51,27 @@ public class BooleanExpressionTests extends ExpressionTestCase {
evaluate("true and true", Boolean.TRUE, Boolean.class);
}
@Test
public void testNot() {
evaluate("!false", Boolean.TRUE, Boolean.class);
evaluate("!true", Boolean.FALSE, Boolean.class);
}
@Test
public void testCombinations01() {
evaluate("false and false or true", Boolean.TRUE, Boolean.class);
evaluate("true and false or true", Boolean.TRUE, Boolean.class);
evaluate("true and false or false", Boolean.FALSE, Boolean.class);
}
@Test
public void testWritability() {
evaluate("true and true", Boolean.TRUE, Boolean.class, false);
evaluate("true or true", Boolean.TRUE, Boolean.class, false);
evaluate("!false", Boolean.TRUE, Boolean.class, false);
}
@Test
public void testBooleanErrors01() {
evaluateAndCheckError("1.0 or false", SpelMessages.TYPE_CONVERSION_ERROR, 0);
evaluateAndCheckError("false or 39.4", SpelMessages.TYPE_CONVERSION_ERROR, 9);

View File

@@ -16,6 +16,8 @@
package org.springframework.expression.spel;
import org.junit.Test;
/**
* Tests invocation of constructors.
*
@@ -23,14 +25,17 @@ package org.springframework.expression.spel;
*/
public class ConstructorInvocationTests extends ExpressionTestCase {
@Test
public void testTypeConstructors() {
evaluate("new String('hello world')", "hello world", String.class);
}
@Test
public void testNonExistentType() {
evaluateAndCheckError("new FooBar()",SpelMessages.PROBLEM_LOCATING_CONSTRUCTOR);
evaluateAndCheckError("new FooBar()",SpelMessages.CONSTRUCTOR_INVOCATION_PROBLEM);
}
@Test
public void testVarargsInvocation01() {
// Calling 'Fruit(String... strings)'
evaluate("new org.springframework.expression.spel.testresources.Fruit('a','b','c').stringscount()", 3, Integer.class);
@@ -41,6 +46,7 @@ public class ConstructorInvocationTests extends ExpressionTestCase {
evaluate("new org.springframework.expression.spel.testresources.Fruit(1,'a',3.0d).stringscount()", 3, Integer.class); // first and last need conversion
}
@Test
public void testVarargsInvocation02() {
// Calling 'Fruit(int i, String... strings)' - returns int+length_of_strings
evaluate("new org.springframework.expression.spel.testresources.Fruit(5,'a','b','c').stringscount()", 8, Integer.class);
@@ -56,6 +62,7 @@ public class ConstructorInvocationTests extends ExpressionTestCase {
* These tests are attempting to call constructors where we need to widen or convert the argument in order to
* satisfy a suitable constructor.
*/
@Test
public void testWidening01() {
// widening of int 3 to double 3 is OK
evaluate("new Double(3)", 3.0d, Double.class);
@@ -63,6 +70,7 @@ public class ConstructorInvocationTests extends ExpressionTestCase {
evaluate("new Long(3)", 3L, Long.class);
}
@Test
public void testArgumentConversion01() {
// Closest ctor will be new String(String) and converter supports Double>String
evaluate("new String(3.0d)", "3.0", String.class);

View File

@@ -15,8 +15,9 @@
*/
package org.springframework.expression.spel;
import junit.framework.TestCase;
import junit.framework.Assert;
import org.junit.Test;
import org.springframework.expression.EvaluationException;
import org.springframework.expression.TypeComparator;
import org.springframework.expression.spel.support.StandardTypeComparator;
@@ -26,59 +27,63 @@ import org.springframework.expression.spel.support.StandardTypeComparator;
*
* @author Andy Clement
*/
public class DefaultComparatorUnitTests extends TestCase {
public class DefaultComparatorUnitTests {
@Test
public void testPrimitives() throws EvaluationException {
TypeComparator comparator = new StandardTypeComparator();
// primitive int
assertTrue(comparator.compare(1, 2) < 0);
assertTrue(comparator.compare(1, 1) == 0);
assertTrue(comparator.compare(2, 1) > 0);
Assert.assertTrue(comparator.compare(1, 2) < 0);
Assert.assertTrue(comparator.compare(1, 1) == 0);
Assert.assertTrue(comparator.compare(2, 1) > 0);
assertTrue(comparator.compare(1.0d, 2) < 0);
assertTrue(comparator.compare(1.0d, 1) == 0);
assertTrue(comparator.compare(2.0d, 1) > 0);
Assert.assertTrue(comparator.compare(1.0d, 2) < 0);
Assert.assertTrue(comparator.compare(1.0d, 1) == 0);
Assert.assertTrue(comparator.compare(2.0d, 1) > 0);
assertTrue(comparator.compare(1.0f, 2) < 0);
assertTrue(comparator.compare(1.0f, 1) == 0);
assertTrue(comparator.compare(2.0f, 1) > 0);
Assert.assertTrue(comparator.compare(1.0f, 2) < 0);
Assert.assertTrue(comparator.compare(1.0f, 1) == 0);
Assert.assertTrue(comparator.compare(2.0f, 1) > 0);
assertTrue(comparator.compare(1L, 2) < 0);
assertTrue(comparator.compare(1L, 1) == 0);
assertTrue(comparator.compare(2L, 1) > 0);
Assert.assertTrue(comparator.compare(1L, 2) < 0);
Assert.assertTrue(comparator.compare(1L, 1) == 0);
Assert.assertTrue(comparator.compare(2L, 1) > 0);
assertTrue(comparator.compare(1, 2L) < 0);
assertTrue(comparator.compare(1, 1L) == 0);
assertTrue(comparator.compare(2, 1L) > 0);
Assert.assertTrue(comparator.compare(1, 2L) < 0);
Assert.assertTrue(comparator.compare(1, 1L) == 0);
Assert.assertTrue(comparator.compare(2, 1L) > 0);
assertTrue(comparator.compare(1L, 2L) < 0);
assertTrue(comparator.compare(1L, 1L) == 0);
assertTrue(comparator.compare(2L, 1L) > 0);
Assert.assertTrue(comparator.compare(1L, 2L) < 0);
Assert.assertTrue(comparator.compare(1L, 1L) == 0);
Assert.assertTrue(comparator.compare(2L, 1L) > 0);
}
@Test
public void testNulls() throws EvaluationException {
TypeComparator comparator = new StandardTypeComparator();
assertTrue(comparator.compare(null,"abc")>0);
assertTrue(comparator.compare(null,null)==0);
assertTrue(comparator.compare("abc",null)<0);
Assert.assertTrue(comparator.compare(null,"abc")>0);
Assert.assertTrue(comparator.compare(null,null)==0);
Assert.assertTrue(comparator.compare("abc",null)<0);
}
@Test
public void testObjects() throws EvaluationException {
TypeComparator comparator = new StandardTypeComparator();
assertTrue(comparator.compare("a","a")==0);
assertTrue(comparator.compare("a","b")<0);
assertTrue(comparator.compare("b","a")>0);
Assert.assertTrue(comparator.compare("a","a")==0);
Assert.assertTrue(comparator.compare("a","b")<0);
Assert.assertTrue(comparator.compare("b","a")>0);
}
@Test
public void testCanCompare() throws EvaluationException {
TypeComparator comparator = new StandardTypeComparator();
assertTrue(comparator.canCompare(null,1));
assertTrue(comparator.canCompare(1,null));
Assert.assertTrue(comparator.canCompare(null,1));
Assert.assertTrue(comparator.canCompare(1,null));
assertTrue(comparator.canCompare(2,1));
assertTrue(comparator.canCompare("abc","def"));
assertTrue(comparator.canCompare("abc",3));
assertFalse(comparator.canCompare(String.class,3));
Assert.assertTrue(comparator.canCompare(2,1));
Assert.assertTrue(comparator.canCompare("abc","def"));
Assert.assertTrue(comparator.canCompare("abc",3));
Assert.assertFalse(comparator.canCompare(String.class,3));
}
}

View File

@@ -16,9 +16,14 @@
package org.springframework.expression.spel;
import junit.framework.Assert;
import org.junit.Test;
import org.springframework.expression.EvaluationContext;
import org.springframework.expression.EvaluationException;
import org.springframework.expression.Expression;
import org.springframework.expression.ParseException;
import org.springframework.expression.spel.standard.SpelExpressionParser;
import org.springframework.expression.spel.support.StandardEvaluationContext;
import org.springframework.expression.spel.support.StandardTypeLocator;
@@ -29,68 +34,95 @@ import org.springframework.expression.spel.support.StandardTypeLocator;
*/
public class EvaluationTests extends ExpressionTestCase {
@Test
public void testElvis01() {
evaluate("'Andy'?:'Dave'","Andy",String.class);
evaluate("null?:'Dave'","Dave",String.class);
}
@Test
public void testSafeNavigation() {
evaluate("null?.null?.null",null,null);
}
@Test
public void testRelOperatorGT01() {
evaluate("3 > 6", "false", Boolean.class);
}
@Test
public void testRelOperatorLT01() {
evaluate("3 < 6", "true", Boolean.class);
}
@Test
public void testRelOperatorLE01() {
evaluate("3 <= 6", "true", Boolean.class);
}
@Test
public void testRelOperatorGE01() {
evaluate("3 >= 6", "false", Boolean.class);
}
@Test
public void testRelOperatorGE02() {
evaluate("3 >= 3", "true", Boolean.class);
}
public void testRelOperatorsIs01() {
@Test
public void testRelOperatorsInstanceof01() {
evaluate("'xyz' instanceof T(int)", "false", Boolean.class);
}
public void testRelOperatorsIs04() {
@Test
public void testRelOperatorsInstanceof04() {
evaluate("null instanceof T(String)", "false", Boolean.class);
}
public void testRelOperatorsIs05() {
@Test
public void testRelOperatorsInstanceof05() {
evaluate("null instanceof T(Integer)", "false", Boolean.class);
}
public void testRelOperatorsIs06() {
@Test
public void testRelOperatorsInstanceof06() {
evaluateAndCheckError("'A' instanceof null", SpelMessages.INSTANCEOF_OPERATOR_NEEDS_CLASS_OPERAND, 15, "null");
}
@Test
public void testRelOperatorsMatches01() {
evaluate("'5.0067' matches '^-?\\d+(\\.\\d{2})?$'", "false", Boolean.class);
}
@Test
public void testRelOperatorsMatches02() {
evaluate("'5.00' matches '^-?\\d+(\\.\\d{2})?$'", "true", Boolean.class);
}
@Test
public void testRelOperatorsMatches03() {
evaluateAndCheckError("null matches '^.*$'", SpelMessages.INVALID_FIRST_OPERAND_FOR_MATCHES_OPERATOR, 0, null);
}
@Test
public void testRelOperatorsMatches04() {
evaluateAndCheckError("'abc' matches null", SpelMessages.INVALID_SECOND_OPERAND_FOR_MATCHES_OPERATOR, 14, null);
}
@Test
public void testRelOperatorsMatches05() {
evaluate("27 matches '^.*2.*$'", true, Boolean.class); // conversion int>string
}
// mixing operators
@Test
public void testMixingOperators01() {
evaluate("true and 5>3", "true", Boolean.class);
}
// property access
@Test
public void testPropertyField01() {
evaluate("name", "Nikola Tesla", String.class, false);
// not writable because (1) name is private (2) there is no setter, only a getter
@@ -99,121 +131,157 @@ public class EvaluationTests extends ExpressionTestCase {
}
// nested properties
@Test
public void testPropertiesNested01() {
evaluate("placeOfBirth.city", "SmilJan", String.class, true);
}
@Test
public void testPropertiesNested02() {
evaluate("placeOfBirth.doubleIt(12)", "24", Integer.class);
}
@Test
public void testPropertiesNested03() throws ParseException {
try {
new SpelExpressionParser().parse("placeOfBirth.23");
Assert.fail();
} catch (SpelParseException spe) {
Assert.assertEquals(spe.getMessageUnformatted(), SpelMessages.UNEXPECTED_DATA_AFTER_DOT);
Assert.assertEquals("23", spe.getInserts()[0]);
}
}
// methods
@Test
public void testMethods01() {
evaluate("echo(12)", "12", String.class);
}
@Test
public void testMethods02() {
evaluate("echo(name)", "Nikola Tesla", String.class);
}
// constructors
@Test
public void testConstructorInvocation01() {
evaluate("new String('hello')", "hello", String.class);
}
@Test
public void testConstructorInvocation05() {
evaluate("new java.lang.String('foobar')", "foobar", String.class);
}
@Test
public void testConstructorInvocation06() throws Exception {
// repeated evaluation to drive use of cached executor
SpelExpression expr = (SpelExpression)parser.parseExpression("new String('wibble')");
String newString = expr.getValue(String.class);
assertEquals("wibble",newString);
Assert.assertEquals("wibble",newString);
newString = expr.getValue(String.class);
assertEquals("wibble",newString);
Assert.assertEquals("wibble",newString);
// not writable
assertFalse(expr.isWritable(new StandardEvaluationContext()));
Assert.assertFalse(expr.isWritable(new StandardEvaluationContext()));
// ast
assertEquals("new String('wibble')",expr.toStringAST());
Assert.assertEquals("new String('wibble')",expr.toStringAST());
}
// unary expressions
@Test
public void testUnaryMinus01() {
evaluate("-5", "-5", Integer.class);
}
@Test
public void testUnaryPlus01() {
evaluate("+5", "5", Integer.class);
}
@Test
public void testUnaryNot01() {
evaluate("!true", "false", Boolean.class);
}
// assignment
@Test
public void testAssignmentToVariables01() {
evaluate("#var1='value1'", "value1", String.class);
}
@Test
public void testTernaryOperator01() {
evaluate("2>4?1:2",2,Integer.class);
}
@Test
public void testTernaryOperator02() {
evaluate("'abc'=='abc'?1:2",1,Integer.class);
}
@Test
public void testTernaryOperator03() {
evaluateAndCheckError("'hello'?1:2", SpelMessages.TYPE_CONVERSION_ERROR); // cannot convert String to boolean
}
@Test
public void testTernaryOperator04() throws Exception {
Expression expr = parser.parseExpression("1>2?3:4");
assertFalse(expr.isWritable(eContext));
Assert.assertFalse(expr.isWritable(eContext));
}
@Test
public void testIndexer03() {
evaluate("'christian'[8]", "n", String.class);
}
@Test
public void testIndexerError() {
evaluateAndCheckError("new org.springframework.expression.spel.testresources.Inventor().inventions[1]",SpelMessages.CANNOT_INDEX_INTO_NULL_VALUE);
}
@Test
public void testStaticRef02() {
evaluate("T(java.awt.Color).green.getRGB()!=0", "true", Boolean.class);
}
// variables and functions
@Test
public void testVariableAccess01() {
evaluate("#answer", "42", Integer.class, true);
}
@Test
public void testFunctionAccess01() {
evaluate("#reverseInt(1,2,3)", "int[3]{3,2,1}", int[].class);
}
@Test
public void testFunctionAccess02() {
evaluate("#reverseString('hello')", "olleh", String.class);
}
// type references
@Test
public void testTypeReferences01() {
evaluate("T(java.lang.String)", "class java.lang.String", Class.class);
}
@Test
public void testTypeReferencesAndQualifiedIdentifierCaching() throws Exception {
SpelExpression expr = (SpelExpression)parser.parseExpression("T(java.lang.String)");
assertFalse(expr.isWritable(new StandardEvaluationContext()));
assertEquals("T(java.lang.String)",expr.toStringAST());
assertEquals(String.class,expr.getValue(Class.class));
Assert.assertFalse(expr.isWritable(new StandardEvaluationContext()));
Assert.assertEquals("T(java.lang.String)",expr.toStringAST());
Assert.assertEquals(String.class,expr.getValue(Class.class));
// use cached QualifiedIdentifier:
assertEquals("T(java.lang.String)",expr.toStringAST());
assertEquals(String.class,expr.getValue(Class.class));
Assert.assertEquals("T(java.lang.String)",expr.toStringAST());
Assert.assertEquals(String.class,expr.getValue(Class.class));
}
@Test
public void testTypeReferencesPrimitive() {
evaluate("T(int)", "int", Class.class);
evaluate("T(byte)", "byte", Class.class);
@@ -225,14 +293,17 @@ public class EvaluationTests extends ExpressionTestCase {
evaluate("T(float)", "float", Class.class);
}
@Test
public void testTypeReferences02() {
evaluate("T(String)", "class java.lang.String", Class.class);
}
@Test
public void testStringType() {
evaluateAndAskForReturnType("getPlaceOfBirth().getCity()", "SmilJan", String.class);
}
@Test
public void testNumbers01() {
evaluateAndAskForReturnType("3*4+5", 17, Integer.class);
evaluateAndAskForReturnType("3*4+5", 17L, Long.class);
@@ -242,39 +313,43 @@ public class EvaluationTests extends ExpressionTestCase {
}
@Test
public void testAdvancedNumerics() throws Exception {
int twentyFour = parser.parseExpression("2.0 * 3e0 * 4").getValue(Integer.class);
assertEquals(24,twentyFour);
Assert.assertEquals(24,twentyFour);
double one = parser.parseExpression("8.0 / 5e0 % 2").getValue(Double.class);
assertEquals(1.6d,one);
Assert.assertEquals(1.6d,one);
int o = parser.parseExpression("8.0 / 5e0 % 2").getValue(Integer.class);
assertEquals(1,o);
Assert.assertEquals(1,o);
int sixteen = parser.parseExpression("-2 ^ 4").getValue(Integer.class);
assertEquals(16,sixteen);
Assert.assertEquals(16,sixteen);
int minusFortyFive = parser.parseExpression("1+2-3*8^2/2/2").getValue(Integer.class);
assertEquals(-45,minusFortyFive);
Assert.assertEquals(-45,minusFortyFive);
}
@Test
public void testComparison() throws Exception {
EvaluationContext context = TestScenarioCreator.getTestEvaluationContext();
boolean trueValue = parser.parseExpression("T(java.util.Date) == Birthdate.Class").getValue(context, Boolean.class);
assertTrue(trueValue);
Assert.assertTrue(trueValue);
}
@Test
public void testResolvingList() throws Exception {
StandardEvaluationContext context = TestScenarioCreator.getTestEvaluationContext();
try {
assertFalse(parser.parseExpression("T(List)!=null").getValue(context, Boolean.class));
fail("should have failed to find List");
Assert.assertFalse(parser.parseExpression("T(List)!=null").getValue(context, Boolean.class));
Assert.fail("should have failed to find List");
} catch (EvaluationException ee) {
// success - List not found
}
((StandardTypeLocator)context.getTypeLocator()).registerImport("java.util");
assertTrue(parser.parseExpression("T(List)!=null").getValue(context, Boolean.class));
Assert.assertTrue(parser.parseExpression("T(List)!=null").getValue(context, Boolean.class));
}
@Test
public void testResolvingString() throws Exception {
Class stringClass = parser.parseExpression("T(String)").getValue(Class.class);
assertEquals(String.class,stringClass);
Assert.assertEquals(String.class,stringClass);
}
}

View File

@@ -23,6 +23,9 @@ import java.util.HashMap;
import java.util.List;
import java.util.Map;
import junit.framework.Assert;
import org.junit.Test;
import org.springframework.core.convert.TypeDescriptor;
import org.springframework.expression.AccessException;
import org.springframework.expression.EvaluationContext;
@@ -31,9 +34,11 @@ import org.springframework.expression.Expression;
import org.springframework.expression.ParseException;
import org.springframework.expression.PropertyAccessor;
import org.springframework.expression.TypedValue;
import org.springframework.expression.spel.antlr.SpelAntlrExpressionParser;
import org.springframework.expression.spel.standard.SpelExpressionParser;
import org.springframework.expression.spel.support.StandardEvaluationContext;
///CLOVER:OFF
/**
* Testcases showing the common scenarios/use-cases for picking up the expression language support.
* The first test shows very basic usage, just drop it in and go. By 'standard infrastructure', it means:<br>
@@ -60,10 +65,11 @@ public class ExpressionLanguageScenarioTests extends ExpressionTestCase {
/**
* Scenario: using the standard infrastructure and running simple expression evaluation.
*/
@Test
public void testScenario_UsingStandardInfrastructure() {
try {
// Create a parser
SpelAntlrExpressionParser parser = new SpelAntlrExpressionParser();
SpelExpressionParser parser = new SpelExpressionParser();
// Parse an expression
Expression expr = parser.parseExpression("new String('hello world')");
// Evaluate it using a 'standard' context
@@ -71,23 +77,24 @@ public class ExpressionLanguageScenarioTests extends ExpressionTestCase {
// They are reusable
value = expr.getValue();
assertEquals("hello world", value);
assertEquals(String.class, value.getClass());
Assert.assertEquals("hello world", value);
Assert.assertEquals(String.class, value.getClass());
} catch (EvaluationException ee) {
ee.printStackTrace();
fail("Unexpected Exception: " + ee.getMessage());
Assert.fail("Unexpected Exception: " + ee.getMessage());
} catch (ParseException pe) {
pe.printStackTrace();
fail("Unexpected Exception: " + pe.getMessage());
Assert.fail("Unexpected Exception: " + pe.getMessage());
}
}
/**
* Scenario: using the standard context but adding your own variables
*/
@Test
public void testScenario_DefiningVariablesThatWillBeAccessibleInExpressions() throws Exception {
// Create a parser
SpelAntlrExpressionParser parser = new SpelAntlrExpressionParser();
SpelExpressionParser parser = new SpelExpressionParser();
// Use the standard evaluation context
StandardEvaluationContext ctx = new StandardEvaluationContext();
ctx.setVariable("favouriteColour","blue");
@@ -97,16 +104,16 @@ public class ExpressionLanguageScenarioTests extends ExpressionTestCase {
Expression expr = parser.parseExpression("#favouriteColour");
Object value = expr.getValue(ctx);
assertEquals("blue", value);
Assert.assertEquals("blue", value);
expr = parser.parseExpression("#primes.get(1)");
value = expr.getValue(ctx);
assertEquals(3, value);
Assert.assertEquals(3, value);
// all prime numbers > 10 from the list (using selection ?{...})
expr = parser.parseExpression("#primes.?[#this>10]");
value = expr.getValue(ctx);
assertEquals("[11, 13, 17]", value.toString());
Assert.assertEquals("[11, 13, 17]", value.toString());
}
@@ -120,9 +127,10 @@ public class ExpressionLanguageScenarioTests extends ExpressionTestCase {
/**
* Scenario: using your own root context object
*/
@Test
public void testScenario_UsingADifferentRootContextObject() throws Exception {
// Create a parser
SpelAntlrExpressionParser parser = new SpelAntlrExpressionParser();
SpelExpressionParser parser = new SpelExpressionParser();
// Use the standard evaluation context
StandardEvaluationContext ctx = new StandardEvaluationContext();
@@ -134,30 +142,30 @@ public class ExpressionLanguageScenarioTests extends ExpressionTestCase {
// read it, set it, read it again
Expression expr = parser.parseExpression("str");
Object value = expr.getValue(ctx);
assertEquals("wibble", value);
Assert.assertEquals("wibble", value);
expr = parser.parseExpression("str");
expr.setValue(ctx, "wobble");
expr = parser.parseExpression("str");
value = expr.getValue(ctx);
assertEquals("wobble", value);
Assert.assertEquals("wobble", value);
// or using assignment within the expression
expr = parser.parseExpression("str='wabble'");
value = expr.getValue(ctx);
expr = parser.parseExpression("str");
value = expr.getValue(ctx);
assertEquals("wabble", value);
Assert.assertEquals("wabble", value);
// private property will be accessed through getter()
expr = parser.parseExpression("property");
value = expr.getValue(ctx);
assertEquals(42, value);
Assert.assertEquals(42, value);
// ... and set through setter
expr = parser.parseExpression("property=4");
value = expr.getValue(ctx);
expr = parser.parseExpression("property");
value = expr.getValue(ctx);
assertEquals(4,value);
Assert.assertEquals(4,value);
}
public static String repeat(String s) { return s+s; }
@@ -165,66 +173,69 @@ public class ExpressionLanguageScenarioTests extends ExpressionTestCase {
/**
* Scenario: using your own java methods and calling them from the expression
*/
@Test
public void testScenario_RegisteringJavaMethodsAsFunctionsAndCallingThem() throws SecurityException, NoSuchMethodException {
try {
// Create a parser
SpelAntlrExpressionParser parser = new SpelAntlrExpressionParser();
SpelExpressionParser parser = new SpelExpressionParser();
// Use the standard evaluation context
StandardEvaluationContext ctx = new StandardEvaluationContext();
ctx.registerFunction("repeat",ExpressionLanguageScenarioTests.class.getDeclaredMethod("repeat",String.class));
Expression expr = parser.parseExpression("#repeat('hello')");
Object value = expr.getValue(ctx);
assertEquals("hellohello", value);
Assert.assertEquals("hellohello", value);
} catch (EvaluationException ee) {
ee.printStackTrace();
fail("Unexpected Exception: " + ee.getMessage());
Assert.fail("Unexpected Exception: " + ee.getMessage());
} catch (ParseException pe) {
pe.printStackTrace();
fail("Unexpected Exception: " + pe.getMessage());
Assert.fail("Unexpected Exception: " + pe.getMessage());
}
}
/**
* Scenario: add a property resolver that will get called in the resolver chain, this one only supports reading.
*/
@Test
public void testScenario_AddingYourOwnPropertyResolvers_1() throws Exception {
// Create a parser
SpelAntlrExpressionParser parser = new SpelAntlrExpressionParser();
SpelExpressionParser parser = new SpelExpressionParser();
// Use the standard evaluation context
StandardEvaluationContext ctx = new StandardEvaluationContext();
ctx.addPropertyAccessor(new FruitColourAccessor());
Expression expr = parser.parseExpression("orange");
Object value = expr.getValue(ctx);
assertEquals(Color.orange, value);
Assert.assertEquals(Color.orange, value);
try {
expr.setValue(ctx, Color.blue);
fail("Should not be allowed to set oranges to be blue !");
} catch (SpelException ee) {
assertEquals(ee.getMessageUnformatted(), SpelMessages.PROPERTY_OR_FIELD_NOT_WRITABLE_ON_NULL);
Assert.fail("Should not be allowed to set oranges to be blue !");
} catch (SpelEvaluationException ee) {
Assert.assertEquals(ee.getMessageUnformatted(), SpelMessages.PROPERTY_OR_FIELD_NOT_WRITABLE_ON_NULL);
}
}
@Test
public void testScenario_AddingYourOwnPropertyResolvers_2() throws Exception {
// Create a parser
SpelAntlrExpressionParser parser = new SpelAntlrExpressionParser();
SpelExpressionParser parser = new SpelExpressionParser();
// Use the standard evaluation context
StandardEvaluationContext ctx = new StandardEvaluationContext();
ctx.addPropertyAccessor(new VegetableColourAccessor());
Expression expr = parser.parseExpression("pea");
Object value = expr.getValue(ctx);
assertEquals(Color.green, value);
Assert.assertEquals(Color.green, value);
try {
expr.setValue(ctx, Color.blue);
fail("Should not be allowed to set peas to be blue !");
Assert.fail("Should not be allowed to set peas to be blue !");
}
catch (SpelException ee) {
assertEquals(ee.getMessageUnformatted(), SpelMessages.PROPERTY_OR_FIELD_NOT_WRITABLE_ON_NULL);
catch (SpelEvaluationException ee) {
Assert.assertEquals(ee.getMessageUnformatted(), SpelMessages.PROPERTY_OR_FIELD_NOT_WRITABLE_ON_NULL);
}
}

View File

@@ -18,6 +18,9 @@ package org.springframework.expression.spel;
import java.util.HashMap;
import java.util.Map;
import junit.framework.Assert;
import org.junit.Test;
import org.springframework.core.convert.TypeDescriptor;
import org.springframework.expression.EvaluationContext;
import org.springframework.expression.EvaluationException;
@@ -34,204 +37,218 @@ import org.springframework.expression.spel.testresources.Inventor;
*/
public class ExpressionStateTests extends ExpressionTestCase {
@Test
public void testConstruction() {
EvaluationContext context = TestScenarioCreator.getTestEvaluationContext();
ExpressionState state = new ExpressionState(context);
assertEquals(context,state.getEvaluationContext());
Assert.assertEquals(context,state.getEvaluationContext());
}
// Local variables are in variable scopes which come and go during evaluation. Normal variables are
// accessible through the evaluation context
@Test
public void testLocalVariables() {
ExpressionState state = getState();
Object value = state.lookupLocalVariable("foo");
assertNull(value);
Assert.assertNull(value);
state.setLocalVariable("foo",34);
value = state.lookupLocalVariable("foo");
assertEquals(34,value);
Assert.assertEquals(34,value);
state.setLocalVariable("foo",null);
value = state.lookupLocalVariable("foo");
assertEquals(null,value);
Assert.assertEquals(null,value);
}
@Test
public void testVariables() {
ExpressionState state = getState();
TypedValue typedValue = state.lookupVariable("foo");
assertEquals(TypedValue.NULL_TYPED_VALUE,typedValue);
Assert.assertEquals(TypedValue.NULL_TYPED_VALUE,typedValue);
state.setVariable("foo",34);
typedValue = state.lookupVariable("foo");
assertEquals(34,typedValue.getValue());
assertEquals(Integer.class,typedValue.getTypeDescriptor().getType());
Assert.assertEquals(34,typedValue.getValue());
Assert.assertEquals(Integer.class,typedValue.getTypeDescriptor().getType());
state.setVariable("foo","abc");
typedValue = state.lookupVariable("foo");
assertEquals("abc",typedValue.getValue());
assertEquals(String.class,typedValue.getTypeDescriptor().getType());
Assert.assertEquals("abc",typedValue.getValue());
Assert.assertEquals(String.class,typedValue.getTypeDescriptor().getType());
}
@Test
public void testNoVariableInteference() {
ExpressionState state = getState();
TypedValue typedValue = state.lookupVariable("foo");
assertEquals(TypedValue.NULL_TYPED_VALUE,typedValue);
Assert.assertEquals(TypedValue.NULL_TYPED_VALUE,typedValue);
state.setLocalVariable("foo",34);
typedValue = state.lookupVariable("foo");
assertEquals(TypedValue.NULL_TYPED_VALUE,typedValue);
Assert.assertEquals(TypedValue.NULL_TYPED_VALUE,typedValue);
state.setVariable("goo","hello");
assertNull(state.lookupLocalVariable("goo"));
Assert.assertNull(state.lookupLocalVariable("goo"));
}
@Test
public void testLocalVariableNestedScopes() {
ExpressionState state = getState();
assertEquals(null,state.lookupLocalVariable("foo"));
Assert.assertEquals(null,state.lookupLocalVariable("foo"));
state.setLocalVariable("foo",12);
assertEquals(12,state.lookupLocalVariable("foo"));
Assert.assertEquals(12,state.lookupLocalVariable("foo"));
state.enterScope(null);
assertEquals(12,state.lookupLocalVariable("foo")); // found in upper scope
Assert.assertEquals(12,state.lookupLocalVariable("foo")); // found in upper scope
state.setLocalVariable("foo","abc");
assertEquals("abc",state.lookupLocalVariable("foo")); // found in nested scope
Assert.assertEquals("abc",state.lookupLocalVariable("foo")); // found in nested scope
state.exitScope();
assertEquals(12,state.lookupLocalVariable("foo")); // found in nested scope
Assert.assertEquals(12,state.lookupLocalVariable("foo")); // found in nested scope
}
@Test
public void testRootContextObject() {
ExpressionState state = getState();
assertEquals(Inventor.class,state.getRootContextObject().getValue().getClass());
Assert.assertEquals(Inventor.class,state.getRootContextObject().getValue().getClass());
state.getEvaluationContext().setRootObject(null);
assertEquals(null,state.getRootContextObject().getValue());
Assert.assertEquals(null,state.getRootContextObject().getValue());
state = new ExpressionState(new StandardEvaluationContext());
assertEquals(TypedValue.NULL_TYPED_VALUE,state.getRootContextObject());
Assert.assertEquals(TypedValue.NULL_TYPED_VALUE,state.getRootContextObject());
((StandardEvaluationContext)state.getEvaluationContext()).setRootObject(null,TypeDescriptor.NULL);
assertEquals(null,state.getRootContextObject().getValue());
Assert.assertEquals(null,state.getRootContextObject().getValue());
}
@Test
public void testActiveContextObject() {
ExpressionState state = getState();
assertEquals(state.getRootContextObject().getValue(),state.getActiveContextObject().getValue());
Assert.assertEquals(state.getRootContextObject().getValue(),state.getActiveContextObject().getValue());
state.pushActiveContextObject(new TypedValue(34));
assertEquals(34,state.getActiveContextObject().getValue());
Assert.assertEquals(34,state.getActiveContextObject().getValue());
state.pushActiveContextObject(new TypedValue("hello"));
assertEquals("hello",state.getActiveContextObject().getValue());
Assert.assertEquals("hello",state.getActiveContextObject().getValue());
state.popActiveContextObject();
assertEquals(34,state.getActiveContextObject().getValue());
Assert.assertEquals(34,state.getActiveContextObject().getValue());
state.popActiveContextObject();
assertEquals(state.getRootContextObject().getValue(),state.getActiveContextObject().getValue());
Assert.assertEquals(state.getRootContextObject().getValue(),state.getActiveContextObject().getValue());
state = new ExpressionState(new StandardEvaluationContext());
assertEquals(TypedValue.NULL_TYPED_VALUE,state.getActiveContextObject());
Assert.assertEquals(TypedValue.NULL_TYPED_VALUE,state.getActiveContextObject());
}
@Test
public void testPopulatedNestedScopes() {
ExpressionState state = getState();
assertNull(state.lookupLocalVariable("foo"));
Assert.assertNull(state.lookupLocalVariable("foo"));
state.enterScope("foo",34);
assertEquals(34,state.lookupLocalVariable("foo"));
Assert.assertEquals(34,state.lookupLocalVariable("foo"));
state.enterScope(null);
state.setLocalVariable("foo",12);
assertEquals(12,state.lookupLocalVariable("foo"));
Assert.assertEquals(12,state.lookupLocalVariable("foo"));
state.exitScope();
assertEquals(34,state.lookupLocalVariable("foo"));
Assert.assertEquals(34,state.lookupLocalVariable("foo"));
state.exitScope();
assertNull(state.lookupLocalVariable("goo"));
Assert.assertNull(state.lookupLocalVariable("goo"));
}
@Test
public void testPopulatedNestedScopesMap() {
ExpressionState state = getState();
assertNull(state.lookupLocalVariable("foo"));
assertNull(state.lookupLocalVariable("goo"));
Assert.assertNull(state.lookupLocalVariable("foo"));
Assert.assertNull(state.lookupLocalVariable("goo"));
Map<String,Object> m = new HashMap<String,Object>();
m.put("foo",34);
m.put("goo","abc");
state.enterScope(m);
assertEquals(34,state.lookupLocalVariable("foo"));
assertEquals("abc",state.lookupLocalVariable("goo"));
Assert.assertEquals(34,state.lookupLocalVariable("foo"));
Assert.assertEquals("abc",state.lookupLocalVariable("goo"));
state.enterScope(null);
state.setLocalVariable("foo",12);
assertEquals(12,state.lookupLocalVariable("foo"));
assertEquals("abc",state.lookupLocalVariable("goo"));
Assert.assertEquals(12,state.lookupLocalVariable("foo"));
Assert.assertEquals("abc",state.lookupLocalVariable("goo"));
state.exitScope();
state.exitScope();
assertNull(state.lookupLocalVariable("foo"));
assertNull(state.lookupLocalVariable("goo"));
Assert.assertNull(state.lookupLocalVariable("foo"));
Assert.assertNull(state.lookupLocalVariable("goo"));
}
@Test
public void testOperators() throws Exception {
ExpressionState state = getState();
try {
state.operate(Operation.ADD,1,2);
fail("should have failed");
Assert.fail("should have failed");
} catch (EvaluationException ee) {
SpelException sEx = (SpelException)ee;
assertEquals(SpelMessages.OPERATOR_NOT_SUPPORTED_BETWEEN_TYPES,sEx.getMessageUnformatted());
SpelEvaluationException sEx = (SpelEvaluationException)ee;
Assert.assertEquals(SpelMessages.OPERATOR_NOT_SUPPORTED_BETWEEN_TYPES,sEx.getMessageUnformatted());
}
try {
state.operate(Operation.ADD,null,null);
fail("should have failed");
Assert.fail("should have failed");
} catch (EvaluationException ee) {
SpelException sEx = (SpelException)ee;
assertEquals(SpelMessages.OPERATOR_NOT_SUPPORTED_BETWEEN_TYPES,sEx.getMessageUnformatted());
SpelEvaluationException sEx = (SpelEvaluationException)ee;
Assert.assertEquals(SpelMessages.OPERATOR_NOT_SUPPORTED_BETWEEN_TYPES,sEx.getMessageUnformatted());
}
}
@Test
public void testComparator() {
ExpressionState state = getState();
assertEquals(state.getEvaluationContext().getTypeComparator(),state.getTypeComparator());
Assert.assertEquals(state.getEvaluationContext().getTypeComparator(),state.getTypeComparator());
}
@Test
public void testTypeLocator() throws EvaluationException {
ExpressionState state = getState();
assertNotNull(state.getEvaluationContext().getTypeLocator());
assertEquals(Integer.class,state.findType("java.lang.Integer"));
Assert.assertNotNull(state.getEvaluationContext().getTypeLocator());
Assert.assertEquals(Integer.class,state.findType("java.lang.Integer"));
try {
state.findType("someMadeUpName");
fail("Should have failed to find it");
Assert.fail("Should have failed to find it");
} catch (EvaluationException ee) {
SpelException sEx = (SpelException)ee;
assertEquals(SpelMessages.TYPE_NOT_FOUND,sEx.getMessageUnformatted());
SpelEvaluationException sEx = (SpelEvaluationException)ee;
Assert.assertEquals(SpelMessages.TYPE_NOT_FOUND,sEx.getMessageUnformatted());
}
}
@Test
public void testTypeConversion() throws EvaluationException {
ExpressionState state = getState();
String s = (String)state.convertValue(34,TypeDescriptor.valueOf(String.class));
assertEquals("34",s);
Assert.assertEquals("34",s);
s = (String)state.convertValue(new TypedValue(34),TypeDescriptor.valueOf(String.class));
assertEquals("34",s);
Assert.assertEquals("34",s);
}
@Test
public void testPropertyAccessors() {
ExpressionState state = getState();
assertEquals(state.getEvaluationContext().getPropertyAccessors(),state.getPropertyAccessors());
Assert.assertEquals(state.getEvaluationContext().getPropertyAccessors(),state.getPropertyAccessors());
}
/**

View File

@@ -19,28 +19,27 @@ package org.springframework.expression.spel;
import java.util.Arrays;
import java.util.List;
import junit.framework.TestCase;
import junit.framework.Assert;
import org.springframework.expression.EvaluationException;
import org.springframework.expression.Expression;
import org.springframework.expression.ExpressionParser;
import org.springframework.expression.ParseException;
import org.springframework.expression.spel.antlr.SpelAntlrExpressionParser;
import org.springframework.expression.spel.support.StandardEvaluationContext;
///CLOVER:OFF
/**
* Common superclass for expression tests.
*
* @author Andy Clement
*/
public abstract class ExpressionTestCase extends TestCase {
public abstract class ExpressionTestCase {
private final static boolean DEBUG = false;
protected final static boolean SHOULD_BE_WRITABLE = true;
protected final static boolean SHOULD_NOT_BE_WRITABLE = false;
protected final static SpelAntlrExpressionParser parser = new SpelAntlrExpressionParser();
protected final static ExpressionParser parser = SpelExpressionParserFactory.getParser();
protected final static StandardEvaluationContext eContext = TestScenarioCreator.getTestEvaluationContext();
/**
@@ -54,13 +53,13 @@ public abstract class ExpressionTestCase extends TestCase {
try {
Expression expr = parser.parseExpression(expression);
if (expr == null) {
fail("Parser returned null for expression");
Assert.fail("Parser returned null for expression");
}
if (DEBUG) {
SpelUtilities.printAbstractSyntaxTree(System.out, expr);
}
// Class<?> expressionType = expr.getValueType();
// assertEquals("Type of the expression is not as expected. Should be '"+expectedResultType+"' but is
// Assert.assertEquals("Type of the expression is not as expected. Should be '"+expectedResultType+"' but is
// '"+expressionType+"'",
// expectedResultType,expressionType);
@@ -71,12 +70,12 @@ public abstract class ExpressionTestCase extends TestCase {
if (expectedValue == null) {
return; // no point doing other checks
}
assertEquals("Expression returned null value, but expected '" + expectedValue + "'", expectedValue,
Assert.assertEquals("Expression returned null value, but expected '" + expectedValue + "'", expectedValue,
null);
}
Class<?> resultType = value.getClass();
assertEquals("Type of the actual result was not as expected. Expected '" + expectedResultType
Assert.assertEquals("Type of the actual result was not as expected. Expected '" + expectedResultType
+ "' but result was of type '" + resultType + "'", expectedResultType, resultType);
// .equals/* isAssignableFrom */(resultType), truers);
@@ -84,17 +83,17 @@ public abstract class ExpressionTestCase extends TestCase {
// in the above expression...
if (expectedValue instanceof String) {
assertEquals("Did not get expected value for expression '" + expression + "'.", expectedValue,
Assert.assertEquals("Did not get expected value for expression '" + expression + "'.", expectedValue,
ExpressionTestCase.stringValueOf(value));
} else {
assertEquals("Did not get expected value for expression '" + expression + "'.", expectedValue, value);
Assert.assertEquals("Did not get expected value for expression '" + expression + "'.", expectedValue, value);
}
} catch (EvaluationException ee) {
ee.printStackTrace();
fail("Unexpected Exception: " + ee.getMessage());
Assert.fail("Unexpected Exception: " + ee.getMessage());
} catch (ParseException pe) {
pe.printStackTrace();
fail("Unexpected Exception: " + pe.getMessage());
Assert.fail("Unexpected Exception: " + pe.getMessage());
}
}
@@ -102,13 +101,13 @@ public abstract class ExpressionTestCase extends TestCase {
try {
Expression expr = parser.parseExpression(expression);
if (expr == null) {
fail("Parser returned null for expression");
Assert.fail("Parser returned null for expression");
}
if (DEBUG) {
SpelUtilities.printAbstractSyntaxTree(System.out, expr);
}
// Class<?> expressionType = expr.getValueType();
// assertEquals("Type of the expression is not as expected. Should be '"+expectedResultType+"' but is
// Assert.assertEquals("Type of the expression is not as expected. Should be '"+expectedResultType+"' but is
// '"+expressionType+"'",
// expectedResultType,expressionType);
@@ -116,23 +115,23 @@ public abstract class ExpressionTestCase extends TestCase {
if (value == null) {
if (expectedValue == null)
return; // no point doing other checks
assertEquals("Expression returned null value, but expected '" + expectedValue + "'", expectedValue,
Assert.assertEquals("Expression returned null value, but expected '" + expectedValue + "'", expectedValue,
null);
}
Class<?> resultType = value.getClass();
assertEquals("Type of the actual result was not as expected. Expected '" + expectedResultType
Assert.assertEquals("Type of the actual result was not as expected. Expected '" + expectedResultType
+ "' but result was of type '" + resultType + "'", expectedResultType, resultType);
// .equals/* isAssignableFrom */(resultType), truers);
assertEquals("Did not get expected value for expression '" + expression + "'.", expectedValue, value);
Assert.assertEquals("Did not get expected value for expression '" + expression + "'.", expectedValue, value);
// isAssignableFrom would allow some room for compatibility
// in the above expression...
} catch (EvaluationException ee) {
SpelException ex = (SpelException) ee;
SpelEvaluationException ex = (SpelEvaluationException) ee;
ex.printStackTrace();
fail("Unexpected EvaluationException: " + ex.getMessage());
Assert.fail("Unexpected EvaluationException: " + ex.getMessage());
} catch (ParseException pe) {
fail("Unexpected ParseException: " + pe.getMessage());
Assert.fail("Unexpected ParseException: " + pe.getMessage());
}
}
@@ -151,7 +150,7 @@ public abstract class ExpressionTestCase extends TestCase {
try {
Expression e = parser.parseExpression(expression);
if (e == null) {
fail("Parser returned null for expression");
Assert.fail("Parser returned null for expression");
}
if (DEBUG) {
SpelUtilities.printAbstractSyntaxTree(System.out, e);
@@ -161,19 +160,19 @@ public abstract class ExpressionTestCase extends TestCase {
if (expectedValue == null)
return; // no point doing other
// checks
assertEquals("Expression returned null value, but expected '" + expectedValue + "'", expectedValue,
Assert.assertEquals("Expression returned null value, but expected '" + expectedValue + "'", expectedValue,
null);
}
Class<? extends Object> resultType = value.getClass();
if (expectedValue instanceof String) {
assertEquals("Did not get expected value for expression '" + expression + "'.", expectedValue,
Assert.assertEquals("Did not get expected value for expression '" + expression + "'.", expectedValue,
ExpressionTestCase.stringValueOf(value));
} else {
assertEquals("Did not get expected value for expression '" + expression + "'.", expectedValue, value);
Assert.assertEquals("Did not get expected value for expression '" + expression + "'.", expectedValue, value);
}
// assertEquals("Did not get expected value for expression '" + expression + "'.", expectedValue,
// Assert.assertEquals("Did not get expected value for expression '" + expression + "'.", expectedValue,
// ExpressionTestCase.stringValueOf(value));
assertEquals("Type of the result was not as expected. Expected '" + expectedClassOfResult
Assert.assertEquals("Type of the result was not as expected. Expected '" + expectedClassOfResult
+ "' but result was of type '" + resultType + "'", expectedClassOfResult
.equals/* isAssignableFrom */(resultType), true);
// TODO isAssignableFrom would allow some room for compatibility
@@ -182,16 +181,16 @@ public abstract class ExpressionTestCase extends TestCase {
boolean isWritable = e.isWritable(eContext);
if (isWritable != shouldBeWritable) {
if (shouldBeWritable)
fail("Expected the expression to be writable but it is not");
Assert.fail("Expected the expression to be writable but it is not");
else
fail("Expected the expression to be readonly but it is not");
Assert.fail("Expected the expression to be readonly but it is not");
}
} catch (EvaluationException ee) {
ee.printStackTrace();
fail("Unexpected Exception: " + ee.getMessage());
Assert.fail("Unexpected Exception: " + ee.getMessage());
} catch (ParseException pe) {
pe.printStackTrace();
fail("Unexpected Exception: " + pe.getMessage());
Assert.fail("Unexpected Exception: " + pe.getMessage());
}
}
@@ -222,7 +221,7 @@ public abstract class ExpressionTestCase extends TestCase {
try {
Expression expr = parser.parseExpression(expression);
if (expr == null) {
fail("Parser returned null for expression");
Assert.fail("Parser returned null for expression");
}
if (expectedReturnType != null) {
@SuppressWarnings("unused")
@@ -231,18 +230,18 @@ public abstract class ExpressionTestCase extends TestCase {
@SuppressWarnings("unused")
Object value = expr.getValue(eContext);
}
fail("Should have failed with message " + expectedMessage);
Assert.fail("Should have failed with message " + expectedMessage);
} catch (EvaluationException ee) {
SpelException ex = (SpelException) ee;
SpelEvaluationException ex = (SpelEvaluationException) ee;
if (ex.getMessageUnformatted() != expectedMessage) {
System.out.println(ex.getMessage());
// System.out.println(ex.getMessage());
ex.printStackTrace();
assertEquals("Failed to get expected message", expectedMessage, ex.getMessageUnformatted());
Assert.assertEquals("Failed to get expected message", expectedMessage, ex.getMessageUnformatted());
}
if (otherProperties != null && otherProperties.length != 0) {
// first one is expected position of the error within the string
int pos = ((Integer) otherProperties[0]).intValue();
assertEquals("Did not get correct position reported in error ", pos, ex.getPosition());
Assert.assertEquals("Did not get correct position reported in error ", pos, ex.getPosition());
if (otherProperties.length > 1) {
// Check inserts match
Object[] inserts = ex.getInserts();
@@ -251,25 +250,25 @@ public abstract class ExpressionTestCase extends TestCase {
}
if (inserts.length < otherProperties.length - 1) {
ex.printStackTrace();
fail("Cannot check " + (otherProperties.length - 1)
Assert.fail("Cannot check " + (otherProperties.length - 1)
+ " properties of the exception, it only has " + inserts.length + " inserts");
}
for (int i = 1; i < otherProperties.length; i++) {
if (otherProperties[i] == null) {
if (inserts[i - 1] != null) {
ex.printStackTrace();
fail("Insert does not match, expected 'null' but insert value was '" + inserts[i - 1]
Assert.fail("Insert does not match, expected 'null' but insert value was '" + inserts[i - 1]
+ "'");
}
} else if (inserts[i - 1] == null) {
if (otherProperties[i] != null) {
ex.printStackTrace();
fail("Insert does not match, expected '" + otherProperties[i]
Assert.fail("Insert does not match, expected '" + otherProperties[i]
+ "' but insert value was 'null'");
}
} else if (!inserts[i - 1].equals(otherProperties[i])) {
ex.printStackTrace();
fail("Insert does not match, expected '" + otherProperties[i] + "' but insert value was '"
Assert.fail("Insert does not match, expected '" + otherProperties[i] + "' but insert value was '"
+ inserts[i - 1] + "'");
}
}
@@ -277,7 +276,7 @@ public abstract class ExpressionTestCase extends TestCase {
}
} catch (ParseException pe) {
pe.printStackTrace();
fail("Unexpected Exception: " + pe.getMessage());
Assert.fail("Unexpected Exception: " + pe.getMessage());
}
}
@@ -293,26 +292,29 @@ public abstract class ExpressionTestCase extends TestCase {
try {
Expression expr = parser.parseExpression(expression);
SpelUtilities.printAbstractSyntaxTree(System.out, expr);
fail("Parsing should have failed!");
Assert.fail("Parsing should have failed!");
} catch (ParseException pe) {
Throwable t = pe.getCause();
if (t == null) {
fail("ParseException caught with no defined cause");
}
if (!(t instanceof SpelException)) {
t.printStackTrace();
fail("Cause of parse exception is not a SpelException");
}
SpelException ex = (SpelException) t;
// pe.printStackTrace();
// Throwable t = pe.getCause();
// if (t == null) {
// Assert.fail("ParseException caught with no defined cause");
// }
// if (!(t instanceof SpelEvaluationException)) {
// t.printStackTrace();
// Assert.fail("Cause of parse exception is not a SpelException");
// }
// SpelEvaluationException ex = (SpelEvaluationException) t;
// pe.printStackTrace();
SpelParseException ex = (SpelParseException)pe;
if (ex.getMessageUnformatted() != expectedMessage) {
System.out.println(ex.getMessage());
// System.out.println(ex.getMessage());
ex.printStackTrace();
assertEquals("Failed to get expected message", expectedMessage, ex.getMessageUnformatted());
Assert.assertEquals("Failed to get expected message", expectedMessage, ex.getMessageUnformatted());
}
if (otherProperties != null && otherProperties.length != 0) {
// first one is expected position of the error within the string
int pos = ((Integer) otherProperties[0]).intValue();
assertEquals("Did not get correct position reported in error ", pos, ex.getPosition());
Assert.assertEquals("Did not get correct position reported in error ", pos, ex.getPosition());
if (otherProperties.length > 1) {
// Check inserts match
Object[] inserts = ex.getInserts();
@@ -321,13 +323,13 @@ public abstract class ExpressionTestCase extends TestCase {
}
if (inserts.length < otherProperties.length - 1) {
ex.printStackTrace();
fail("Cannot check " + (otherProperties.length - 1)
Assert.fail("Cannot check " + (otherProperties.length - 1)
+ " properties of the exception, it only has " + inserts.length + " inserts");
}
for (int i = 1; i < otherProperties.length; i++) {
if (!inserts[i - 1].equals(otherProperties[i])) {
ex.printStackTrace();
fail("Insert does not match, expected '" + otherProperties[i] + "' but insert value was '"
Assert.fail("Insert does not match, expected '" + otherProperties[i] + "' but insert value was '"
+ inserts[i - 1] + "'");
}
}

View File

@@ -19,6 +19,10 @@ package org.springframework.expression.spel;
import java.util.ArrayList;
import java.util.List;
import junit.framework.Assert;
import org.junit.Before;
import org.junit.Test;
import org.springframework.core.convert.TypeDescriptor;
import org.springframework.core.convert.support.DefaultTypeConverter;
import org.springframework.core.convert.support.GenericTypeConverter;
@@ -48,43 +52,45 @@ public class ExpressionTestsUsingCoreConversionService extends ExpressionTestCas
listOfInteger.add(6);
}
@Before
public void setUp() throws Exception {
super.setUp();
typeDescriptorForListOfString = new TypeDescriptor(ExpressionTestsUsingCoreConversionService.class.getDeclaredField("listOfString"));
typeDescriptorForListOfInteger = new TypeDescriptor(ExpressionTestsUsingCoreConversionService.class.getDeclaredField("listOfInteger"));
ExpressionTestsUsingCoreConversionService.typeDescriptorForListOfString = new TypeDescriptor(ExpressionTestsUsingCoreConversionService.class.getDeclaredField("listOfString"));
ExpressionTestsUsingCoreConversionService.typeDescriptorForListOfInteger = new TypeDescriptor(ExpressionTestsUsingCoreConversionService.class.getDeclaredField("listOfInteger"));
}
/**
* Test the service can convert what we are about to use in the expression evaluation tests.
*/
@Test
public void testConversionsAvailable() throws Exception {
TypeConvertorUsingConversionService tcs = new TypeConvertorUsingConversionService();
// ArrayList containing List<Integer> to List<String>
Class<?> clazz = typeDescriptorForListOfString.getElementType();
assertEquals(String.class,clazz);
Assert.assertEquals(String.class,clazz);
List l = (List) tcs.convertValue(listOfInteger, typeDescriptorForListOfString);
assertNotNull(l);
Assert.assertNotNull(l);
// ArrayList containing List<String> to List<Integer>
clazz = typeDescriptorForListOfInteger.getElementType();
assertEquals(Integer.class,clazz);
Assert.assertEquals(Integer.class,clazz);
l = (List) tcs.convertValue(listOfString, typeDescriptorForListOfString);
assertNotNull(l);
Assert.assertNotNull(l);
}
@Test
public void testSetParameterizedList() throws Exception {
StandardEvaluationContext context = TestScenarioCreator.getTestEvaluationContext();
Expression e = parser.parseExpression("listOfInteger.size()");
assertEquals(0,e.getValue(context,Integer.class).intValue());
Assert.assertEquals(0,e.getValue(context,Integer.class).intValue());
context.setTypeConverter(new TypeConvertorUsingConversionService());
// Assign a List<String> to the List<Integer> field - the component elements should be converted
parser.parseExpression("listOfInteger").setValue(context,listOfString);
assertEquals(3,e.getValue(context,Integer.class).intValue()); // size now 3
Assert.assertEquals(3,e.getValue(context,Integer.class).intValue()); // size now 3
Class clazz = parser.parseExpression("listOfInteger[1].getClass()").getValue(context,Class.class); // element type correctly Integer
assertEquals(Integer.class,clazz);
Assert.assertEquals(Integer.class,clazz);
}
@@ -103,7 +109,7 @@ public class ExpressionTestsUsingCoreConversionService extends ExpressionTestCas
return this.service.canConvert(sourceType, typeDescriptor);
}
@SuppressWarnings("unchecked")
@SuppressWarnings("cast")
public <T> T convertValue(Object value, Class<T> targetType) throws EvaluationException {
return (T) this.service.convert(value,TypeDescriptor.valueOf(targetType));
}

View File

@@ -20,11 +20,17 @@ import java.io.PrintStream;
import java.util.ArrayList;
import java.util.List;
import junit.framework.Assert;
import org.junit.Test;
import org.springframework.expression.EvaluationContext;
import org.springframework.expression.EvaluationException;
import org.springframework.expression.ParseException;
import org.springframework.expression.TypedValue;
import org.springframework.expression.spel.ast.FormatHelper;
import org.springframework.expression.spel.support.ReflectionHelper;
import org.springframework.expression.spel.support.ReflectivePropertyResolver;
import org.springframework.expression.spel.support.StandardEvaluationContext;
import org.springframework.expression.spel.support.StandardTypeConverter;
import org.springframework.expression.spel.support.ReflectionHelper.ArgsMatchKind;
@@ -35,20 +41,23 @@ import org.springframework.expression.spel.support.ReflectionHelper.ArgsMatchKin
*/
public class HelperTests extends ExpressionTestCase {
@Test
public void testFormatHelperForClassName() {
assertEquals("java.lang.String",FormatHelper.formatClassNameForMessage(String.class));
assertEquals("java.lang.String[]",FormatHelper.formatClassNameForMessage(new String[1].getClass()));
assertEquals("int[]",FormatHelper.formatClassNameForMessage(new int[1].getClass()));
assertEquals("int[][]",FormatHelper.formatClassNameForMessage(new int[1][2].getClass()));
assertEquals("null",FormatHelper.formatClassNameForMessage(null));
Assert.assertEquals("java.lang.String",FormatHelper.formatClassNameForMessage(String.class));
Assert.assertEquals("java.lang.String[]",FormatHelper.formatClassNameForMessage(new String[1].getClass()));
Assert.assertEquals("int[]",FormatHelper.formatClassNameForMessage(new int[1].getClass()));
Assert.assertEquals("int[][]",FormatHelper.formatClassNameForMessage(new int[1][2].getClass()));
Assert.assertEquals("null",FormatHelper.formatClassNameForMessage(null));
}
@Test
public void testFormatHelperForMethod() {
assertEquals("foo(java.lang.String)",FormatHelper.formatMethodForMessage("foo", String.class));
assertEquals("goo(java.lang.String,int[])",FormatHelper.formatMethodForMessage("goo", String.class,new int[1].getClass()));
assertEquals("boo()",FormatHelper.formatMethodForMessage("boo"));
Assert.assertEquals("foo(java.lang.String)",FormatHelper.formatMethodForMessage("foo", String.class));
Assert.assertEquals("goo(java.lang.String,int[])",FormatHelper.formatMethodForMessage("goo", String.class,new int[1].getClass()));
Assert.assertEquals("boo()",FormatHelper.formatMethodForMessage("boo"));
}
@Test
public void testUtilities() throws ParseException {
SpelExpression expr = (SpelExpression)parser.parseExpression("3+4+5+6+7-2");
ByteArrayOutputStream baos = new ByteArrayOutputStream();
@@ -75,16 +84,18 @@ public class HelperTests extends ExpressionTestCase {
// CompoundExpression value:2
// IntLiteral value:2
// ===> Expression '3+4+5+6+7-2' - AST end
assertTrue(s.indexOf("===> Expression '3+4+5+6+7-2' - AST start")!=-1);
assertTrue(s.indexOf(" OperatorPlus value:((((3 + 4) + 5) + 6) + 7) #children:2")!=-1);
Assert.assertTrue(s.indexOf("===> Expression '3+4+5+6+7-2' - AST start")!=-1);
Assert.assertTrue(s.indexOf(" OperatorPlus value:((((3 + 4) + 5) + 6) + 7) #children:2")!=-1);
}
@Test
public void testTypedValue() {
TypedValue tValue = new TypedValue("hello");
assertEquals(String.class,tValue.getTypeDescriptor().getType());
assertEquals("TypedValue: hello of type java.lang.String",tValue.toString());
Assert.assertEquals(String.class,tValue.getTypeDescriptor().getType());
Assert.assertEquals("TypedValue: hello of type java.lang.String",tValue.toString());
}
@Test
public void testReflectionHelperCompareArguments_ExactMatching() {
StandardTypeConverter typeConverter = new StandardTypeConverter();
@@ -95,6 +106,7 @@ public class HelperTests extends ExpressionTestCase {
checkMatch(new Class[]{String.class,Integer.class},new Class[]{String.class,Integer.class},typeConverter,ArgsMatchKind.EXACT);
}
@Test
public void testReflectionHelperCompareArguments_CloseMatching() {
StandardTypeConverter typeConverter = new StandardTypeConverter();
@@ -108,6 +120,7 @@ public class HelperTests extends ExpressionTestCase {
checkMatch(new Class[]{String.class,Sub.class},new Class[]{String.class,Super.class},typeConverter,ArgsMatchKind.CLOSE);
}
@Test
public void testReflectionHelperCompareArguments_RequiresConversionMatching() {
// TODO these are failing - for investigation
StandardTypeConverter typeConverter = new StandardTypeConverter();
@@ -125,6 +138,7 @@ public class HelperTests extends ExpressionTestCase {
checkMatch(new Class[]{Integer.TYPE,Sub.class,Boolean.TYPE},new Class[]{Integer.class, Super.class,Boolean.class},typeConverter,ArgsMatchKind.REQUIRES_CONVERSION,0,2);
}
@Test
public void testReflectionHelperCompareArguments_NotAMatch() {
StandardTypeConverter typeConverter = new StandardTypeConverter();
@@ -132,6 +146,7 @@ public class HelperTests extends ExpressionTestCase {
checkMatch(new Class[]{Super.class,String.class},new Class[]{Sub.class,String.class},typeConverter,null);
}
@Test
public void testReflectionHelperCompareArguments_Varargs_ExactMatching() {
StandardTypeConverter tc = new StandardTypeConverter();
Class<?> stringArrayClass = new String[0].getClass();
@@ -184,6 +199,7 @@ public class HelperTests extends ExpressionTestCase {
// what happens on (Integer,String) passed to (Integer[]) ?
}
@Test
public void testConvertArguments() throws Exception {
StandardTypeConverter tc = new StandardTypeConverter();
@@ -206,8 +222,9 @@ public class HelperTests extends ExpressionTestCase {
args = new Object[]{3,false,3.0d};
ReflectionHelper.convertArguments(new Class[]{String.class,String[].class}, true, tc, new int[]{0,1,2}, args);
checkArguments(args, "3","false","3.0");
}
}
@Test
public void testConvertArguments2() throws EvaluationException {
StandardTypeConverter tc = new StandardTypeConverter();
@@ -230,9 +247,9 @@ public class HelperTests extends ExpressionTestCase {
args = new Object[]{3,false,3.0f};
try {
ReflectionHelper.convertAllArguments(new Class[]{String.class,String[].class}, true, null, args);
fail("Should have failed because no converter supplied");
} catch (SpelException se) {
assertEquals(SpelMessages.TYPE_CONVERSION_ERROR,se.getMessageUnformatted());
Assert.fail("Should have failed because no converter supplied");
} catch (SpelEvaluationException se) {
Assert.assertEquals(SpelMessages.TYPE_CONVERSION_ERROR,se.getMessageUnformatted());
}
// null value
@@ -241,21 +258,78 @@ public class HelperTests extends ExpressionTestCase {
checkArguments(args,"3",null,"3.0");
}
@Test
public void testSetupArguments() {
Object[] newArray = ReflectionHelper.setupArgumentsForVarargsInvocation(new Class[]{new String[0].getClass()},"a","b","c");
assertEquals(1,newArray.length);
Assert.assertEquals(1,newArray.length);
Object firstParam = newArray[0];
assertEquals(String.class,firstParam.getClass().getComponentType());
Assert.assertEquals(String.class,firstParam.getClass().getComponentType());
Object[] firstParamArray = (Object[])firstParam;
assertEquals(3,firstParamArray.length);
assertEquals("a",firstParamArray[0]);
assertEquals("b",firstParamArray[1]);
assertEquals("c",firstParamArray[2]);
Assert.assertEquals(3,firstParamArray.length);
Assert.assertEquals("a",firstParamArray[0]);
Assert.assertEquals("b",firstParamArray[1]);
Assert.assertEquals("c",firstParamArray[2]);
}
@Test
public void testReflectivePropertyResolver() throws Exception {
ReflectivePropertyResolver rpr = new ReflectivePropertyResolver();
Tester t = new Tester();
t.setProperty("hello");
EvaluationContext ctx = new StandardEvaluationContext(t);
Assert.assertTrue(rpr.canRead(ctx, t, "property"));
Assert.assertEquals("hello",rpr.read(ctx, t, "property").getValue());
Assert.assertEquals("hello",rpr.read(ctx, t, "property").getValue()); // cached accessor used
Assert.assertTrue(rpr.canRead(ctx, t, "field"));
Assert.assertEquals(3,rpr.read(ctx, t, "field").getValue());
Assert.assertEquals(3,rpr.read(ctx, t, "field").getValue()); // cached accessor used
Assert.assertTrue(rpr.canWrite(ctx, t, "property"));
rpr.write(ctx, t, "property","goodbye");
rpr.write(ctx, t, "property","goodbye"); // cached accessor used
Assert.assertTrue(rpr.canWrite(ctx, t, "field"));
rpr.write(ctx, t, "field",12);
rpr.write(ctx, t, "field",12);
// Attempted write as first activity on this field and property to drive testing
// of populating type descriptor cache
rpr.write(ctx,t,"field2",3);
rpr.write(ctx, t, "property2","doodoo");
Assert.assertEquals(3,rpr.read(ctx,t,"field2").getValue());
// Attempted read as first activity on this field and property (no canRead before them)
Assert.assertEquals(0,rpr.read(ctx,t,"field3").getValue());
Assert.assertEquals("doodoo",rpr.read(ctx,t,"property3").getValue());
// Access through is method
// Assert.assertEquals(0,rpr.read(ctx,t,"field3").getValue());
Assert.assertEquals(false,rpr.read(ctx,t,"property4").getValue());
Assert.assertTrue(rpr.canRead(ctx,t,"property4"));
}
// test classes
static class Tester {
String property;
public int field = 3;
public int field2;
public int field3 = 0;
String property2;
String property3 = "doodoo";
boolean property4 = false;
public String getProperty() { return property; }
public void setProperty(String value) { property = value; }
public void setProperty2(String value) { property2 = value; }
public String getProperty3() { return property3; }
public boolean isProperty4() { return property4; }
}
static class Super {
}
@@ -273,25 +347,25 @@ public class HelperTests extends ExpressionTestCase {
private void checkMatch(Class[] inputTypes, Class[] expectedTypes, StandardTypeConverter typeConverter,ArgsMatchKind expectedMatchKind,int... argsForConversion) {
ReflectionHelper.ArgumentsMatchInfo matchInfo = ReflectionHelper.compareArguments(expectedTypes, inputTypes, typeConverter);
if (expectedMatchKind==null) {
assertNull("Did not expect them to match in any way", matchInfo);
Assert.assertNull("Did not expect them to match in any way", matchInfo);
} else {
assertNotNull("Should not be a null match", matchInfo);
Assert.assertNotNull("Should not be a null match", matchInfo);
}
if (expectedMatchKind==ArgsMatchKind.EXACT) {
assertTrue(matchInfo.isExactMatch());
assertNull(matchInfo.argsRequiringConversion);
Assert.assertTrue(matchInfo.isExactMatch());
Assert.assertNull(matchInfo.argsRequiringConversion);
} else if (expectedMatchKind==ArgsMatchKind.CLOSE) {
assertTrue(matchInfo.isCloseMatch());
assertNull(matchInfo.argsRequiringConversion);
Assert.assertTrue(matchInfo.isCloseMatch());
Assert.assertNull(matchInfo.argsRequiringConversion);
} else if (expectedMatchKind==ArgsMatchKind.REQUIRES_CONVERSION) {
assertTrue("expected to be a match requiring conversion, but was "+matchInfo,matchInfo.isMatchRequiringConversion());
Assert.assertTrue("expected to be a match requiring conversion, but was "+matchInfo,matchInfo.isMatchRequiringConversion());
if (argsForConversion==null) {
fail("there are arguments that need conversion");
Assert.fail("there are arguments that need conversion");
}
assertEquals("The array of args that need conversion is different length to that expected",argsForConversion.length, matchInfo.argsRequiringConversion.length);
Assert.assertEquals("The array of args that need conversion is different length to that expected",argsForConversion.length, matchInfo.argsRequiringConversion.length);
for (int a=0;a<argsForConversion.length;a++) {
assertEquals(argsForConversion[a],matchInfo.argsRequiringConversion[a]);
Assert.assertEquals(argsForConversion[a],matchInfo.argsRequiringConversion[a]);
}
}
}
@@ -302,37 +376,37 @@ public class HelperTests extends ExpressionTestCase {
private void checkMatch2(Class[] inputTypes, Class[] expectedTypes, StandardTypeConverter typeConverter,ArgsMatchKind expectedMatchKind,int... argsForConversion) {
ReflectionHelper.ArgumentsMatchInfo matchInfo = ReflectionHelper.compareArgumentsVarargs(expectedTypes, inputTypes, typeConverter);
if (expectedMatchKind==null) {
assertNull("Did not expect them to match in any way: "+matchInfo, matchInfo);
Assert.assertNull("Did not expect them to match in any way: "+matchInfo, matchInfo);
} else {
assertNotNull("Should not be a null match", matchInfo);
Assert.assertNotNull("Should not be a null match", matchInfo);
}
if (expectedMatchKind==ArgsMatchKind.EXACT) {
assertTrue(matchInfo.isExactMatch());
assertNull(matchInfo.argsRequiringConversion);
Assert.assertTrue(matchInfo.isExactMatch());
Assert.assertNull(matchInfo.argsRequiringConversion);
} else if (expectedMatchKind==ArgsMatchKind.CLOSE) {
assertTrue(matchInfo.isCloseMatch());
assertNull(matchInfo.argsRequiringConversion);
Assert.assertTrue(matchInfo.isCloseMatch());
Assert.assertNull(matchInfo.argsRequiringConversion);
} else if (expectedMatchKind==ArgsMatchKind.REQUIRES_CONVERSION) {
assertTrue("expected to be a match requiring conversion, but was "+matchInfo,matchInfo.isMatchRequiringConversion());
Assert.assertTrue("expected to be a match requiring conversion, but was "+matchInfo,matchInfo.isMatchRequiringConversion());
if (argsForConversion==null) {
fail("there are arguments that need conversion");
Assert.fail("there are arguments that need conversion");
}
assertEquals("The array of args that need conversion is different length to that expected",argsForConversion.length, matchInfo.argsRequiringConversion.length);
Assert.assertEquals("The array of args that need conversion is different length to that expected",argsForConversion.length, matchInfo.argsRequiringConversion.length);
for (int a=0;a<argsForConversion.length;a++) {
assertEquals(argsForConversion[a],matchInfo.argsRequiringConversion[a]);
Assert.assertEquals(argsForConversion[a],matchInfo.argsRequiringConversion[a]);
}
}
}
private void checkArguments(Object[] args, Object... expected) {
assertEquals(expected.length,args.length);
Assert.assertEquals(expected.length,args.length);
for (int i=0;i<expected.length;i++) {
checkArgument(expected[i],args[i]);
}
}
private void checkArgument(Object expected, Object actual) {
assertEquals(expected,actual);
Assert.assertEquals(expected,actual);
}
}

View File

@@ -17,6 +17,9 @@ package org.springframework.expression.spel;
import java.util.ArrayList;
import junit.framework.Assert;
import org.junit.Test;
import org.springframework.expression.spel.support.StandardEvaluationContext;
/**
@@ -28,90 +31,106 @@ import org.springframework.expression.spel.support.StandardEvaluationContext;
*/
public class InProgressTests extends ExpressionTestCase {
@Test
public void testRelOperatorsBetween01() {
evaluate("1 between listOneFive", "true", Boolean.class);
// evaluate("1 between {1, 5}", "true", Boolean.class); // no inline list building at the moment
}
@Test
public void testRelOperatorsBetweenErrors01() {
evaluateAndCheckError("1 between T(String)", SpelMessages.BETWEEN_RIGHT_OPERAND_MUST_BE_TWO_ELEMENT_LIST, 12);
evaluateAndCheckError("1 between T(String)", SpelMessages.BETWEEN_RIGHT_OPERAND_MUST_BE_TWO_ELEMENT_LIST, 10);
}
@Test
public void testRelOperatorsBetweenErrors03() {
evaluateAndCheckError("1 between listOfNumbersUpToTen", SpelMessages.BETWEEN_RIGHT_OPERAND_MUST_BE_TWO_ELEMENT_LIST, 10);
}
// PROJECTION
@Test
public void testProjection01() {
evaluate("listOfNumbersUpToTen.![#this<5?'y':'n']","[y, y, y, y, n, n, n, n, n, n]",ArrayList.class);
// inline list creation not supported at the moment
// evaluate("{1,2,3,4,5,6,7,8,9,10}.!{#isEven(#this)}", "[n, y, n, y, n, y, n, y, n, y]", ArrayList.class);
}
@Test
public void testProjection02() {
// inline map creation not supported at the moment
// evaluate("#{'a':'y','b':'n','c':'y'}.![value=='y'?key:null].nonnull().sort()", "[a, c]", ArrayList.class);
evaluate("mapOfNumbersUpToTen.![key>5?value:null]", "[null, null, null, null, null, six, seven, eight, nine, ten]", ArrayList.class);
}
@Test
public void testProjection05() {
evaluateAndCheckError("'abc'.![true]", SpelMessages.PROJECTION_NOT_SUPPORTED_ON_TYPE);
}
@Test
public void testProjection06() throws Exception {
SpelExpression expr = (SpelExpression)parser.parseExpression("'abc'.![true]");
assertEquals("'abc'.![true]",expr.toStringAST());
assertFalse(expr.isWritable(new StandardEvaluationContext()));
Assert.assertEquals("'abc'.![true]",expr.toStringAST());
Assert.assertFalse(expr.isWritable(new StandardEvaluationContext()));
}
// SELECTION
@Test
public void testSelection02() {
evaluate("testMap.keySet().?[#this matches '.*o.*']", "[monday]", ArrayList.class);
evaluate("testMap.keySet().?[#this matches '.*r.*'].contains('saturday')", "true", Boolean.class);
evaluate("testMap.keySet().?[#this matches '.*r.*'].size()", "3", Integer.class);
}
@Test
public void testSelectionError_NonBooleanSelectionCriteria() {
evaluateAndCheckError("listOfNumbersUpToTen.?['nonboolean']",
SpelMessages.RESULT_OF_SELECTION_CRITERIA_IS_NOT_BOOLEAN);
}
@Test
public void testSelection03() {
evaluate("mapOfNumbersUpToTen.?[key>5].size()", "5", Integer.class);
// evaluate("listOfNumbersUpToTen.?{#this>5}", "5", ArrayList.class);
}
@Test
public void testSelection04() {
evaluateAndCheckError("mapOfNumbersUpToTen.?['hello'].size()",SpelMessages.RESULT_OF_SELECTION_CRITERIA_IS_NOT_BOOLEAN);
}
@Test
public void testSelectionFirst01() {
evaluate("listOfNumbersUpToTen.^[#isEven(#this) == 'y']", "2", Integer.class);
}
@Test
public void testSelectionFirst02() {
evaluate("mapOfNumbersUpToTen.^[key>5].size()", "1", Integer.class);
}
@Test
public void testSelectionLast01() {
evaluate("listOfNumbersUpToTen.$[#isEven(#this) == 'y']", "10", Integer.class);
}
@Test
public void testSelectionLast02() {
evaluate("mapOfNumbersUpToTen.$[key>5].size()", "1", Integer.class);
}
@Test
public void testSelectionAST() throws Exception {
SpelExpression expr = (SpelExpression)parser.parseExpression("'abc'.^[true]");
assertEquals("'abc'.^[true]",expr.toStringAST());
assertFalse(expr.isWritable(new StandardEvaluationContext()));
Assert.assertEquals("'abc'.^[true]",expr.toStringAST());
Assert.assertFalse(expr.isWritable(new StandardEvaluationContext()));
expr = (SpelExpression)parser.parseExpression("'abc'.?[true]");
assertEquals("'abc'.?[true]",expr.toStringAST());
assertFalse(expr.isWritable(new StandardEvaluationContext()));
Assert.assertEquals("'abc'.?[true]",expr.toStringAST());
Assert.assertFalse(expr.isWritable(new StandardEvaluationContext()));
expr = (SpelExpression)parser.parseExpression("'abc'.$[true]");
assertEquals("'abc'.$[true]",expr.toStringAST());
assertFalse(expr.isWritable(new StandardEvaluationContext()));
Assert.assertEquals("'abc'.$[true]",expr.toStringAST());
Assert.assertFalse(expr.isWritable(new StandardEvaluationContext()));
}
// Constructor invocation

View File

@@ -16,8 +16,9 @@
package org.springframework.expression.spel;
import junit.framework.TestCase;
import junit.framework.Assert;
import org.junit.Test;
import org.springframework.expression.EvaluationContext;
import org.springframework.expression.EvaluationException;
import org.springframework.expression.common.LiteralExpression;
@@ -26,8 +27,9 @@ import org.springframework.expression.spel.support.StandardEvaluationContext;
/**
* @author Andy Clement
*/
public class LiteralExpressionTests extends TestCase {
public class LiteralExpressionTests {
@Test
public void testGetValue() throws Exception {
LiteralExpression lEx = new LiteralExpression("somevalue");
checkString("somevalue", lEx.getValue());
@@ -35,34 +37,36 @@ public class LiteralExpressionTests extends TestCase {
EvaluationContext ctx = new StandardEvaluationContext();
checkString("somevalue", lEx.getValue(ctx));
checkString("somevalue", lEx.getValue(ctx, String.class));
assertEquals("somevalue", lEx.getExpressionString());
assertFalse(lEx.isWritable(new StandardEvaluationContext()));
Assert.assertEquals("somevalue", lEx.getExpressionString());
Assert.assertFalse(lEx.isWritable(new StandardEvaluationContext()));
}
@Test
public void testSetValue() {
try {
LiteralExpression lEx = new LiteralExpression("somevalue");
lEx.setValue(new StandardEvaluationContext(), "flibble");
fail("Should have got an exception that the value cannot be set");
Assert.fail("Should have got an exception that the value cannot be set");
}
catch (EvaluationException ee) {
// success, not allowed - whilst here, check the expression value in the exception
assertEquals(ee.getExpressionString(), "somevalue");
Assert.assertEquals(ee.getExpressionString(), "somevalue");
}
}
@Test
public void testGetValueType() throws Exception {
LiteralExpression lEx = new LiteralExpression("somevalue");
assertEquals(String.class, lEx.getValueType());
assertEquals(String.class, lEx.getValueType(new StandardEvaluationContext()));
Assert.assertEquals(String.class, lEx.getValueType());
Assert.assertEquals(String.class, lEx.getValueType(new StandardEvaluationContext()));
}
private void checkString(String expectedString, Object value) {
if (!(value instanceof String)) {
fail("Result was not a string, it was of type " + value.getClass() + " (value=" + value + ")");
Assert.fail("Result was not a string, it was of type " + value.getClass() + " (value=" + value + ")");
}
if (!((String) value).equals(expectedString)) {
fail("Did not get expected result. Should have been '" + expectedString + "' but was '" + value + "'");
Assert.fail("Did not get expected result. Should have been '" + expectedString + "' but was '" + value + "'");
}
}

View File

@@ -16,6 +16,9 @@
package org.springframework.expression.spel;
import junit.framework.Assert;
import org.junit.Test;
import org.springframework.expression.spel.support.StandardEvaluationContext;
/**
@@ -25,47 +28,58 @@ import org.springframework.expression.spel.support.StandardEvaluationContext;
*/
public class LiteralTests extends ExpressionTestCase {
@Test
public void testLiteralBoolean01() {
evaluate("false", "false", Boolean.class);
}
@Test
public void testLiteralBoolean02() {
evaluate("true", "true", Boolean.class);
}
@Test
public void testLiteralInteger01() {
evaluate("1", "1", Integer.class);
}
@Test
public void testLiteralInteger02() {
evaluate("1415", "1415", Integer.class);
}
@Test
public void testLiteralString01() {
evaluate("'Hello World'", "Hello World", String.class);
}
@Test
public void testLiteralString02() {
evaluate("'joe bloggs'", "joe bloggs", String.class);
}
@Test
public void testLiteralString03() {
evaluate("'hello'", "hello", String.class);
}
@Test
public void testLiteralString04() {
evaluate("'Tony''s Pizza'", "Tony's Pizza", String.class);
evaluate("'Tony\\r''s Pizza'", "Tony\\r's Pizza", String.class);
}
@Test
public void testLiteralString05() {
evaluate("\"Hello World\"", "Hello World", String.class);
}
@Test
public void testLiteralString06() {
evaluate("\"Hello ' World\"", "Hello ' World", String.class);
}
@Test
public void testHexIntLiteral01() {
evaluate("0x7FFFF", "524287", Integer.class);
evaluate("0x7FFFFL", 524287L, Long.class);
@@ -73,18 +87,21 @@ public class LiteralTests extends ExpressionTestCase {
evaluate("0X7FFFFl", 524287L, Long.class);
}
@Test
public void testLongIntLiteral01() {
evaluate("0xCAFEBABEL", 3405691582L, Long.class);
}
@Test
public void testLongIntInteractions01() {
evaluate("0x20 * 2L", 64L, Long.class);
// ask for the result to be made into an Integer
evaluateAndAskForReturnType("0x20 * 2L", 64, Integer.class);
// ask for the result to be made into an Integer knowing that it will not fit
evaluateAndCheckError("0x1220 * 0xffffffffL", Integer.class, SpelMessages.TYPE_CONVERSION_ERROR, -1);
evaluateAndCheckError("0x1220 * 0xffffffffL", Integer.class, SpelMessages.TYPE_CONVERSION_ERROR, 0);
}
@Test
public void testSignedIntLiterals() {
evaluate("-1", -1, Integer.class);
evaluate("-0xa", -10, Integer.class);
@@ -92,6 +109,7 @@ public class LiteralTests extends ExpressionTestCase {
evaluate("-0x20l", -32L, Long.class);
}
@Test
public void testLiteralReal01_CreatingDoubles() {
evaluate("1.25", 1.25d, Double.class);
evaluate("2.99", 2.99d, Double.class);
@@ -104,46 +122,51 @@ public class LiteralTests extends ExpressionTestCase {
evaluate("-3.141D", -3.141d, Double.class);
}
@Test
public void testLiteralReal02_CreatingFloats() {
// For now, everything becomes a double...
evaluate("1.25f", 1.25d, Double.class);
evaluate("2.99f", 2.99d, Double.class);
evaluate("-3.141f", -3.141d, Double.class);
evaluate("2.5f", 2.5d, Double.class);
evaluate("-3.5f", -3.5d, Double.class);
evaluate("1.25F", 1.25d, Double.class);
evaluate("2.99F", 2.99d, Double.class);
evaluate("-3.141F", -3.141d, Double.class);
evaluate("2.5F", 2.5d, Double.class);
evaluate("-3.5F", -3.5d, Double.class);
}
@Test
public void testLiteralReal03_UsingExponents() {
evaluate("6.0221415E+23", "6.0221415E23", Double.class);
evaluate("6.0221415e+23", "6.0221415E23", Double.class);
evaluate("6.0221415E+23d", "6.0221415E23", Double.class);
evaluate("6.0221415e+23D", "6.0221415E23", Double.class);
evaluate("6.0221415E+23f", "6.0221415E23", Double.class);
evaluate("6.0221415e+23F", "6.0221415E23", Double.class);
evaluate("6E2f", 600.0d, Double.class);
}
@Test
public void testLiteralReal04_BadExpressions() {
parseAndCheckError("6.1e23e22", SpelMessages.PARSE_PROBLEM, 6, "mismatched input 'e22' expecting EOF");
parseAndCheckError("6.1f23e22", SpelMessages.PARSE_PROBLEM, 4, "mismatched input '23e22' expecting EOF");
parseAndCheckError("6.1e23e22", SpelMessages.MORE_INPUT, 6, "e22");
parseAndCheckError("6.1f23e22", SpelMessages.MORE_INPUT, 4, "23e22");
}
@Test
public void testLiteralNull01() {
evaluate("null", null, null);
}
@Test
public void testConversions() {
// getting the expression type to be what we want - either:
evaluate("new Integer(37).byteValue()", (byte) 37, Byte.class); // calling byteValue() on Integer.class
evaluateAndAskForReturnType("new Integer(37)", (byte) 37, Byte.class); // relying on registered type converters
}
@Test
public void testNotWritable() throws Exception {
SpelExpression expr = (SpelExpression)parser.parseExpression("37");
assertFalse(expr.isWritable(new StandardEvaluationContext()));
Assert.assertFalse(expr.isWritable(new StandardEvaluationContext()));
expr = (SpelExpression)parser.parseExpression("37L");
assertFalse(expr.isWritable(new StandardEvaluationContext()));
Assert.assertFalse(expr.isWritable(new StandardEvaluationContext()));
expr = (SpelExpression)parser.parseExpression("true");
assertFalse(expr.isWritable(new StandardEvaluationContext()));
Assert.assertFalse(expr.isWritable(new StandardEvaluationContext()));
}
}

View File

@@ -18,13 +18,17 @@ package org.springframework.expression.spel;
import java.util.Map;
import junit.framework.Assert;
import org.junit.Test;
import org.springframework.expression.AccessException;
import org.springframework.expression.EvaluationContext;
import org.springframework.expression.Expression;
import org.springframework.expression.ExpressionParser;
import org.springframework.expression.PropertyAccessor;
import org.springframework.expression.TypedValue;
import org.springframework.expression.spel.antlr.SpelAntlrExpressionParser;
import org.springframework.expression.spel.ast.CommonTypeDescriptors;
import org.springframework.expression.spel.standard.SpelExpressionParser;
import org.springframework.expression.spel.support.StandardEvaluationContext;
/**
@@ -34,32 +38,36 @@ import org.springframework.expression.spel.support.StandardEvaluationContext;
*/
public class MapAccessTests extends ExpressionTestCase {
@Test
public void testSimpleMapAccess01() {
evaluate("testMap.get('monday')", "montag", String.class);
}
@Test
public void testMapAccessThroughIndexer() {
evaluate("testMap['monday']", "montag", String.class);
}
@Test
public void testCustomMapAccessor() throws Exception {
SpelAntlrExpressionParser parser = new SpelAntlrExpressionParser();
ExpressionParser parser = new SpelExpressionParser();
StandardEvaluationContext ctx = TestScenarioCreator.getTestEvaluationContext();
ctx.addPropertyAccessor(new MapAccessor());
Expression expr = parser.parseExpression("testMap.monday");
Object value = expr.getValue(ctx, String.class);
assertEquals("montag", value);
Assert.assertEquals("montag", value);
}
@Test
public void testVariableMapAccess() throws Exception {
SpelAntlrExpressionParser parser = new SpelAntlrExpressionParser();
ExpressionParser parser = new SpelExpressionParser();
StandardEvaluationContext ctx = TestScenarioCreator.getTestEvaluationContext();
ctx.setVariable("day", "saturday");
Expression expr = parser.parseExpression("testMap[#day]");
Object value = expr.getValue(ctx, String.class);
assertEquals("samstag", value);
Assert.assertEquals("samstag", value);
}

View File

@@ -16,14 +16,16 @@
package org.springframework.expression.spel;
import org.junit.Test;
/**
* Tests invocation of methods.
*
* @author Andy Clement
*/
@SuppressWarnings("unused")
public class MethodInvocationTests extends ExpressionTestCase {
@Test
public void testSimpleAccess01() {
evaluate("getPlaceOfBirth().getCity()", "SmilJan", String.class);
}
@@ -39,6 +41,7 @@ public class MethodInvocationTests extends ExpressionTestCase {
// evaluate("new int[]{4,3,2,1,2,3}.distinct().count()", 4, Integer.class);
// }
@Test
public void testStringClass() {
evaluate("new java.lang.String('hello').charAt(2)", 'l', Character.class);
evaluate("new java.lang.String('hello').charAt(2).equals('l'.charAt(0))", true, Boolean.class);
@@ -46,11 +49,13 @@ public class MethodInvocationTests extends ExpressionTestCase {
evaluate("' abcba '.trim()", "abcba", String.class);
}
@Test
public void testNonExistentMethods() {
// name is ok but madeup() does not exist
evaluateAndCheckError("name.madeup()", SpelMessages.METHOD_NOT_FOUND, 5);
}
@Test
public void testWidening01() {
// widening of int 3 to double 3 is OK
evaluate("new Double(3.0d).compareTo(8)", -1, Integer.class);
@@ -58,12 +63,14 @@ public class MethodInvocationTests extends ExpressionTestCase {
evaluate("new Double(3.0d).compareTo(2)", 1, Integer.class);
}
@Test
public void testArgumentConversion01() {
// Rely on Double>String conversion for calling startsWith()
evaluate("new String('hello 2.0 to you').startsWith(7.0d)", false, Boolean.class);
evaluate("new String('7.0 foobar').startsWith(7.0d)", true, Boolean.class);
}
@Test
public void testVarargsInvocation01() {
// Calling 'public int aVarargsMethod(String... strings)'
evaluate("aVarargsMethod('a','b','c')", 3, Integer.class);
@@ -75,6 +82,7 @@ public class MethodInvocationTests extends ExpressionTestCase {
// evaluate("aVarargsMethod(new String[]{'a','b','c'})", 3, Integer.class);
}
@Test
public void testVarargsInvocation02() {
// Calling 'public int aVarargsMethod2(int i, String... strings)' - returns int+length_of_strings
evaluate("aVarargsMethod2(5,'a','b','c')", 8, Integer.class);
@@ -86,6 +94,7 @@ public class MethodInvocationTests extends ExpressionTestCase {
// evaluate("aVarargsMethod2(8,new String[]{'a','b','c'})", 11, Integer.class);
}
@Test
public void testInvocationOnNullContextObject() {
evaluateAndCheckError("null.toString()",SpelMessages.METHOD_CALL_ON_NULL_OBJECT_NOT_ALLOWED);
}

View File

@@ -16,6 +16,9 @@
package org.springframework.expression.spel;
import junit.framework.Assert;
import org.junit.Test;
import org.springframework.expression.EvaluationException;
import org.springframework.expression.Operation;
import org.springframework.expression.OperatorOverloader;
@@ -49,6 +52,7 @@ public class OperatorOverloaderTests extends ExpressionTestCase {
}
@Test
public void testSimpleOperations() throws Exception {
// no built in support for this:
evaluateAndCheckError("'abc'+true",SpelMessages.OPERATOR_NOT_SUPPORTED_BETWEEN_TYPES);
@@ -57,9 +61,9 @@ public class OperatorOverloaderTests extends ExpressionTestCase {
eContext.setOperatorOverloader(new StringAndBooleanAddition());
SpelExpression expr = (SpelExpression)parser.parseExpression("'abc'+true");
assertEquals("abctrue",expr.getValue(eContext));
Assert.assertEquals("abctrue",expr.getValue(eContext));
expr = (SpelExpression)parser.parseExpression("'abc'-true");
assertEquals("abc",expr.getValue(eContext));
Assert.assertEquals("abc",expr.getValue(eContext));
}
}

View File

@@ -16,6 +16,9 @@
package org.springframework.expression.spel;
import junit.framework.Assert;
import org.junit.Test;
import org.springframework.expression.spel.ast.Operator;
/**
@@ -25,14 +28,17 @@ import org.springframework.expression.spel.ast.Operator;
*/
public class OperatorTests extends ExpressionTestCase {
@Test
public void testIntegerLiteral() {
evaluate("3", 3, Integer.class);
}
@Test
public void testRealLiteral() {
evaluate("3.5", 3.5d, Double.class);
}
@Test
public void testLessThan() {
evaluate("3 < 5", true, Boolean.class);
evaluate("5 < 3", false, Boolean.class);
@@ -44,6 +50,7 @@ public class OperatorTests extends ExpressionTestCase {
evaluate("'def' < 'abc'",false,Boolean.class);
}
@Test
public void testLessThanOrEqual() {
evaluate("3 <= 5", true, Boolean.class);
evaluate("5 <= 3", false, Boolean.class);
@@ -59,6 +66,7 @@ public class OperatorTests extends ExpressionTestCase {
evaluate("'abc' <= 'abc'",true,Boolean.class);
}
@Test
public void testEqual() {
evaluate("3 == 5", false, Boolean.class);
evaluate("5 == 3", false, Boolean.class);
@@ -68,6 +76,7 @@ public class OperatorTests extends ExpressionTestCase {
evaluate("'abc' == null", false, Boolean.class);
}
@Test
public void testNotEqual() {
evaluate("3 != 5", true, Boolean.class);
evaluate("5 != 3", true, Boolean.class);
@@ -76,6 +85,7 @@ public class OperatorTests extends ExpressionTestCase {
evaluate("3.0f != 3.0f", false, Boolean.class);
}
@Test
public void testGreaterThanOrEqual() {
evaluate("3 >= 5", false, Boolean.class);
evaluate("5 >= 3", true, Boolean.class);
@@ -92,6 +102,7 @@ public class OperatorTests extends ExpressionTestCase {
}
@Test
public void testGreaterThan() {
evaluate("3 > 5", false, Boolean.class);
evaluate("5 > 3", true, Boolean.class);
@@ -103,18 +114,29 @@ public class OperatorTests extends ExpressionTestCase {
evaluate("'def' > 'abc'",true,Boolean.class);
}
@Test
public void testMultiplyStringInt() {
evaluate("'a' * 5", "aaaaa", String.class);
}
@Test
public void testMultiplyDoubleDoubleGivesDouble() {
evaluate("3.0d * 5.0d", 15.0d, Double.class);
}
@Test
public void testMathOperatorAdd02() {
evaluate("'hello' + ' ' + 'world'", "hello world", String.class);
}
@Test
public void testMathOperatorsInChains() {
evaluate("1+2+3",6,Integer.class);
evaluate("2*3*4",24,Integer.class);
evaluate("12-1-2",9,Integer.class);
}
@Test
public void testIntegerArithmetic() {
evaluate("2 + 4", "6", Integer.class);
evaluate("5 - 4", "1", Integer.class);
@@ -125,6 +147,7 @@ public class OperatorTests extends ExpressionTestCase {
evaluate("3 % 2", 1, Integer.class);
}
@Test
public void testPlus() throws Exception {
evaluate("7 + 2", "9", Integer.class);
evaluate("3.0f + 5.0f", 8.0d, Double.class);
@@ -136,9 +159,9 @@ public class OperatorTests extends ExpressionTestCase {
// AST:
SpelExpression expr = (SpelExpression)parser.parseExpression("+3");
assertEquals("+3",expr.toStringAST());
Assert.assertEquals("+3",expr.toStringAST());
expr = (SpelExpression)parser.parseExpression("2+3");
assertEquals("(2 + 3)",expr.toStringAST());
Assert.assertEquals("(2 + 3)",expr.toStringAST());
// use as a unary operator
evaluate("+5d",5d,Double.class);
@@ -153,15 +176,16 @@ public class OperatorTests extends ExpressionTestCase {
evaluate("5 + new Integer('37')",42,Integer.class);
}
@Test
public void testMinus() throws Exception {
evaluate("'c' - 2", "a", String.class);
evaluate("3.0f - 5.0f", -2.0d, Double.class);
evaluateAndCheckError("'ab' - 2", SpelMessages.OPERATOR_NOT_SUPPORTED_BETWEEN_TYPES);
evaluateAndCheckError("2-'ab'",SpelMessages.OPERATOR_NOT_SUPPORTED_BETWEEN_TYPES);
SpelExpression expr = (SpelExpression)parser.parseExpression("-3");
assertEquals("-3",expr.toStringAST());
Assert.assertEquals("-3",expr.toStringAST());
expr = (SpelExpression)parser.parseExpression("2-3");
assertEquals("(2 - 3)",expr.toStringAST());
Assert.assertEquals("(2 - 3)",expr.toStringAST());
evaluate("-5d",-5d,Double.class);
evaluate("-5L",-5L,Long.class);
@@ -169,28 +193,33 @@ public class OperatorTests extends ExpressionTestCase {
evaluateAndCheckError("-'abc'",SpelMessages.OPERATOR_NOT_SUPPORTED_BETWEEN_TYPES);
}
@Test
public void testModulus() {
evaluate("3%2",1,Integer.class);
evaluate("3L%2L",1L,Long.class);
evaluate("3.0d%2.0d",1d,Double.class);
evaluate("5.0f % 3.1f", 1.9d, Double.class);
evaluate("3.0f%2.0f",1d,Double.class);
evaluate("5.0d % 3.1d", 1.9d, Double.class);
evaluateAndCheckError("'abc'%'def'",SpelMessages.OPERATOR_NOT_SUPPORTED_BETWEEN_TYPES);
}
@Test
public void testDivide() {
evaluate("3.0f / 5.0f", 0.6d, Double.class);
evaluate("4L/2L",2L,Long.class);
evaluateAndCheckError("'abc'/'def'",SpelMessages.OPERATOR_NOT_SUPPORTED_BETWEEN_TYPES);
}
@Test
public void testMathOperatorDivide_ConvertToDouble() {
evaluateAndAskForReturnType("8/4", new Double(2.0), Double.class);
}
@Test
public void testMathOperatorDivide04_ConvertToFloat() {
evaluateAndAskForReturnType("8/4", new Float(2.0), Float.class);
}
@Test
public void testDoubles() {
evaluate("3.0d == 5.0d", false, Boolean.class);
evaluate("3.0d == 3.0d", true, Boolean.class);
@@ -203,49 +232,52 @@ public class OperatorTests extends ExpressionTestCase {
evaluate("6.0d % 3.5d", 2.5d, Double.class);
}
@Test
public void testOperatorNames() throws Exception {
Operator node = getOperatorNode((SpelExpression)parser.parseExpression("1==3"));
assertEquals("==",node.getOperatorName());
Assert.assertEquals("==",node.getOperatorName());
node = getOperatorNode((SpelExpression)parser.parseExpression("1!=3"));
assertEquals("!=",node.getOperatorName());
Assert.assertEquals("!=",node.getOperatorName());
node = getOperatorNode((SpelExpression)parser.parseExpression("3/3"));
assertEquals("/",node.getOperatorName());
Assert.assertEquals("/",node.getOperatorName());
node = getOperatorNode((SpelExpression)parser.parseExpression("3+3"));
assertEquals("+",node.getOperatorName());
Assert.assertEquals("+",node.getOperatorName());
node = getOperatorNode((SpelExpression)parser.parseExpression("3-3"));
assertEquals("-",node.getOperatorName());
Assert.assertEquals("-",node.getOperatorName());
node = getOperatorNode((SpelExpression)parser.parseExpression("3<4"));
assertEquals("<",node.getOperatorName());
Assert.assertEquals("<",node.getOperatorName());
node = getOperatorNode((SpelExpression)parser.parseExpression("3<=4"));
assertEquals("<=",node.getOperatorName());
Assert.assertEquals("<=",node.getOperatorName());
node = getOperatorNode((SpelExpression)parser.parseExpression("3*4"));
assertEquals("*",node.getOperatorName());
Assert.assertEquals("*",node.getOperatorName());
node = getOperatorNode((SpelExpression)parser.parseExpression("3%4"));
assertEquals("%",node.getOperatorName());
Assert.assertEquals("%",node.getOperatorName());
node = getOperatorNode((SpelExpression)parser.parseExpression("3>=4"));
assertEquals(">=",node.getOperatorName());
Assert.assertEquals(">=",node.getOperatorName());
node = getOperatorNode((SpelExpression)parser.parseExpression("3 between 4"));
assertEquals("between",node.getOperatorName());
Assert.assertEquals("between",node.getOperatorName());
node = getOperatorNode((SpelExpression)parser.parseExpression("3 ^ 4"));
assertEquals("^",node.getOperatorName());
Assert.assertEquals("^",node.getOperatorName());
}
@Test
public void testOperatorOverloading() {
evaluateAndCheckError("'a' * '2'", SpelMessages.OPERATOR_NOT_SUPPORTED_BETWEEN_TYPES);
evaluateAndCheckError("'a' ^ '2'", SpelMessages.OPERATOR_NOT_SUPPORTED_BETWEEN_TYPES);
}
@Test
public void testPower() {
evaluate("3^2",9,Integer.class);
evaluate("3.0d^2.0d",9.0d,Double.class);
@@ -253,14 +285,16 @@ public class OperatorTests extends ExpressionTestCase {
evaluate("(2^32)^2",9223372036854775807L,Long.class);
}
@Test
public void testMixedOperands_FloatsAndDoubles() {
evaluate("3.0d + 5.0f", 8.0d, Double.class);
evaluate("3.0D - 5.0f", -2.0d, Double.class);
evaluate("3.0f * 5.0d", 15.0d, Double.class);
evaluate("3.0f / 5.0D", 0.6d, Double.class);
evaluate("5.0D % 3.1f", 1.9d, Double.class);
evaluate("5.0D % 3f", 2.0d, Double.class);
}
@Test
public void testMixedOperands_DoublesAndInts() {
evaluate("3.0d + 5", 8.0d, Double.class);
evaluate("3.0D - 5", -2.0d, Double.class);
@@ -271,6 +305,7 @@ public class OperatorTests extends ExpressionTestCase {
evaluate("5.5D % 3", 2.5, Double.class);
}
@Test
public void testStrings() {
evaluate("'abc' == 'abc'",true,Boolean.class);
evaluate("'abc' == 'def'",false,Boolean.class);
@@ -278,6 +313,7 @@ public class OperatorTests extends ExpressionTestCase {
evaluate("'abc' != 'def'",true,Boolean.class);
}
@Test
public void testLongs() {
evaluate("3L == 4L", false, Boolean.class);
evaluate("3L == 3L", true, Boolean.class);

View File

@@ -16,15 +16,16 @@
package org.springframework.expression.spel;
import org.junit.Test;
/**
* Tests the messages and exceptions that come out for badly formed expressions
*
* @author Andy Clement
*/
public class ParserErrorMessagesTests extends ExpressionTestCase {
// TODO extract expected insert messages into constants (just in case of changes)?
// TODO review poor messages, marked // POOR below
@Test
public void testBrokenExpression01() {
// will not fit into an int, needs L suffix
parseAndCheckError("0xCAFEBABE", SpelMessages.NOT_AN_INTEGER);
@@ -32,26 +33,30 @@ public class ParserErrorMessagesTests extends ExpressionTestCase {
parseAndCheckError("0xCAFEBABECAFEBABEL", SpelMessages.NOT_A_LONG);
}
@Test
public void testBrokenExpression02() {
// rogue 'G' on the end
parseAndCheckError("0xB0BG", SpelMessages.PARSE_PROBLEM, 5, "mismatched input 'G' expecting EOF");
parseAndCheckError("0xB0BG", SpelMessages.MORE_INPUT, 5, "G");
}
@Test
public void testBrokenExpression04() {
// missing right operand
parseAndCheckError("true or ", SpelMessages.PARSE_PROBLEM, -1, "no viable alternative at input '<EOF>'"); // POOR
parseAndCheckError("true or ", SpelMessages.RIGHT_OPERAND_PROBLEM, 5);
}
@Test
public void testBrokenExpression05() {
// missing right operand
parseAndCheckError("1 + ", SpelMessages.PARSE_PROBLEM, -1, "no viable alternative at input '<EOF>'"); // POOR
parseAndCheckError("1 + ", SpelMessages.RIGHT_OPERAND_PROBLEM, 2);
}
@Test
public void testBrokenExpression07() {
// T() can only take an identifier (possibly qualified), not a literal
// message ought to say identifier rather than ID
parseAndCheckError("null instanceof T('a')", SpelMessages.PARSE_PROBLEM, 18,
"mismatched input ''a'' expecting ID"); // POOR
parseAndCheckError("null instanceof T('a')", SpelMessages.NOT_EXPECTED_TOKEN, 18,
"identifier","literal_string");
}
}

View File

@@ -16,10 +16,11 @@
package org.springframework.expression.spel;
import junit.framework.TestCase;
import junit.framework.Assert;
import org.junit.Test;
import org.springframework.expression.ParseException;
import org.springframework.expression.spel.antlr.SpelAntlrExpressionParser;
import org.springframework.expression.spel.standard.SpelExpressionParser;
/**
* Parse some expressions and check we get the AST we expect. Rather than inspecting each node in the AST, we ask it to
@@ -27,105 +28,129 @@ import org.springframework.expression.spel.antlr.SpelAntlrExpressionParser;
*
* @author Andy Clement
*/
public class ParsingTests extends TestCase {
public class ParsingTests {
private SpelAntlrExpressionParser parser = new SpelAntlrExpressionParser();
private SpelExpressionParser parser = new SpelExpressionParser();
// literals
@Test
public void testLiteralBoolean01() {
parseCheck("false");
}
@Test
public void testLiteralLong01() {
parseCheck("37L", "37");
}
@Test
public void testLiteralBoolean02() {
parseCheck("true");
}
@Test
public void testLiteralBoolean03() {
parseCheck("!true");
}
@Test
public void testLiteralInteger01() {
parseCheck("1");
}
@Test
public void testLiteralInteger02() {
parseCheck("1415");
}
@Test
public void testLiteralString01() {
parseCheck("'hello'");
}
@Test
public void testLiteralString02() {
parseCheck("'joe bloggs'");
}
@Test
public void testLiteralString03() {
parseCheck("'Tony''s Pizza'", "'Tony's Pizza'");
}
@Test
public void testLiteralReal01() {
parseCheck("6.0221415E+23", "6.0221415E23");
}
@Test
public void testLiteralHex01() {
parseCheck("0x7FFFFFFF", "2147483647");
}
@Test
public void testLiteralDate01() {
parseCheck("date('1974/08/24')");
}
@Test
public void testLiteralDate02() {
parseCheck("date('19740824T131030','yyyyMMddTHHmmss')");
}
@Test
public void testLiteralNull01() {
parseCheck("null");
}
// boolean operators
@Test
public void testBooleanOperatorsOr01() {
parseCheck("false or false", "(false or false)");
}
@Test
public void testBooleanOperatorsOr02() {
parseCheck("false or true", "(false or true)");
}
@Test
public void testBooleanOperatorsOr03() {
parseCheck("true or false", "(true or false)");
}
@Test
public void testBooleanOperatorsOr04() {
parseCheck("true or false", "(true or false)");
}
@Test
public void testBooleanOperatorsMix01() {
parseCheck("false or true and false", "(false or (true and false))");
}
// relational operators
@Test
public void testRelOperatorsGT01() {
parseCheck("3>6", "(3 > 6)");
}
@Test
public void testRelOperatorsLT01() {
parseCheck("3<6", "(3 < 6)");
}
@Test
public void testRelOperatorsLE01() {
parseCheck("3<=6", "(3 <= 6)");
}
@Test
public void testRelOperatorsGE01() {
parseCheck("3>=6", "(3 >= 6)");
}
@Test
public void testRelOperatorsGE02() {
parseCheck("3>=3", "(3 >= 3)");
}
@@ -142,6 +167,7 @@ public class ParsingTests extends TestCase {
// parseCheck("'efg' between {'abc', 'xyz'}", "('efg' between {'abc','xyz'})");
// }// true
@Test
public void testRelOperatorsIs01() {
parseCheck("'xyz' instanceof int", "('xyz' instanceof int)");
}// false
@@ -150,44 +176,54 @@ public class ParsingTests extends TestCase {
// parseCheck("{1, 2, 3, 4, 5} instanceof List", "({1,2,3,4,5} instanceof List)");
// }// true
@Test
public void testRelOperatorsMatches01() {
parseCheck("'5.0067' matches '^-?\\d+(\\.\\d{2})?$'", "('5.0067' matches '^-?\\d+(\\.\\d{2})?$')");
}// false
@Test
public void testRelOperatorsMatches02() {
parseCheck("'5.00' matches '^-?\\d+(\\.\\d{2})?$'", "('5.00' matches '^-?\\d+(\\.\\d{2})?$')");
}// true
// mathematical operators
@Test
public void testMathOperatorsAdd01() {
parseCheck("2+4", "(2 + 4)");
}
@Test
public void testMathOperatorsAdd02() {
parseCheck("'a'+'b'", "('a' + 'b')");
}
@Test
public void testMathOperatorsAdd03() {
parseCheck("'hello'+' '+'world'", "(('hello' + ' ') + 'world')");
}
@Test
public void testMathOperatorsSubtract01() {
parseCheck("5-4", "(5 - 4)");
}
@Test
public void testMathOperatorsMultiply01() {
parseCheck("7*4", "(7 * 4)");
}
@Test
public void testMathOperatorsDivide01() {
parseCheck("8/4", "(8 / 4)");
}
@Test
public void testMathOperatorModulus01() {
parseCheck("7 % 4", "(7 % 4)");
}
// mixed operators
@Test
public void testMixedOperators01() {
parseCheck("true and 5>3", "(true and (5 > 3))");
}
@@ -239,14 +275,17 @@ public class ParsingTests extends TestCase {
// }// normalized to '.' for separator in QualifiedIdentifier
// properties
@Test
public void testProperties01() {
parseCheck("name");
}
@Test
public void testProperties02() {
parseCheck("placeofbirth.CitY");
}
@Test
public void testProperties03() {
parseCheck("a.b.c.d.e");
}
@@ -278,19 +317,23 @@ public class ParsingTests extends TestCase {
// }
// methods
@Test
public void testMethods01() {
parseCheck("echo(12)");
}
@Test
public void testMethods02() {
parseCheck("echo(name)");
}
@Test
public void testMethods03() {
parseCheck("age.doubleItAndAdd(12)");
}
// constructors
@Test
public void testConstructors01() {
parseCheck("new String('hello')");
}
@@ -309,14 +352,17 @@ public class ParsingTests extends TestCase {
// }
// variables and functions
@Test
public void testVariables01() {
parseCheck("#foo");
}
@Test
public void testFunctions01() {
parseCheck("#fn(1,2,3)");
}
@Test
public void testFunctions02() {
parseCheck("#fn('hello')");
}
@@ -342,6 +388,7 @@ public class ParsingTests extends TestCase {
// }
// assignment
@Test
public void testAssignmentToVariables01() {
parseCheck("#var1='value1'");
}
@@ -349,6 +396,7 @@ public class ParsingTests extends TestCase {
// ternary operator
@Test
public void testTernaryOperator01() {
parseCheck("1>2?3:4","(1 > 2) ? 3 : 4");
}
@@ -369,10 +417,12 @@ public class ParsingTests extends TestCase {
// } // 120
// Type references
@Test
public void testTypeReferences01() {
parseCheck("T(java.lang.String)");
}
@Test
public void testTypeReferences02() {
parseCheck("T(String)");
}
@@ -401,12 +451,12 @@ public class ParsingTests extends TestCase {
SpelUtilities.printAbstractSyntaxTree(System.err, e);
}
if (e == null) {
fail("Parsed exception was null");
Assert.fail("Parsed exception was null");
}
assertEquals("String form of AST does not match expected output", expectedStringFormOfAST, e.toStringAST());
Assert.assertEquals("String form of AST does not match expected output", expectedStringFormOfAST, e.toStringAST());
} catch (ParseException ee) {
ee.printStackTrace();
fail("Unexpected Exception: " + ee.getMessage());
Assert.fail("Unexpected Exception: " + ee.getMessage());
}
}

View File

@@ -16,27 +16,31 @@
package org.springframework.expression.spel;
import junit.framework.TestCase;
import junit.framework.Assert;
import org.junit.Test;
import org.springframework.expression.EvaluationContext;
import org.springframework.expression.Expression;
import org.springframework.expression.spel.antlr.SpelAntlrExpressionParser;
import org.springframework.expression.ExpressionParser;
///CLOVER:OFF
/**
* Tests the evaluation of real expressions in a real context.
*
* @author Andy Clement
*/
public class PerformanceTests extends TestCase {
public class PerformanceTests {
public static final int ITERATIONS = 10000;
public static final boolean report = true;
private static SpelAntlrExpressionParser parser = new SpelAntlrExpressionParser();
private static ExpressionParser parser = SpelExpressionParserFactory.getParser();
private static EvaluationContext eContext = TestScenarioCreator.getTestEvaluationContext();
private static final boolean DEBUG = false;
@Test
public void testPerformanceOfPropertyAccess() throws Exception {
long starttime = 0;
long endtime = 0;
@@ -45,18 +49,18 @@ public class PerformanceTests extends TestCase {
for (int i = 0; i < ITERATIONS; i++) {
Expression expr = parser.parseExpression("placeOfBirth.city");
if (expr == null) {
fail("Parser returned null for expression");
Assert.fail("Parser returned null for expression");
}
Object value = expr.getValue(eContext);
expr.getValue(eContext);
}
starttime = System.currentTimeMillis();
for (int i = 0; i < ITERATIONS; i++) {
Expression expr = parser.parseExpression("placeOfBirth.city");
if (expr == null) {
fail("Parser returned null for expression");
Assert.fail("Parser returned null for expression");
}
Object value = expr.getValue(eContext);
expr.getValue(eContext);
}
endtime = System.currentTimeMillis();
long freshParseTime = endtime - starttime;
@@ -66,11 +70,11 @@ public class PerformanceTests extends TestCase {
Expression expr = parser.parseExpression("placeOfBirth.city");
if (expr == null) {
fail("Parser returned null for expression");
Assert.fail("Parser returned null for expression");
}
starttime = System.currentTimeMillis();
for (int i = 0; i < ITERATIONS; i++) {
Object value = expr.getValue(eContext);
expr.getValue(eContext);
}
endtime = System.currentTimeMillis();
long reuseTime = endtime - starttime;
@@ -80,7 +84,7 @@ public class PerformanceTests extends TestCase {
if (reuseTime > freshParseTime) {
System.out.println("Fresh parse every time, ITERATIONS iterations = " + freshParseTime + "ms");
System.out.println("Reuse SpelExpression, ITERATIONS iterations = " + reuseTime + "ms");
fail("Should have been quicker to reuse!");
Assert.fail("Should have been quicker to reuse!");
}
}
@@ -92,18 +96,18 @@ public class PerformanceTests extends TestCase {
for (int i = 0; i < ITERATIONS; i++) {
Expression expr = parser.parseExpression("getPlaceOfBirth().getCity()");
if (expr == null) {
fail("Parser returned null for expression");
Assert.fail("Parser returned null for expression");
}
Object value = expr.getValue(eContext);
expr.getValue(eContext);
}
starttime = System.currentTimeMillis();
for (int i = 0; i < ITERATIONS; i++) {
Expression expr = parser.parseExpression("getPlaceOfBirth().getCity()");
if (expr == null) {
fail("Parser returned null for expression");
Assert.fail("Parser returned null for expression");
}
Object value = expr.getValue(eContext);
expr.getValue(eContext);
}
endtime = System.currentTimeMillis();
long freshParseTime = endtime - starttime;
@@ -113,11 +117,11 @@ public class PerformanceTests extends TestCase {
Expression expr = parser.parseExpression("getPlaceOfBirth().getCity()");
if (expr == null) {
fail("Parser returned null for expression");
Assert.fail("Parser returned null for expression");
}
starttime = System.currentTimeMillis();
for (int i = 0; i < ITERATIONS; i++) {
Object value = expr.getValue(eContext);
expr.getValue(eContext);
}
endtime = System.currentTimeMillis();
long reuseTime = endtime - starttime;
@@ -128,7 +132,7 @@ public class PerformanceTests extends TestCase {
if (reuseTime > freshParseTime) {
System.out.println("Fresh parse every time, ITERATIONS iterations = " + freshParseTime + "ms");
System.out.println("Reuse SpelExpression, ITERATIONS iterations = " + reuseTime + "ms");
fail("Should have been quicker to reuse!");
Assert.fail("Should have been quicker to reuse!");
}
}

View File

@@ -16,16 +16,21 @@
package org.springframework.expression.spel;
import junit.framework.Assert;
import org.junit.Test;
import org.springframework.expression.AccessException;
import org.springframework.expression.EvaluationContext;
import org.springframework.expression.EvaluationException;
import org.springframework.expression.Expression;
import org.springframework.expression.PropertyAccessor;
import org.springframework.expression.TypedValue;
import org.springframework.expression.spel.antlr.SpelAntlrExpressionParser;
import org.springframework.expression.spel.ast.CommonTypeDescriptors;
import org.springframework.expression.spel.standard.SpelExpressionParser;
import org.springframework.expression.spel.support.StandardEvaluationContext;
///CLOVER:OFF
/**
* Tests accessing of properties.
*
@@ -33,18 +38,22 @@ import org.springframework.expression.spel.support.StandardEvaluationContext;
*/
public class PropertyAccessTests extends ExpressionTestCase {
@Test
public void testSimpleAccess01() {
evaluate("name", "Nikola Tesla", String.class);
}
@Test
public void testSimpleAccess02() {
evaluate("placeOfBirth.city", "SmilJan", String.class);
}
@Test
public void testSimpleAccess03() {
evaluate("stringArrayOfThreeItems.length", "3", Integer.class);
}
@Test
public void testNonExistentPropertiesAndMethods() {
// madeup does not exist as a property
evaluateAndCheckError("madeup", SpelMessages.PROPERTY_OR_FIELD_NOT_READABLE, 0);
@@ -57,36 +66,38 @@ public class PropertyAccessTests extends ExpressionTestCase {
* The standard reflection resolver cannot find properties on null objects but some
* supplied resolver might be able to - so null shouldn't crash the reflection resolver.
*/
@Test
public void testAccessingOnNullObject() throws Exception {
SpelExpression expr = (SpelExpression)parser.parseExpression("madeup");
EvaluationContext context = new StandardEvaluationContext(null);
try {
expr.getValue(context);
fail("Should have failed - default property resolver cannot resolve on null");
Assert.fail("Should have failed - default property resolver cannot resolve on null");
} catch (Exception e) {
checkException(e,SpelMessages.PROPERTY_OR_FIELD_NOT_READABLE_ON_NULL);
}
assertFalse(expr.isWritable(context));
Assert.assertFalse(expr.isWritable(context));
try {
expr.setValue(context,"abc");
fail("Should have failed - default property resolver cannot resolve on null");
Assert.fail("Should have failed - default property resolver cannot resolve on null");
} catch (Exception e) {
checkException(e,SpelMessages.PROPERTY_OR_FIELD_NOT_WRITABLE_ON_NULL);
}
}
private void checkException(Exception e, SpelMessages expectedMessage) {
if (e instanceof SpelException) {
SpelMessages sm = ((SpelException)e).getMessageUnformatted();
assertEquals("Expected exception type did not occur",expectedMessage,sm);
if (e instanceof SpelEvaluationException) {
SpelMessages sm = ((SpelEvaluationException)e).getMessageUnformatted();
Assert.assertEquals("Expected exception type did not occur",expectedMessage,sm);
} else {
fail("Should be a SpelException "+e);
Assert.fail("Should be a SpelException "+e);
}
}
@Test
// Adding a new property accessor just for a particular type
public void testAddingSpecificPropertyAccessor() throws Exception {
SpelAntlrExpressionParser parser = new SpelAntlrExpressionParser();
SpelExpressionParser parser = new SpelExpressionParser();
StandardEvaluationContext ctx = new StandardEvaluationContext();
// Even though this property accessor is added after the reflection one, it specifically
@@ -95,22 +106,22 @@ public class PropertyAccessTests extends ExpressionTestCase {
ctx.addPropertyAccessor(new StringyPropertyAccessor());
Expression expr = parser.parseExpression("new String('hello').flibbles");
Integer i = expr.getValue(ctx, Integer.class);
assertEquals((int) i, 7);
Assert.assertEquals((int) i, 7);
// The reflection one will be used for other properties...
expr = parser.parseExpression("new String('hello').CASE_INSENSITIVE_ORDER");
Object o = expr.getValue(ctx);
assertNotNull(o);
Assert.assertNotNull(o);
expr = parser.parseExpression("new String('hello').flibbles");
expr.setValue(ctx, 99);
i = expr.getValue(ctx, Integer.class);
assertEquals((int) i, 99);
Assert.assertEquals((int) i, 99);
// Cannot set it to a string value
try {
expr.setValue(ctx, "not allowed");
fail("Should not have been allowed");
Assert.fail("Should not have been allowed");
} catch (EvaluationException e) {
// success - message will be: EL1063E:(pos 20): A problem occurred whilst attempting to set the property
// 'flibbles': 'Cannot set flibbles to an object of type 'class java.lang.String''

View File

@@ -18,6 +18,9 @@ package org.springframework.expression.spel;
import java.lang.reflect.Method;
import junit.framework.Assert;
import org.junit.Test;
import org.springframework.core.MethodParameter;
import org.springframework.core.convert.TypeDescriptor;
import org.springframework.expression.AccessException;
@@ -29,7 +32,7 @@ import org.springframework.expression.MethodResolver;
import org.springframework.expression.PropertyAccessor;
import org.springframework.expression.TypeConverter;
import org.springframework.expression.TypedValue;
import org.springframework.expression.spel.antlr.SpelAntlrExpressionParser;
import org.springframework.expression.spel.standard.SpelExpressionParser;
import org.springframework.expression.spel.support.ReflectionHelper;
import org.springframework.expression.spel.support.StandardEvaluationContext;
@@ -41,28 +44,30 @@ import org.springframework.expression.spel.support.StandardEvaluationContext;
*/
public class ScenariosForSpringSecurity extends ExpressionTestCase {
@Test
public void testScenario01_Roles() throws Exception {
try {
SpelAntlrExpressionParser parser = new SpelAntlrExpressionParser();
SpelExpressionParser parser = new SpelExpressionParser();
StandardEvaluationContext ctx = new StandardEvaluationContext();
Expression expr = parser.parseExpression("hasAnyRole('MANAGER','TELLER')");
ctx.setRootObject(new Person("Ben"));
Boolean value = expr.getValue(ctx,Boolean.class);
assertFalse(value);
Assert.assertFalse(value);
ctx.setRootObject(new Manager("Luke"));
value = expr.getValue(ctx,Boolean.class);
assertTrue(value);
Assert.assertTrue(value);
} catch (EvaluationException ee) {
ee.printStackTrace();
fail("Unexpected SpelException: " + ee.getMessage());
Assert.fail("Unexpected SpelException: " + ee.getMessage());
}
}
@Test
public void testScenario02_ComparingNames() throws Exception {
SpelAntlrExpressionParser parser = new SpelAntlrExpressionParser();
SpelExpressionParser parser = new SpelExpressionParser();
StandardEvaluationContext ctx = new StandardEvaluationContext();
ctx.addPropertyAccessor(new SecurityPrincipalAccessor());
@@ -73,11 +78,11 @@ public class ScenariosForSpringSecurity extends ExpressionTestCase {
ctx.setRootObject(new Person("Andy"));
Boolean value = expr.getValue(ctx,Boolean.class);
assertTrue(value);
Assert.assertTrue(value);
ctx.setRootObject(new Person("Christian"));
value = expr.getValue(ctx,Boolean.class);
assertFalse(value);
Assert.assertFalse(value);
// (2) Or register an accessor that can understand 'p' and return the right person
expr = parser.parseExpression("p.name == principal.name");
@@ -88,15 +93,16 @@ public class ScenariosForSpringSecurity extends ExpressionTestCase {
pAccessor.setPerson(new Person("Andy"));
value = expr.getValue(ctx,Boolean.class);
assertTrue(value);
Assert.assertTrue(value);
pAccessor.setPerson(new Person("Christian"));
value = expr.getValue(ctx,Boolean.class);
assertFalse(value);
Assert.assertFalse(value);
}
@Test
public void testScenario03_Arithmetic() throws Exception {
SpelAntlrExpressionParser parser = new SpelAntlrExpressionParser();
SpelExpressionParser parser = new SpelExpressionParser();
StandardEvaluationContext ctx = new StandardEvaluationContext();
// Might be better with a as a variable although it would work as a property too...
@@ -108,17 +114,18 @@ public class ScenariosForSpringSecurity extends ExpressionTestCase {
ctx.setVariable("a",1.0d); // referenced as #a in the expression
ctx.setRootObject(new Supervisor("Ben")); // so non-qualified references 'hasRole()' 'hasIpAddress()' are invoked against it
value = expr.getValue(ctx,Boolean.class);
assertTrue(value);
Assert.assertTrue(value);
ctx.setRootObject(new Manager("Luke"));
ctx.setVariable("a",1.043d);
value = expr.getValue(ctx,Boolean.class);
assertFalse(value);
Assert.assertFalse(value);
}
// Here i'm going to change which hasRole() executes and make it one of my own Java methods
@Test
public void testScenario04_ControllingWhichMethodsRun() throws Exception {
SpelAntlrExpressionParser parser = new SpelAntlrExpressionParser();
SpelExpressionParser parser = new SpelExpressionParser();
StandardEvaluationContext ctx = new StandardEvaluationContext();
ctx.setRootObject(new Supervisor("Ben")); // so non-qualified references 'hasRole()' 'hasIpAddress()' are invoked against it);
@@ -133,7 +140,7 @@ public class ScenariosForSpringSecurity extends ExpressionTestCase {
ctx.setVariable("a",1.0d); // referenced as #a in the expression
value = expr.getValue(ctx,Boolean.class);
assertTrue(value);
Assert.assertTrue(value);
// ctx.setRootObject(new Manager("Luke"));
// ctx.setVariable("a",1.043d);

View File

@@ -20,6 +20,9 @@ import java.util.ArrayList;
import java.util.Collection;
import java.util.Set;
import junit.framework.Assert;
import org.junit.Test;
import org.springframework.expression.EvaluationException;
import org.springframework.expression.Expression;
import org.springframework.expression.ParseException;
@@ -37,22 +40,27 @@ public class SetValueTests extends ExpressionTestCase {
private final static boolean DEBUG = false;
@Test
public void testSetProperty() {
setValue("wonNobelPrize", true);
}
@Test
public void testSetNestedProperty() {
setValue("placeOfBirth.city", "Wien");
}
@Test
public void testSetArrayElementValue() {
setValue("inventions[0]", "Just the telephone");
}
@Test
public void testSetElementOfNull() {
setValueExpectError("new org.springframework.expression.spel.testresources.Inventor().inventions[1]",SpelMessages.CANNOT_INDEX_INTO_NULL_VALUE);
}
@Test
public void testSetArrayElementValueAllPrimitiveTypes() {
setValue("arrayContainer.ints[1]", 3);
setValue("arrayContainer.floats[1]", 3.0f);
@@ -64,6 +72,7 @@ public class SetValueTests extends ExpressionTestCase {
setValue("arrayContainer.chars[1]", (char) 3);
}
@Test
public void testSetArrayElementValueAllPrimitiveTypesErrors() {
// none of these sets are possible due to (expected) conversion problems
setValueExpectError("arrayContainer.ints[1]", "wibble");
@@ -76,62 +85,74 @@ public class SetValueTests extends ExpressionTestCase {
setValueExpectError("arrayContainer.chars[1]", "NaC");
}
@Test
public void testSetArrayElementNestedValue() {
setValue("placesLived[0].city", "Wien");
}
@Test
public void testSetListElementValue() {
setValue("placesLivedList[0]", new PlaceOfBirth("Wien"));
}
public void testSetGenericListElementValueTypeCoersionFail() {
@Test
public void testSetGenericListElementValueTypeCoersionfail() {
// no type converter registered for String > PlaceOfBirth
setValueExpectError("placesLivedList[0]", "Wien");
}
@Test
public void testSetGenericListElementValueTypeCoersionOK() {
setValue("booleanList[0]", "true", Boolean.TRUE);
}
@Test
public void testSetListElementNestedValue() {
setValue("placesLived[0].city", "Wien");
}
@Test
public void testSetArrayElementInvalidIndex() {
setValueExpectError("placesLived[23]", "Wien");
setValueExpectError("placesLivedList[23]", "Wien");
}
@Test
public void testSetMapElements() {
setValue("testMap['montag']","lundi");
}
@Test
public void testIndexingIntoUnsupportedType() {
setValueExpectError("'hello'[3]", 'p');
}
@Test
public void testSetPropertyTypeCoersion() {
setValue("publicBoolean", "true", Boolean.TRUE);
}
@Test
public void testSetPropertyTypeCoersionThroughSetter() {
setValue("SomeProperty", "true", Boolean.TRUE);
}
@Test
public void testAssign() throws Exception {
StandardEvaluationContext eContext = TestScenarioCreator.getTestEvaluationContext();
Expression e = parse("publicName='Andy'");
assertFalse(e.isWritable(eContext));
assertEquals("Andy",e.getValue(eContext));
Assert.assertFalse(e.isWritable(eContext));
Assert.assertEquals("Andy",e.getValue(eContext));
}
/*
* Testing the coercion of both the keys and the values to the correct type
*/
@Test
public void testSetGenericMapElementRequiresCoercion() throws Exception {
StandardEvaluationContext eContext = TestScenarioCreator.getTestEvaluationContext();
Expression e = parse("mapOfStringToBoolean[42]");
assertNull(e.getValue(eContext));
Assert.assertNull(e.getValue(eContext));
// Key should be coerced to string representation of 42
e.setValue(eContext, "true");
@@ -139,18 +160,18 @@ public class SetValueTests extends ExpressionTestCase {
// All keys should be strings
Set ks = parse("mapOfStringToBoolean.keySet()").getValue(eContext,Set.class);
for (Object o: ks) {
assertEquals(String.class,o.getClass());
Assert.assertEquals(String.class,o.getClass());
}
// All values should be booleans
Collection vs = parse("mapOfStringToBoolean.values()").getValue(eContext,Collection.class);
for (Object o: vs) {
assertEquals(Boolean.class,o.getClass());
Assert.assertEquals(Boolean.class,o.getClass());
}
// One final test check coercion on the key for a map lookup
Object o = e.getValue(eContext);
assertEquals(Boolean.TRUE,o);
Assert.assertEquals(Boolean.TRUE,o);
}
@@ -165,17 +186,17 @@ public class SetValueTests extends ExpressionTestCase {
try {
Expression e = parser.parseExpression(expression);
if (e == null) {
fail("Parser returned null for expression");
Assert.fail("Parser returned null for expression");
}
if (DEBUG) {
SpelUtilities.printAbstractSyntaxTree(System.out, e);
}
StandardEvaluationContext lContext = TestScenarioCreator.getTestEvaluationContext();
e.setValue(lContext, value);
fail("expected an error");
Assert.fail("expected an error");
} catch (ParseException pe) {
pe.printStackTrace();
fail("Unexpected Exception: " + pe.getMessage());
Assert.fail("Unexpected Exception: " + pe.getMessage());
} catch (EvaluationException ee) {
// success!
}
@@ -185,21 +206,21 @@ public class SetValueTests extends ExpressionTestCase {
try {
Expression e = parser.parseExpression(expression);
if (e == null) {
fail("Parser returned null for expression");
Assert.fail("Parser returned null for expression");
}
if (DEBUG) {
SpelUtilities.printAbstractSyntaxTree(System.out, e);
}
StandardEvaluationContext lContext = TestScenarioCreator.getTestEvaluationContext();
assertTrue("Expression is not writeable but should be", e.isWritable(lContext));
Assert.assertTrue("Expression is not writeable but should be", e.isWritable(lContext));
e.setValue(lContext, value);
assertEquals("Retrieved value was not equal to set value", value, e.getValue(lContext));
Assert.assertEquals("Retrieved value was not equal to set value", value, e.getValue(lContext));
} catch (EvaluationException ee) {
ee.printStackTrace();
fail("Unexpected Exception: " + ee.getMessage());
Assert.fail("Unexpected Exception: " + ee.getMessage());
} catch (ParseException pe) {
pe.printStackTrace();
fail("Unexpected Exception: " + pe.getMessage());
Assert.fail("Unexpected Exception: " + pe.getMessage());
}
}
@@ -211,26 +232,26 @@ public class SetValueTests extends ExpressionTestCase {
try {
Expression e = parser.parseExpression(expression);
if (e == null) {
fail("Parser returned null for expression");
Assert.fail("Parser returned null for expression");
}
if (DEBUG) {
SpelUtilities.printAbstractSyntaxTree(System.out, e);
}
StandardEvaluationContext lContext = TestScenarioCreator.getTestEvaluationContext();
assertTrue("Expression is not writeable but should be", e.isWritable(lContext));
Assert.assertTrue("Expression is not writeable but should be", e.isWritable(lContext));
e.setValue(lContext, value);
Object a = expectedValue;
Object b = e.getValue(lContext);
if (!a.equals(b)) {
fail("Not the same: ["+a+"] type="+a.getClass()+" ["+b+"] type="+b.getClass());
// assertEquals("Retrieved value was not equal to set value", expectedValue, e.getValue(lContext));
Assert.fail("Not the same: ["+a+"] type="+a.getClass()+" ["+b+"] type="+b.getClass());
// Assert.assertEquals("Retrieved value was not equal to set value", expectedValue, e.getValue(lContext));
}
} catch (EvaluationException ee) {
ee.printStackTrace();
fail("Unexpected Exception: " + ee.getMessage());
Assert.fail("Unexpected Exception: " + ee.getMessage());
} catch (ParseException pe) {
pe.printStackTrace();
fail("Unexpected Exception: " + pe.getMessage());
Assert.fail("Unexpected Exception: " + pe.getMessage());
}
}
}

View File

@@ -24,11 +24,14 @@ import java.util.HashMap;
import java.util.List;
import java.util.Map;
import junit.framework.Assert;
import org.junit.Test;
import org.springframework.expression.EvaluationContext;
import org.springframework.expression.Expression;
import org.springframework.expression.ExpressionParser;
import org.springframework.expression.ParserContext;
import org.springframework.expression.spel.antlr.SpelAntlrExpressionParser;
import org.springframework.expression.spel.standard.SpelExpressionParser;
import org.springframework.expression.spel.support.StandardEvaluationContext;
import org.springframework.expression.spel.testresources.Inventor;
import org.springframework.expression.spel.testresources.PlaceOfBirth;
@@ -68,6 +71,7 @@ public class SpelDocumentationTests extends ExpressionTestCase {
public Inventor[] Members = new Inventor[1];
public List Members2 = new ArrayList();
public Map<String,Object> officers = new HashMap<String,Object>();
@SuppressWarnings("unchecked")
IEEE() {
officers.put("president",pupin);
List linv = new ArrayList();
@@ -85,18 +89,22 @@ public class SpelDocumentationTests extends ExpressionTestCase {
public void setName(String n) { this.name = n; }
}
@Test
public void testMethodInvocation() {
evaluate("'Hello World'.concat('!')","Hello World!",String.class);
}
@Test
public void testBeanPropertyAccess() {
evaluate("new String('Hello World'.bytes)","Hello World",String.class);
}
@Test
public void testArrayLengthAccess() {
evaluate("'Hello World'.bytes.length",11,Integer.class);
}
@Test
public void testRootObject() throws Exception {
GregorianCalendar c = new GregorianCalendar();
c.set(1856, 7, 9);
@@ -104,65 +112,70 @@ public class SpelDocumentationTests extends ExpressionTestCase {
// The constructor arguments are name, birthday, and nationaltiy.
Inventor tesla = new Inventor("Nikola Tesla", c.getTime(), "Serbian");
ExpressionParser parser = new SpelAntlrExpressionParser();
ExpressionParser parser = new SpelExpressionParser();
Expression exp = parser.parseExpression("name");
EvaluationContext context = new StandardEvaluationContext();
context.setRootObject(tesla);
String name = (String) exp.getValue(context);
assertEquals("Nikola Tesla",name);
Assert.assertEquals("Nikola Tesla",name);
}
@Test
public void testEqualityCheck() throws Exception {
ExpressionParser parser = new SpelAntlrExpressionParser();
ExpressionParser parser = new SpelExpressionParser();
EvaluationContext context = new StandardEvaluationContext();
context.setRootObject(tesla);
Expression exp = parser.parseExpression("name == 'Nikola Tesla'");
boolean isEqual = exp.getValue(context, Boolean.class); // evaluates to true
assertTrue(isEqual);
Assert.assertTrue(isEqual);
}
// Section 7.4.1
@Test
public void testXMLBasedConfig() {
evaluate("(T(java.lang.Math).random() * 100.0 )>0",true,Boolean.class);
}
// Section 7.5
@Test
public void testLiterals() throws Exception {
ExpressionParser parser = new SpelAntlrExpressionParser();
ExpressionParser parser = new SpelExpressionParser();
String helloWorld = (String) parser.parseExpression("'Hello World'").getValue(); // evals to "Hello World"
assertEquals("Hello World",helloWorld);
Assert.assertEquals("Hello World",helloWorld);
double avogadrosNumber = (Double) parser.parseExpression("6.0221415E+23").getValue();
assertEquals(6.0221415E+23,avogadrosNumber);
Assert.assertEquals(6.0221415E+23,avogadrosNumber);
int maxValue = (Integer) parser.parseExpression("0x7FFFFFFF").getValue(); // evals to 2147483647
assertEquals(Integer.MAX_VALUE,maxValue);
Assert.assertEquals(Integer.MAX_VALUE,maxValue);
boolean trueValue = (Boolean) parser.parseExpression("true").getValue();
assertTrue(trueValue);
Assert.assertTrue(trueValue);
Object nullValue = parser.parseExpression("null").getValue();
assertNull(nullValue);
Assert.assertNull(nullValue);
}
@Test
public void testPropertyAccess() throws Exception {
EvaluationContext context = TestScenarioCreator.getTestEvaluationContext();
int year = (Integer) parser.parseExpression("Birthdate.Year + 1900").getValue(context); // 1856
assertEquals(1856,year);
Assert.assertEquals(1856,year);
String city = (String) parser.parseExpression("placeOfBirth.City").getValue(context);
assertEquals("SmilJan",city);
Assert.assertEquals("SmilJan",city);
}
@Test
public void testPropertyNavigation() throws Exception {
ExpressionParser parser = new SpelAntlrExpressionParser();
ExpressionParser parser = new SpelExpressionParser();
// Inventions Array
StandardEvaluationContext teslaContext = TestScenarioCreator.getTestEvaluationContext();
@@ -170,7 +183,7 @@ public class SpelDocumentationTests extends ExpressionTestCase {
// evaluates to "Induction motor"
String invention = parser.parseExpression("inventions[3]").getValue(teslaContext, String.class);
assertEquals("Induction motor",invention);
Assert.assertEquals("Induction motor",invention);
// Members List
StandardEvaluationContext societyContext = new StandardEvaluationContext();
@@ -180,15 +193,16 @@ public class SpelDocumentationTests extends ExpressionTestCase {
// evaluates to "Nikola Tesla"
String name = parser.parseExpression("Members[0].Name").getValue(societyContext, String.class);
assertEquals("Nikola Tesla",name);
Assert.assertEquals("Nikola Tesla",name);
// List and Array navigation
// evaluates to "Wireless communication"
invention = parser.parseExpression("Members[0].Inventions[6]").getValue(societyContext, String.class);
assertEquals("Wireless communication",invention);
Assert.assertEquals("Wireless communication",invention);
}
@Test
public void testDictionaryAccess() throws Exception {
StandardEvaluationContext societyContext = new StandardEvaluationContext();
societyContext.setRootObject(new IEEE());
@@ -200,7 +214,7 @@ public class SpelDocumentationTests extends ExpressionTestCase {
// setting values
Inventor i = parser.parseExpression("officers['advisors'][0]").getValue(societyContext,Inventor.class);
assertEquals("Nikola Tesla",i.getName());
Assert.assertEquals("Nikola Tesla",i.getName());
parser.parseExpression("officers['advisors'][0].PlaceOfBirth.Country").setValue(societyContext, "Croatia");
@@ -208,48 +222,52 @@ public class SpelDocumentationTests extends ExpressionTestCase {
// 7.5.3
@Test
public void testMethodInvocation2() throws Exception {
// string literal, evaluates to "bc"
String c = parser.parseExpression("'abc'.substring(1, 3)").getValue(String.class);
assertEquals("bc",c);
Assert.assertEquals("bc",c);
StandardEvaluationContext societyContext = new StandardEvaluationContext();
societyContext.setRootObject(new IEEE());
// evaluates to true
boolean isMember = parser.parseExpression("isMember('Mihajlo Pupin')").getValue(societyContext, Boolean.class);
assertTrue(isMember);
Assert.assertTrue(isMember);
}
// 7.5.4.1
@Test
public void testRelationalOperators() throws Exception {
boolean result = parser.parseExpression("2 == 2").getValue(Boolean.class);
assertTrue(result);
Assert.assertTrue(result);
// evaluates to false
result = parser.parseExpression("2 < -5.0").getValue(Boolean.class);
assertFalse(result);
Assert.assertFalse(result);
// evaluates to true
result = parser.parseExpression("'black' < 'block'").getValue(Boolean.class);
assertTrue(result);
Assert.assertTrue(result);
}
@Test
public void testOtherOperators() throws Exception {
// evaluates to false
boolean falseValue = parser.parseExpression("'xyz' instanceof T(int)").getValue(Boolean.class);
assertFalse(falseValue);
Assert.assertFalse(falseValue);
// evaluates to true
boolean trueValue = parser.parseExpression("'5.00' matches '^-?\\d+(\\.\\d{2})?$'").getValue(Boolean.class);
assertTrue(trueValue);
Assert.assertTrue(trueValue);
//evaluates to false
falseValue = parser.parseExpression("'5.0067' matches '^-?\\d+(\\.\\d{2})?$'").getValue(Boolean.class);
assertFalse(falseValue);
Assert.assertFalse(falseValue);
}
// 7.5.4.2
@Test
public void testLogicalOperators() throws Exception {
StandardEvaluationContext societyContext = new StandardEvaluationContext();
@@ -259,7 +277,7 @@ public class SpelDocumentationTests extends ExpressionTestCase {
// evaluates to false
boolean falseValue = parser.parseExpression("true and false").getValue(Boolean.class);
assertFalse(falseValue);
Assert.assertFalse(falseValue);
// evaluates to true
String expression = "isMember('Nikola Tesla') and isMember('Mihajlo Pupin')";
boolean trueValue = parser.parseExpression(expression).getValue(societyContext, Boolean.class);
@@ -268,71 +286,73 @@ public class SpelDocumentationTests extends ExpressionTestCase {
// evaluates to true
trueValue = parser.parseExpression("true or false").getValue(Boolean.class);
assertTrue(trueValue);
Assert.assertTrue(trueValue);
// evaluates to true
expression = "isMember('Nikola Tesla') or isMember('Albert Einstien')";
trueValue = parser.parseExpression(expression).getValue(societyContext, Boolean.class);
assertTrue(trueValue);
Assert.assertTrue(trueValue);
// -- NOT --
// evaluates to false
falseValue = parser.parseExpression("!true").getValue(Boolean.class);
assertFalse(falseValue);
Assert.assertFalse(falseValue);
// -- AND and NOT --
expression = "isMember('Nikola Tesla') and !isMember('Mihajlo Pupin')";
falseValue = parser.parseExpression(expression).getValue(societyContext, Boolean.class);
assertFalse(falseValue);
Assert.assertFalse(falseValue);
}
// 7.5.4.3
@Test
public void testNumericalOperators() throws Exception {
// Addition
int two = parser.parseExpression("1 + 1").getValue(Integer.class); // 2
assertEquals(2,two);
Assert.assertEquals(2,two);
String testString = parser.parseExpression("'test' + ' ' + 'string'").getValue(String.class); // 'test string'
assertEquals("test string",testString);
Assert.assertEquals("test string",testString);
// Subtraction
int four = parser.parseExpression("1 - -3").getValue(Integer.class); // 4
assertEquals(4,four);
Assert.assertEquals(4,four);
double d = parser.parseExpression("1000.00 - 1e4").getValue(Double.class); // -9000
assertEquals(-9000.0d,d);
Assert.assertEquals(-9000.0d,d);
// Multiplication
int six = parser.parseExpression("-2 * -3").getValue(Integer.class); // 6
assertEquals(6,six);
Assert.assertEquals(6,six);
double twentyFour = parser.parseExpression("2.0 * 3e0 * 4").getValue(Double.class); // 24.0
assertEquals(24.0d,twentyFour);
Assert.assertEquals(24.0d,twentyFour);
// Division
int minusTwo = parser.parseExpression("6 / -3").getValue(Integer.class); // -2
assertEquals(-2,minusTwo);
Assert.assertEquals(-2,minusTwo);
double one = parser.parseExpression("8.0 / 4e0 / 2").getValue(Double.class); // 1.0
assertEquals(1.0d,one);
Assert.assertEquals(1.0d,one);
// Modulus
int three = parser.parseExpression("7 % 4").getValue(Integer.class); // 3
assertEquals(3,three);
Assert.assertEquals(3,three);
int oneInt = parser.parseExpression("8 / 5 % 2").getValue(Integer.class); // 1
assertEquals(1,oneInt);
Assert.assertEquals(1,oneInt);
// Operator precedence
int minusTwentyOne = parser.parseExpression("1+2-3*8").getValue(Integer.class); // -21
assertEquals(-21,minusTwentyOne);
Assert.assertEquals(-21,minusTwentyOne);
}
// 7.5.5
@Test
public void testAssignment() throws Exception {
Inventor inventor = new Inventor();
StandardEvaluationContext inventorContext = new StandardEvaluationContext();
@@ -340,37 +360,40 @@ public class SpelDocumentationTests extends ExpressionTestCase {
parser.parseExpression("foo").setValue(inventorContext, "Alexander Seovic2");
assertEquals("Alexander Seovic2",parser.parseExpression("foo").getValue(inventorContext,String.class));
Assert.assertEquals("Alexander Seovic2",parser.parseExpression("foo").getValue(inventorContext,String.class));
// alternatively
String aleks = parser.parseExpression("foo = 'Alexandar Seovic'").getValue(inventorContext, String.class);
assertEquals("Alexandar Seovic",parser.parseExpression("foo").getValue(inventorContext,String.class));
assertEquals("Alexandar Seovic",aleks);
Assert.assertEquals("Alexandar Seovic",parser.parseExpression("foo").getValue(inventorContext,String.class));
Assert.assertEquals("Alexandar Seovic",aleks);
}
// 7.5.6
@Test
public void testTypes() throws Exception {
Class dateClass = parser.parseExpression("T(java.util.Date)").getValue(Class.class);
assertEquals(Date.class,dateClass);
Assert.assertEquals(Date.class,dateClass);
boolean trueValue = parser.parseExpression("T(java.math.RoundingMode).CEILING < T(java.math.RoundingMode).FLOOR").getValue(Boolean.class);
assertTrue(trueValue);
Assert.assertTrue(trueValue);
}
// 7.5.7
@Test
public void testConstructors() throws Exception {
StandardEvaluationContext societyContext = new StandardEvaluationContext();
societyContext.setRootObject(new IEEE());
Inventor einstein =
parser.parseExpression("new org.springframework.expression.spel.testresources.Inventor('Albert Einstein',new java.util.Date(), 'German')").getValue(Inventor.class);
assertEquals("Albert Einstein", einstein.getName());
Assert.assertEquals("Albert Einstein", einstein.getName());
//create new inventor instance within add method of List
parser.parseExpression("Members2.add(new org.springframework.expression.spel.testresources.Inventor('Albert Einstein', 'German'))").getValue(societyContext);
}
// 7.5.8
@Test
public void testVariables() throws Exception {
Inventor tesla = new Inventor("Nikola Tesla", "Serbian");
StandardEvaluationContext context = new StandardEvaluationContext();
@@ -380,42 +403,46 @@ public class SpelDocumentationTests extends ExpressionTestCase {
parser.parseExpression("foo = #newName").getValue(context);
assertEquals("Mike Tesla",tesla.getFoo());
Assert.assertEquals("Mike Tesla",tesla.getFoo());
}
@SuppressWarnings("unchecked")
@Test
public void testSpecialVariables() throws Exception {
// create an array of integers
List<Integer> primes = new ArrayList<Integer>();
primes.addAll(Arrays.asList(2,3,5,7,11,13,17));
// create parser and set variable 'primes' as the array of integers
ExpressionParser parser = new SpelAntlrExpressionParser();
ExpressionParser parser = new SpelExpressionParser();
StandardEvaluationContext context = new StandardEvaluationContext();
context.setVariable("primes",primes);
// all prime numbers > 10 from the list (using selection ?{...})
List<Integer> primesGreaterThanTen = (List<Integer>) parser.parseExpression("#primes.?[#this>10]").getValue(context);
assertEquals("[11, 13, 17]",primesGreaterThanTen.toString());
Assert.assertEquals("[11, 13, 17]",primesGreaterThanTen.toString());
}
// 7.5.9
@Test
public void testFunctions() throws Exception {
ExpressionParser parser = new SpelAntlrExpressionParser();
ExpressionParser parser = new SpelExpressionParser();
StandardEvaluationContext context = new StandardEvaluationContext();
context.registerFunction("reverseString",
StringUtils.class.getDeclaredMethod("reverseString", new Class[] { String.class }));
String helloWorldReversed = parser.parseExpression("#reverseString('hello world')").getValue(context, String.class);
assertEquals("dlrow olleh",helloWorldReversed);
Assert.assertEquals("dlrow olleh",helloWorldReversed);
}
// 7.5.10
@Test
public void testTernary() throws Exception {
String falseString = parser.parseExpression("false ? 'trueExp' : 'falseExp'").getValue(String.class);
assertEquals("falseExp",falseString);
Assert.assertEquals("falseExp",falseString);
StandardEvaluationContext societyContext = new StandardEvaluationContext();
societyContext.setRootObject(new IEEE());
@@ -428,26 +455,29 @@ public class SpelDocumentationTests extends ExpressionTestCase {
"+ Name + ' Society' : #queryName + ' is not a member of the ' + Name + ' Society'";
String queryResultString = parser.parseExpression(expression).getValue(societyContext, String.class);
assertEquals("Nikola Tesla is a member of the IEEE Society",queryResultString);
Assert.assertEquals("Nikola Tesla is a member of the IEEE Society",queryResultString);
// queryResultString = "Nikola Tesla is a member of the IEEE Society"
}
// 7.5.11
@SuppressWarnings("unchecked")
@Test
public void testSelection() throws Exception {
StandardEvaluationContext societyContext = new StandardEvaluationContext();
societyContext.setRootObject(new IEEE());
List<Inventor> list = (List<Inventor>) parser.parseExpression("Members2.?[nationality == 'Serbian']").getValue(societyContext);
assertEquals(1,list.size());
assertEquals("Nikola Tesla",list.get(0).getName());
Assert.assertEquals(1,list.size());
Assert.assertEquals("Nikola Tesla",list.get(0).getName());
}
// 7.5.12
@Test
public void testTemplating() throws Exception {
String randomPhrase =
parser.parseExpression("random number is ${T(java.lang.Math).random()}", new TemplatedParserContext()).getValue(String.class);
assertTrue(randomPhrase.startsWith("random number"));
Assert.assertTrue(randomPhrase.startsWith("random number"));
}
static class TemplatedParserContext implements ParserContext {

View File

@@ -16,12 +16,15 @@
package org.springframework.expression.spel;
import junit.framework.Assert;
import org.junit.Test;
import org.springframework.expression.AccessException;
import org.springframework.expression.EvaluationContext;
import org.springframework.expression.Expression;
import org.springframework.expression.ParserContext;
import org.springframework.expression.PropertyAccessor;
import org.springframework.expression.spel.antlr.SpelAntlrExpressionParser;
import org.springframework.expression.spel.standard.SpelExpressionParser;
import org.springframework.expression.spel.support.ReflectivePropertyResolver;
/**
@@ -31,10 +34,12 @@ import org.springframework.expression.spel.support.ReflectivePropertyResolver;
*/
public class SpringEL300Tests extends ExpressionTestCase {
@Test
public void testNPE_SPR5661() {
evaluate("joinThreeStrings('a',null,'c')", "anullc", String.class);
}
@Test
public void testNPE_SPR5673() throws Exception {
ParserContext hashes = TemplateExpressionParsingTests.HASH_DELIMITED_PARSER_CONTEXT;
ParserContext dollars = TemplateExpressionParsingTests.DEFAULT_TEMPLATE_PARSER_CONTEXT;
@@ -69,20 +74,21 @@ public class SpringEL300Tests extends ExpressionTestCase {
checkTemplateParsingError("Hello ${","No ending suffix '}' for expression starting at character 6: ${");
}
@Test
public void testAccessingNullPropertyViaReflection_SPR5663() throws AccessException {
PropertyAccessor propertyAccessor = new ReflectivePropertyResolver();
EvaluationContext context = TestScenarioCreator.getTestEvaluationContext();
assertFalse(propertyAccessor.canRead(context, null, "abc"));
assertFalse(propertyAccessor.canWrite(context, null, "abc"));
Assert.assertFalse(propertyAccessor.canRead(context, null, "abc"));
Assert.assertFalse(propertyAccessor.canWrite(context, null, "abc"));
try {
propertyAccessor.read(context, null, "abc");
fail("Should have failed with an AccessException");
Assert.fail("Should have failed with an AccessException");
} catch (AccessException ae) {
// success
}
try {
propertyAccessor.write(context, null, "abc","foo");
fail("Should have failed with an AccessException");
Assert.fail("Should have failed with an AccessException");
} catch (AccessException ae) {
// success
}
@@ -96,9 +102,9 @@ public class SpringEL300Tests extends ExpressionTestCase {
}
private void checkTemplateParsing(String expression, ParserContext context, String expectedValue) throws Exception {
SpelAntlrExpressionParser parser = new SpelAntlrExpressionParser();
SpelExpressionParser parser = new SpelExpressionParser();
Expression expr = parser.parseExpression(expression,context);
assertEquals(expectedValue,expr.getValue(TestScenarioCreator.getTestEvaluationContext()));
Assert.assertEquals(expectedValue,expr.getValue(TestScenarioCreator.getTestEvaluationContext()));
}
private void checkTemplateParsingError(String expression,String expectedMessage) throws Exception {
@@ -106,15 +112,15 @@ public class SpringEL300Tests extends ExpressionTestCase {
}
private void checkTemplateParsingError(String expression,ParserContext context, String expectedMessage) throws Exception {
SpelAntlrExpressionParser parser = new SpelAntlrExpressionParser();
SpelExpressionParser parser = new SpelExpressionParser();
try {
parser.parseExpression(expression,context);
fail("Should have failed");
Assert.fail("Should have failed");
} catch (Exception e) {
if (!e.getMessage().equals(expectedMessage)) {
e.printStackTrace();
}
assertEquals(expectedMessage,e.getMessage());
Assert.assertEquals(expectedMessage,e.getMessage());
}
}

View File

@@ -17,8 +17,9 @@ package org.springframework.expression.spel;
import java.util.List;
import junit.framework.TestCase;
import junit.framework.Assert;
import org.junit.Test;
import org.springframework.expression.EvaluationException;
import org.springframework.expression.spel.support.StandardTypeLocator;
@@ -27,31 +28,32 @@ import org.springframework.expression.spel.support.StandardTypeLocator;
*
* @author Andy Clement
*/
public class StandardTypeLocatorTests extends TestCase {
public class StandardTypeLocatorTests {
@Test
public void testImports() throws EvaluationException {
StandardTypeLocator locator = new StandardTypeLocator();
assertEquals(Integer.class,locator.findType("java.lang.Integer"));
assertEquals(String.class,locator.findType("java.lang.String"));
Assert.assertEquals(Integer.class,locator.findType("java.lang.Integer"));
Assert.assertEquals(String.class,locator.findType("java.lang.String"));
List<String> prefixes = locator.getImportPrefixes();
assertEquals(1,prefixes.size());
assertTrue(prefixes.contains("java.lang"));
assertFalse(prefixes.contains("java.util"));
Assert.assertEquals(1,prefixes.size());
Assert.assertTrue(prefixes.contains("java.lang"));
Assert.assertFalse(prefixes.contains("java.util"));
assertEquals(Boolean.class,locator.findType("Boolean"));
Assert.assertEquals(Boolean.class,locator.findType("Boolean"));
// currently does not know about java.util by default
// assertEquals(java.util.List.class,locator.findType("List"));
try {
locator.findType("URL");
fail("Should have failed");
Assert.fail("Should have failed");
} catch (EvaluationException ee) {
SpelException sEx = (SpelException)ee;
assertEquals(SpelMessages.TYPE_NOT_FOUND,sEx.getMessageUnformatted());
SpelEvaluationException sEx = (SpelEvaluationException)ee;
Assert.assertEquals(SpelMessages.TYPE_NOT_FOUND,sEx.getMessageUnformatted());
}
locator.registerImport("java.net");
assertEquals(java.net.URL.class,locator.findType("URL"));
Assert.assertEquals(java.net.URL.class,locator.findType("URL"));
}

View File

@@ -16,12 +16,16 @@
package org.springframework.expression.spel;
import junit.framework.Assert;
import org.junit.Test;
import org.springframework.expression.EvaluationContext;
import org.springframework.expression.Expression;
import org.springframework.expression.ParseException;
import org.springframework.expression.ParserContext;
import org.springframework.expression.common.CompositeStringExpression;
import org.springframework.expression.spel.antlr.SpelAntlrExpressionParser;
import org.springframework.expression.common.TemplateParserContext;
import org.springframework.expression.spel.standard.SpelExpressionParser;
import org.springframework.expression.spel.support.StandardEvaluationContext;
/**
@@ -54,144 +58,162 @@ public class TemplateExpressionParsingTests extends ExpressionTestCase {
}
};
@Test
public void testParsingSimpleTemplateExpression01() throws Exception {
SpelAntlrExpressionParser parser = new SpelAntlrExpressionParser();
SpelExpressionParser parser = new SpelExpressionParser();
Expression expr = parser.parseExpression("hello ${'world'}", DEFAULT_TEMPLATE_PARSER_CONTEXT);
Object o = expr.getValue();
assertEquals("hello world", o.toString());
Assert.assertEquals("hello world", o.toString());
}
@Test
public void testParsingSimpleTemplateExpression02() throws Exception {
SpelAntlrExpressionParser parser = new SpelAntlrExpressionParser();
SpelExpressionParser parser = new SpelExpressionParser();
Expression expr = parser.parseExpression("hello ${'to'} you", DEFAULT_TEMPLATE_PARSER_CONTEXT);
Object o = expr.getValue();
assertEquals("hello to you", o.toString());
Assert.assertEquals("hello to you", o.toString());
}
@Test
public void testParsingSimpleTemplateExpression03() throws Exception {
SpelAntlrExpressionParser parser = new SpelAntlrExpressionParser();
SpelExpressionParser parser = new SpelExpressionParser();
Expression expr = parser.parseExpression("The quick ${'brown'} fox jumped over the ${'lazy'} dog",
DEFAULT_TEMPLATE_PARSER_CONTEXT);
Object o = expr.getValue();
assertEquals("The quick brown fox jumped over the lazy dog", o.toString());
Assert.assertEquals("The quick brown fox jumped over the lazy dog", o.toString());
}
@Test
public void testParsingSimpleTemplateExpression04() throws Exception {
SpelAntlrExpressionParser parser = new SpelAntlrExpressionParser();
SpelExpressionParser parser = new SpelExpressionParser();
Expression expr = parser.parseExpression("${'hello'} world", DEFAULT_TEMPLATE_PARSER_CONTEXT);
Object o = expr.getValue();
assertEquals("hello world", o.toString());
Assert.assertEquals("hello world", o.toString());
expr = parser.parseExpression("", DEFAULT_TEMPLATE_PARSER_CONTEXT);
o = expr.getValue();
assertEquals("", o.toString());
Assert.assertEquals("", o.toString());
expr = parser.parseExpression("abc", DEFAULT_TEMPLATE_PARSER_CONTEXT);
o = expr.getValue();
assertEquals("abc", o.toString());
Assert.assertEquals("abc", o.toString());
}
@Test
public void testCompositeStringExpression() throws Exception {
SpelAntlrExpressionParser parser = new SpelAntlrExpressionParser();
SpelExpressionParser parser = new SpelExpressionParser();
Expression ex = parser.parseExpression("hello ${'world'}", DEFAULT_TEMPLATE_PARSER_CONTEXT);
checkString("hello world", ex.getValue());
checkString("hello world", ex.getValue(String.class));
EvaluationContext ctx = new StandardEvaluationContext();
checkString("hello world", ex.getValue(ctx));
checkString("hello world", ex.getValue(ctx, String.class));
assertEquals("hello ${'world'}", ex.getExpressionString());
assertFalse(ex.isWritable(new StandardEvaluationContext()));
Assert.assertEquals("hello ${'world'}", ex.getExpressionString());
Assert.assertFalse(ex.isWritable(new StandardEvaluationContext()));
}
@Test
public void testNestedExpressions() throws Exception {
SpelAntlrExpressionParser parser = new SpelAntlrExpressionParser();
SpelExpressionParser parser = new SpelExpressionParser();
// treat the nested ${..} as a part of the expression
Expression ex = parser.parseExpression("hello ${listOfNumbersUpToTen.$[#this<5]} world",DEFAULT_TEMPLATE_PARSER_CONTEXT);
String s = ex.getValue(TestScenarioCreator.getTestEvaluationContext(),String.class);
assertEquals("hello 4 world",s);
Assert.assertEquals("hello 4 world",s);
// not a useful expression but tests nested expression syntax that clashes with template prefix/suffix
ex = parser.parseExpression("hello ${listOfNumbersUpToTen.$[#root.listOfNumbersUpToTen.$[#this%2==1]==3]} world",DEFAULT_TEMPLATE_PARSER_CONTEXT);
assertEquals(CompositeStringExpression.class,ex.getClass());
Assert.assertEquals(CompositeStringExpression.class,ex.getClass());
CompositeStringExpression cse = (CompositeStringExpression)ex;
Expression[] exprs = cse.getExpressions();
assertEquals(3,exprs.length);
assertEquals("listOfNumbersUpToTen.$[#root.listOfNumbersUpToTen.$[#this%2==1]==3]",exprs[1].getExpressionString());
Assert.assertEquals(3,exprs.length);
Assert.assertEquals("listOfNumbersUpToTen.$[#root.listOfNumbersUpToTen.$[#this%2==1]==3]",exprs[1].getExpressionString());
s = ex.getValue(TestScenarioCreator.getTestEvaluationContext(),String.class);
assertEquals("hello world",s);
Assert.assertEquals("hello world",s);
ex = parser.parseExpression("hello ${listOfNumbersUpToTen.$[#this<5]} ${listOfNumbersUpToTen.$[#this>5]} world",DEFAULT_TEMPLATE_PARSER_CONTEXT);
s = ex.getValue(TestScenarioCreator.getTestEvaluationContext(),String.class);
assertEquals("hello 4 10 world",s);
Assert.assertEquals("hello 4 10 world",s);
try {
ex = parser.parseExpression("hello ${listOfNumbersUpToTen.$[#this<5]} ${listOfNumbersUpToTen.$[#this>5] world",DEFAULT_TEMPLATE_PARSER_CONTEXT);
fail("Should have failed");
Assert.fail("Should have failed");
} catch (ParseException pe) {
assertEquals("No ending suffix '}' for expression starting at character 41: ${listOfNumbersUpToTen.$[#this>5] world",pe.getMessage());
Assert.assertEquals("No ending suffix '}' for expression starting at character 41: ${listOfNumbersUpToTen.$[#this>5] world",pe.getMessage());
}
try {
ex = parser.parseExpression("hello ${listOfNumbersUpToTen.$[#root.listOfNumbersUpToTen.$[#this%2==1==3]} world",DEFAULT_TEMPLATE_PARSER_CONTEXT);
fail("Should have failed");
Assert.fail("Should have failed");
} catch (ParseException pe) {
assertEquals("Found closing '}' at position 74 but most recent opening is '[' at position 30",pe.getMessage());
Assert.assertEquals("Found closing '}' at position 74 but most recent opening is '[' at position 30",pe.getMessage());
}
}
@Test
public void testClashingWithSuffixes() throws Exception {
// Just wanting to use the prefix or suffix within the template:
Expression ex = parser.parseExpression("hello ${3+4} world",DEFAULT_TEMPLATE_PARSER_CONTEXT);
String s = ex.getValue(TestScenarioCreator.getTestEvaluationContext(),String.class);
assertEquals("hello 7 world",s);
Assert.assertEquals("hello 7 world",s);
ex = parser.parseExpression("hello ${3+4} wo${'${'}rld",DEFAULT_TEMPLATE_PARSER_CONTEXT);
s = ex.getValue(TestScenarioCreator.getTestEvaluationContext(),String.class);
assertEquals("hello 7 wo${rld",s);
Assert.assertEquals("hello 7 wo${rld",s);
ex = parser.parseExpression("hello ${3+4} wo}rld",DEFAULT_TEMPLATE_PARSER_CONTEXT);
s = ex.getValue(TestScenarioCreator.getTestEvaluationContext(),String.class);
assertEquals("hello 7 wo}rld",s);
Assert.assertEquals("hello 7 wo}rld",s);
}
@Test
public void testParsingNormalExpressionThroughTemplateParser() throws Exception {
Expression expr = parser.parseExpression("1+2+3");
assertEquals(6,expr.getValue());
Assert.assertEquals(6,expr.getValue());
expr = parser.parseExpression("1+2+3",null);
assertEquals(6,expr.getValue());
Assert.assertEquals(6,expr.getValue());
}
@Test
public void testErrorCases() throws Exception {
try {
parser.parseExpression("hello ${'world'", DEFAULT_TEMPLATE_PARSER_CONTEXT);
fail("Should have failed");
Assert.fail("Should have failed");
} catch (ParseException pe) {
assertEquals("No ending suffix '}' for expression starting at character 6: ${'world'",pe.getMessage());
assertEquals("hello ${'world'",pe.getExpressionString());
Assert.assertEquals("No ending suffix '}' for expression starting at character 6: ${'world'",pe.getMessage());
Assert.assertEquals("hello ${'world'",pe.getExpressionString());
}
try {
parser.parseExpression("hello ${'wibble'${'world'}", DEFAULT_TEMPLATE_PARSER_CONTEXT);
fail("Should have failed");
Assert.fail("Should have failed");
} catch (ParseException pe) {
assertEquals("No ending suffix '}' for expression starting at character 6: ${'wibble'${'world'}",pe.getMessage());
Assert.assertEquals("No ending suffix '}' for expression starting at character 6: ${'wibble'${'world'}",pe.getMessage());
}
try {
parser.parseExpression("hello ${} world", DEFAULT_TEMPLATE_PARSER_CONTEXT);
fail("Should have failed");
Assert.fail("Should have failed");
} catch (ParseException pe) {
assertEquals("No expression defined within delimiter '${}' at character 6",pe.getMessage());
Assert.assertEquals("No expression defined within delimiter '${}' at character 6",pe.getMessage());
}
}
@Test
public void testTemplateParserContext() {
TemplateParserContext tpc = new TemplateParserContext("abc","def");
Assert.assertEquals("abc", tpc.getExpressionPrefix());
Assert.assertEquals("def", tpc.getExpressionSuffix());
Assert.assertTrue(tpc.isTemplate());
}
// ---
private void checkString(String expectedString, Object value) {
if (!(value instanceof String)) {
fail("Result was not a string, it was of type " + value.getClass() + " (value=" + value + ")");
Assert.fail("Result was not a string, it was of type " + value.getClass() + " (value=" + value + ")");
}
if (!value.equals(expectedString)) {
fail("Did not get expected result. Should have been '" + expectedString + "' but was '" + value + "'");
Assert.fail("Did not get expected result. Should have been '" + expectedString + "' but was '" + value + "'");
}
}

View File

@@ -16,7 +16,10 @@
package org.springframework.expression.spel;
import org.springframework.expression.spel.antlr.SpelAntlrExpressionParser;
import junit.framework.Assert;
import org.junit.Test;
import org.springframework.expression.spel.standard.SpelExpressionParser;
import org.springframework.expression.spel.support.StandardEvaluationContext;
@@ -27,27 +30,32 @@ import org.springframework.expression.spel.support.StandardEvaluationContext;
*/
public class VariableAndFunctionTests extends ExpressionTestCase {
@Test
public void testVariableAccess01() {
evaluate("#answer", "42", Integer.class, SHOULD_BE_WRITABLE);
evaluate("#answer / 2", 21, Integer.class, SHOULD_NOT_BE_WRITABLE);
}
@Test
public void testVariableAccess_WellKnownVariables() {
evaluate("#this.getName()","Nikola Tesla",String.class);
evaluate("#root.getName()","Nikola Tesla",String.class);
}
@Test
public void testFunctionAccess01() {
evaluate("#reverseInt(1,2,3)", "int[3]{3,2,1}", int[].class);
evaluate("#reverseInt('1',2,3)", "int[3]{3,2,1}", int[].class); // requires type conversion of '1' to 1
evaluateAndCheckError("#reverseInt(1)", SpelMessages.INCORRECT_NUMBER_OF_ARGUMENTS_TO_FUNCTION, 1, 1, 3);
evaluateAndCheckError("#reverseInt(1)", SpelMessages.INCORRECT_NUMBER_OF_ARGUMENTS_TO_FUNCTION, 0, 1, 3);
}
@Test
public void testFunctionAccess02() {
evaluate("#reverseString('hello')", "olleh", String.class);
evaluate("#reverseString(37)", "73", String.class); // requires type conversion of 37 to '37'
}
@Test
public void testCallVarargsFunction() {
evaluate("#varargsFunctionReverseStringsAndMerge('a','b','c')", "cba", String.class);
evaluate("#varargsFunctionReverseStringsAndMerge('a')", "a", String.class);
@@ -61,18 +69,19 @@ public class VariableAndFunctionTests extends ExpressionTestCase {
evaluate("#varargsFunctionReverseStringsAndMerge2(5,25)", "525", String.class);
}
@Test
public void testCallingIllegalFunctions() throws Exception {
SpelAntlrExpressionParser parser = new SpelAntlrExpressionParser();
SpelExpressionParser parser = new SpelExpressionParser();
StandardEvaluationContext ctx = new StandardEvaluationContext();
ctx.setVariable("notStatic", this.getClass().getMethod("nonStatic"));
try {
@SuppressWarnings("unused")
Object v = parser.parseExpression("#notStatic()").getValue(ctx);
fail("Should have failed with exception - cannot call non static method that way");
} catch (SpelException se) {
Assert.fail("Should have failed with exception - cannot call non static method that way");
} catch (SpelEvaluationException se) {
if (se.getMessageUnformatted() != SpelMessages.FUNCTION_MUST_BE_STATIC) {
se.printStackTrace();
fail("Should have failed a message about the function needing to be static, not: "
Assert.fail("Should have failed a message about the function needing to be static, not: "
+ se.getMessageUnformatted());
}
}

View File

@@ -0,0 +1,358 @@
/*
* Copyright 2002-2009 the original author or authors.
*
* 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.springframework.expression.spel.standard;
import junit.framework.Assert;
import org.junit.Test;
import org.springframework.expression.EvaluationException;
import org.springframework.expression.ExpressionException;
import org.springframework.expression.ParseException;
import org.springframework.expression.spel.SpelExpression;
import org.springframework.expression.spel.SpelMessages;
import org.springframework.expression.spel.SpelNode;
import org.springframework.expression.spel.SpelParseException;
import org.springframework.expression.spel.ast.OperatorAnd;
import org.springframework.expression.spel.ast.OperatorOr;
public class SpelParserTests {
@Test
public void theMostBasic() throws EvaluationException,ParseException {
SpelExpressionParser parser = new SpelExpressionParser();
SpelExpression expr = parser.parse("2");
Assert.assertNotNull(expr);
Assert.assertNotNull(expr.getAST());
Assert.assertEquals(2,expr.getValue());
Assert.assertEquals(Integer.class,expr.getValueType());
}
@Test
public void whitespace() throws EvaluationException,ParseException {
SpelExpressionParser parser = new SpelExpressionParser();
SpelExpression expr = parser.parse("2 + 3");
Assert.assertEquals(5,expr.getValue());
expr = parser.parse("2 + 3");
Assert.assertEquals(5,expr.getValue());
expr = parser.parse("2\n+ 3");
Assert.assertEquals(5,expr.getValue());
expr = parser.parse("2\r\n+\t3");
Assert.assertEquals(5,expr.getValue());
}
@Test
public void arithmeticPlus1() throws EvaluationException,ParseException {
SpelExpressionParser parser = new SpelExpressionParser();
SpelExpression expr = parser.parse("2+2");
Assert.assertNotNull(expr);
Assert.assertNotNull(expr.getAST());
Assert.assertEquals(4,expr.getValue());
}
@Test
public void arithmeticPlus2() throws EvaluationException,ParseException {
SpelExpressionParser parser = new SpelExpressionParser();
SpelExpression expr = parser.parse("37+41");
Assert.assertEquals(78,expr.getValue());
}
@Test
public void arithmeticMultiply1() throws EvaluationException,ParseException {
SpelExpressionParser parser = new SpelExpressionParser();
SpelExpression expr = parser.parse("2*3");
Assert.assertNotNull(expr);
Assert.assertNotNull(expr.getAST());
// printAst(expr.getAST(),0);
Assert.assertEquals(6,expr.getValue());
}
@Test
public void arithmeticPrecedence1() throws EvaluationException,ParseException {
SpelExpressionParser parser = new SpelExpressionParser();
SpelExpression expr = parser.parse("2*3+5");
Assert.assertEquals(11,expr.getValue());
}
@Test
public void generalExpressions() throws Exception {
try {
SpelExpressionParser parser = new SpelExpressionParser();
parser.parse("new String[3]");
Assert.fail();
} catch (ParseException e) {
Assert.assertTrue(e instanceof SpelParseException);
SpelParseException spe = (SpelParseException)e;
Assert.assertEquals(SpelMessages.MISSING_CONSTRUCTOR_ARGS,spe.getMessageUnformatted());
Assert.assertEquals(10,spe.getPosition());
}
try {
SpelExpressionParser parser = new SpelExpressionParser();
parser.parse("new String");
Assert.fail();
} catch (ParseException e) {
Assert.assertTrue(e instanceof SpelParseException);
SpelParseException spe = (SpelParseException)e;
Assert.assertEquals(SpelMessages.MISSING_CONSTRUCTOR_ARGS,spe.getMessageUnformatted());
Assert.assertEquals(10,spe.getPosition());
}
try {
SpelExpressionParser parser = new SpelExpressionParser();
parser.parse("new String(3,");
Assert.fail();
} catch (ParseException e) {
Assert.assertTrue(e instanceof SpelParseException);
SpelParseException spe = (SpelParseException)e;
Assert.assertEquals(SpelMessages.RUN_OUT_OF_ARGUMENTS,spe.getMessageUnformatted());
Assert.assertEquals(10,spe.getPosition());
}
try {
SpelExpressionParser parser = new SpelExpressionParser();
parser.parse("new String(3");
Assert.fail();
} catch (ParseException e) {
Assert.assertTrue(e instanceof SpelParseException);
SpelParseException spe = (SpelParseException)e;
Assert.assertEquals(SpelMessages.RUN_OUT_OF_ARGUMENTS,spe.getMessageUnformatted());
Assert.assertEquals(10,spe.getPosition());
}
try {
SpelExpressionParser parser = new SpelExpressionParser();
parser.parse("new String(");
Assert.fail();
} catch (ParseException e) {
Assert.assertTrue(e instanceof SpelParseException);
SpelParseException spe = (SpelParseException)e;
Assert.assertEquals(SpelMessages.RUN_OUT_OF_ARGUMENTS,spe.getMessageUnformatted());
Assert.assertEquals(10,spe.getPosition());
}
try {
SpelExpressionParser parser = new SpelExpressionParser();
parser.parse("\"abc");
Assert.fail();
} catch (ParseException e) {
Assert.assertTrue(e instanceof SpelParseException);
SpelParseException spe = (SpelParseException)e;
Assert.assertEquals(SpelMessages.NON_TERMINATING_DOUBLE_QUOTED_STRING,spe.getMessageUnformatted());
Assert.assertEquals(0,spe.getPosition());
}
try {
SpelExpressionParser parser = new SpelExpressionParser();
parser.parse("'abc");
Assert.fail();
} catch (ParseException e) {
Assert.assertTrue(e instanceof SpelParseException);
SpelParseException spe = (SpelParseException)e;
Assert.assertEquals(SpelMessages.NON_TERMINATING_QUOTED_STRING,spe.getMessageUnformatted());
Assert.assertEquals(0,spe.getPosition());
}
}
@Test
public void arithmeticPrecedence2() throws EvaluationException,ParseException {
SpelExpressionParser parser = new SpelExpressionParser();
SpelExpression expr = parser.parse("2+3*5");
Assert.assertEquals(17,expr.getValue());
}
@Test
public void arithmeticPrecedence3() throws EvaluationException,ParseException {
SpelExpression expr = new SpelExpressionParser().parse("3+10/2");
Assert.assertEquals(8,expr.getValue());
}
@Test
public void arithmeticPrecedence4() throws EvaluationException,ParseException {
SpelExpression expr = new SpelExpressionParser().parse("10/2+3");
Assert.assertEquals(8,expr.getValue());
}
@Test
public void arithmeticPrecedence5() throws EvaluationException,ParseException {
SpelExpression expr = new SpelExpressionParser().parse("(4+10)/2");
Assert.assertEquals(7,expr.getValue());
}
@Test
public void arithmeticPrecedence6() throws EvaluationException,ParseException {
SpelExpression expr = new SpelExpressionParser().parse("(3+2)*2");
Assert.assertEquals(10,expr.getValue());
}
@Test
public void booleanOperators() throws EvaluationException,ParseException {
SpelExpression expr = new SpelExpressionParser().parse("true");
Assert.assertEquals(Boolean.TRUE,expr.getValue(Boolean.class));
expr = new SpelExpressionParser().parse("false");
Assert.assertEquals(Boolean.FALSE,expr.getValue(Boolean.class));
expr = new SpelExpressionParser().parse("false and false");
Assert.assertEquals(Boolean.FALSE,expr.getValue(Boolean.class));
expr = new SpelExpressionParser().parse("true and (true or false)");
Assert.assertEquals(Boolean.TRUE,expr.getValue(Boolean.class));
expr = new SpelExpressionParser().parse("true and true or false");
Assert.assertEquals(Boolean.TRUE,expr.getValue(Boolean.class));
expr = new SpelExpressionParser().parse("!true");
Assert.assertEquals(Boolean.FALSE,expr.getValue(Boolean.class));
expr = new SpelExpressionParser().parse("!(false or true)");
Assert.assertEquals(Boolean.FALSE,expr.getValue(Boolean.class));
}
@Test
public void testStringLiterals() throws EvaluationException,ParseException {
SpelExpression expr = new SpelExpressionParser().parse("'howdy'");
Assert.assertEquals("howdy",expr.getValue());
expr = new SpelExpressionParser().parse("'hello '' world'");
Assert.assertEquals("hello ' world",expr.getValue());
}
@Test
public void testStringLiterals2() throws EvaluationException,ParseException {
SpelExpression expr = new SpelExpressionParser().parse("'howdy'.substring(0,2)");
Assert.assertEquals("ho",expr.getValue());
}
@Test
public void testPositionalInformation() throws EvaluationException, ParseException {
SpelExpression expr = new SpelExpressionParser().parse("true and true or false");
SpelNode rootAst = expr.getAST();
OperatorOr operatorOr = (OperatorOr)rootAst;
OperatorAnd operatorAnd = (OperatorAnd)operatorOr.getLeftOperand();
SpelNode rightOrOperand = operatorOr.getRightOperand();
// check position for final 'false'
Assert.assertEquals(17, rightOrOperand.getStartPosition());
Assert.assertEquals(22, rightOrOperand.getEndPosition());
// check position for first 'true'
Assert.assertEquals(0, operatorAnd.getLeftOperand().getStartPosition());
Assert.assertEquals(4, operatorAnd.getLeftOperand().getEndPosition());
// check position for second 'true'
Assert.assertEquals(9, operatorAnd.getRightOperand().getStartPosition());
Assert.assertEquals(13, operatorAnd.getRightOperand().getEndPosition());
// check position for OperatorAnd
Assert.assertEquals(5, operatorAnd.getStartPosition());
Assert.assertEquals(8, operatorAnd.getEndPosition());
// check position for OperatorOr
Assert.assertEquals(14, operatorOr.getStartPosition());
Assert.assertEquals(16, operatorOr.getEndPosition());
}
@Test
public void testTokenKind() {
TokenKind tk = TokenKind.BANG;
Assert.assertFalse(tk.hasPayload());
Assert.assertEquals("BANG(!)",tk.toString());
tk = TokenKind.MINUS;
Assert.assertFalse(tk.hasPayload());
Assert.assertEquals("MINUS(-)",tk.toString());
tk = TokenKind.LITERAL_STRING;
Assert.assertEquals("LITERAL_STRING",tk.toString());
Assert.assertTrue(tk.hasPayload());
}
@Test
public void testToken() {
Token token = new Token(TokenKind.BANG,0,3);
Assert.assertEquals(TokenKind.BANG,token.kind);
Assert.assertEquals(0,token.startpos);
Assert.assertEquals(3,token.endpos);
Assert.assertEquals("[BANG(!)](0,3)",token.toString());
token = new Token(TokenKind.LITERAL_STRING,"abc".toCharArray(),0,3);
Assert.assertEquals(TokenKind.LITERAL_STRING,token.kind);
Assert.assertEquals(0,token.startpos);
Assert.assertEquals(3,token.endpos);
Assert.assertEquals("[LITERAL_STRING:abc](0,3)",token.toString());
}
@Test
public void testExceptions() {
ExpressionException exprEx = new ExpressionException("test");
Assert.assertEquals("test", exprEx.getMessage());
Assert.assertEquals("test", exprEx.toDetailedString());
exprEx = new ExpressionException("wibble","test");
Assert.assertEquals("test", exprEx.getMessage());
Assert.assertEquals("Expression 'wibble': test", exprEx.toDetailedString());
exprEx = new ExpressionException("wibble",3, "test");
Assert.assertEquals("test", exprEx.getMessage());
Assert.assertEquals("Expression 'wibble' @ 3: test", exprEx.toDetailedString());
}
@Test
public void testNumerics() {
checkNumber("2",2,Integer.class);
checkNumber("22",22,Integer.class);
checkNumber("+22",22,Integer.class);
checkNumber("-22",-22,Integer.class);
checkNumber("2L",2L,Long.class);
checkNumber("22l",22L,Long.class);
checkNumber("0x1",1,Integer.class);
checkNumber("0x1L",1L,Long.class);
checkNumber("0xa",10,Integer.class);
checkNumber("0xAL",10L,Long.class);
checkNumberError("0x",SpelMessages.NOT_AN_INTEGER);
checkNumberError("0xL",SpelMessages.NOT_A_LONG);
checkNumberError(".324",SpelMessages.UNEXPECTED_DATA_AFTER_DOT);
checkNumberError("3.4L",SpelMessages.REAL_CANNOT_BE_LONG);
// Number is parsed as a float, but immediately promoted to a double
checkNumber("3.5f",3.5d,Double.class);
checkNumber("1.2e3", 1.2e3d, Double.class);
checkNumber("1.2e+3", 1.2e3d, Double.class);
checkNumber("1.2e-3", 1.2e-3d, Double.class);
checkNumber("1.2e3", 1.2e3d, Double.class);
checkNumber("1.e+3", 1.e3d, Double.class);
checkNumber("1e+3", 1e3d, Double.class);
}
private void checkNumber(String expression, Object value, Class<?> type) {
try {
SpelExpressionParser parser = new SpelExpressionParser();
SpelExpression expr = parser.parse(expression);
Object o = expr.getValue();
Assert.assertEquals(value,o);
Assert.assertEquals(type,o.getClass());
} catch (Exception e) {
e.printStackTrace();
Assert.fail(e.getMessage());
}
}
private void checkNumberError(String expression, SpelMessages expectedMessage) {
try {
SpelExpressionParser parser = new SpelExpressionParser();
parser.parse(expression);
Assert.fail();
} catch (ParseException e) {
Assert.assertTrue(e instanceof SpelParseException);
SpelParseException spe = (SpelParseException)e;
Assert.assertEquals(expectedMessage,spe.getMessageUnformatted());
}
}
}

View File

@@ -0,0 +1,79 @@
/*
* Copyright 2002-2009 the original author or authors.
*
* 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.springframework.expression.spel.support;
import java.util.List;
import org.junit.Assert;
import org.junit.Test;
import org.springframework.core.convert.support.DefaultTypeConverter;
import org.springframework.expression.EvaluationException;
import org.springframework.expression.Operation;
import org.springframework.expression.OperatorOverloader;
import org.springframework.expression.TypeComparator;
import org.springframework.expression.TypeConverter;
import org.springframework.expression.TypeLocator;
public class StandardComponentsTests {
@Test
public void testStandardEvaluationContext() {
StandardEvaluationContext context = new StandardEvaluationContext();
Assert.assertNotNull(context.getTypeComparator());
TypeComparator tc = new StandardTypeComparator();
context.setTypeComparator(tc);
Assert.assertEquals(tc,context.getTypeComparator());
TypeLocator tl = new StandardTypeLocator();
context.setTypeLocator(tl);
Assert.assertEquals(tl,context.getTypeLocator());
}
@Test
public void testStandardOperatorOverloader() throws EvaluationException {
OperatorOverloader oo = new StandardOperatorOverloader();
Assert.assertFalse(oo.overridesOperation(Operation.ADD, null, null));
try {
oo.operate(Operation.ADD, 2, 3);
Assert.fail("should have failed");
} catch (EvaluationException e) {
// success
}
}
@Test
public void testStandardTypeLocator() {
StandardTypeLocator tl = new StandardTypeLocator();
List<String> prefixes = tl.getImportPrefixes();
Assert.assertEquals(1,prefixes.size());
tl.registerImport("java.util");
prefixes = tl.getImportPrefixes();
Assert.assertEquals(2,prefixes.size());
tl.removeImport("java.util");
prefixes = tl.getImportPrefixes();
Assert.assertEquals(1,prefixes.size());
}
@Test
public void testStandardTypeConverter() throws EvaluationException {
TypeConverter tc = new StandardTypeConverter(new DefaultTypeConverter());
tc.convertValue(3,Double.class);
}
}

View File

@@ -1,7 +1,19 @@
/**
*
/*
* Copyright 2002-2009 the original author or authors.
*
* 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.springframework.expression.spel.testresources;
package org.springframework.expression.spel.testresources;
/**
* Hold the various kinds of primitive array for access through the test evaluation context.