|
9 | 9 | from py4j.java_gateway import JavaGateway
|
10 | 10 | from py4j.protocol import Py4JNetworkError
|
11 | 11 | from time import sleep
|
| 12 | +from multiprocessing import Process |
| 13 | +from py4j.java_gateway import JavaGateway, GatewayParameters |
12 | 14 |
|
13 | 15 | PY4J_JAVA_PATH='.:../thirdParty/lib//py4j0.10.9.jar:$ZINGG_HOME/common/client/target/zingg-common-client-0.4.0-SNAPSHOT.jar'
|
14 |
| -def start_example_server(): |
| 16 | +def compileGatewayEntry(): |
15 | 17 | subprocess.call([
|
16 | 18 | "javac", "-cp", PY4J_JAVA_PATH,
|
17 | 19 | "TestPy4JGateway.java"])
|
| 20 | + |
| 21 | +def startGatewayEntry(): |
18 | 22 | subprocess.call([
|
19 | 23 | "java", "-Xmx512m", "-cp", PY4J_JAVA_PATH,
|
20 | 24 | "TestPy4JGateway"])
|
| 25 | + |
| 26 | +def start_example_app_process(): |
| 27 | + # XXX DO NOT FORGET TO KILL THE PROCESS IF THE TEST DOES NOT SUCCEED |
| 28 | + p = Process(target=startGatewayEntry) |
| 29 | + p.start() |
| 30 | + sleep(2) |
| 31 | + return p |
21 | 32 |
|
22 |
| -def check_connection(gateway): |
| 33 | +def check_connection(gateway_parameters=None): |
| 34 | + test_gateway = JavaGateway(gateway_parameters=gateway_parameters) |
23 | 35 | try:
|
24 |
| - gateway.jvm.System.currentTimeMillis() |
| 36 | + # Call a dummy method just to make sure we can connect to the JVM |
| 37 | + test_gateway.jvm.System.currentTimeMillis() |
25 | 38 | except Py4JNetworkError:
|
| 39 | + # We could not connect. Let"s wait a long time. |
| 40 | + # If it fails after that, there is a bug with our code! |
26 | 41 | sleep(2)
|
| 42 | + finally: |
| 43 | + test_gateway.close() |
| 44 | + |
| 45 | +def safe_shutdown(instance): |
| 46 | + if hasattr(instance, 'gateway'): |
| 47 | + try: |
| 48 | + instance.gateway.shutdown() |
| 49 | + except Exception: |
| 50 | + print("exception") |
27 | 51 |
|
28 |
| -class MyJavaClass: |
29 |
| - def addition(self, a, b): |
30 |
| - return a + b |
| 52 | + |
31 | 53 |
|
32 | 54 | class MyJavaIntegrationTest(unittest.TestCase):
|
33 | 55 | def setUp(self):
|
34 |
| - start_example_server() |
35 |
| - self.gateway = JavaGateway() |
36 |
| - check_connection(self.gateway) |
| 56 | + compileGatewayEntry() |
| 57 | + self.p = start_example_app_process() |
| 58 | + self.gateway = JavaGateway( |
| 59 | + gateway_parameters=GatewayParameters(auto_convert=True)) |
37 | 60 |
|
38 | 61 | def tearDown(self):
|
39 |
| - self.gateway.close() |
| 62 | + safe_shutdown(self) |
| 63 | + self.p.join() |
| 64 | + sleep(2) |
| 65 | + |
40 | 66 |
|
41 | 67 | def test_jvm_access(self):
|
42 | 68 | print("Accessing the JVM...")
|
|
0 commit comments