Debian Codegraph @

test/jpypetest/test_jshort.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 sys
19 import jpype
20 import common
21 import random
22 import _jpype
23 import jpype
24 from jpype import java
25 from jpype.types import *
26 try:
27 import numpy as np
28 except ImportError:
29 pass
30
31 VALUES = [random.randint(-2**15, 2**15 - 1) for i in range(10)]
32
33
34 class JShortTestCase(common.JPypeTestCase):
35 def setUp(self):
36 common.JPypeTestCase.setUp(self)
37 self.cls = JClass("jpype.common.Fixture")
38 self.fixture = self.cls()
39
40 @common.requireInstrumentation
41 def testJPNumberLong_int(self):
42 jd = JShort(1)
43 _jpype.fault("PyJPNumberLong_int")
44 with self.assertRaisesRegex(SystemError, "fault"):
45 int(jd)
46 _jpype.fault("PyJPModule_getContext")
47 with self.assertRaisesRegex(SystemError, "fault"):
48 int(jd)
49 int(jd)
50
51 @common.requireInstrumentation
52 def testJPNumberLong_float(self):
53 jd = JShort(1)
54 _jpype.fault("PyJPNumberLong_float")
55 with self.assertRaisesRegex(SystemError, "fault"):
56 float(jd)
57 _jpype.fault("PyJPModule_getContext")
58 with self.assertRaisesRegex(SystemError, "fault"):
59 float(jd)
60 float(jd)
61
62 @common.requireInstrumentation
63 def testJPNumberLong_str(self):
64 jd = JShort(1)
65 _jpype.fault("PyJPNumberLong_str")
66 with self.assertRaisesRegex(SystemError, "fault"):
67 str(jd)
68 _jpype.fault("PyJPModule_getContext")
69 with self.assertRaisesRegex(SystemError, "fault"):
70 str(jd)
71 str(jd)
72
73 @common.requireInstrumentation
74 def testJPNumberLong_repr(self):
75 jd = JShort(1)
76 _jpype.fault("PyJPNumberLong_repr")
77 with self.assertRaisesRegex(SystemError, "fault"):
78 repr(jd)
79 _jpype.fault("PyJPModule_getContext")
80 with self.assertRaisesRegex(SystemError, "fault"):
81 repr(jd)
82 repr(jd)
83
84 @common.requireInstrumentation
85 def testJPNumberLong_compare(self):
86 jd = JShort(1)
87 _jpype.fault("PyJPNumberLong_compare")
88 with self.assertRaisesRegex(SystemError, "fault"):
89 jd == 1
90 _jpype.fault("PyJPModule_getContext")
91 with self.assertRaisesRegex(SystemError, "fault"):
92 jd == 1
93 jd == 1
94
95 @common.requireInstrumentation
96 def testJPNumberLong_hash(self):
97 jd = JShort(1)
98 _jpype.fault("PyJPNumberLong_hash")
99 with self.assertRaises(SystemError):
100 hash(jd)
101 _jpype.fault("PyJPModule_getContext")
102 with self.assertRaises(SystemError):
103 hash(jd)
104 hash(jd)
105
106 @common.requireInstrumentation
107 def testFault(self):
108 _jpype.fault("JPShortType::findJavaConversion")
109 with self.assertRaises(SystemError):
110 JShort(1.0)
111
112 @common.requireInstrumentation
113 def testConversionFault(self):
114 _jpype.fault("JPShortType::findJavaConversion")
115 with self.assertRaisesRegex(SystemError, "fault"):
116 JShort._canConvertToJava(object())
117
118 @common.requireInstrumentation
119 def testArrayFault(self):
120 ja = JArray(JShort)(5)
121 _jpype.fault("JPJavaFrame::NewShortArray")
122 with self.assertRaisesRegex(SystemError, "fault"):
123 JArray(JShort)(1)
124 _jpype.fault("JPJavaFrame::SetShortArrayRegion")
125 with self.assertRaisesRegex(SystemError, "fault"):
126 ja[0] = 0
127 _jpype.fault("JPJavaFrame::GetShortArrayRegion")
128 with self.assertRaisesRegex(SystemError, "fault"):
129 print(ja[0])
130 _jpype.fault("JPJavaFrame::GetShortArrayElements")
131 # Special case, only BufferError is allowed from getBuffer
132 with self.assertRaises(BufferError):
133 memoryview(ja[0:3])
134 _jpype.fault("JPJavaFrame::ReleaseShortArrayElements")
135 with self.assertRaisesRegex(SystemError, "fault"):
136 ja[0:3] = bytes([1, 2, 3])
137 _jpype.fault("JPJavaFrame::ReleaseShortArrayElements")
138 with self.assertRaisesRegex(SystemError, "fault"):
139 jpype.JObject(ja[::2], jpype.JObject)
140 _jpype.fault("JPJavaFrame::ReleaseShortArrayElements")
141
142 def f():
143 # Special case no fault is allowed
144 memoryview(ja[0:3])
145 f()
146 _jpype.fault("JPShortType::setArrayRange")
147 with self.assertRaisesRegex(SystemError, "fault"):
148 ja[1:3] = [0, 0]
149
150 def testFromJShortWiden(self):
151 self.assertEqual(JShort(JByte(123)), 123)
152 self.assertEqual(JShort(JShort(12345)), 12345)
153 self.assertEqual(JShort(JInt(12345678)), JShort(12345678))
154 self.assertEqual(JShort(JLong(12345678)), JShort(12345678))
155
156 def testFromNone(self):
157 with self.assertRaises(TypeError):
158 JShort(None)
159 self.assertEqual(JShort._canConvertToJava(None), "none")
160
161 def testUnBox(self):
162 self.assertEqual(JShort(java.lang.Double(1.2345)), 1)
163
164 def testFromFloat(self):
165 self.assertEqual(JShort._canConvertToJava(1.2345), "explicit")
166
167 def testFromLong(self):
168 self.assertEqual(JShort(12345), 12345)
169 self.assertEqual(JShort._canConvertToJava(12345), "implicit")
170
171 def testFromObject(self):
172 with self.assertRaises(TypeError):
173 JShort(object())
174 with self.assertRaises(TypeError):
175 JShort(JObject())
176 with self.assertRaises(TypeError):
177 JShort(JString("A"))
178 self.assertEqual(JShort._canConvertToJava(object()), "none")
179 ja = JArray(JShort)(5)
180 with self.assertRaises(TypeError):
181 ja[1] = object()
182 jf = JClass("jpype.common.Fixture")
183 with self.assertRaises(TypeError):
184 jf.static_short_field = object()
185 with self.assertRaises(TypeError):
186 jf().short_field = object()
187
188 def testCallFloatFromNone(self):
189 with self.assertRaises(TypeError):
190 self.fixture.callShort(None)
191 with self.assertRaises(TypeError):
192 self.fixture.static_short_field = None
193 with self.assertRaises(TypeError):
194 self.fixture.short_field = None
195
196 def testThrow(self):
197 # Check throw
198 with self.assertRaises(JException):
199 self.fixture.throwFloat()
200 with self.assertRaises(JException):
201 self.cls.throwStaticFloat()
202 with self.assertRaises(JException):
203 self.fixture.throwStaticFloat()
204
205 def checkType(self, q):
206 # Check field
207 self.fixture.short_field = q
208 self.assertEqual(self.fixture.short_field, q)
209 self.assertEqual(self.fixture.getShort(), q)
210 # Check static field
211 self.cls.static_short_field = q
212 self.assertEqual(self.fixture.static_short_field, q)
213 self.assertEqual(self.fixture.getStaticShort(), q)
214 self.assertEqual(self.cls.getStaticShort(), q)
215 # Check call
216 self.assertEqual(self.fixture.callShort(q), q)
217 self.assertEqual(self.cls.callStaticShort(q), q)
218
219 def checkTypeFail(self, q, exc=TypeError):
220 with self.assertRaises(exc):
221 self.fixture.short_field = q
222 with self.assertRaises(exc):
223 self.fixture.callShort(q)
224 with self.assertRaises(exc):
225 self.fixture.callStaticShort(q)
226
227 def testCastFloat(self):
228 self.fixture.short_field = JShort(6.0)
229 self.assertEqual(self.fixture.short_field, 6)
230
231 def testCheckInt(self):
232 self.checkType(1)
233
234 def testCheckFloat(self):
235 self.checkTypeFail(2.0)
236
237 def testCheckRange(self):
238 self.checkType(2**15 - 1)
239 self.checkType(-2**15)
240 self.checkTypeFail(2**15, exc=OverflowError)
241 self.checkTypeFail(-2**15 - 1, exc=OverflowError)
242
243 def testExplicitRange(self):
244 # These will not overflow as they are explicit casts
245 self.assertEqual(JShort(2**16), 0)
246 self.assertEqual(JShort(-2**16), 0)
247
248 def testCheckBool(self):
249 self.checkType(True)
250 self.checkType(False)
251
252 def testCheckJBoolean(self):
253 self.checkTypeFail(JBoolean(True))
254 self.checkTypeFail(JBoolean(False))
255
256 def testCheckJChar(self):
257 self.checkType(JChar("A"))
258
259 def testCheckJByte(self):
260 self.checkType(JByte(-128))
261 self.checkType(JByte(127))
262
263 def testCheckJShort(self):
264 self.checkType(JShort(-2**15))
265 self.checkType(JShort(2**15 - 1))
266
267 def testCheckJInt(self):
268 self.checkTypeFail(JInt(-2**31 + 1))
269 self.checkTypeFail(JInt(2**31 - 1))
270
271 def testCheckJLong(self):
272 self.checkTypeFail(JLong(-2**63 + 1))
273 self.checkTypeFail(JLong(2**63 - 1))
274
275 @common.requireNumpy
276 def testCheckNumpyInt8(self):
277 self.checkType(np.random.randint(-127, 128, dtype=np.int8))
278 self.checkType(np.random.randint(0, 255, dtype=np.uint8))
279 self.checkType(np.uint8(0))
280 self.checkType(np.uint8(255))
281 self.checkType(np.int8(-128))
282 self.checkType(np.int8(127))
283
284 @common.requireNumpy
285 def testCheckNumpyInt16(self):
286 self.checkType(np.random.randint(-2**15, 2**15 - 1, dtype=np.int16))
287 self.checkType(np.uint16(0))
288 self.checkTypeFail(np.uint16(2**16 - 1), exc=OverflowError)
289 self.checkType(np.int16(-2**15))
290 self.checkType(np.int16(2**15 - 1))
291
292 @common.requireNumpy
293 def testCheckNumpyInt32(self):
294 self.checkType(np.uint32(0))
295 self.checkTypeFail(np.uint32(2**32 - 1), exc=OverflowError)
296 self.checkTypeFail(np.int32(-2**31), exc=OverflowError)
297 self.checkTypeFail(np.int32(2**31 - 1), exc=OverflowError)
298
299 @common.requireNumpy
300 def testCheckNumpyInt64(self):
301 #self.checkTypeFail(np.random.randint(-2**63,2**63-1, dtype=np.int64))
302 # FIXME OverflowError
303 #self.checkType(np.uint64(np.random.randint(0,2**64-1, dtype=np.uint64)))
304 # FIXME OverflowError
305 # self.checkType(np.uint64(2**64-1))
306 self.checkTypeFail(np.int64(-2**63), exc=OverflowError)
307 self.checkTypeFail(np.int64(2**63 - 1), exc=OverflowError)
308
309 @common.requireNumpy
310 def testCheckNumpyFloat32(self):
311 self.checkTypeFail(np.float32(np.random.rand()))
312
313 @common.requireNumpy
314 def testCheckNumpyFloat64(self):
315 self.checkTypeFail(np.float64(np.random.rand()))
316
317 def checkArrayType(self, a, expected):
318 # Check init
319 ja = JArray(JShort)(a)
320 self.assertElementsEqual(ja, expected)
321 ja = JArray(JShort)(len(a))
322 ja[:] = a
323 self.assertElementsEqual(ja, expected)
324 return ja
325
326 def checkArrayTypeFail(self, a):
327 # Check init
328 ja = JArray(JShort)(a)
329 ja = JArray(JShort)(len(a))
330 ja[:] = a
331
332 def testArrayConversion(self):
333 a = [random.randint(-2**15, 2**15 - 1) for i in range(100)]
334 jarr = self.checkArrayType(a, a)
335 result = jarr[2:10]
336 self.assertEqual(len(a[2:10]), len(result))
337 self.assertElementsAlmostEqual(a[2:10], result)
338
339 # empty slice
340 result = jarr[-1:3]
341 expected = a[-1:3]
342 self.assertElementsAlmostEqual(expected, result)
343
344 result = jarr[3:-2]
345 expected = a[3:-2]
346 self.assertElementsAlmostEqual(expected, result)
347
348 @common.requireNumpy
349 def testArrayInitFromNPInt(self):
350 a = np.random.randint(-2**31, 2**31 - 1, size=100, dtype=np.int_)
351 self.checkArrayType(a, a.astype(np.int16))
352
353 @common.requireNumpy
354 def testArrayInitFromNPInt8(self):
355 a = np.random.randint(-2**7, 2**7 - 1, size=100, dtype=np.int8)
356 self.checkArrayType(a, a)
357
358 @common.requireNumpy
359 def testArrayInitFromNPInt16(self):
360 a = np.random.randint(-2**15, 2**15 - 1, size=100, dtype=np.int16)
361 self.checkArrayType(a, a)
362
363 @common.requireNumpy
364 def testArrayInitFromNPInt32(self):
365 a = np.random.randint(-2**31, 2**31 - 1, size=100, dtype=np.int32)
366 self.checkArrayType(a, a.astype(np.int16))
367
368 @common.requireNumpy
369 def testArrayInitFromNPInt64(self):
370 a = np.random.randint(-2**63, 2**63 - 1, size=100, dtype=np.int64)
371 self.checkArrayType(a, a.astype(np.int16))
372
373 @common.requireNumpy
374 def testArrayInitFromNPFloat32(self):
375 a = np.random.random(100).astype(np.float32)
376 self.checkArrayType(a, a.astype(np.int16))
377
378 @common.requireNumpy
379 def testArrayInitFromNPFloat64(self):
380 a = np.random.random(100).astype(np.float64)
381 self.checkArrayType(a, a.astype(np.int16))
382
383 def testArraySetRange(self):
384 ja = JArray(JShort)(3)
385 ja[0:1] = [123]
386 self.assertEqual(ja[0], 123)
387 ja[0:1] = [-1]
388 self.assertEqual(ja[0], -1)
389 with self.assertRaises(TypeError):
390 ja[0:1] = [1.000]
391 with self.assertRaises(TypeError):
392 ja[0:1] = [java.lang.Double(321)]
393 with self.assertRaises(TypeError):
394 ja[0:1] = [object()]
395
396 def testArrayConversionFail(self):
397 jarr = JArray(JShort)(VALUES)
398 with self.assertRaises(TypeError):
399 jarr[1] = 'a'
400
401 def testArraySliceLength(self):
402 jarr = JArray(JShort)(VALUES)
403 jarr[1:2] = [1]
404 with self.assertRaises(ValueError):
405 jarr[1:2] = [1, 2, 3]
406
407 def testArrayConversionInt(self):
408 jarr = JArray(JShort)(VALUES)
409 result = jarr[0: len(jarr)]
410 self.assertElementsEqual(VALUES, result)
411 result = jarr[2:10]
412 self.assertElementsEqual(VALUES[2:10], result)
413
414 def testArrayConversionError(self):
415 jarr = JArray(JShort, 1)(10)
416 with self.assertRaises(TypeError):
417 jarr[1:2] = [dict()]
418 # -1 is returned by python, if conversion fails also, ensure this works
419 jarr[1:2] = [-1]
420
421 def testArrayClone(self):
422 array = JArray(JShort, 2)([[1, 2], [3, 4]])
423 carray = array.clone()
424 # Verify the first dimension is cloned
425 self.assertFalse(array.equals(carray))
426 # Copy is shallow
427 self.assertTrue(array[0].equals(carray[0]))
428
429 def testArrayGetSlice(self):
430 contents = VALUES
431 array = JArray(JShort)(contents)
432 self.assertEqual(list(array[1:]), contents[1:])
433 self.assertEqual(list(array[:-1]), contents[:-1])
434 self.assertEqual(list(array[1:-1]), contents[1:-1])
435
436 def testArraySetSlice(self):
437 contents = [1, 2, 3, 4]
438 array = JArray(JShort)(contents)
439 array[1:] = [5, 6, 7]
440 contents[1:] = [5, 6, 7]
441 self.assertEqual(list(array[:]), contents[:])
442 array[:-1] = [8, 9, 10]
443 contents[:-1] = [8, 9, 10]
444 self.assertEqual(list(array[:]), contents[:])
445
446 def testArrayGetSliceStep(self):
447 contents = VALUES
448 array = JArray(JShort)(contents)
449 self.assertEqual(list(array[::2]), contents[::2])
450 self.assertEqual(list(array[::3]), contents[::3])
451 self.assertEqual(list(array[::4]), contents[::4])
452 self.assertEqual(list(array[::5]), contents[::5])
453 self.assertEqual(list(array[::6]), contents[::6])
454 self.assertEqual(list(array[::7]), contents[::7])
455 self.assertEqual(list(array[::8]), contents[::8])
456 self.assertEqual(list(array[1::3]), contents[1::3])
457 self.assertEqual(list(array[1:-2:3]), contents[1:-2:3])
458
459 def testArraySliceStepNeg(self):
460 contents = VALUES
461 array = JArray(JShort)(contents)
462 self.assertEqual(list(array[::-1]), contents[::-1])
463 self.assertEqual(list(array[::-2]), contents[::-2])
464 self.assertEqual(list(array[::-3]), contents[::-3])
465 self.assertEqual(list(array[::-4]), contents[::-4])
466 self.assertEqual(list(array[::-5]), contents[::-5])
467 self.assertEqual(list(array[::-6]), contents[::-6])
468 self.assertEqual(list(array[2::-3]), contents[2::-3])
469 self.assertEqual(list(array[-2::-3]), contents[-2::-3])
470
471 def testArraySetArraySliceStep(self):
472 contents = [1, 2, 3, 4, 5, 6]
473 array = JArray(JShort)(contents)
474 array[::2] = [5, 6, 7]
475 contents[::2] = [5, 6, 7]
476 self.assertEqual(list(array[:]), contents[:])
477
478 def testArrayEquals(self):
479 contents = VALUES
480 array = JArray(JShort)(contents)
481 array2 = JArray(JShort)(contents)
482 self.assertEqual(array, array)
483 self.assertNotEqual(array, array2)
484
485 def testArrayIter(self):
486 contents = VALUES
487 array = JArray(JShort)(contents)
488 contents2 = [i for i in array]
489 self.assertEqual(contents, contents2)
490
491 def testArrayGetOutOfBounds(self):
492 contents = [1, 2, 3, 4]
493 array = JArray(JShort)(contents)
494 with self.assertRaises(IndexError):
495 array[5]
496 self.assertEqual(array[-1], contents[-1])
497 self.assertEqual(array[-4], contents[-4])
498 with self.assertRaises(IndexError):
499 array[-5]
500
501 def testArraySetOutOfBounds(self):
502 contents = [1, 2, 3, 4]
503 array = JArray(JShort)(contents)
504 with self.assertRaises(IndexError):
505 array[5] = 1
506 array[-1] = 5
507 contents[-1] = 5
508 array[-4] = 6
509 contents[-4] = 6
510 self.assertEqual(list(array[:]), contents)
511 with self.assertRaises(IndexError):
512 array[-5] = 1
513
514 def testArraySliceCast(self):
515 JA = JArray(JShort)
516 ja = JA(VALUES)
517 ja2 = ja[::2]
518 jo = jpype.JObject(ja2, jpype.JObject)
519 ja3 = jpype.JObject(jo, JA)
520 self.assertEqual(type(jo), jpype.JClass("java.lang.Object"))
521 self.assertEqual(type(ja2), JA)
522 self.assertEqual(type(ja3), JA)
523 self.assertEqual(list(ja2), list(ja3))
524
525 def testArrayReverse(self):
526 n = list(VALUES)
527 ja = JArray(JShort)(n)
528 a = [i for i in reversed(ja)]
529 n = [i for i in reversed(n)]
530 self.assertEqual(a, n)
531
532 def testArrayHash(self):
533 ja = JArray(JShort)([1, 2, 3])
534 self.assertIsInstance(hash(ja), int)
535
536 @common.requireNumpy
537 def testArrayBufferDims(self):
538 ja = JArray(JShort)(5)
539 a = np.zeros((5, 2))
540 with self.assertRaisesRegex(TypeError, "incorrect"):
541 ja[:] = a
542
543 def testArrayBadItem(self):
544 class q(object):
545 def __int__(self):
546 raise SystemError("nope")
547
548 def __index__(self):
549 raise SystemError("nope")
550 ja = JArray(JShort)(5)
551 a = [1, 2, q(), 3, 4]
552 with self.assertRaisesRegex(SystemError, "nope"):
553 ja[:] = a
554
555 def testArrayBadDims(self):
556 class q(bytes):
557 # Lie about our length
558 def __len__(self):
559 return 5
560 a = q([1, 2, 3])
561 ja = JArray(JShort)(5)
562 with self.assertRaisesRegex(ValueError, "Slice"):
563 ja[:] = [1, 2, 3]
564 with self.assertRaisesRegex(ValueError, "mismatch"):
565 ja[:] = a