File: ScriptEngineTest.java

package info (click to toggle)
jython 2.7.3%2Brepack1-1
  • links: PTS, VCS
  • area: main
  • in suites: bookworm, forky, sid, trixie
  • size: 62,820 kB
  • sloc: python: 641,384; java: 306,981; xml: 2,066; sh: 514; ansic: 126; makefile: 77
file content (394 lines) | stat: -rw-r--r-- 16,725 bytes parent folder | download | duplicates (2)
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
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
package org.python.jsr223;

import java.io.IOException;
import java.io.StringReader;
import java.math.BigInteger;
import java.util.Arrays;

import javax.script.Bindings;
import javax.script.Compilable;
import javax.script.CompiledScript;
import javax.script.Invocable;
import javax.script.ScriptContext;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;
import javax.script.SimpleScriptContext;

import org.junit.Assert;
import org.python.core.Options;
import org.python.core.PyList;
import org.python.core.PyString;

import junit.framework.TestCase;

public class ScriptEngineTest extends TestCase {

    public void testEvalString() throws ScriptException {
        ScriptEngineManager manager = new ScriptEngineManager();
        ScriptEngine pythonEngine = manager.getEngineByName("python");
        ScriptContext context = pythonEngine.getContext();
        context.setAttribute(ScriptEngine.FILENAME, "sample.py", ScriptContext.ENGINE_SCOPE);
        assertNull(pythonEngine.eval("x = 5"));
        assertEquals(5, pythonEngine.eval("x"));
        assertEquals("sample.py", pythonEngine.eval("__file__"));
        pythonEngine.eval("import sys");
        assertEquals(Arrays.asList("sample.py"), pythonEngine.eval("sys.argv"));
    }

    public void testEvalStringArgv() throws ScriptException {
        ScriptEngineManager manager = new ScriptEngineManager();
        ScriptEngine pythonEngine = manager.getEngineByName("python");
        ScriptContext context = pythonEngine.getContext();
        context.setAttribute(ScriptEngine.FILENAME, "sample.py", ScriptContext.ENGINE_SCOPE);
        context.setAttribute(ScriptEngine.ARGV, new String[] {"foo", "bar"}, ScriptContext.ENGINE_SCOPE);
        assertNull(pythonEngine.eval("x = 5"));
        assertEquals(5, pythonEngine.eval("x"));
        assertEquals("sample.py", pythonEngine.eval("__file__"));
        pythonEngine.eval("import sys");
        assertEquals(Arrays.asList("sample.py", "foo", "bar"), pythonEngine.eval("sys.argv"));
    }

    public void testEvalStringNoFilenameWithArgv() throws ScriptException {
        ScriptEngineManager manager = new ScriptEngineManager();
        ScriptEngine pythonEngine = manager.getEngineByName("python");
        ScriptContext context = pythonEngine.getContext();
        context.setAttribute(ScriptEngine.ARGV, new String[] {"foo", "bar"}, ScriptContext.ENGINE_SCOPE);
        assertNull(pythonEngine.eval("x = 5"));
        assertEquals(5, pythonEngine.eval("x"));
        boolean gotExpectedException = false;
        try {
            pythonEngine.eval("__file__");
        } catch (ScriptException e) {
            assertTrue(e.getMessage().startsWith("NameError: "));
            gotExpectedException = true;
        }
        if (!gotExpectedException) {
            fail("Excepted __file__ to be undefined");
        }
        pythonEngine.eval("import sys");
        assertEquals(Arrays.asList("foo", "bar"), pythonEngine.eval("sys.argv"));
    }

    public void testSyntaxError() {
        ScriptEngineManager manager = new ScriptEngineManager();
        ScriptEngine pythonEngine = manager.getEngineByName("python");

        try {
            pythonEngine.eval("5q");
        } catch (ScriptException e) {
            assertEquals(e.getColumnNumber(), 1);
            assertEquals(e.getLineNumber(), 1);
            assertTrue(e.getMessage().startsWith("SyntaxError: "));
            return;
        }
        assertTrue("Expected a ScriptException", false);
    }

