Debian Codegraph @

test/jpypetest/test_proxy.py

raw symbols SCIP
1 # *****************************************************************************
2 #
3 # Licensed under the Apache License, Version 2.0 (the "License");
4 # you may not use this file except in compliance with the License.
5 # You may obtain a copy of the License at
6 #
7 # http://www.apache.org/licenses/LICENSE-2.0
8 #
9 # Unless required by applicable law or agreed to in writing, software
10 # distributed under the License is distributed on an "AS IS" BASIS,
11 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 # See the License for the specific language governing permissions and
13 # limitations under the License.
14 #
15 # See NOTICE file for details.
16 #
17 # *****************************************************************************
18 import contextlib
19 import sys
20
21 from jpype import *
22 import _jpype
23 import common
24 import subrun
25
26
27 def _testMethod1():
28 return 33
29
30
31 def _testMethod2():
32 return 32
33
34
35 def _testMethod3():
36 return "Foo"
37
38
39 class C:
40 def testMethod1(self):
41 return 43
42
43 def testMethod2(self):
44 return 42
45
46 def testMethod3(self):
47 return "Bar"
48
49 def write(self, bytes, start, length):
50 return bytes, start, length
51
52
53 class ThreadCallbackImpl:
54 def __init__(self):
55 self.values = []
56
57 def notifyValue(self, val):
58 self.values.append(val)
59
60
61 class ProxyTestCase(common.JPypeTestCase):
62
63 def setUp(self):
64 super(ProxyTestCase, self).setUp()
65 self.package = JPackage("jpype.proxy")
66 self._triggers = self.package.ProxyTriggers
67
68 def testProxyDecl(self):
69 d = {
70 'testMethod1': _testMethod1,
71 'testMethod2': _testMethod2,
72 }
73 itf1 = self.package.TestInterface1
74 itf2 = self.package.TestInterface2
75 proxy = JProxy(itf1, dict=d)
76 proxy = JProxy([itf1], dict=d)
77 proxy = JProxy([itf1, itf2], dict=d)
78 proxy = JProxy("jpype.proxy.TestInterface1", dict=d)
79 proxy = JProxy(["jpype.proxy.TestInterface1"], dict=d)
80
81 def testNotImplemented(self):
82 itf1 = self.package.TestInterface1
83 proxy = JObject(JProxy(itf1, dict={}), itf1)
84 with self.assertRaises(JClass("java.lang.NoSuchMethodError")):
85 proxy.testMethod1()
86
87 def testProxyRoundTrip(self):
88
89 @JImplements(java.lang.Runnable)
90 class MyRun(object):
91 @JOverride
92 def run(self):
93 pass
94
95 al = JClass('java.util.ArrayList')()
96 runner = MyRun()
97 al.add(runner)
98 self.assertIs(al.get(0), runner)
99
100 def testProxyLeak(self):
101
102 @JImplements(java.lang.Runnable)
103 class MyRun(object):
104 @JOverride
105 def run(self):
106 pass
107
108 al = JClass('java.util.ArrayList')()
109 runner = MyRun()
110 al.add(runner)
111 initial = sys.getrefcount(runner)
112 for i in range(0, 10):
113 self.assertIs(al.get(0), runner)
114 final = sys.getrefcount(runner)
115 self.assertEqual(initial, final)
116
117 def testProxyDeclFail1(self):
118 itf1 = self.package.TestInterface1
119 # Missing required arguments
120 with self.assertRaisesRegex(TypeError, "must be specified"):
121 proxy = JProxy(itf1)
122
123 def testProxyDeclFail2(self):
124 itf1 = self.package.TestInterface1
125 # Not a str, JClass, or str
126 with self.assertRaisesRegex(TypeError, "is not a Java interface"):
127 proxy = JProxy(int(1), dict={})
128
129 def testProxyImplementsForm1(self):
130 itf1 = self.package.TestInterface1
131 itf2 = self.package.TestInterface2
132
133 @JImplements(itf1)
134 class MyImpl(object):
135 @JOverride
136 def testMethod1(self):
137 pass
138
139 def testDefault1(self):
140 itf1 = self.package.TestInterface1
141
142 @JImplements(itf1)
143 class MyImpl(object):
144 @JOverride
145 def testMethod1(self):
146 pass
147
148 obj = itf1@MyImpl()
149 self.assertEqual(obj.testDefault(), 1234)
150
151 def testDefault2(self):
152 itf1 = self.package.TestInterface1
153
154 @JImplements(itf1)
155 class MyImpl(object):
156 @JOverride
157 def testMethod1(self):
158 pass
159
160 @JOverride
161 def testDefault(self):
162 return 5678
163
164 obj = itf1@MyImpl()
165 self.assertEqual(obj.testDefault(), 5678)
166
167 def testProxyImplementsForm2(self):
168 itf1 = self.package.TestInterface1
169 itf2 = self.package.TestInterface2
170
171 @JImplements(itf1, itf2)
172 class MyImpl(object):
173 @JOverride
174 def testMethod1(self):
175 pass
176
177 @JOverride
178 def testMethod2(self):
179 pass
180
181 @JOverride
182 def write(self):
183 pass
184
185 def testProxyImplementsForm3(self):
186 @JImplements("jpype.proxy.TestInterface1")
187 class MyImpl(object):
188 @JOverride
189 def testMethod1(self):
190 pass
191
192 def testProxyImplementsForm4(self):
193 @JImplements("jpype.proxy.TestInterface1", "jpype.proxy.TestInterface2")
194 class MyImpl(object):
195 @JOverride
196 def testMethod1(self):
197 pass
198
199 @JOverride
200 def testMethod2(self):
201 pass
202
203 @JOverride
204 def write(self):
205 pass
206
207 def testProxyImplementsFail1(self):
208 with self.assertRaisesRegex(TypeError, "least one Java interface"):
209 # Empty interfaces
210 @JImplements()
211 class MyImpl(object):
212 @JOverride
213 def testMethod1(self):
214 pass
215
216 def testProxyImplementsFail2(self):
217 with self.assertRaisesRegex(TypeError, "is not a Java interface"):
218 # Wrong type
219 @JImplements(int(1))
220 class MyImpl(object):
221 @JOverride
222 def testMethod1(self):
223 pass
224
225 def testProxyImplementsFail3(self):
226 with self.assertRaisesRegex(NotImplementedError, "requires method"):
227 # Missing implementation
228 @JImplements("jpype.proxy.TestInterface1")
229 class MyImpl(object):
230 def testMethod1(self):
231 pass
232
233 def testProxyImplementsFail4(self):
234 with self.assertRaisesRegex(TypeError, "is not a Java interface"):
235 # extends
236 @JImplements("java.lang.StringBuilder")
237 class MyImpl(object):
238 def testMethod1(self):
239 pass
240
241 def testProxyWithDict(self):
242 d = {
243 'testMethod1': _testMethod1,
244 'testMethod2': _testMethod2,
245 }
246 itf1 = self.package.TestInterface1
247 itf2 = self.package.TestInterface2
248 proxy = JProxy([itf1, itf2], dict=d)
249
250 result = self._triggers.testProxy(proxy)
251
252 expected = ['Test Method1 = 33', 'Test Method2 = 32']
253 self.assertSequenceEqual(result, expected)
254
255 def testProxyWithDictInherited(self):
256 d = {
257 'testMethod2': _testMethod2,
258 'testMethod3': _testMethod3,
259 }
260 itf3 = self.package.TestInterface3
261 proxy = JProxy(itf3, dict=d)
262
263 result = self._triggers.testProxy(proxy)
264
265 expected = ['Test Method2 = 32', 'Test Method3 = Foo']
266 self.assertSequenceEqual(result, expected)
267
268 def testProxyWithInst(self):
269 itf3 = self.package.TestInterface3
270 c = C()
271 proxy = JProxy(itf3, inst=c)
272
273 result = self._triggers.testProxy(proxy)
274
275 expected = ['Test Method2 = 42', 'Test Method3 = Bar']
276 self.assertSequenceEqual(result, expected)
277
278 def testProxyWithThread(self):
279 itf = self.package.TestThreadCallback
280 tcb = ThreadCallbackImpl()
281 proxy = JProxy(itf, inst=tcb)
282
283 self._triggers().testProxyWithThread(proxy)
284 self.assertEqual(tcb.values, ['Waiting for thread start',
285 '1', '2', '3',
286 'Thread finished'])
287
288 def testProxyWithArguments(self):
289 itf2 = self.package.TestInterface2
290 c = C()
291 proxy = JProxy(itf2, inst=c)
292
293 result = self._triggers().testCallbackWithParameters(proxy)
294
295 bytes, start, length = result
296 self.assertSequenceEqual(bytes, [1, 2, 3, 4])
297 self.assertEqual(start, 12)
298 self.assertEqual(length, 13)
299
300 def testProxyWithMultipleInterface(self):
301 itf1 = self.package.TestInterface1
302 itf2 = self.package.TestInterface2
303 c = C()
304 proxy = JProxy([itf1, itf2], inst=c)
305
306 try:
307 result = self._triggers.testProxy(proxy)
308 except Exception as ex:
309 raise ex
310
311 expected = ['Test Method1 = 43', 'Test Method2 = 42']
312 self.assertSequenceEqual(result, expected)
313
314 def testProxyWithMultipleInterfaceInherited(self):
315 itf2 = self.package.TestInterface2
316 itf3 = self.package.TestInterface3
317 c = C()
318 proxy = JProxy([itf2, itf3], inst=c)
319
320 result = self._triggers().testCallbackWithParameters(proxy)
321
322 bytes, start, length = result
323 self.assertSequenceEqual(bytes, [1, 2, 3, 4])
324 self.assertEqual(start, 12)
325 self.assertEqual(length, 13)
326
327 def testProxyJObjectCast(self):
328 jrun = JClass('java.lang.Runnable')
329 jobj = JClass("java.lang.Object")
330
331 @JImplements(jrun)
332 class MyClass(object):
333 @JOverride
334 def run(self):
335 pass
336 self.assertIsInstance(JObject(MyClass(), jrun), jrun)
337 self.assertIsInstance(JObject(MyClass()), jobj)
338
339 def testProxyConvert(self):
340 # This was tests that arguments and "self" both
341 # convert to the same object
342 TestInterface5 = JClass("jpype.proxy.TestInterface5")
343 ProxyTriggers = JClass("jpype.proxy.ProxyTriggers")
344
345 @JImplements(TestInterface5)
346 class Bomb(object):
347 @JOverride
348 def equals(self, other):
349 return type(self) == type(other)
350
351 b = Bomb()
352 t = ProxyTriggers()
353 self.assertTrue(t.testEquals(b))
354
355 def testProxyBoth(self):
356 myobj = object()
357 def myimpl(x):
358 self.assertEqual(myobj, x)
359 return 33
360 d = {
361 'testMethod1': myimpl,
362 }
363 itf1 = self.package.TestInterface1
364 jobj = itf1@JProxy(inst=myobj, dict=d, intf=itf1)
365 self.assertEqual(jobj.testMethod1(), 33)
366
367 def testValid(self):
368 @JImplements("java.util.Comparator")
369 class ValidComparator(object):
370 @JOverride
371 def compare(self, _o1, _o2):
372 return 0
373
374 @JOverride
375 def equals(self, _obj):
376 return True
377 arr = JArray(JString)(["a", "b"])
378 java.util.Arrays.sort(arr, ValidComparator())
379
380 def testRaisePython(self):
381 @JImplements("java.util.Comparator")
382 class RaiseException(object):
383 def __init__(self, exc):
384 self.exc = exc
385
386 @JOverride
387 def compare(self, _o1, _o2):
388 raise self.exc("nobody expects the Python exception!")
389
390 @JOverride
391 def equals(self, _obj):
392 return True
393 arr = JArray(JString)(["a", "b"])
394 with self.assertRaises(TypeError):
395 java.util.Arrays.sort(arr, RaiseException(TypeError))
396 with self.assertRaises(ValueError):
397 java.util.Arrays.sort(arr, RaiseException(ValueError))
398 with self.assertRaises(SyntaxError):
399 java.util.Arrays.sort(arr, RaiseException(SyntaxError))
400 with self.assertRaises(java.lang.RuntimeException):
401 java.util.Arrays.sort(
402 arr, RaiseException(java.lang.RuntimeException))
403
404 def testBad(self):
405 @JImplements("java.util.Comparator")
406 class TooManyParams(object):
407 @JOverride
408 def compare(self, _o1, _o2, _o3):
409 return 0
410
411 @JOverride
412 def equals(self, _obj):
413 return True
414
415 @JImplements("java.util.Comparator")
416 class TooFewParams(object):
417 @JOverride
418 def compare(self, _o1):
419 return 0
420
421 @JOverride
422 def equals(self, _obj):
423 return True
424
425 arr = JArray(JString)(["a", "b"])
426 with self.assertRaises(TypeError):
427 java.util.Arrays.sort(arr, TooManyParams())
428 with self.assertRaises(TypeError):
429 java.util.Arrays.sort(arr, TooFewParams())
430
431 def testUnwrap(self):
432 fixture = JClass("jpype.common.Fixture")()
433
434 @JImplements("java.io.Serializable")
435 class Q(object):
436 pass
437
438 q = Q()
439 self.assertEqual(JProxy.unwrap(q), q)
440 q2 = fixture.callObject(q)
441 self.assertEqual(JProxy.unwrap(q2), q)
442
443 class R(object):
444 pass
445 r = R()
446 s = JProxy("java.io.Serializable", inst=r)
447 self.assertEqual(JProxy.unwrap(s), r)
448 s2 = fixture.callObject(s)
449 self.assertEqual(JProxy.unwrap(s2), r)
450
451 def testConvert(self):
452 fixture = JClass("jpype.common.Fixture")()
453
454 class R(object):
455 pass
456 r = R()
457 # Verify with not asked to auto convert it doesn't
458 s = JProxy("java.io.Serializable", inst=r)
459 s2 = fixture.callObject(s)
460 self.assertEqual(s2, s)
461 self.assertNotEqual(s2, r)
462
463 # Verify that when asked to auto convert it does
464 s = JProxy("java.io.Serializable", inst=r, convert=True)
465 s2 = fixture.callObject(s)
466 self.assertNotEqual(s2, s)
467 self.assertEqual(s2, r)
468
469 def testMethods(self):
470 fixture = JClass("jpype.common.Fixture")()
471
472 @JImplements("java.io.Serializable")
473 class R(object):
474 pass
475 r = R()
476 s = JObject(r)
477 # Check if Java will be able to work with this object safely
478 self.assertTrue(s.equals(s))
479 self.assertIsInstance(s.getClass(), java.lang.Class)
480 self.assertIsInstance(s.toString(), java.lang.String)
481 self.assertIsInstance(s.hashCode(), int)
482
483 def testMethods2(self):
484 fixture = JClass("jpype.common.Fixture")()
485
486 class R(object):
487 pass
488 r = JProxy("java.io.Serializable", inst=R())
489 s = JObject(r)
490 # Check if Java will be able to work with this object safely
491 self.assertTrue(s.equals(s))
492 self.assertIsInstance(s.getClass(), java.lang.Class)
493 self.assertIsInstance(s.toString(), java.lang.String)
494 self.assertIsInstance(s.hashCode(), int)
495
496 def testDeferredCheckingFailure(self):
497 @JImplements("java.lang.Runnable", deferred=True)
498 class MyImpl(object):
499 pass
500
501 with self.assertRaisesRegex(NotImplementedError, "requires method"):
502 MyImpl()
503
504 def testDeferredCheckingValid(self):
505 @JImplements("java.lang.Runnable", deferred=True)
506 class MyImpl(object):
507 @JOverride
508 def run(self):
509 pass
510
511 assert isinstance(MyImpl(), MyImpl)
512
513 def testWeak(self):
514 hc = java.lang.System.identityHashCode
515
516 @JImplements("java.io.Serializable")
517 class MyObj(object):
518 pass
519
520 def f():
521 obj = MyObj()
522 jobj = JObject(obj)
523 i = hc(obj)
524 return i, obj
525 i0, obj = f()
526 i1 = hc(obj)
527 # These should be the same if unless the reference was broken
528 self.assertEqual(i0, i1)
529
530 def testFunctional(self):
531 def SupplierFunc():
532 return 561
533 js = JObject(SupplierFunc, "java.util.function.Supplier")
534 self.assertEqual(js.get(), 561)
535
536 def testFunctionalLambda(self):
537 js = JObject(lambda x: 2 * x, "java.util.function.DoubleUnaryOperator")
538 self.assertEqual(js.applyAsDouble(1), 2.0)
539
540 def testBadImplements(self):
541 with self.assertRaises(TypeError):
542 @JImplements("java.lang.Runnable")
543 def MyImpl(object):
544 @JOverride
545 def run(self):
546 pass
547
548 def testInternal(self):
549 with self.assertRaises(TypeError):
550 _jpype._JProxy(None, None, None)
551 with self.assertRaises(TypeError):
552 _jpype._JProxy(None, None, [])
553 with self.assertRaises(TypeError):
554 _jpype._JProxy(None, None, [type])
555
556
557 @subrun.TestCase(individual=True)
558 class TestProxyDefinitionWithoutJVM(common.JPypeTestCase):
559 def setUp(self):
560 # Explicitly *don't* call the parent setUp as this would start the JVM.
561 pass
562
563 @contextlib.contextmanager
564 def assertRaisesJVMNotRunning(self):
565 with self.assertRaisesRegex(
566 RuntimeError, "Java Virtual Machine is not running"):
567 yield
568
569 def testDeferredCheckingNeedsJVM(self):
570 @JImplements("java.lang.Runnable", deferred=True)
571 class MyImpl(object):
572 pass
573
574 with self.assertRaisesJVMNotRunning():
575 MyImpl()
576
577 def testNotDeferredChecking(self):
578 with self.assertRaisesJVMNotRunning():
579 @JImplements("java.lang.Runnable", deferred=False)
580 class MyImpl(object):
581 pass
582
583 def testDeferredDefault(self):
584 with self.assertRaisesJVMNotRunning():
585 @JImplements("java.lang.Runnable")
586 class MyImpl(object):
587 pass
588
589 def testValidDeferredJVMNotRunning(self):
590 @JImplements("java.lang.Runnable", deferred=True)
591 class MyImpl(object):
592 @JOverride
593 def run(self):
594 pass
595
596 with self.assertRaisesJVMNotRunning():
597 MyImpl()
598
599 def testValidDeferredJVMRunning(self):
600 @JImplements("java.lang.Runnable", deferred=True)
601 class MyImpl(object):
602 @JOverride
603 def run(self):
604 pass
605
606 startJVM()
607 assert isinstance(MyImpl(), MyImpl)
608