1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35 package groovy.lang;
36
37 import groovy.util.GroovyTestCase;
38
39 import java.io.ByteArrayInputStream;
40 import java.util.HashMap;
41 import java.util.Map;
42
43 import org.codehaus.groovy.control.CompilerConfiguration;
44
45 import junit.framework.Test;
46 import junit.framework.TestSuite;
47 import junit.textui.TestRunner;
48
49 /***
50 * @author sam
51 *
52 * To change the template for this generated type comment go to Window -
53 * Preferences - Java - Code Generation - Code and Comments
54 */
55 public class GroovyShellTest extends GroovyTestCase {
56
57 private String script1 = "test = 1";
58
59 public static void main(String[] args) {
60 TestRunner.run(suite());
61 }
62
63 public static Test suite() {
64 return new TestSuite(GroovyShellTest.class);
65 }
66
67 public void testExecuteScript() {
68 GroovyShell shell = new GroovyShell();
69 try {
70 Object result = shell.evaluate(new ByteArrayInputStream(script1.getBytes()), "Test.groovy");
71 assertEquals(new Integer(1), result);
72 }
73 catch (Exception e) {
74 assertTrue(false);
75 }
76 }
77
78 private static class PropertyHolder {
79 private Map map = new HashMap();
80 public void set(String key, Object value) {
81 map.put(key, value);
82 }
83 public Object get(String key) {
84 return map.get(key);
85 }
86 }
87
88 private String script2 = "test.prop = 2\nreturn test.prop";
89
90 public void testExecuteScriptWithContext() {
91 Binding context = new Binding();
92 context.setVariable("test", new PropertyHolder());
93 GroovyShell shell = new GroovyShell(context);
94 try {
95 Object result = shell.evaluate(new ByteArrayInputStream(script2.getBytes()), "Test.groovy");
96 assertEquals(new Integer(2), result);
97 }
98 catch (Exception e) {
99 fail(e.toString());
100 }
101 }
102
103 public void testScriptWithDerivedBaseClass() throws Exception {
104 Binding context = new Binding();
105 CompilerConfiguration config = new CompilerConfiguration();
106 config.setScriptBaseClass(DerivedScript.class.getName());
107 GroovyShell shell = new GroovyShell(context, config);
108 Object result = shell.evaluate("x = 'abc'; doSomething(cheese)");
109 assertEquals("I like Cheddar", result);
110 assertEquals("abc", context.getVariable("x"));
111 }
112 }