    public void testPythonException() {
        ScriptEngineManager manager = new ScriptEngineManager();
        ScriptEngine pythonEngine = manager.getEngineByName("python");

        try {
            pythonEngine.eval("pass\ndel undefined");
        } catch (ScriptException e) {
            assertEquals(e.getLineNumber(), 2);
            assertTrue(e.getMessage().startsWith("NameError: "));
            return;
        }
        assertTrue("Expected a ScriptException", false);
    }

    public void testScriptFilename() {
        ScriptEngineManager manager = new ScriptEngineManager();
        ScriptEngine pythonEngine = manager.getEngineByName("python");
        SimpleScriptContext scriptContext = new SimpleScriptContext();
        scriptContext.setAttribute(ScriptEngine.FILENAME, "sample.py", ScriptContext.ENGINE_SCOPE);
        try {
            pythonEngine.eval("foo", scriptContext);
        } catch (ScriptException e) {
            assertEquals("sample.py", e.getFileName());
            return;
        }
        assertTrue("Expected a ScriptException", false);
    }

    public void testCompileEvalString() throws ScriptException {
        ScriptEngineManager manager = new ScriptEngineManager();
        ScriptEngine pythonEngine = manager.getEngineByName("python");
        ScriptContext context = pythonEngine.getContext();
        context.setAttribute(ScriptEngine.FILENAME, "sample.py", ScriptContext.ENGINE_SCOPE);
        CompiledScript five = ((Compilable)pythonEngine).compile("5");
        assertEquals(5, five.eval());
        assertEquals("sample.py", pythonEngine.eval("__file__"));
        pythonEngine.eval("import sys");
        assertEquals(Arrays.asList("sample.py"), pythonEngine.eval("sys.argv"));
    }

    public void testEvalReader() throws ScriptException {
        ScriptEngineManager manager = new ScriptEngineManager();
        ScriptEngine pythonEngine = manager.getEngineByName("python");
        ScriptContext context = pythonEngine.getContext();
        context.setAttribute(ScriptEngine.FILENAME, "sample.py", ScriptContext.ENGINE_SCOPE);
        assertNull(pythonEngine.eval(new StringReader("x = 5")));
        assertEquals(5, pythonEngine.eval(new StringReader("x")));
        assertEquals("sample.py", pythonEngine.eval("__file__"));
        pythonEngine.eval("import sys");
        assertEquals(Arrays.asList("sample.py"), pythonEngine.eval("sys.argv"));
    }

    public void testCompileEvalReader() throws ScriptException {
        ScriptEngineManager manager = new ScriptEngineManager();
        ScriptEngine pythonEngine = manager.getEngineByName("python");
        ScriptContext context = pythonEngine.getContext();
        context.setAttribute(ScriptEngine.FILENAME, "sample.py", ScriptContext.ENGINE_SCOPE);
        CompiledScript five = ((Compilable)pythonEngine).compile(new StringReader("5"));
        assertEquals(5, five.eval());
        assertEquals("sample.py", pythonEngine.eval("__file__"));
        pythonEngine.eval("import sys");
        assertEquals(Arrays.asList("sample.py"), pythonEngine.eval("sys.argv"));
    }

    public void testBindings() throws ScriptException {
        ScriptEngineManager manager = new ScriptEngineManager();
        ScriptEngine pythonEngine = manager.getEngineByName("python");

        pythonEngine.put("a", 42);
        assertEquals(42, pythonEngine.eval("a"));
        assertNull(pythonEngine.eval("x = 5"));
        assertEquals(5, pythonEngine.get("x"));
        assertNull(pythonEngine.eval("del x"));
        assertNull(pythonEngine.get("x"));
    }

    static class ThreadLocalBindingsTest implements Runnable {

        ScriptEngine engine;
        int value;
        Object x;
        Object name;
        Throwable exception;

        public ThreadLocalBindingsTest(ScriptEngine engine, int value) {
            this.engine = engine;
            this.value = value;
        }

        //@formatter:off
        static final String script = String.join("\n", new String[] {
            "try:",
            "    a",
            "except NameError:",
            "   pass",
            "else:",
            "   raise Exception('a is defined', a)"});
        //@formatter:on

        @Override
        public void run() {
            try {
                Bindings bindings = engine.createBindings();
                assertNull(engine.eval(script, bindings));
                bindings.put("x", value);
                x = engine.eval("x", bindings);
                name = engine.eval("__name__", bindings);
            } catch (Throwable e) {
                e.printStackTrace();
                exception = e;
            }
        }
    }

