This project has retired. For details please refer to its
Attic page.
TestJythonBasic xref
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18 package org.apache.giraph.jython;
19
20 import org.junit.Test;
21 import org.python.core.PyClass;
22 import org.python.core.PyDictionary;
23 import org.python.core.PyInteger;
24 import org.python.core.PyList;
25 import org.python.core.PyObject;
26 import org.python.util.PythonInterpreter;
27
28 import static org.junit.Assert.assertEquals;
29 import static org.junit.Assert.assertTrue;
30
31 public class TestJythonBasic {
32 private static final double DELTA = 0.0000001;
33
34 @Test
35 public void testBasic() {
36 String jython =
37 "class Foo:\n" +
38 " def __init__(self):\n" +
39 " self.map = {\"32\": 32, \"4.3\": 4.3}\n" +
40 " self.list = [ 2, 9, 11 ]\n" +
41 " self.ival = 17\n" +
42 "\n" +
43 "def get_map(foo):\n" +
44 " return foo.map\n" +
45 "\n" +
46 "def get_list(foo):\n" +
47 " return foo.list\n" +
48 "\n" +
49 "def get_ival(foo):\n" +
50 " return foo.ival\n" +
51 "";
52
53 PythonInterpreter interpreter = new PythonInterpreter();
54 interpreter.exec(jython);
55
56 PyObject fooClass = interpreter.get("Foo");
57 assertTrue(fooClass instanceof PyClass);
58
59 PyObject getMapFunc = interpreter.get("get_map");
60 PyObject getListFunc = interpreter.get("get_list");
61 PyObject getIValFunc = interpreter.get("get_ival");
62
63 PyObject foo = fooClass.__call__();
64
65 PyObject mapResult = getMapFunc.__call__(foo);
66 assertTrue(mapResult instanceof PyDictionary);
67 PyDictionary pyMapResult = ((PyDictionary) mapResult);
68 assertEquals(2, pyMapResult.size());
69 Object thirtyTwo = pyMapResult.get("32");
70 assertTrue(thirtyTwo instanceof Integer);
71 assertEquals(32, ((Integer) thirtyTwo).intValue());
72 Object fourPointThree = pyMapResult.get("4.3");
73 assertTrue(fourPointThree instanceof Double);
74 assertEquals(4.3, (Double) fourPointThree, DELTA);
75
76 PyObject listResult = getListFunc.__call__(foo);
77 assertTrue(listResult instanceof PyList);
78 PyList pyListResult = (PyList) listResult;
79 assertEquals(3, pyListResult.size());
80 assertEquals(2, pyListResult.get(0));
81 assertEquals(9, pyListResult.get(1));
82 assertEquals(11, pyListResult.get(2));
83
84 PyObject ivalResult = getIValFunc.__call__(foo);
85 assertTrue(ivalResult instanceof PyInteger);
86 assertEquals(17, ((PyInteger) ivalResult).getValue());
87 }
88 }