1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19 package org.apache.maven.shared.scriptinterpreter;
20
21 import java.io.ByteArrayOutputStream;
22 import java.io.File;
23 import java.io.PrintStream;
24 import java.util.Collections;
25 import java.util.HashMap;
26 import java.util.List;
27 import java.util.Map;
28
29 import org.junit.jupiter.api.Test;
30
31 import static org.junit.jupiter.api.Assertions.assertEquals;
32
33
34
35
36
37
38 class GroovyScriptInterpreterTest {
39 @Test
40 void testEvaluateScript() throws Exception {
41 ByteArrayOutputStream out = new ByteArrayOutputStream();
42 try (ScriptInterpreter interpreter = new GroovyScriptInterpreter()) {
43 assertEquals(
44 Boolean.TRUE,
45 interpreter.evaluateScript("print \"Test\"\nreturn true", null, new PrintStream(out)));
46 }
47 assertEquals("Test", out.toString());
48 }
49
50 @Test
51 void testEvaluateScriptWithDefaultClassPath() throws Exception {
52 ByteArrayOutputStream out = new ByteArrayOutputStream();
53 try (ScriptInterpreter interpreter = new GroovyScriptInterpreter()) {
54 assertEquals(
55 Boolean.TRUE,
56 interpreter.evaluateScript(
57 "print getClass().getResource( \"/class-path.txt\" ).getPath().toURI().getPath()\nreturn true",
58 null,
59 new PrintStream(out)));
60 }
61
62 String testClassPath =
63 new File("target/test-classes/class-path.txt").toURI().getPath();
64 assertEquals(testClassPath, out.toString());
65 }
66
67 @Test
68 void testEvaluateScriptWithCustomClassPath() throws Exception {
69 ByteArrayOutputStream out = new ByteArrayOutputStream();
70 try (ScriptInterpreter interpreter = new GroovyScriptInterpreter()) {
71
72 List<String> classPath = Collections.singletonList(new File("src/test-class-path").getAbsolutePath());
73 interpreter.setClassPath(classPath);
74
75 assertEquals(
76 Boolean.TRUE,
77 interpreter.evaluateScript(
78 "print getClass().getResource( \"/class-path.txt\" ).getPath().toURI().getPath()\nreturn true",
79 null,
80 new PrintStream(out)));
81 }
82
83 String testClassPath =
84 new File("src/test-class-path/class-path.txt").toURI().getPath();
85 assertEquals(testClassPath, out.toString());
86 }
87
88 @Test
89 void testEvaluateScriptVars() throws Exception {
90 Map<String, Object> vars = new HashMap<>();
91 vars.put("testVar", "data");
92 ByteArrayOutputStream out = new ByteArrayOutputStream();
93 try (ScriptInterpreter interpreter = new GroovyScriptInterpreter()) {
94 assertEquals(
95 Boolean.TRUE, interpreter.evaluateScript("print testVar\nreturn true", vars, new PrintStream(out)));
96 }
97 assertEquals("data", out.toString());
98 }
99 }