    /**
     * Test that, with the use of a {@code Bindings} argument to {@code ScriptEngine.eval}, the
     * interpreter is presented with a distinct name space, whether in a thread or not, and
     * that __name__ == "__main__" in the engine-scoped name space (only).
     *
     * @throws Exception
     */
    public void testThreadLocalBindings() throws ScriptException, InterruptedException {
        ScriptEngineManager manager = new ScriptEngineManager();
        ScriptEngine pythonEngine = manager.getEngineByName("python");

        pythonEngine.put("a", 42);
        pythonEngine.put("x", 15);

        // Examine name space of the engine with Bindings
        ThreadLocalBindingsTest test = new ThreadLocalBindingsTest(pythonEngine, -7);
        test.run();     // This does not start a thread
        assertNull(test.exception);
        assertEquals(-7, test.x);
        assertEquals("__builtin__", test.name);

        // Examine name space of the engine with Bindings and in a thread
        ThreadLocalBindingsTest test2 = new ThreadLocalBindingsTest(pythonEngine, -22);
        Thread thread = new Thread(test2);
        thread.start(); // This *does* start a thread
        thread.join();
        assertNull(test2.exception);
        assertEquals(-22, test2.x);
        assertEquals("__builtin__", test2.name);

        // Test name space of the pythonEngine without Bindings is unaffected
        assertEquals(15, pythonEngine.get("x"));
        assertNull(pythonEngine.eval("del x"));
        assertNull(pythonEngine.get("x"));
        assertEquals("__main__", pythonEngine.eval("__name__"));
    }

    public void testInvoke() throws ScriptException, NoSuchMethodException {
        ScriptEngineManager manager = new ScriptEngineManager();
        ScriptEngine pythonEngine = manager.getEngineByName("python");
        Invocable invocableEngine = (Invocable)pythonEngine;

        assertNull(pythonEngine.eval("def f(x): return abs(x)"));
        assertEquals(5, invocableEngine.invokeFunction("f", -5));
        assertEquals("spam", invocableEngine.invokeMethod(new PyString("  spam  "), "strip"));
        assertEquals("spam", invocableEngine.invokeMethod("  spam  ", "strip"));
    }

    public void testInvokeFunctionNoSuchMethod() throws ScriptException {
        ScriptEngineManager manager = new ScriptEngineManager();
        Invocable invocableEngine = (Invocable)manager.getEngineByName("python");

        try {
            invocableEngine.invokeFunction("undefined");
        } catch (NoSuchMethodException e) {
            return;
        }
        assertTrue("Expected a NoSuchMethodException", false);
    }

    public void testInvokeMethodNoSuchMethod() throws ScriptException {
        ScriptEngineManager manager = new ScriptEngineManager();
        Invocable invocableEngine = (Invocable)manager.getEngineByName("python");

        try {
            invocableEngine.invokeMethod("eggs", "undefined");
            fail("Expected a NoSuchMethodException");
        } catch (NoSuchMethodException e) {
            assertEquals("undefined", e.getMessage());
        }
    }

    public void testGetInterface() throws ScriptException, IOException {
        ScriptEngineManager manager = new ScriptEngineManager();
        ScriptEngine pythonEngine = manager.getEngineByName("python");
        Invocable invocableEngine = (Invocable)pythonEngine;

        assertNull(pythonEngine.eval("def read(cb): return 1"));
        Readable readable = invocableEngine.getInterface(Readable.class);
        assertEquals(1, readable.read(null));

        assertNull(pythonEngine.eval("class C(object):\n" + "    def read(self, cb): return 2\n"
                + "c = C()"));
        readable = invocableEngine.getInterface(pythonEngine.get("c"), Readable.class);
        assertEquals(2, readable.read(null));
    }

    public void testInvokeMethodNoSuchArgs() throws ScriptException, NoSuchMethodException {
        ScriptEngineManager manager = new ScriptEngineManager();
        ScriptEngine pythonEngine = manager.getEngineByName("python");
        Invocable invocableEngine = (Invocable)pythonEngine;

        Object newStringCapitalize = invocableEngine.invokeMethod("test", "capitalize");
        assertEquals(newStringCapitalize, "Test");
    }

