Browse Source

Polish SpEL examples and tests

pull/31778/head
Sam Brannen 2 years ago
parent
commit
9f305bfaab
  1. 6
      framework-docs/modules/ROOT/pages/core/expressions/language-ref/variables.adoc
  2. 2
      spring-expression/src/test/java/org/springframework/expression/spel/EvaluationTests.java
  3. 89
      spring-expression/src/test/java/org/springframework/expression/spel/SpelDocumentationTests.java
  4. 11
      spring-expression/src/test/java/org/springframework/expression/spel/testresources/Inventor.java

6
framework-docs/modules/ROOT/pages/core/expressions/language-ref/variables.adoc

@ -1,8 +1,8 @@
[[expressions-ref-variables]] [[expressions-ref-variables]]
= Variables = Variables
You can reference variables in the expression by using the `#variableName` syntax. Variables You can reference variables in an expression by using the `#variableName` syntax. Variables
are set by using the `setVariable` method on `EvaluationContext` implementations. are set by using the `setVariable()` method in `EvaluationContext` implementations.
[NOTE] [NOTE]
==== ====
@ -29,7 +29,7 @@ Java::
context.setVariable("newName", "Mike Tesla"); context.setVariable("newName", "Mike Tesla");
parser.parseExpression("name = #newName").getValue(context, tesla); parser.parseExpression("name = #newName").getValue(context, tesla);
System.out.println(tesla.getName()) // "Mike Tesla" System.out.println(tesla.getName()); // "Mike Tesla"
---- ----
Kotlin:: Kotlin::

2
spring-expression/src/test/java/org/springframework/expression/spel/EvaluationTests.java

