java_gateway_test.py
44.5 KB
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
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
# -*- coding: UTF-8 -*-
"""
Created on Dec 10, 2009
@author: barthelemy
"""
from __future__ import unicode_literals, absolute_import
from collections import deque
from contextlib import contextmanager
from decimal import Decimal
import gc
import math
from multiprocessing import Process
import os
from socket import AF_INET, SOCK_STREAM, socket
import subprocess
import tempfile
from threading import Thread
import time
from traceback import print_exc
import unittest
from py4j.compat import (
range, isbytearray, ispython3bytestr, bytearray2, long,
Queue)
from py4j.finalizer import ThreadSafeFinalizer
from py4j.java_gateway import (
JavaGateway, JavaMember, get_field, get_method,
GatewayClient, set_field, java_import, JavaObject, is_instance_of,
GatewayParameters, CallbackServerParameters, quiet_close, DEFAULT_PORT,
set_default_callback_accept_timeout, GatewayConnectionGuard,
get_java_class)
from py4j.protocol import (
Py4JError, Py4JJavaError, Py4JNetworkError, decode_bytearray,
encode_bytearray, escape_new_line, unescape_new_line, smart_decode)
SERVER_PORT = 25333
TEST_PORT = 25332
PY4J_PREFIX_PATH = os.path.dirname(os.path.realpath(__file__))
PY4J_JAVA_PATHS = [
os.path.join(PY4J_PREFIX_PATH,
"../../../../py4j-java/build/classes/main"), # gradle
os.path.join(PY4J_PREFIX_PATH,
"../../../../py4j-java/build/classes/test"), # gradle
os.path.join(PY4J_PREFIX_PATH,
"../../../../py4j-java/build/classes/java/main"), # gradle 4
os.path.join(PY4J_PREFIX_PATH,
"../../../../py4j-java/build/classes/java/test"), # gradle 4
os.path.join(PY4J_PREFIX_PATH,
"../../../../py4j-java/build/resources/main"), # gradle
os.path.join(PY4J_PREFIX_PATH,
"../../../../py4j-java/build/resources/test"), # gradle
os.path.join(PY4J_PREFIX_PATH,
"../../../../py4j-java/target/classes/"), # maven
os.path.join(PY4J_PREFIX_PATH,
"../../../../py4j-java/target/test-classes/"), # maven
os.path.join(PY4J_PREFIX_PATH,
"../../../../py4j-java/bin"), # ant
]
PY4J_JAVA_PATH = os.pathsep.join(PY4J_JAVA_PATHS)
set_default_callback_accept_timeout(0.125)
def stderr_is_polluted(line):
"""May occur depending on the environment in which py4j is executed.
The stderr ccanot be relied on when it occurs.
"""
return "Picked up _JAVA_OPTIONS" in line
def sleep(sleep_time=0.250):
"""Default sleep time to enable the OS to reuse address and port.
"""
time.sleep(sleep_time)
def start_echo_server():
subprocess.call(["java", "-cp", PY4J_JAVA_PATH, "py4j.EchoServer"])
def start_echo_server_process():
# XXX DO NOT FORGET TO KILL THE PROCESS IF THE TEST DOES NOT SUCCEED
sleep()
p = Process(target=start_echo_server)
p.start()
sleep(1.5)
return p
def start_example_server():
subprocess.call([
"java", "-Xmx512m", "-cp", PY4J_JAVA_PATH,
"py4j.examples.ExampleApplication"])
def start_short_timeout_example_server():
subprocess.call([
"java", "-Xmx512m", "-cp", PY4J_JAVA_PATH,
"py4j.examples.ExampleApplication$ExampleShortTimeoutApplication"])
def start_ipv6_example_server():
subprocess.call([
"java", "-Xmx512m", "-cp", PY4J_JAVA_PATH,
"py4j.examples.ExampleApplication$ExampleIPv6Application"])
def start_example_app_process():
# XXX DO NOT FORGET TO KILL THE PROCESS IF THE TEST DOES NOT SUCCEED
p = Process(target=start_example_server)
p.start()
sleep()
check_connection()
return p
def start_short_timeout_app_process():
# XXX DO NOT FORGET TO KILL THE PROCESS IF THE TEST DOES NOT SUCCEED
p = Process(target=start_short_timeout_example_server)
p.start()
sleep()
check_connection()
return p
def start_ipv6_app_process():
# XXX DO NOT FORGET TO KILL THE PROCESS IF THE TEST DOES NOT SUCCEED
p = Process(target=start_ipv6_example_server)
p.start()
# Sleep twice because we do not check connections.
sleep()
sleep()
return p
def check_connection(gateway_parameters=None):
test_gateway = JavaGateway(gateway_parameters=gateway_parameters)
try:
# Call a dummy method just to make sure we can connect to the JVM
test_gateway.jvm.System.currentTimeMillis()
except Py4JNetworkError:
# We could not connect. Let"s wait a long time.
# If it fails after that, there is a bug with our code!
sleep(2)
finally:
test_gateway.close()
def get_socket():
testSocket = socket(AF_INET, SOCK_STREAM)
testSocket.connect(("127.0.0.1", TEST_PORT))
return testSocket
def safe_shutdown(instance):
if hasattr(instance, 'gateway'):
try:
instance.gateway.shutdown()
except Exception:
print_exc()
@contextmanager
def gateway(*args, **kwargs):
g = JavaGateway(
gateway_parameters=GatewayParameters(
*args, auto_convert=True, **kwargs))
time = g.jvm.System.currentTimeMillis()
try:
yield g
# Call a dummy method to make sure we haven't corrupted the streams
assert time <= g.jvm.System.currentTimeMillis()
finally:
g.shutdown()
@contextmanager
def example_app_process():
p = start_example_app_process()
try:
yield p
finally:
p.join()
class TestConnection(object):
"""Connection that does nothing. Useful for testing."""
counter = -1
def __init__(self, return_message="yro"):
self.address = "127.0.0.1"
self.port = 1234
self.return_message = return_message
self.is_connected = True
def start(self):
pass
def stop(self):
pass
def send_command(self, command):
TestConnection.counter += 1
if not command.startswith("m\nd\n"):
self.last_message = command
return self.return_message + str(TestConnection.counter)
class ProtocolTest(unittest.TestCase):
def tearDown(self):
# Safety check in case there was an exception...
safe_shutdown(self)
def testEscape(self):
self.assertEqual("Hello\t\rWorld\n\\", unescape_new_line(
escape_new_line("Hello\t\rWorld\n\\")))
self.assertEqual("Hello\t\rWorld\n\\", unescape_new_line(
escape_new_line("Hello\t\rWorld\n\\")))
def testProtocolSend(self):
testConnection = TestConnection()
self.gateway = JavaGateway()
# Replace gateway client by test connection
self.gateway.set_gateway_client(testConnection)
e = self.gateway.getExample()
self.assertEqual("c\nt\ngetExample\ne\n", testConnection.last_message)
e.method1(1, True, "Hello\nWorld", e, None, 1.5)
self.assertEqual(
"c\no0\nmethod1\ni1\nbTrue\nsHello\\nWorld\nro0\nn\nd1.5\ne\n",
testConnection.last_message)
del(e)
def testProtocolReceive(self):
p = start_echo_server_process()
try:
testSocket = get_socket()
testSocket.sendall("!yo\n".encode("utf-8"))
testSocket.sendall("!yro0\n".encode("utf-8"))
testSocket.sendall("!yo\n".encode("utf-8"))
testSocket.sendall("!ysHello World\n".encode("utf-8"))
# No extra echange (method3) because it is already cached.
testSocket.sendall("!yi123\n".encode("utf-8"))
testSocket.sendall("!yd1.25\n".encode("utf-8"))
testSocket.sendall("!yo\n".encode("utf-8"))
testSocket.sendall("!yn\n".encode("utf-8"))
testSocket.sendall("!yo\n".encode("utf-8"))
testSocket.sendall("!ybTrue\n".encode("utf-8"))
testSocket.sendall("!yo\n".encode("utf-8"))
testSocket.sendall("!yL123\n".encode("utf-8"))
testSocket.sendall("!ydinf\n".encode("utf-8"))
testSocket.close()
sleep()
self.gateway = JavaGateway(
gateway_parameters=GatewayParameters(auto_field=True))
ex = self.gateway.getNewExample()
self.assertEqual("Hello World", ex.method3(1, True))
self.assertEqual(123, ex.method3())
self.assertAlmostEqual(1.25, ex.method3())
self.assertTrue(ex.method2() is None)
self.assertTrue(ex.method4())
self.assertEqual(long(123), ex.method8())
self.assertEqual(float("inf"), ex.method8())
self.gateway.shutdown()
except Exception:
print_exc()
self.fail("Problem occurred")
p.join()
class IntegrationTest(unittest.TestCase):
def setUp(self):
self.p = start_echo_server_process()
# This is to ensure that the server is started before connecting to it!
def tearDown(self):
# Safety check in case there was an exception...
safe_shutdown(self)
self.p.join()
def testIntegration(self):
try:
testSocket = get_socket()
testSocket.sendall("!yo\n".encode("utf-8"))
testSocket.sendall("!yro0\n".encode("utf-8"))
testSocket.sendall("!yo\n".encode("utf-8"))
testSocket.sendall("!ysHello World\n".encode("utf-8"))
testSocket.sendall("!yro1\n".encode("utf-8"))
testSocket.sendall("!yo\n".encode("utf-8"))
testSocket.sendall("!ysHello World2\n".encode("utf-8"))
testSocket.close()
sleep()
self.gateway = JavaGateway(
gateway_parameters=GatewayParameters(auto_field=True))
ex = self.gateway.getNewExample()
response = ex.method3(1, True)
self.assertEqual("Hello World", response)
ex2 = self.gateway.entry_point.getNewExample()
response = ex2.method3(1, True)
self.assertEqual("Hello World2", response)
self.gateway.shutdown()
except Exception:
self.fail("Problem occurred")
def testException(self):
try:
testSocket = get_socket()
testSocket.sendall("!yo\n".encode("utf-8"))
testSocket.sendall("!yro0\n".encode("utf-8"))
testSocket.sendall("!yo\n".encode("utf-8"))
testSocket.sendall(b"!x\n")
testSocket.close()
sleep()
self.gateway = JavaGateway(
gateway_parameters=GatewayParameters(auto_field=True))
ex = self.gateway.getNewExample()
self.assertRaises(Py4JError, lambda: ex.method3(1, True))
self.gateway.shutdown()
except Exception:
self.fail("Problem occurred")
class CloseTest(unittest.TestCase):
def testNoCallbackServer(self):
# Test that the program can continue to move on and that no close
# is required.
JavaGateway()
self.assertTrue(True)
def testCallbackServer(self):
# A close is required to stop the thread.
gateway = JavaGateway(
callback_server_parameters=CallbackServerParameters())
gateway.close()
self.assertTrue(True)
sleep(2)
class MethodTest(unittest.TestCase):
def setUp(self):
self.p = start_example_app_process()
# This is to ensure that the server is started before connecting to it!
self.gateway = JavaGateway()
def tearDown(self):
safe_shutdown(self)
self.p.join()
def testNoneArg(self):
ex = self.gateway.getNewExample()
try:
ex.method2(None)
ex2 = ex.method4(None)
self.assertEquals(ex2.getField1(), 3)
self.assertEquals(2, ex.method7(None))
except Exception:
print_exc()
self.fail()
def testUnicode(self):
sb = self.gateway.jvm.java.lang.StringBuffer()
sb.append("\r\n\tHello\r\n\t")
self.assertEqual("\r\n\tHello\r\n\t", sb.toString())
def testEscape(self):
sb = self.gateway.jvm.java.lang.StringBuffer()
sb.append("\r\n\tHello\r\n\t")
self.assertEqual("\r\n\tHello\r\n\t", sb.toString())
class FieldTest(unittest.TestCase):
def setUp(self):
self.p = start_example_app_process()
def tearDown(self):
safe_shutdown(self)
self.p.join()
def testAutoField(self):
self.gateway = JavaGateway(
gateway_parameters=GatewayParameters(auto_field=True))
ex = self.gateway.getNewExample()
self.assertEqual(ex.field10, 10)
self.assertEqual(ex.field11, long(11))
sb = ex.field20
sb.append("Hello")
self.assertEqual("Hello", sb.toString())
self.assertTrue(ex.field21 is None)
def testAutoFieldDeprecated(self):
self.gateway = JavaGateway(auto_field=True)
ex = self.gateway.getNewExample()
self.assertEqual(ex.field10, 10)
def testNoField(self):
self.gateway = JavaGateway(
gateway_parameters=GatewayParameters(auto_field=True))
ex = self.gateway.getNewExample()
member = ex.field50
self.assertTrue(isinstance(member, JavaMember))
def testNoAutoField(self):
self.gateway = JavaGateway(
gateway_parameters=GatewayParameters(auto_field=False))
ex = self.gateway.getNewExample()
self.assertTrue(isinstance(ex.field10, JavaMember))
self.assertTrue(isinstance(ex.field50, JavaMember))
self.assertEqual(10, get_field(ex, "field10"))
# This field does not exist
self.assertRaises(Exception, get_field, ex, "field50")
# With auto field = True
ex._auto_field = True
sb = ex.field20
sb.append("Hello")
self.assertEqual("Hello", sb.toString())
def testSetField(self):
self.gateway = JavaGateway(
gateway_parameters=GatewayParameters(auto_field=False))
ex = self.gateway.getNewExample()
set_field(ex, "field10", 2334)
self.assertEquals(get_field(ex, "field10"), 2334)
sb = self.gateway.jvm.java.lang.StringBuffer("Hello World!")
set_field(ex, "field21", sb)
self.assertEquals(get_field(ex, "field21").toString(), "Hello World!")
self.assertRaises(Exception, set_field, ex, "field1", 123)
def testGetMethod(self):
# This is necessary if a field hides a method...
self.gateway = JavaGateway()
ex = self.gateway.getNewExample()
self.assertEqual(1, get_method(ex, "method1")())
class DeprecatedTest(unittest.TestCase):
def setUp(self):
self.p = start_example_app_process()
def test_gateway_client(self):
gateway_client = GatewayClient(port=DEFAULT_PORT)
self.gateway = JavaGateway(gateway_client=gateway_client)
i = self.gateway.jvm.System.currentTimeMillis()
self.assertGreater(i, 0)
def tearDown(self):
safe_shutdown(self)
self.p.join()
class UtilityTest(unittest.TestCase):
def setUp(self):
self.p = start_example_app_process()
self.gateway = JavaGateway()
def tearDown(self):
safe_shutdown(self)
self.p.join()
def testGetJavaClass(self):
ArrayList = self.gateway.jvm.java.util.ArrayList
clazz1 = ArrayList._java_lang_class
clazz2 = get_java_class(ArrayList)
self.assertEqual("java.util.ArrayList", clazz1.getName())
self.assertEqual("java.util.ArrayList", clazz2.getName())
self.assertEqual("java.lang.Class", clazz1.getClass().getName())
self.assertEqual("java.lang.Class", clazz2.getClass().getName())
def testIsInstance(self):
a_list = self.gateway.jvm.java.util.ArrayList()
a_map = self.gateway.jvm.java.util.HashMap()
# FQN
self.assertTrue(is_instance_of(self.gateway, a_list, "java.util.List"))
self.assertFalse(
is_instance_of(
self.gateway, a_list, "java.lang.String"))
# JavaClass
self.assertTrue(
is_instance_of(
self.gateway, a_list, self.gateway.jvm.java.util.List))
self.assertFalse(
is_instance_of(
self.gateway, a_list, self.gateway.jvm.java.lang.String))
# JavaObject
self.assertTrue(is_instance_of(self.gateway, a_list, a_list))
self.assertFalse(is_instance_of(self.gateway, a_list, a_map))
class MemoryManagementTest(unittest.TestCase):
def setUp(self):
ThreadSafeFinalizer.clear_finalizers(True)
self.p = start_example_app_process()
def tearDown(self):
safe_shutdown(self)
self.p.join()
gc.collect()
def testNoAttach(self):
self.gateway = JavaGateway()
gateway2 = JavaGateway()
sb = self.gateway.jvm.java.lang.StringBuffer()
sb.append("Hello World")
self.gateway.shutdown()
self.assertRaises(Exception, lambda: sb.append("Python"))
self.assertRaises(
Exception, lambda: gateway2.jvm.java.lang.StringBuffer())
def testDetach(self):
self.gateway = JavaGateway()
gc.collect()
finalizers_size_start = len(ThreadSafeFinalizer.finalizers)
sb = self.gateway.jvm.java.lang.StringBuffer()
sb.append("Hello World")
self.gateway.detach(sb)
sb2 = self.gateway.jvm.java.lang.StringBuffer()
sb2.append("Hello World")
sb2._detach()
gc.collect()
self.assertEqual(
len(ThreadSafeFinalizer.finalizers) - finalizers_size_start, 0)
self.gateway.shutdown()
def testGCCollect(self):
self.gateway = JavaGateway()
gc.collect()
finalizers_size_start = len(ThreadSafeFinalizer.finalizers)
def internal():
sb = self.gateway.jvm.java.lang.StringBuffer()
sb.append("Hello World")
sb2 = self.gateway.jvm.java.lang.StringBuffer()
sb2.append("Hello World")
finalizers_size_middle = len(ThreadSafeFinalizer.finalizers)
return finalizers_size_middle
finalizers_size_middle = internal()
gc.collect()
# Before collection: two objects created + two returned objects (append
# returns a stringbuffer reference for easy chaining).
self.assertEqual(finalizers_size_middle, 4)
# Assert after collection
self.assertEqual(
len(ThreadSafeFinalizer.finalizers) - finalizers_size_start, 0)
self.gateway.shutdown()
def testGCCollectNoMemoryManagement(self):
self.gateway = JavaGateway(
gateway_parameters=GatewayParameters(
enable_memory_management=False))
gc.collect()
# Should have nothing in the finalizers
self.assertEqual(len(ThreadSafeFinalizer.finalizers), 0)
def internal():
sb = self.gateway.jvm.java.lang.StringBuffer()
sb.append("Hello World")
sb2 = self.gateway.jvm.java.lang.StringBuffer()
sb2.append("Hello World")
finalizers_size_middle = len(ThreadSafeFinalizer.finalizers)
return finalizers_size_middle
finalizers_size_middle = internal()
gc.collect()
# Before collection: two objects created + two returned objects (append
# returns a stringbuffer reference for easy chaining).
self.assertEqual(finalizers_size_middle, 0)
# Assert after collection
self.assertEqual(len(ThreadSafeFinalizer.finalizers), 0)
self.gateway.shutdown()
class TypeConversionTest(unittest.TestCase):
def setUp(self):
self.p = start_example_app_process()
self.gateway = JavaGateway()
def tearDown(self):
safe_shutdown(self)
self.p.join()
def testLongInt(self):
ex = self.gateway.getNewExample()
self.assertEqual(1, ex.method7(1234))
self.assertEqual(4, ex.method7(2147483648))
self.assertEqual(4, ex.method7(-2147483649))
self.assertEqual(4, ex.method7(long(2147483648)))
self.assertEqual(long(4), ex.method8(3))
self.assertEqual(4, ex.method8(3))
self.assertEqual(long(4), ex.method8(long(3)))
self.assertEqual(long(4), ex.method9(long(3)))
try:
ex.method8(3000000000000000000000000000000000000)
self.fail("Should not be able to convert overflowing long")
except Py4JError:
self.assertTrue(True)
# Check that the connection is not broken (refs #265)
self.assertEqual(4, ex.method8(3))
def testBigDecimal(self):
ex = self.gateway.getNewExample()
self.assertEqual(Decimal("2147483.647"), ex.method10(2147483647, 3))
self.assertEqual(Decimal("-13.456"), ex.method10(Decimal("-14.456")))
def testFloatConversion(self):
java_inf = self.gateway.jvm.java.lang.Double.parseDouble("Infinity")
self.assertEqual(float("inf"), java_inf)
java_inf = self.gateway.jvm.java.lang.Double.parseDouble("+Infinity")
self.assertEqual(float("inf"), java_inf)
java_neg_inf = self.gateway.jvm.java.lang.Double.parseDouble(
"-Infinity")
self.assertEqual(float("-inf"), java_neg_inf)
java_nan = self.gateway.jvm.java.lang.Double.parseDouble("NaN")
self.assertTrue(math.isnan(java_nan))
python_double = 17.133574204226083
java_float = self.gateway.jvm.java.lang.Double(python_double)
self.assertAlmostEqual(python_double, java_float, 15)
def testUnboxingInt(self):
ex = self.gateway.getNewExample()
self.assertEqual(4, ex.getInteger(4))
class UnicodeTest(unittest.TestCase):
def setUp(self):
self.p = start_example_app_process()
self.gateway = JavaGateway()
def tearDown(self):
safe_shutdown(self)
self.p.join()
# def testUtfMethod(self):
# ex = self.gateway.jvm.py4j.examples.UTFExample()
# Only works for Python 3
# self.assertEqual(2, ex.strangeMéthod())
def testUnicodeString(self):
# NOTE: this is unicode because of import future unicode literal...
ex = self.gateway.jvm.py4j.examples.UTFExample()
s1 = "allo"
s2 = "alloé"
array1 = ex.getUtfValue(s1)
array2 = ex.getUtfValue(s2)
self.assertEqual(len(s1), len(array1))
self.assertEqual(len(s2), len(array2))
self.assertEqual(ord(s1[0]), array1[0])
self.assertEqual(ord(s2[4]), array2[4])
class StreamTest(unittest.TestCase):
def setUp(self):
self.p = start_example_app_process()
self.gateway = JavaGateway()
def tearDown(self):
safe_shutdown(self)
self.p.join()
def testBinarySuccess(self):
e = self.gateway.getNewExample()
# not binary - just get the Java object
v1 = e.getStream()
self.assertTrue(
is_instance_of(
self.gateway, v1, "java.nio.channels.ReadableByteChannel"))
# pull it as a binary stream
with e.getStream.stream() as conn:
self.assertTrue(isinstance(conn, GatewayConnectionGuard))
expected =\
"Lorem ipsum dolor sit amet, consectetur adipiscing elit."
self.assertEqual(expected, smart_decode(conn.read(len(expected))))
def testBinaryFailure(self):
e = self.gateway.getNewExample()
self.assertRaises(Py4JJavaError, lambda: e.getBrokenStream())
self.assertRaises(Py4JJavaError, lambda: e.getBrokenStream.stream())
def testNotAStream(self):
e = self.gateway.getNewExample()
self.assertEqual(1, e.method1())
self.assertRaises(Py4JError, lambda: e.method1.stream())
class ByteTest(unittest.TestCase):
def setUp(self):
self.p = start_example_app_process()
self.gateway = JavaGateway()
def tearDown(self):
safe_shutdown(self)
self.p.join()
def testJavaByteConversion(self):
ex = self.gateway.jvm.py4j.examples.UTFExample()
ba = bytearray([0, 1, 127, 128, 255, 216, 1, 220])
self.assertEqual(0, ex.getPositiveByteValue(ba[0]))
self.assertEqual(1, ex.getPositiveByteValue(ba[1]))
self.assertEqual(127, ex.getPositiveByteValue(ba[2]))
self.assertEqual(128, ex.getPositiveByteValue(ba[3]))
self.assertEqual(255, ex.getPositiveByteValue(ba[4]))
self.assertEqual(216, ex.getPositiveByteValue(ba[5]))
self.assertEqual(0, ex.getJavaByteValue(ba[0]))
self.assertEqual(1, ex.getJavaByteValue(ba[1]))
self.assertEqual(127, ex.getJavaByteValue(ba[2]))
self.assertEqual(-128, ex.getJavaByteValue(ba[3]))
self.assertEqual(-1, ex.getJavaByteValue(ba[4]))
def testProtocolConversion(self):
# b1 = tobytestr("abc\n")
b2 = bytearray([1, 2, 3, 255, 0, 128, 127])
# encoded1 = encode_bytearray(b1)
encoded2 = encode_bytearray(b2)
# self.assertEqual(b1, decode_bytearray(encoded1))
self.assertEqual(b2, decode_bytearray(encoded2))
def testBytesType(self):
ex = self.gateway.jvm.py4j.examples.UTFExample()
int_list = [0, 1, 10, 127, 128, 255]
ba1 = bytearray(int_list)
# Same for Python2, bytes for Python 3
ba2 = bytearray2(int_list)
a1 = ex.getBytesValue(ba1)
a2 = ex.getBytesValue(ba2)
for i1, i2 in zip(a1, int_list):
self.assertEqual(i1, i2)
for i1, i2 in zip(a2, int_list):
self.assertEqual(i1, i2)
def testBytesType2(self):
ex = self.gateway.jvm.py4j.examples.UTFExample()
int_list = [0, 1, 10, 127, 255, 128]
a1 = ex.getBytesValue()
# Python 2: bytearray (because str is too easy to confuse with normal
# strings)
# Python 3: bytes (because bytes is closer to the byte[] representation
# in Java)
self.assertTrue(isbytearray(a1) or ispython3bytestr(a1))
for i1, i2 in zip(a1, int_list):
self.assertEqual(i1, i2)
def testLargeByteArray(self):
# Regression test for #109, an error when passing large byte arrays.
self.gateway.jvm.java.nio.ByteBuffer.wrap(bytearray(range(255)))
class ExceptionTest(unittest.TestCase):
def setUp(self):
self.p = start_example_app_process()
self.gateway = JavaGateway()
def tearDown(self):
safe_shutdown(self)
self.p.join()
def testJavaError(self):
try:
self.gateway.jvm.Integer.valueOf("allo")
except Py4JJavaError as e:
self.assertEqual(
"java.lang.NumberFormatException",
e.java_exception.getClass().getName())
except Exception:
self.fail()
def testJavaConstructorError(self):
try:
self.gateway.jvm.Integer("allo")
except Py4JJavaError as e:
self.assertEqual(
"java.lang.NumberFormatException",
e.java_exception.getClass().getName())
except Exception:
self.fail()
def doError(self):
id = ""
try:
self.gateway.jvm.Integer.valueOf("allo")
except Py4JJavaError as e:
id = e.java_exception._target_id
return id
def testJavaErrorGC(self):
id = self.doError()
java_object = JavaObject(id, self.gateway._gateway_client)
try:
# Should fail because it should have been garbage collected...
java_object.getCause()
self.fail()
except Py4JError:
self.assertTrue(True)
def testReflectionError(self):
try:
self.gateway.jvm.Integer.valueOf2("allo")
except Py4JJavaError:
self.fail()
except Py4JNetworkError:
self.fail()
except Py4JError:
self.assertTrue(True)
def testStrError(self):
try:
self.gateway.jvm.Integer.valueOf("allo")
except Py4JJavaError as e:
self.assertTrue(str(e).startswith(
"An error occurred while calling z:java.lang.Integer.valueOf."
"\n: java.lang.NumberFormatException:"))
except Exception:
self.fail()
class JVMTest(unittest.TestCase):
def setUp(self):
self.p = start_example_app_process()
self.gateway = JavaGateway()
def tearDown(self):
safe_shutdown(self)
self.p.join()
def testConstructors(self):
jvm = self.gateway.jvm
sb = jvm.java.lang.StringBuffer("hello")
sb.append("hello world")
sb.append(1)
self.assertEqual(sb.toString(), "hellohello world1")
l1 = jvm.java.util.ArrayList()
l1.append("hello world")
l1.append(1)
self.assertEqual(2, len(l1))
self.assertEqual("hello world", l1[0])
l2 = ["hello world", 1]
self.assertEqual(str(l2), str(l1))
def testStaticMethods(self):
System = self.gateway.jvm.java.lang.System
self.assertGreater(System.currentTimeMillis(), 0)
self.assertEqual("123", self.gateway.jvm.java.lang.String.valueOf(123))
def testStaticFields(self):
Short = self.gateway.jvm.java.lang.Short
self.assertEqual(-32768, Short.MIN_VALUE)
System = self.gateway.jvm.java.lang.System
self.assertFalse(System.out.checkError())
def testDefaultImports(self):
self.assertGreater(self.gateway.jvm.System.currentTimeMillis(), 0)
self.assertEqual("123", self.gateway.jvm.String.valueOf(123))
def testNone(self):
ex = self.gateway.entry_point.getNewExample()
ex.method4(None)
def testJavaGatewayServer(self):
server = self.gateway.java_gateway_server
self.assertEqual(
server.getListeningPort(), DEFAULT_PORT)
def testJVMView(self):
newView = self.gateway.new_jvm_view("myjvm")
time = newView.System.currentTimeMillis()
self.assertGreater(time, 0)
time = newView.java.lang.System.currentTimeMillis()
self.assertGreater(time, 0)
def testImport(self):
newView = self.gateway.new_jvm_view("myjvm")
java_import(self.gateway.jvm, "java.util.*")
java_import(self.gateway.jvm, "java.io.File")
self.assertIsNotNone(self.gateway.jvm.ArrayList())
self.assertIsNotNone(self.gateway.jvm.File("hello.txt"))
self.assertRaises(Exception, lambda: newView.File("test.txt"))
java_import(newView, "java.util.HashSet")
self.assertIsNotNone(newView.HashSet())
def testEnum(self):
self.assertEqual("FOO", str(self.gateway.jvm.py4j.examples.Enum2.FOO))
def testInnerClass(self):
self.assertEqual(
"FOO",
str(self.gateway.jvm.py4j.examples.EnumExample.MyEnum.FOO))
self.assertEqual(
"HELLO2",
self.gateway.jvm.py4j.examples.EnumExample.InnerClass.MY_CONSTANT2)
class HelpTest(unittest.TestCase):
def setUp(self):
self.p = start_example_app_process()
self.gateway = JavaGateway()
def tearDown(self):
safe_shutdown(self)
self.p.join()
def testHelpObject(self):
ex = self.gateway.getNewExample()
help_page = self.gateway.help(ex, short_name=True, display=False)
self.assertGreater(len(help_page), 1)
def testHelpObjectWithPattern(self):
ex = self.gateway.getNewExample()
help_page = self.gateway.help(
ex, pattern="m*", short_name=True, display=False)
self.assertGreater(len(help_page), 1)
def testHelpClass(self):
String = self.gateway.jvm.java.lang.String
help_page = self.gateway.help(String, short_name=False, display=False)
self.assertGreater(len(help_page), 1)
self.assertIn("String", help_page)
class Runner(Thread):
def __init__(self, runner_range, gateway):
Thread.__init__(self)
self.range = runner_range
self.gateway = gateway
self.ok = True
def run(self):
ex = self.gateway.getNewExample()
for i in self.range:
try:
l = ex.getList(i)
if len(l) != i:
self.ok = False
break
self.gateway.detach(l)
# gc.collect()
except Exception:
self.ok = False
break
class ThreadTest(unittest.TestCase):
def setUp(self):
self.p = start_example_app_process()
gateway_client = GatewayClient()
self.gateway = JavaGateway()
self.gateway.set_gateway_client(gateway_client)
def tearDown(self):
safe_shutdown(self)
self.p.join()
def testStress(self):
# Real stress test!
# runner1 = Runner(xrange(1,10000,2),self.gateway)
# runner2 = Runner(xrange(1000,1000000,10000), self.gateway)
# runner3 = Runner(xrange(1000,1000000,10000), self.gateway)
# Small stress test
runner1 = Runner(range(1, 10000, 1000), self.gateway)
runner2 = Runner(range(1000, 1000000, 100000), self.gateway)
runner3 = Runner(range(1000, 1000000, 100000), self.gateway)
runner1.start()
runner2.start()
runner3.start()
runner1.join()
runner2.join()
runner3.join()
self.assertTrue(runner1.ok)
self.assertTrue(runner2.ok)
self.assertTrue(runner3.ok)
class GatewayLauncherTest(unittest.TestCase):
def tearDown(self):
safe_shutdown(self)
def testDefaults(self):
self.gateway = JavaGateway.launch_gateway()
self.assertTrue(self.gateway.jvm)
def testJavaPath(self):
self.gateway = JavaGateway.launch_gateway(java_path=None)
self.assertTrue(self.gateway.jvm)
def testCreateNewProcessGroup(self):
self.gateway = JavaGateway.launch_gateway(
create_new_process_group=True)
self.assertTrue(self.gateway.jvm)
def testJavaopts(self):
self.gateway = JavaGateway.launch_gateway(javaopts=["-Xmx64m"])
self.assertTrue(self.gateway.jvm)
def testRedirectToNull(self):
self.gateway = JavaGateway.launch_gateway()
for i in range(4097): # Hangs if not properly redirected
self.gateway.jvm.System.out.println("Test")
def testRedirectToNullOtherProcessGroup(self):
self.gateway = JavaGateway.launch_gateway(
create_new_process_group=True)
for i in range(4097): # Hangs if not properly redirected
self.gateway.jvm.System.out.println("Test")
def testRedirectToQueue(self):
end = os.linesep
qout = Queue()
qerr = Queue()
self.gateway = JavaGateway.launch_gateway(
redirect_stdout=qout, redirect_stderr=qerr)
for i in range(10):
self.gateway.jvm.System.out.println("Test")
self.gateway.jvm.System.err.println("Test2")
sleep()
for i in range(10):
self.assertEqual("Test{0}".format(end), qout.get())
# Assert IN because some Java/OS outputs some garbage on stderr.
line = qerr.get()
if stderr_is_polluted(line):
line = qerr.get()
self.assertIn("Test2{0}".format(end), line)
self.assertTrue(qout.empty)
self.assertTrue(qerr.empty)
def testRedirectToDeque(self):
end = os.linesep
qout = deque()
qerr = deque()
self.gateway = JavaGateway.launch_gateway(
redirect_stdout=qout, redirect_stderr=qerr)
for i in range(10):
self.gateway.jvm.System.out.println("Test")
self.gateway.jvm.System.err.println("Test2")
sleep()
for i in range(10):
self.assertEqual("Test{0}".format(end), qout.pop())
# Assert IN because some Java/OS outputs some garbage on stderr.
line = qerr.pop()
if stderr_is_polluted(line):
line = qerr.pop()
self.assertEqual("Test2{0}".format(end), line)
self.assertEqual(0, len(qout))
self.assertEqual(0, len(qerr))
def testRedirectToFile(self):
end = os.linesep
(out_handle, outpath) = tempfile.mkstemp(text=True)
(err_handle, errpath) = tempfile.mkstemp(text=True)
stdout = open(outpath, "w")
stderr = open(errpath, "w")
try:
self.gateway = JavaGateway.launch_gateway(
redirect_stdout=stdout, redirect_stderr=stderr)
for i in range(10):
self.gateway.jvm.System.out.println("Test")
self.gateway.jvm.System.err.println("Test2")
self.gateway.shutdown()
sleep()
# Should not be necessary
quiet_close(stdout)
quiet_close(stderr)
# Test that the redirect files were written to correctly
with open(outpath, "r") as stdout:
lines = stdout.readlines()
self.assertEqual(10, len(lines))
self.assertEqual("Test{0}".format(end), lines[0])
with open(errpath, "r") as stderr:
lines = stderr.readlines()
if not stderr_is_polluted(lines[0]):
self.assertEqual(10, len(lines))
# XXX Apparently, it's \n by default even on windows...
# Go figure
self.assertEqual("Test2\n", lines[0])
finally:
os.close(out_handle)
os.close(err_handle)
os.unlink(outpath)
os.unlink(errpath)
def testGatewayAuth(self):
self.gateway = JavaGateway.launch_gateway(enable_auth=True)
# Make sure the default client can connect to the server.
klass = self.gateway.jvm.java.lang.String
help_page = self.gateway.help(klass, short_name=True, display=False)
self.assertGreater(len(help_page), 1)
# Replace the client with one that does not authenticate.
# Make sure it fails.
bad_client = GatewayClient(gateway_parameters=GatewayParameters(
address=self.gateway.gateway_parameters.address,
port=self.gateway.gateway_parameters.port))
self.gateway.set_gateway_client(bad_client)
try:
self.gateway.help(klass, short_name=True, display=False)
self.fail("Expected failure to communicate with gateway server.")
except Exception:
# Expected
pass
finally:
# Restore a good client. This allows the gateway to be shut down.
good_client = GatewayClient(
gateway_parameters=self.gateway.gateway_parameters)
self.gateway.set_gateway_client(good_client)
class WaitOperator(object):
def __init__(self, sleepTime):
self.sleepTime = sleepTime
self.callCount = 0
def doOperation(self, i, j):
self.callCount += 1
if self.callCount == 1:
sleep(self.sleepTime)
return i + j
class Java:
implements = ["py4j.examples.Operator"]
class IPv6Test(unittest.TestCase):
def testIpV6(self):
self.p = start_ipv6_app_process()
gateway = JavaGateway(
gateway_parameters=GatewayParameters(address="::1"),
callback_server_parameters=CallbackServerParameters(address="::1"))
try:
timeMillis = gateway.jvm.System.currentTimeMillis()
self.assertGreater(timeMillis, 0)
operator = WaitOperator(0.1)
opExample = gateway.jvm.py4j.examples.OperatorExample()
a_list = opExample.randomBinaryOperator(operator)
self.assertEqual(a_list[0] + a_list[1], a_list[2])
finally:
gateway.shutdown()
self.p.join()
class RetryTest(unittest.TestCase):
def testBadRetry(self):
"""Should not retry from Python to Java.
Python calls a long Java method. The call goes through, but the
response takes a long time to get back.
If there is a bug, Python will fail on read and retry (sending the same
call twice).
If there is no bug, Python will fail on read and raise an Exception.
"""
self.p = start_example_app_process()
gateway = JavaGateway(
gateway_parameters=GatewayParameters(read_timeout=0.250))
try:
value = gateway.entry_point.getNewExample().sleepFirstTimeOnly(500)
self.fail(
"Should never retry once the first command went through."
"number of calls made: {0}".format(value))
except Py4JError:
self.assertTrue(True)
finally:
gateway.shutdown()
self.p.join()
def testGoodRetry(self):
"""Should retry from Python to Java.
Python calls Java twice in a row, then waits, then calls again.
Java fails when it does not receive calls quickly.
If there is a bug, Python will fail on the third call because the Java
connection was closed and it did not retry.
If there is a bug, Python might not fail because Java did not close the
connection on timeout. The connection used to call Java will be the
same one for all calls (and an assertion will fail).
If there is no bug, Python will call Java twice with the same
connection. On the third call, the write will fail, and a new
connection will be created.
"""
self.p = start_short_timeout_app_process()
gateway = JavaGateway()
connections = gateway._gateway_client.deque
try:
# Call #1
gateway.jvm.System.currentTimeMillis()
str_connection = str(connections[0])
# Call #2 after, should not create new connections if the system is
# not too slow :-)
gateway.jvm.System.currentTimeMillis()
self.assertEqual(1, len(connections))
str_connection2 = str(connections[0])
self.assertEqual(str_connection, str_connection2)
sleep(0.5)
gateway.jvm.System.currentTimeMillis()
self.assertEqual(1, len(connections))
str_connection3 = str(connections[0])
# A new connection was automatically created.
self.assertNotEqual(str_connection, str_connection3)
except Py4JError:
self.fail("Should retry automatically by default.")
finally:
gateway.shutdown()
self.p.join()
def testBadRetryFromJava(self):
"""Should not retry from Java to Python.
Similar use case as testBadRetry, but from Java: Java calls a long
Python operation.
If there is a bug, Java will call Python, then read will fail, then it
will call Python again.
If there is no bug, Java will call Python, read will fail, then Java
will raise an Exception that will be received as a Py4JError on the
Python side.
"""
self.p = start_short_timeout_app_process()
gateway = JavaGateway(
callback_server_parameters=CallbackServerParameters())
try:
operator = WaitOperator(0.5)
opExample = gateway.jvm.py4j.examples.OperatorExample()
opExample.randomBinaryOperator(operator)
self.fail(
"Should never retry once the first command went through."
" number of calls made: {0}".format(operator.callCount))
except Py4JJavaError:
self.assertTrue(True)
finally:
gateway.shutdown()
self.p.join()
def testGoodRetryFromJava(self):
"""Should retry from Java to Python.
Similar use case as testGoodRetry, but from Java: Python calls Java,
which calls Python back two times in a row. Then python waits for a
while. Python then calls Java, which calls Python.
Because Python Callback server has been waiting for too much time, the
receiving socket has closed so the call from Java to Python will fail
on send, and Java must retry by creating a new connection
(CallbackConnection).
"""
self.p = start_example_app_process()
gateway = JavaGateway(
callback_server_parameters=CallbackServerParameters(
read_timeout=0.250))
try:
operator = WaitOperator(0)
opExample = gateway.jvm.py4j.examples.OperatorExample()
opExample.randomBinaryOperator(operator)
str_connection = str(list(gateway._callback_server.connections)[0])
opExample.randomBinaryOperator(operator)
str_connection2 = str(
list(gateway._callback_server.connections)[0])
sleep(0.5)
opExample.randomBinaryOperator(operator)
str_connection3 = str(
list(gateway._callback_server.connections)[0])
self.assertEqual(str_connection, str_connection2)
self.assertNotEqual(str_connection, str_connection3)
except Py4JJavaError:
self.fail("Java callbackclient did not retry.")
finally:
gateway.shutdown()
self.p.join()
if __name__ == "__main__":
unittest.main()