PageRenderTime 57ms CodeModel.GetById 22ms RepoModel.GetById 1ms app.codeStats 0ms

/src/test/java/org/mvel2/tests/core/ControlFlowTests.java

https://github.com/sherl0cks/mvel
Java | 480 lines | 370 code | 104 blank | 6 comment | 10 complexity | 2b605c21f1bc2cfbd3e8ab15b0a95425 MD5 | raw file
Possible License(s): BSD-3-Clause, Apache-2.0
  1. package org.mvel2.tests.core;
  2. import org.mvel2.MVEL;
  3. import org.mvel2.ParserConfiguration;
  4. import org.mvel2.ParserContext;
  5. import org.mvel2.compiler.ExecutableStatement;
  6. import org.mvel2.tests.core.res.Base;
  7. import org.mvel2.tests.core.res.Foo;
  8. import java.util.*;
  9. import java.io.Serializable;
  10. import static org.mvel2.MVEL.compileExpression;
  11. import static org.mvel2.MVEL.eval;
  12. import static org.mvel2.MVEL.executeExpression;
  13. public class ControlFlowTests extends AbstractTest {
  14. public void testSimpleIfStatement() {
  15. test("if (true) { System.out.println(\"test!\") } \n");
  16. }
  17. public void testAnd() {
  18. assertEquals(true, test("c != null && foo.bar.name == 'dog' && foo.bar.woof"));
  19. }
  20. public void testAnd2() {
  21. assertEquals(true, test("c!=null&&foo.bar.name=='dog'&&foo.bar.woof"));
  22. }
  23. public void testComplexAnd() {
  24. assertEquals(true, test("(pi * hour) > 0 && foo.happy() == 'happyBar'"));
  25. }
  26. public void testShortPathExpression() {
  27. assertEquals(null, MVEL.eval("3 > 4 && foo.toUC('test'); foo.register", new Base(), createTestMap()));
  28. }
  29. public void testShortPathExpression2() {
  30. assertEquals(true, test("4 > 3 || foo.toUC('test')"));
  31. }
  32. public void testShortPathExpression4() {
  33. assertEquals(true, test("4>3||foo.toUC('test')"));
  34. }
  35. public void testOr() {
  36. assertEquals(true, test("fun || true"));
  37. }
  38. public void testOrOperator() {
  39. assertEquals(true, test("true||true"));
  40. }
  41. public void testOrOperator2() {
  42. assertEquals(true, test("2 > 3 || 3 > 2"));
  43. }
  44. public void testOrOperator3() {
  45. assertEquals(true, test("pi > 5 || pi > 6 || pi > 3"));
  46. }
  47. public void testShortPathExpression3() {
  48. assertEquals(false, test("defnull != null && defnull.length() > 0"));
  49. }
  50. public void testMultiStatement() {
  51. assertEquals(true, test("populate(); barfoo == 'sarah'"));
  52. }
  53. public void testTernary() {
  54. assertEquals("foobie", test("zero==0?'foobie':zero"));
  55. }
  56. public void testTernary2() {
  57. assertEquals("blimpie", test("zero==1?'foobie':'blimpie'"));
  58. }
  59. public void testTernary3() {
  60. assertEquals("foobiebarbie", test("zero==1?'foobie':'foobie'+'barbie'"));
  61. }
  62. public void testTernary5() {
  63. assertEquals("skat!", test("isdef someWierdVar ? 'squid' : 'skat!';"));
  64. }
  65. public void testEmptyIf() {
  66. assertEquals(5, test("a = 5; if (a == 5) { }; return a;"));
  67. }
  68. public void testEmptyIf2() {
  69. assertEquals(5, test("a=5;if(a==5){};return a;"));
  70. }
  71. public void testIf() {
  72. String ex = "if (5 > 4) { return 10; } else { return 5; }";
  73. assertEquals(10, MVEL.eval(ex));
  74. Serializable s = MVEL.compileExpression(ex);
  75. assertEquals(10, MVEL.executeExpression(s));
  76. }
  77. public void testIf2() {
  78. assertEquals(10, test("if (5 < 4) { return 5; } else { return 10; }"));
  79. }
  80. public void testIf3() {
  81. String ex = "if(5<4){return 5;}else{return 10;}";
  82. assertEquals(10, MVEL.eval(ex));
  83. assertEquals(10, test("if(5<4){return 5;}else{return 10;}"));
  84. }
  85. public void testIfAndElse() {
  86. assertEquals(true, test("if (false) { return false; } else { return true; }"));
  87. }
  88. public void testIfAndElseif() {
  89. assertEquals(true, test("if (false) { return false; } else if(100 < 50) { return false; } else if (10 > 5) return true;"));
  90. }
  91. public void testIfAndElseif2() {
  92. assertEquals(true, MVEL.eval("if (false) { return false; } else if(100 < 50) { return false; } else if (10 > 5) return true;"));
  93. }
  94. public void testIfAndElseif3() {
  95. assertEquals(true, MVEL.executeExpression(MVEL.compileExpression("if (false) { return false; } else if(100 < 50) { return false; } else if (10 > 5) return true;")));
  96. }
  97. public void testIfAndElseIfCondensedGrammar() {
  98. assertEquals("Foo244", test("if (false) return 'Bar'; else return 'Foo244';"));
  99. }
  100. public void testTernary4() {
  101. assertEquals("<test>", test("true ? '<test>' : '<poo>'"));
  102. }
  103. public void testPrecedenceOrder1() {
  104. String ex = "50 > 60 && 20 < 10 || 100 > 90";
  105. System.out.println("Expression: " + ex);
  106. assertTrue((Boolean) MVEL.eval(ex));
  107. }
  108. public void testDoLoop() {
  109. assertEquals(10, test("i = 0; do { i++ } while (i != 10); i"));
  110. }
  111. public void testDoLoop2() {
  112. assertEquals(50, test("i=100;do{i--}until(i==50); i"));
  113. }
  114. public void testForLoop() {
  115. String ex = "String str = ''; for(i=0;i<6;i++) { str += i }; str";
  116. assertEquals("012345", MVEL.eval(ex, new HashMap()));
  117. assertEquals("012345", test(ex));
  118. }
  119. public void testForLoop2() {
  120. assertEquals("012345", MVEL.eval("String str='';for(i=0;i<6;i++){str+=i};str", new HashMap()));
  121. }
  122. public void testUntilLoop() {
  123. assertEquals("012345", test("String str = ''; int i = 0; until (i == 6) { str += i++; }; str"));
  124. }
  125. public void testQualifiedForLoop() {
  126. ParserContext pCtx = new ParserContext();
  127. pCtx.setStrongTyping(true);
  128. pCtx.addImport(Foo.class);
  129. pCtx.addInput("l", ArrayList.class, new Class[]{Foo.class});
  130. List l = new ArrayList();
  131. l.add(new Foo());
  132. l.add(new Foo());
  133. l.add(new Foo());
  134. Map vars = new HashMap();
  135. vars.put("l", l);
  136. Serializable s = MVEL.compileExpression("String s = ''; for (Foo f : l) { s += f.name }; s", pCtx);
  137. String r = (String) MVEL.executeExpression(s, vars);
  138. assertEquals("dogdogdog", r);
  139. }
  140. public void testForLoopWithVar() {
  141. String str = "int height = 100; int j = 0; for (i = 0; i < height; i++) {j++ }; return j;";
  142. ParserConfiguration pconf = new ParserConfiguration();
  143. ParserContext pctx = new ParserContext(pconf);
  144. pctx.setStrongTyping(true);
  145. ExecutableStatement stmt = (ExecutableStatement) MVEL.compileExpression(str, pctx);
  146. Map vars = new HashMap();
  147. assertEquals( new Integer(100), MVEL.executeExpression(stmt, vars) );
  148. }
  149. public void testEmptyLoopSemantics() {
  150. Serializable s = MVEL.compileExpression("for (i = 0; i < 100000000000; i++) { }");
  151. MVEL.executeExpression(s, new HashMap());
  152. }
  153. public void testLoopWithEscape() {
  154. Serializable s = MVEL.compileExpression("x = 0; for (; x < 10000; x++) {}");
  155. Map<String, Object> vars = new HashMap<String, Object>();
  156. MVEL.executeExpression(s, vars);
  157. assertEquals(10000, vars.get("x"));
  158. vars.remove("x");
  159. MVEL.eval("x = 0; for (; x < 10000; x++) {}", vars);
  160. assertEquals(10000, vars.get("x"));
  161. }
  162. public static class TargetClass {
  163. private short _targetValue = 5;
  164. public short getTargetValue() {
  165. return _targetValue;
  166. }
  167. }
  168. public void testNestedMethodCall() {
  169. List elements = new ArrayList();
  170. elements.add(new TargetClass());
  171. Map variableMap = new HashMap();
  172. variableMap.put("elements",
  173. elements);
  174. eval("results = new java.util.ArrayList(); foreach (element : elements) { " +
  175. "if( {5} contains element.targetValue.intValue()) { results.add(element); } }; results",
  176. variableMap);
  177. }
  178. public void testStaticallyTypedItemInForEach() {
  179. assertEquals("1234",
  180. test("StringBuffer sbuf = new StringBuffer(); foreach (int i : new int[] { 1,2,3,4 })" +
  181. " { sbuf.append(i); }; sbuf.toString()"));
  182. }
  183. public void testJIRA115() {
  184. String exp = "results = new java.util.ArrayList(); foreach (element : elements) { " +
  185. "if( {1,32769,32767} contains element ) { results.add(element); } }; results";
  186. Map map = new HashMap();
  187. map.put("elements",
  188. new int[]{1, 32769, 32767});
  189. ArrayList result = (ArrayList) MVEL.eval(exp,
  190. map);
  191. assertEquals(3,
  192. result.size());
  193. }
  194. public void testStringWithTernaryIf() {
  195. test("System.out.print(\"Hello : \" + (foo != null ? \"FOO!\" : \"NO FOO\") + \". Bye.\");");
  196. }
  197. private static Object testTernary(int i,
  198. String expression) throws Exception {
  199. Object val;
  200. Object val2;
  201. try {
  202. val = executeExpression(compileExpression(expression),
  203. JIRA124_CTX);
  204. }
  205. catch (Exception e) {
  206. System.out.println("FailedCompiled[" + i + "]:" + expression);
  207. throw e;
  208. }
  209. try {
  210. val2 = MVEL.eval(expression,
  211. JIRA124_CTX);
  212. }
  213. catch (Exception e) {
  214. System.out.println("FailedEval[" + i + "]:" + expression);
  215. throw e;
  216. }
  217. if (((val == null || val2 == null) && val != val2) || (val != null && !val.equals(val2))) {
  218. throw new AssertionError("results do not match (" + String.valueOf(val)
  219. + " != " + String.valueOf(val2) + ")");
  220. }
  221. return val;
  222. }
  223. private static Map<String, Boolean> JIRA124_CTX = Collections.singletonMap("testValue",
  224. true);
  225. public void testJIRA124() throws Exception {
  226. assertEquals("A",
  227. testTernary(1,
  228. "testValue == true ? 'A' : 'B' + 'C'"));
  229. assertEquals("AB",
  230. testTernary(2,
  231. "testValue ? 'A' + 'B' : 'C'"));
  232. assertEquals("A",
  233. testTernary(3,
  234. "(testValue ? 'A' : 'B' + 'C')"));
  235. assertEquals("AB",
  236. testTernary(4,
  237. "(testValue ? 'A' + 'B' : 'C')"));
  238. assertEquals("A",
  239. testTernary(5,
  240. "(testValue ? 'A' : ('B' + 'C'))"));
  241. assertEquals("AB",
  242. testTernary(6,
  243. "(testValue ? ('A' + 'B') : 'C')"));
  244. JIRA124_CTX = Collections.singletonMap("testValue",
  245. false);
  246. assertEquals("BC",
  247. testTernary(1,
  248. "testValue ? 'A' : 'B' + 'C'"));
  249. assertEquals("C",
  250. testTernary(2,
  251. "testValue ? 'A' + 'B' : 'C'"));
  252. assertEquals("BC",
  253. testTernary(3,
  254. "(testValue ? 'A' : 'B' + 'C')"));
  255. assertEquals("C",
  256. testTernary(4,
  257. "(testValue ? 'A' + 'B' : 'C')"));
  258. assertEquals("BC",
  259. testTernary(5,
  260. "(testValue ? 'A' : ('B' + 'C'))"));
  261. assertEquals("C",
  262. testTernary(6,
  263. "(testValue ? ('A' + 'B') : 'C')"));
  264. }
  265. /**
  266. * Community provided test cases
  267. */
  268. @SuppressWarnings({"unchecked"})
  269. public void testCalculateAge() {
  270. Calendar c1 = Calendar.getInstance();
  271. c1.set(1999,
  272. 0,
  273. 10); // 1999 jan 20
  274. Map objectMap = new HashMap(1);
  275. Map propertyMap = new HashMap(1);
  276. propertyMap.put("GEBDAT",
  277. c1.getTime());
  278. objectMap.put("EV_VI_ANT1",
  279. propertyMap);
  280. assertEquals("N",
  281. testCompiledSimple(
  282. "new org.mvel2.tests.core.res.PDFFieldUtil().calculateAge(EV_VI_ANT1.GEBDAT) >= 25 ? 'Y' : 'N'",
  283. null,
  284. objectMap));
  285. }
  286. public void testSubEvaluation() {
  287. HashMap<String, Object> map = new HashMap<String, Object>();
  288. map.put("EV_BER_BER_NR",
  289. "12345");
  290. map.put("EV_BER_BER_PRIV",
  291. Boolean.FALSE);
  292. assertEquals("12345",
  293. testCompiledSimple("EV_BER_BER_NR + ((EV_BER_BER_PRIV != empty && EV_BER_BER_PRIV == true) ? \"/PRIVAT\" : '')",
  294. null,
  295. map));
  296. map.put("EV_BER_BER_PRIV",
  297. Boolean.TRUE);
  298. assertEquals("12345/PRIVAT",
  299. testCompiledSimple("EV_BER_BER_NR + ((EV_BER_BER_PRIV != empty && EV_BER_BER_PRIV == true) ? \"/PRIVAT\" : '')",
  300. null,
  301. map));
  302. }
  303. public void testCompactIfElse() {
  304. assertEquals("foo",
  305. test("if (false) 'bar'; else 'foo';"));
  306. }
  307. public void testForInitializerScope() {
  308. String ex = "for (int i = 0; i < 10; i++) { 'fop'; }\n" +
  309. "for (int i = 0; i < 10; i++) { 'foo'; }";
  310. Serializable s = MVEL.compileExpression(ex);
  311. MVEL.executeExpression(s, new HashMap());
  312. }
  313. public void testForEachTerminateFlow() {
  314. String ex = "for(int i=0;i<5;i++) {\n" +
  315. "System.out.println(\"LOOP\" + i);\n" +
  316. "return true;\n" +
  317. "}\n" +
  318. "System.out.println(\"END\");";
  319. Serializable s = MVEL.compileExpression(ex);
  320. assertEquals(true, MVEL.executeExpression(s, new HashMap()));
  321. }
  322. public final void testFunctionCall() {
  323. MVEL.eval(
  324. "def test() { for(i = 0; i < 3; i++) { System.out.println('...') } } \n" +
  325. "test()",
  326. new HashMap<String, Object>());
  327. }
  328. public void testMultipleArgumentsInFunction() {
  329. String expression = "def cond(x, y) {\n" +
  330. "\tif (x ~= \"fet.*\") {\n" +
  331. "\t\tif ((x.endsWith(('sock')))) {\n" +
  332. " \t\t\treturn 1;\n" +
  333. "\t\t} else if ((x.endsWith(('lock')))) {\n" +
  334. " \t\t\treturn [1: ((y > 12) ? 1 : 2), 2: (12 + 1)];\n" +
  335. "\t\t} ;\n" +
  336. "\t}\n" +
  337. "(null).print();\n" + // THIS LINE SHOULD NEVER EXECUTE BUT IT DOES, INCORRECT!
  338. "\n" +
  339. "}\n" +
  340. "\n" +
  341. "cond('fetlock', 12)";
  342. Exception thrown = null;
  343. try {
  344. MVEL.executeExpression(MVEL.compileExpression(expression), new HashMap());
  345. }
  346. catch (Exception e) {
  347. thrown = e;
  348. }
  349. assertNull("Return statement not being honored!", thrown);
  350. }
  351. public void testDhanji1() {
  352. String expression = "def insert(i, ls) {\n" +
  353. " if (ls == empty) {\n" +
  354. " return [];\n" +
  355. " }\n" +
  356. " if (ls is java.util.List) {\n" +
  357. " x = ls[0];\n" +
  358. " xs = ls.size() == 1 ? [] : ls.subList(1, ls.size());\n" +
  359. " return (((i <= x) ? ([i, x] + xs) : insert(i, xs)));\n" +
  360. " }\n" +
  361. "}\n" +
  362. "\n" +
  363. "insert(2, [1, 3, 4])";
  364. Object o = MVEL.eval(expression, new HashMap<String, Object>());
  365. System.out.println(o);
  366. }
  367. // public void testDhanji2() {
  368. // System.out.println(MVEL.eval("x = 1; y = 2; [x,y] + [3,4]", new HashMap<String, Object>()));
  369. // }
  370. private static int fibonacci(int n) {
  371. if (n < 2)
  372. return 1;
  373. else
  374. return fibonacci(n - 2) + fibonacci(n - 1);
  375. }
  376. }