@ -554,7 +554,7 @@ class EvaluationTests extends AbstractExpressionTests {
@Test @Test
void propertyField() { void propertyField() {
evaluate("name", "Nikola Tesla", String.class, false); evaluate("name", "Nikola Tesla", String.class, true);
// not writable because (1) name is private (2) there is no setter, only a getter // not writable because (1) name is private (2) there is no setter, only a getter
evaluateAndCheckError("madeup", SpelMessage.PROPERTY_OR_FIELD_NOT_READABLE, 0, "madeup", evaluateAndCheckError("madeup", SpelMessage.PROPERTY_OR_FIELD_NOT_READABLE, 0, "madeup",
"org.springframework.expression.spel.testresources.Inventor"); "org.springframework.expression.spel.testresources.Inventor");

89
spring-expression/src/test/java/org/springframework/expression/spel/SpelDocumentationTests.java

@ -34,6 +34,7 @@ import org.springframework.expression.Expression;
import org.springframework.expression.ExpressionParser; import org.springframework.expression.ExpressionParser;
import org.springframework.expression.ParserContext; import org.springframework.expression.ParserContext;
import org.springframework.expression.spel.standard.SpelExpressionParser; import org.springframework.expression.spel.standard.SpelExpressionParser;
import org.springframework.expression.spel.support.SimpleEvaluationContext;
import org.springframework.expression.spel.support.StandardEvaluationContext; import org.springframework.expression.spel.support.StandardEvaluationContext;
import org.springframework.expression.spel.testresources.Inventor; import org.springframework.expression.spel.testresources.Inventor;
import org.springframework.expression.spel.testresources.PlaceOfBirth; import org.springframework.expression.spel.testresources.PlaceOfBirth;
@ -42,12 +43,13 @@ import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.within; import static org.assertj.core.api.Assertions.within;
/** /**
* Test the examples specified in the documentation. * Test the examples used in the reference documentation.
* *
* <p>NOTE: any outgoing changes from this file upon synchronizing with the repo may indicate that * <p>NOTE: any changes in this file may indicate that you need to update the
* you need to update the documentation too ! * documentation too!
* *
* @author Andy Clement * @author Andy Clement
* @author Sam Brannen
*/ */
@SuppressWarnings("rawtypes") @SuppressWarnings("rawtypes")
class SpelDocumentationTests extends AbstractExpressionTests { class SpelDocumentationTests extends AbstractExpressionTests {
@ -61,15 +63,15 @@ class SpelDocumentationTests extends AbstractExpressionTests {
c.set(1856, 7, 9); c.set(1856, 7, 9);
tesla = new Inventor("Nikola Tesla", c.getTime(), "Serbian"); tesla = new Inventor("Nikola Tesla", c.getTime(), "Serbian");
tesla.setPlaceOfBirth(new PlaceOfBirth("SmilJan")); tesla.setPlaceOfBirth(new PlaceOfBirth("SmilJan"));
tesla.setInventions(new String[] { "Telephone repeater", "Rotating magnetic field principle", tesla.setInventions("Telephone repeater", "Rotating magnetic field principle",
"Polyphase alternating-current system", "Induction motor", "Alternating-current power transmission", "Polyphase alternating-current system", "Induction motor", "Alternating-current power transmission",
"Tesla coil transformer", "Wireless communication", "Radio", "Fluorescent lights" }); "Tesla coil transformer", "Wireless communication", "Radio", "Fluorescent lights");
pupin = new Inventor("Pupin", c.getTime(), "Idvor"); pupin = new Inventor("Pupin", c.getTime(), "Idvor");
pupin.setPlaceOfBirth(new PlaceOfBirth("Idvor")); pupin.setPlaceOfBirth(new PlaceOfBirth("Idvor"));
} }
@Test @Test
void methodInvocation() { void methodInvocation() {
evaluate("'Hello World'.concat('!')","Hello World!",String.class); evaluate("'Hello World'.concat('!')","Hello World!",String.class);
@ -86,11 +88,11 @@ class SpelDocumentationTests extends AbstractExpressionTests {
} }
@Test @Test
void rootObject() throws Exception { void rootObject() {
GregorianCalendar c = new GregorianCalendar(); GregorianCalendar c = new GregorianCalendar();
c.set(1856, 7, 9); c.set(1856, 7, 9);
// The constructor arguments are name, birthday, and nationaltiy. // The constructor arguments are name, birthday, and nationality.
Inventor tesla = new Inventor("Nikola Tesla", c.getTime(), "Serbian"); Inventor tesla = new Inventor("Nikola Tesla", c.getTime(), "Serbian");
ExpressionParser parser = new SpelExpressionParser(); ExpressionParser parser = new SpelExpressionParser();
@ -104,7 +106,7 @@ class SpelDocumentationTests extends AbstractExpressionTests {
} }
@Test @Test
void equalityCheck() throws Exception { void equalityCheck() {
ExpressionParser parser = new SpelExpressionParser(); ExpressionParser parser = new SpelExpressionParser();
StandardEvaluationContext context = new StandardEvaluationContext(); StandardEvaluationContext context = new StandardEvaluationContext();
@ -124,7 +126,7 @@ class SpelDocumentationTests extends AbstractExpressionTests {
// Section 7.5 // Section 7.5
@Test @Test
void literals() throws Exception { void literals() {
ExpressionParser parser = new SpelExpressionParser(); ExpressionParser parser = new SpelExpressionParser();
String helloWorld = (String) parser.parseExpression("'Hello World'").getValue(); // evals to "Hello World" String helloWorld = (String) parser.parseExpression("'Hello World'").getValue(); // evals to "Hello World"
@ -144,7 +146,7 @@ class SpelDocumentationTests extends AbstractExpressionTests {
} }
@Test @Test
void propertyAccess() throws Exception { void propertyAccess() {
EvaluationContext context = TestScenarioCreator.getTestEvaluationContext(); EvaluationContext context = TestScenarioCreator.getTestEvaluationContext();
int year = (Integer) parser.parseExpression("Birthdate.Year + 1900").getValue(context); // 1856 int year = (Integer) parser.parseExpression("Birthdate.Year + 1900").getValue(context); // 1856
assertThat(year).isEqualTo(1856); assertThat(year).isEqualTo(1856);
@ -154,7 +156,7 @@ class SpelDocumentationTests extends AbstractExpressionTests {
} }
@Test @Test
void propertyNavigation() throws Exception { void propertyNavigation() {
ExpressionParser parser = new SpelExpressionParser(); ExpressionParser parser = new SpelExpressionParser();
// Inventions Array // Inventions Array
@ -182,7 +184,7 @@ class SpelDocumentationTests extends AbstractExpressionTests {
} }
@Test @Test
void dictionaryAccess() throws Exception { void dictionaryAccess() {
StandardEvaluationContext societyContext = new StandardEvaluationContext(); StandardEvaluationContext societyContext = new StandardEvaluationContext();
societyContext.setRootObject(new IEEE()); societyContext.setRootObject(new IEEE());
// Officer's Dictionary // Officer's Dictionary
@ -201,13 +203,10 @@ class SpelDocumentationTests extends AbstractExpressionTests {
Inventor i2 = parser.parseExpression("reverse[0]['advisors'][0]").getValue(societyContext,Inventor.class); Inventor i2 = parser.parseExpression("reverse[0]['advisors'][0]").getValue(societyContext,Inventor.class);
assertThat(i2.getName()).isEqualTo("Nikola Tesla"); assertThat(i2.getName()).isEqualTo("Nikola Tesla");
} }
// 7.5.3
@Test @Test
void methodInvocation2() throws Exception { void methodInvocation2() {
// string literal, evaluates to "bc" // string literal, evaluates to "bc"
String c = parser.parseExpression("'abc'.substring(1, 3)").getValue(String.class); String c = parser.parseExpression("'abc'.substring(1, 3)").getValue(String.class);
assertThat(c).isEqualTo("bc"); assertThat(c).isEqualTo("bc");
@ -219,10 +218,8 @@ class SpelDocumentationTests extends AbstractExpressionTests {
assertThat(isMember).isTrue(); assertThat(isMember).isTrue();
} }
// 7.5.4.1
@Test @Test
void relationalOperators() throws Exception { void relationalOperators() {
boolean result = parser.parseExpression("2 == 2").getValue(Boolean.class); boolean result = parser.parseExpression("2 == 2").getValue(Boolean.class);
assertThat(result).isTrue(); assertThat(result).isTrue();
// evaluates to false // evaluates to false
@ -235,7 +232,7 @@ class SpelDocumentationTests extends AbstractExpressionTests {
} }
@Test @Test
void otherOperators() throws Exception { void otherOperators() {
// evaluates to false // evaluates to false
boolean falseValue = parser.parseExpression("'xyz' instanceof T(int)").getValue(Boolean.class); boolean falseValue = parser.parseExpression("'xyz' instanceof T(int)").getValue(Boolean.class);
assertThat(falseValue).isFalse(); assertThat(falseValue).isFalse();
@ -249,11 +246,8 @@ class SpelDocumentationTests extends AbstractExpressionTests {
assertThat(falseValue).isFalse(); assertThat(falseValue).isFalse();
} }
// 7.5.4.2
@Test @Test
void logicalOperators() throws Exception { void logicalOperators() {
StandardEvaluationContext societyContext = new StandardEvaluationContext(); StandardEvaluationContext societyContext = new StandardEvaluationContext();
societyContext.setRootObject(new IEEE()); societyContext.setRootObject(new IEEE());
@ -283,17 +277,14 @@ class SpelDocumentationTests extends AbstractExpressionTests {
falseValue = parser.parseExpression("!true").getValue(Boolean.class); falseValue = parser.parseExpression("!true").getValue(Boolean.class);
assertThat(falseValue).isFalse(); assertThat(falseValue).isFalse();
// -- AND and NOT -- // -- AND and NOT --
expression = "isMember('Nikola Tesla') and !isMember('Mihajlo Pupin')"; expression = "isMember('Nikola Tesla') and !isMember('Mihajlo Pupin')";
falseValue = parser.parseExpression(expression).getValue(societyContext, Boolean.class); falseValue = parser.parseExpression(expression).getValue(societyContext, Boolean.class);
assertThat(falseValue).isFalse(); assertThat(falseValue).isFalse();
} }
// 7.5.4.3
@Test @Test
void numericalOperators() throws Exception { void numericalOperators() {
// Addition // Addition
int two = parser.parseExpression("1 + 1").getValue(Integer.class); // 2 int two = parser.parseExpression("1 + 1").getValue(Integer.class); // 2
assertThat(two).isEqualTo(2); assertThat(two).isEqualTo(2);
@ -334,10 +325,8 @@ class SpelDocumentationTests extends AbstractExpressionTests {
assertThat(minusTwentyOne).isEqualTo(-21); assertThat(minusTwentyOne).isEqualTo(-21);
} }
// 7.5.5
@Test @Test
void assignment() throws Exception { void assignment() {
Inventor inventor = new Inventor(); Inventor inventor = new Inventor();
StandardEvaluationContext inventorContext = new StandardEvaluationContext(); StandardEvaluationContext inventorContext = new StandardEvaluationContext();
inventorContext.setRootObject(inventor); inventorContext.setRootObject(inventor);
@ -345,27 +334,23 @@ class SpelDocumentationTests extends AbstractExpressionTests {
parser.parseExpression("foo").setValue(inventorContext, "Alexander Seovic2"); parser.parseExpression("foo").setValue(inventorContext, "Alexander Seovic2");
assertThat(parser.parseExpression("foo").getValue(inventorContext,String.class)).isEqualTo("Alexander Seovic2"); assertThat(parser.parseExpression("foo").getValue(inventorContext,String.class)).isEqualTo("Alexander Seovic2");
// alternatively
// alternatively
String aleks = parser.parseExpression("foo = 'Alexandar Seovic'").getValue(inventorContext, String.class); String aleks = parser.parseExpression("foo = 'Alexandar Seovic'").getValue(inventorContext, String.class);
assertThat(parser.parseExpression("foo").getValue(inventorContext,String.class)).isEqualTo("Alexandar Seovic"); assertThat(parser.parseExpression("foo").getValue(inventorContext,String.class)).isEqualTo("Alexandar Seovic");
assertThat(aleks).isEqualTo("Alexandar Seovic"); assertThat(aleks).isEqualTo("Alexandar Seovic");
} }
// 7.5.6
@Test @Test
void types() throws Exception { void types() {
Class<?> dateClass = parser.parseExpression("T(java.util.Date)").getValue(Class.class); Class<?> dateClass = parser.parseExpression("T(java.util.Date)").getValue(Class.class);
assertThat(dateClass).isEqualTo(Date.class); assertThat(dateClass).isEqualTo(Date.class);
boolean trueValue = parser.parseExpression("T(java.math.RoundingMode).CEILING < T(java.math.RoundingMode).FLOOR").getValue(Boolean.class); boolean trueValue = parser.parseExpression("T(java.math.RoundingMode).CEILING < T(java.math.RoundingMode).FLOOR").getValue(Boolean.class);
assertThat(trueValue).isTrue(); assertThat(trueValue).isTrue();
} }
// 7.5.7
@Test @Test
void constructors() throws Exception { void constructors() {
StandardEvaluationContext societyContext = new StandardEvaluationContext(); StandardEvaluationContext societyContext = new StandardEvaluationContext();
societyContext.setRootObject(new IEEE()); societyContext.setRootObject(new IEEE());
Inventor einstein = Inventor einstein =
@ -375,19 +360,16 @@ class SpelDocumentationTests extends AbstractExpressionTests {
parser.parseExpression("Members2.add(new org.springframework.expression.spel.testresources.Inventor('Albert Einstein', 'German'))").getValue(societyContext); parser.parseExpression("Members2.add(new org.springframework.expression.spel.testresources.Inventor('Albert Einstein', 'German'))").getValue(societyContext);
} }
// 7.5.8
@Test @Test
void variables() throws Exception { void variables() {
Inventor tesla = new Inventor("Nikola Tesla", "Serbian"); Inventor tesla = new Inventor("Nikola Tesla", "Serbian");
StandardEvaluationContext context = new StandardEvaluationContext();
context.setVariable("newName", "Mike Tesla");
context.setRootObject(tesla); EvaluationContext context = SimpleEvaluationContext.forReadWriteDataBinding().build();
context.setVariable("newName", "Mike Tesla");
parser.parseExpression("foo = #newName").getValue(context); parser.parseExpression("name = #newName").getValue(context, tesla);
assertThat(tesla.getFoo()).isEqualTo("Mike Tesla"); assertThat(tesla.getName()).isEqualTo("Mike Tesla");
} }
@Test @Test
@ -406,7 +388,6 @@ class SpelDocumentationTests extends AbstractExpressionTests {
assertThat(primesGreaterThanTen.toString()).isEqualTo("[11, 13, 17]"); assertThat(primesGreaterThanTen.toString()).isEqualTo("[11, 13, 17]");
} }
// 7.5.9
@Test @Test
void functions() throws Exception { void functions() throws Exception {
@ -450,10 +431,8 @@ class SpelDocumentationTests extends AbstractExpressionTests {
assertThat(message).isEqualTo("This is a prerecorded message with 3 words: <Oh Hello World!>"); assertThat(message).isEqualTo("This is a prerecorded message with 3 words: <Oh Hello World!>");
} }
// 7.5.10
@Test @Test
void ternary() throws Exception { void ternary() {
String falseString = parser.parseExpression("false ? 'trueExp' : 'falseExp'").getValue(String.class); String falseString = parser.parseExpression("false ? 'trueExp' : 'falseExp'").getValue(String.class);
assertThat(falseString).isEqualTo("falseExp"); assertThat(falseString).isEqualTo("falseExp");
@ -472,11 +451,9 @@ class SpelDocumentationTests extends AbstractExpressionTests {
// queryResultString = "Nikola Tesla is a member of the IEEE Society" // queryResultString = "Nikola Tesla is a member of the IEEE Society"
} }
// 7.5.11
@Test @Test
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
void selection() throws Exception { void selection() {
StandardEvaluationContext societyContext = new StandardEvaluationContext(); StandardEvaluationContext societyContext = new StandardEvaluationContext();
societyContext.setRootObject(new IEEE()); societyContext.setRootObject(new IEEE());
List<Inventor> list = (List<Inventor>) parser.parseExpression("Members2.?[nationality == 'Serbian']").getValue(societyContext); List<Inventor> list = (List<Inventor>) parser.parseExpression("Members2.?[nationality == 'Serbian']").getValue(societyContext);
@ -484,10 +461,8 @@ class SpelDocumentationTests extends AbstractExpressionTests {
assertThat(list.get(0).getName()).isEqualTo("Nikola Tesla"); assertThat(list.get(0).getName()).isEqualTo("Nikola Tesla");
} }
// 7.5.12
@Test @Test
void templating() throws Exception { void templating() {
String randomPhrase = String randomPhrase =
parser.parseExpression("random number is ${T(java.lang.Math).random()}", new TemplatedParserContext()).getValue(String.class); parser.parseExpression("random number is ${T(java.lang.Math).random()}", new TemplatedParserContext()).getValue(String.class);
assertThat(randomPhrase).startsWith("random number"); assertThat(randomPhrase).startsWith("random number");

11
spring-expression/src/test/java/org/springframework/expression/spel/testresources/Inventor.java

@ -1,5 +1,5 @@
/* /*
* Copyright 2002-2021 the original author or authors. * Copyright 2002-2023 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@ -109,7 +109,7 @@ public class Inventor {
return inventions; return inventions;
} }
public void setInventions(String[] inventions) { public void setInventions(String... inventions) {
this.inventions = inventions; this.inventions = inventions;
} }
@ -138,6 +138,10 @@ public class Inventor {
return pob.getCity(); return pob.getCity();
} }
public void setName(String name) {
this.name = name;
}
public String getName() { public String getName() {
return name; return name;
} }
@ -214,6 +218,9 @@ public class Inventor {
} }
public Inventor(String... strings) { public Inventor(String... strings) {
if (strings.length > 0) {
this.name = strings[0];
}
} }
public boolean getSomeProperty() { public boolean getSomeProperty() {

Loading…
Cancel
Save