    public void testPdb() {
        ScriptEngineManager manager = new ScriptEngineManager();
        ScriptEngine pythonEngine = manager.getEngineByName("python");
        // String from issue 1674
        String pdbString = "from pdb import set_trace; set_trace()";
        try {
            pythonEngine.eval(pdbString);
            fail("bdb.BdbQuit expected");
        } catch (ScriptException e) {
            assertTrue(e.getMessage().startsWith("bdb.BdbQuit"));
        }
    }

    // FIXME PyScriptEngineScope lacks items(), iteritems(), and other dict methods
    // This should be added in a future release

    public void testScope_repr() throws ScriptException {
        ScriptEngineManager manager = new ScriptEngineManager();
        ScriptEngine pythonEngine = manager.getEngineByName("python");
        pythonEngine.eval("a = 4");
        pythonEngine.eval("b = 'hi'");
        String repr = (String)pythonEngine.eval("repr(locals())");
        // locals() contains builtins as of 2.7.0, so we need to selectively test
        Assert.assertTrue(repr.contains("'a': 4"));
        Assert.assertTrue(repr.contains("'b': u'hi'"));
    }

    public void testScope_iter() throws ScriptException {
        ScriptEngineManager manager = new ScriptEngineManager();
        ScriptEngine pythonEngine = manager.getEngineByName("python");
        pythonEngine.eval("a = 4");
        pythonEngine.eval("b = 'hi'");
        PyList locals = (PyList) pythonEngine.eval("sorted((item for item in locals()))");
        Assert.assertTrue(locals.contains("a"));
        Assert.assertTrue(locals.contains("b"));
        Assert.assertTrue(locals.contains("__name__"));
    }

    public void testScope_lookup() throws ScriptException {
        ScriptEngineManager manager = new ScriptEngineManager();
        ScriptEngine pythonEngine = manager.getEngineByName("python");
        pythonEngine.eval("a = 4");
        pythonEngine.eval("b = 'hi'");
        pythonEngine.eval("var_a = locals()['a']");
        pythonEngine.eval("arepr = repr(var_a)");
        assertEquals("4", pythonEngine.get("arepr"));
    }

    public void testIssue1681() throws ScriptException {
        ScriptEngineManager manager = new ScriptEngineManager();
        ScriptEngine pythonEngine = manager.getEngineByName("python");
        pythonEngine.eval("from org.python.jsr223 import PythonCallable\n"
                + "class MyPythonCallable(PythonCallable):\n"
                + "    def getAString(self): return 'a string'\n\n"
                + "result = MyPythonCallable().getAString()\n" //
                + "test = MyPythonCallable()\n" //
                + "result2 = test.getAString()");
        assertEquals("a string", pythonEngine.get("result"));
        assertEquals("a string", pythonEngine.get("result2"));
    }

    public void testIssue1698() throws ScriptException {
        ScriptEngineManager manager = new ScriptEngineManager();
        ScriptEngine pythonEngine = manager.getEngineByName("python");
        pythonEngine.eval("import warnings");
        // Would previously fail
        pythonEngine.eval("warnings.warn('test')");
    }

    public void testSiteImportedByDefault() throws ScriptException {
        ScriptEngineManager manager = new ScriptEngineManager();
        ScriptEngine pythonEngine = manager.getEngineByName("python");
        pythonEngine.eval("import sys");
        pythonEngine.eval("'site' in sys.modules");
    }

    public void testSiteCanBeNotImported() throws ScriptException {
        try {
            Options.importSite = false;
            ScriptEngineManager manager = new ScriptEngineManager();
            ScriptEngine pythonEngine = manager.getEngineByName("python");

            pythonEngine.eval("import sys");
            pythonEngine.eval("'site' not in sys.modules");
        } finally {
            Options.importSite = true;
        }
    }

    public void testIssue2090() throws ScriptException {
        ScriptEngineManager manager = new ScriptEngineManager();
        ScriptEngine pythonEngine = manager.getEngineByName("python");
        pythonEngine.eval("a = 10L\n" + "b = a-1");
        Object r = pythonEngine.get("b");
        assertEquals(new BigInteger("9"), r);
    }
}