Debian Codegraph @

pypy/module/array/test/test_array.py

raw symbols SCIP
1 import sys
2 import pytest
3
4
5 class AppTestArray(object):
6 spaceconfig = {'usemodules': ['array', 'struct', 'binascii']}
7
8 def setup_class(cls):
9 cls.w_array = cls.space.appexec([], """():
10 import array
11 return array.array
12 """)
13 cls.w_tempfile = cls.space.wrap(
14 str(pytest.ensuretemp('array').join('tmpfile')))
15 cls.w_maxint = cls.space.wrap(sys.maxint)
16 cls.w_runappdirect = cls.space.wrap(cls.runappdirect)
17
18 def test_ctor(self):
19 assert len(self.array('i')) == 0
20
21 raises(TypeError, self.array, 'hi')
22 raises(TypeError, self.array, 1)
23 raises(ValueError, self.array, 'x')
24
25 a = self.array('u')
26 raises(TypeError, a.append, 7)
27 raises(TypeError, a.append, 'hi')
28 a.append('h')
29 assert a[0] == 'h'
30 assert type(a[0]) is str
31 assert len(a) == 1
32
33 a = self.array('i', (1, 2, 3))
34 b = self.array('h', (1, 2, 3))
35 assert a == b
36
37 for tc in 'bhilBHILQqfd':
38 assert self.array(tc).typecode == tc
39 raises(TypeError, self.array, tc, None)
40
41 a = self.array('i', (1, 2, 3))
42 b = self.array('h', a)
43 assert list(b) == [1, 2, 3]
44
45 def test_value_range(self):
46 import sys
47 values = (-129, 128, -128, 127, 0, 255, -1, 256,
48 -32768, 32767, -32769, 32768, 65535, 65536,
49 -2147483647, -2147483648, 2147483647, 4294967295, 4294967296,
50 )
51 for bb in (8, 16, 32, 64, 128, 256, 512, 1024):
52 for b in (bb - 1, bb, bb + 1):
53 values += (2 ** b, 2 ** b + 1, 2 ** b - 1,
54 -2 ** b, -2 ** b + 1, -2 ** b - 1)
55
56 for tc, ok, pt in (('b', ( -128, 34, 127), int),
57 ('B', ( 0, 23, 255), int),
58 ('h', (-32768, 30535, 32767), int),
59 ('H', ( 0, 56783, 65535), int),
60 ('i', (-32768, 30535, 32767), int),
61 ('I', ( 0, 56783, 65535), int),
62 ('l', (-2 ** 32 // 2, 34, 2 ** 32 // 2 - 1), int),
63 ('L', (0, 3523532, 2 ** 32 - 1), int),
64 ):
65 a = self.array(tc, ok)
66 assert len(a) == len(ok)
67 for v in ok:
68 a.append(v)
69 for i, v in enumerate(ok * 2):
70 assert a[i] == v
71 assert type(a[i]) is pt or (
72 # A special case: we return ints in Array('I') on 64-bits,
73 # and in Array('L') on 64-bit Windows,
74 # whereas CPython returns longs. The difference is
75 # probably acceptable.
76 (tc == 'I' or tc == 'L' and sys.platform == 'win32') and
77 sys.maxint > 2147483647 and type(a[i]) is int)
78 for v in ok:
79 a[1] = v
80 assert a[0] == ok[0]
81 assert a[1] == v
82 assert a[2] == ok[2]
83 assert len(a) == 2 * len(ok)
84 for v in values:
85 try:
86 a[1] = v
87 assert a[0] == ok[0]
88 assert a[1] == v
89 assert a[2] == ok[2]
90 except OverflowError:
91 pass
92
93 for tc in 'BHILQ':
94 a = self.array(tc)
95 itembits = a.itemsize * 8
96 vals = [0, 2 ** itembits - 1]
97 a.fromlist(vals)
98 assert a.tolist() == vals
99
100 a = self.array(tc.lower())
101 vals = [-1 * (2 ** itembits) // 2, (2 ** itembits) // 2 - 1]
102 a.fromlist(vals)
103 assert a.tolist() == vals
104
105 def test_float(self):
106 values = [0, 1, 2.5, -4.25]
107 for tc in 'fd':
108 a = self.array(tc, values)
109 assert len(a) == len(values)
110 for i, v in enumerate(values):
111 assert a[i] == v
112 assert type(a[i]) is float
113 a[1] = 10.125
114 assert a[0] == 0
115 assert a[1] == 10.125
116 assert a[2] == 2.5
117 assert len(a) == len(values)
118
119 def test_nan(self):
120 for tc in 'fd':
121 a = self.array(tc, [float('nan')])
122 b = self.array(tc, [float('nan')])
123 assert not a == b
124 assert a != b
125 assert not a > b
126 assert not a >= b
127 assert not a < b
128 assert not a <= b
129 assert a.count(float('nan')) == 0
130
131 def test_itemsize(self):
132 for t in 'bB':
133 assert(self.array(t).itemsize >= 1)
134 for t in 'uhHiI':
135 assert(self.array(t).itemsize >= 2)
136 for t in 'lLf':
137 assert(self.array(t).itemsize >= 4)
138 for t in 'd':
139 assert(self.array(t).itemsize >= 8)
140 for t in 'Qq':
141 assert(self.array(t).itemsize >= 8)
142
143 inttypes = 'bhil'
144 for t in inttypes:
145 a = self.array(t, [1, 2, 3])
146 b = a.itemsize
147 for v in (-2 ** (8 * b) // 2, 2 ** (8 * b) // 2 - 1):
148 a[1] = v
149 assert a[0] == 1 and a[1] == v and a[2] == 3
150 raises(OverflowError, a.append, -2 ** (8 * b) // 2 - 1)
151 raises(OverflowError, a.append, 2 ** (8 * b) // 2)
152
153 a = self.array(t.upper(), [1, 2, 3])
154 b = a.itemsize
155 for v in (0, 2 ** (8 * b) - 1):
156 a[1] = v
157 assert a[0] == 1 and a[1] == v and a[2] == 3
158 raises(OverflowError, a.append, -1)
159 raises(OverflowError, a.append, 2 ** (8 * b))
160
161 def test_errormessage(self):
162 a = self.array("L", [1, 2, 3])
163 excinfo = raises(TypeError, "a[0] = 'abc'")
164 assert str(excinfo.value) == "array item must be integer"
165
166 def test_fromstring(self):
167 a = self.array('b')
168 assert not hasattr("a", "fromstring")
169
170 def test_frombytes(self):
171 import sys
172 for t in 'bBhHiIlLfd':
173 a = self.array(t)
174 a.frombytes(b'\x00' * a.itemsize * 2)
175 assert len(a) == 2 and a[0] == 0 and a[1] == 0
176 if a.itemsize > 1:
177 raises(ValueError, a.frombytes, b'\x00' * (a.itemsize - 1))
178 raises(ValueError, a.frombytes, b'\x00' * (a.itemsize + 1))
179 raises(ValueError, a.frombytes, b'\x00' * (2 * a.itemsize - 1))
180 raises(ValueError, a.frombytes, b'\x00' * (2 * a.itemsize + 1))
181 b = self.array(t, b'\x00' * a.itemsize * 2)
182 assert len(b) == 2 and b[0] == 0 and b[1] == 0
183 if t in 'bB':
184 old_items = a.tolist()
185 try:
186 a.frombytes(a)
187 except BufferError:
188 # CPython behavior:
189 # "cannot resize an array that is exporting buffers"
190 # This is the general error we get when we try to
191 # resize the array while a buffer to that array is
192 # alive.
193 assert a.tolist() == old_items
194 else:
195 # PyPy behavior: we can't reasonably implement that.
196 # It's harder to crash PyPy in this case, but not
197 # impossible, because of get_raw_address(). Too
198 # bad I suppose.
199 assert a.tolist() == old_items * 2
200 else:
201 if '__pypy__' in sys.modules:
202 old_items = a.tolist()
203 a.frombytes(a)
204 assert a.tolist() == old_items * 2
205 else:
206 raises(TypeError, a.frombytes, a)
207
208 def test_fromfile(self):
209 def myfile(c, s):
210 f = open(self.tempfile, 'wb')
211 f.write(c * s)
212 f.close()
213 return open(self.tempfile, 'rb')
214
215 f = myfile(b'\x00', 100)
216 for t in 'bBhHiIlLfd':
217 a = self.array(t)
218 a.fromfile(f, 2)
219 assert len(a) == 2 and a[0] == 0 and a[1] == 0
220
221 a = self.array('b')
222 a.fromfile(myfile(b'\x01', 20), 2)
223 assert len(a) == 2 and a[0] == 1 and a[1] == 1
224
225 a = self.array('h')
226 a.fromfile(myfile(b'\x01', 20), 2)
227 assert len(a) == 2 and a[0] == 257 and a[1] == 257
228
229 a = self.array('h')
230 raises(EOFError, a.fromfile, myfile(b'\x01', 2), 2)
231 assert len(a) == 1 and a[0] == 257
232
233 a = self.array('h')
234 raises(ValueError, a.fromfile, myfile(b'\x01', 3), 2)
235 # ValueError: bytes length not a multiple of item size
236 assert len(a) == 0
237
238 def test_fromfile_no_warning(self):
239 import warnings
240 # check that fromfile defers to frombytes, not fromstring
241 class FakeF(object):
242 def read(self, n):
243 return b"a" * n
244 a = self.array('b')
245 with warnings.catch_warnings(record=True) as w:
246 # Cause all warnings to always be triggered.
247 warnings.simplefilter("always")
248 a.fromfile(FakeF(), 4)
249 assert len(w) == 0
250
251 def test_fromlist(self):
252 a = self.array('b')
253 raises(OverflowError, a.fromlist, [1, 2, 400])
254 assert len(a) == 0
255
256 raises(OverflowError, a.extend, [1, 2, 400])
257 assert len(a) == 2 and a[0] == 1 and a[1] == 2
258
259 raises(OverflowError, self.array, 'b', [1, 2, 400])
260
261 a = self.array('b', [1, 2])
262 assert len(a) == 2 and a[0] == 1 and a[1] == 2
263
264 a = self.array('b')
265 raises(TypeError, a.fromlist, (1, 2, 400))
266
267 raises(OverflowError, a.extend, (1, 2, 400))
268 assert len(a) == 2 and a[0] == 1 and a[1] == 2
269
270 raises(TypeError, a.extend, self.array('i', (7, 8)))
271 assert len(a) == 2 and a[0] == 1 and a[1] == 2
272
273 def gen():
274 for i in range(4):
275 yield i + 10
276 a = self.array('i', gen())
277 assert len(a) == 4 and a[2] == 12
278
279 raises(OverflowError, self.array, 'b', (1, 2, 400))
280
281 a = self.array('b', (1, 2))
282 assert len(a) == 2 and a[0] == 1 and a[1] == 2
283
284 a.extend(a)
285 assert repr(a) == "array('b', [1, 2, 1, 2])"
286
287 def test_fromunicode(self):
288 raises(ValueError, self.array('i').fromunicode, u'hi')
289 a = self.array('u')
290 a.fromunicode(u'hi')
291 assert len(a) == 2 and a[0] == 'h' and a[1] == 'i'
292
293 b = self.array('u', u'hi')
294 assert len(b) == 2 and b[0] == 'h' and b[1] == 'i'
295
296 def test_setslice_to_extend(self):
297 a = self.array('i')
298 a[0:1] = self.array('i', [9])
299 a[1:5] = self.array('i', [99])
300 assert list(a) == [9, 99]
301
302 def test_sequence(self):
303 a = self.array('i', [1, 2, 3, 4])
304 assert len(a) == 4
305 assert a[0] == 1 and a[1] == 2 and a[2] == 3 and a[3] == 4
306 assert a[-4] == 1 and a[-3] == 2 and a[-2] == 3 and a[-1] == 4
307 a[-2] = 5
308 assert a[0] == 1 and a[1] == 2 and a[2] == 5 and a[3] == 4
309
310 for i in (4, -5):
311 raises(IndexError, a.__getitem__, i)
312
313 b = a[0:2]
314 assert len(b) == 2 and b[0] == 1 and b[1] == 2
315 b[0] = 6
316 assert len(b) == 2 and b[0] == 6 and b[1] == 2
317 assert a[0] == 1 and a[1] == 2 and a[2] == 5 and a[3] == 4
318 assert a.itemsize == b.itemsize
319
320 b = a[0:100]
321 assert len(b) == 4
322 assert b[0] == 1 and b[1] == 2 and b[2] == 5 and b[3] == 4
323
324 l1 = [2 * i + 1 for i in range(10)]
325 a1 = self.array('i', l1)
326 for start in range(10):
327 for stop in range(start, 10):
328 for step in range(1, 10):
329 l2 = l1[start:stop:step]
330 a2 = a1[start:stop:step]
331 assert len(l2) == len(a2)
332 for i in range(len(l2)):
333 assert l2[i] == a2[i]
334
335 a = self.array('i', [1, 2, 3, 4])
336 a[1:3] = self.array('i', [5, 6])
337 assert len(a) == 4
338 assert a[0] == 1 and a[1] == 5 and a[2] == 6 and a[3] == 4
339 a[0:-1:2] = self.array('i', [7, 8])
340 assert a[0] == 7 and a[1] == 5 and a[2] == 8 and a[3] == 4
341
342 raises(ValueError, "a[1:2:4] = self.array('i', [5, 6, 7])")
343 raises(TypeError, "a[1:3] = self.array('I', [5, 6])")
344 raises(TypeError, "a[1:3] = [5, 6]")
345
346 def test_resizingslice(self):
347 a = self.array('i', [1, 2, 3])
348 a[1:2] = self.array('i', [7, 8, 9])
349 assert repr(a) == "array('i', [1, 7, 8, 9, 3])"
350 a[1:2] = self.array('i', [10])
351 assert repr(a) == "array('i', [1, 10, 8, 9, 3])"
352 a[1:2] = self.array('i')
353 assert repr(a) == "array('i', [1, 8, 9, 3])"
354
355 a[1:3] = self.array('i', [11, 12, 13])
356 assert repr(a) == "array('i', [1, 11, 12, 13, 3])"
357 a[1:3] = self.array('i', [14])
358 assert repr(a) == "array('i', [1, 14, 13, 3])"
359 a[1:3] = self.array('i')
360 assert repr(a) == "array('i', [1, 3])"
361
362 a[1:1] = self.array('i', [15, 16, 17])
363 assert repr(a) == "array('i', [1, 15, 16, 17, 3])"
364 a[1:1] = self.array('i', [18])
365 assert repr(a) == "array('i', [1, 18, 15, 16, 17, 3])"
366 a[1:1] = self.array('i')
367 assert repr(a) == "array('i', [1, 18, 15, 16, 17, 3])"
368
369 a[:] = self.array('i', [20, 21, 22])
370 assert repr(a) == "array('i', [20, 21, 22])"
371
372 def test_reversingslice(self):
373 a = self.array('i', [22, 21, 20])
374 assert repr(a[::-1]) == "array('i', [20, 21, 22])"
375 assert repr(a[2:1:-1]) == "array('i', [20])"
376 assert repr(a[2:-1:-1]) == "array('i')"
377 assert repr(a[-1:0:-1]) == "array('i', [20, 21])"
378 del a
379
380 for a in range(-4, 5):
381 for b in range(-4, 5):
382 for c in [-4, -3, -2, -1, 1, 2, 3, 4]:
383 lst = [1, 2, 3]
384 arr = self.array('i', lst)
385 assert repr(arr[a:b:c]) == \
386 repr(self.array('i', lst[a:b:c]))
387 for vals in ([4, 5], [6], []):
388 try:
389 ok = False
390 lst[a:b:c] = vals
391 ok = True
392 arr[a:b:c] = self.array('i', vals)
393 assert repr(arr) == repr(self.array('i', lst))
394 except ValueError:
395 assert not ok
396 del arr
397 # make sure array.__del__ is called before the leak check
398 import gc; gc.collect()
399
400 def test_getslice_large_step(self):
401 import sys
402 a = self.array('b', [1, 2, 3])
403 assert list(a[1::sys.maxsize]) == [2]
404
405 def test_setslice_large_step(self):
406 import sys
407 a = self.array('b', [1, 2, 3])
408 a[1::sys.maxsize] = self.array('b', [42])
409 assert a.tolist() == [1, 42, 3]
410
411 def test_toxxx(self):
412 a = self.array('i', [1, 2, 3])
413 l = a.tolist()
414 assert type(l) is list and len(l) == 3
415 assert a[0] == 1 and a[1] == 2 and a[2] == 3
416
417 b = self.array('i', a.tobytes())
418 assert len(b) == 3 and b[0] == 1 and b[1] == 2 and b[2] == 3
419
420 a = self.array('i', [0, 0, 0])
421 assert a.tobytes() == b'\x00' * 3 * a.itemsize
422 s = self.array('i', [1, 2, 3]).tobytes()
423 assert 0x00 in s
424 assert 0x01 in s
425 assert 0x02 in s
426 assert 0x03 in s
427 a = self.array('i', s)
428 assert a[0] == 1 and a[1] == 2 and a[2] == 3
429
430 from struct import unpack
431 values = (-129, 128, -128, 127, 0, 255, -1, 256, -32760, 32760)
432 s = self.array('i', values).tobytes()
433 fmt = 'i' * len(values)
434 a = unpack(fmt, s)
435 assert a == values
436
437 for tcodes, values in (('bhilfd', (-128, 127, 0, 1, 7, -10)),
438 ('BHILfd', (127, 0, 1, 7, 255, 169)),
439 ('hilHILfd', (32760, 30123, 3422, 23244))):
440 for tc in tcodes:
441 values += ((2 ** self.array(tc).itemsize) // 2 - 1, )
442 s = self.array(tc, values).tobytes()
443 a = unpack(tc * len(values), s)
444 assert a == values
445
446 f = open(self.tempfile, 'wb')
447 self.array('b', (ord('h'), ord('i'))).tofile(f)
448 f.close()
449 assert open(self.tempfile, 'rb').readline() == b'hi'
450
451 a = self.array('b')
452 a.fromfile(open(self.tempfile, 'rb'), 2)
453 assert repr(a) == "array('b', [104, 105])"
454
455 raises(ValueError, self.array('i').tounicode)
456 assert self.array('u', u'hello').tounicode() == u'hello'
457
458 def test_empty_tostring(self):
459 a = self.array('l')
460 assert not hasattr(a, "tostring")
461
462 def test_buffer(self):
463 a = self.array('h', b'Hi')
464 buf = memoryview(a)
465 assert buf[0] == 26952
466 raises(IndexError, 'buf[1]')
467 assert buf.tobytes() == b'Hi'
468 assert buf.tolist() == [26952]
469 assert buf.format == 'h'
470 assert buf.itemsize == 2
471 assert buf.shape == (1,)
472 assert buf.ndim == 1
473 assert buf.strides == (2,)
474 assert not buf.readonly
475
476 def test_buffer_write(self):
477 a = self.array('b', b'hello')
478 buf = memoryview(a)
479 try:
480 buf[3] = b'L'
481 except TypeError:
482 skip("memoryview(array) returns a read-only buffer on CPython")
483 assert a.tobytes() == b'helLo'
484
485 def test_buffer_keepalive(self):
486 import sys
487 if '__pypy__' not in sys.builtin_module_names:
488 skip("CPython: cannot resize an array that is exporting buffers")
489 buf = memoryview(self.array('b', b'text'))
490 assert buf[2] == ord('x')
491 #
492 a = self.array('b', b'foobarbaz')
493 buf = memoryview(a)
494 a.frombytes(b'some extra text')
495 assert buf[:] == b'foobarbazsome extra text'
496
497 def test_memview_multi_tobytes(self):
498 a = self.array('i', list(b"abcdef"))
499 m = memoryview(a)
500 assert m.tobytes() == a.tobytes()
501
502 def test_list_methods(self):
503 assert repr(self.array('i')) == "array('i')"
504 assert repr(self.array('i', [1, 2, 3])) == "array('i', [1, 2, 3])"
505 assert repr(self.array('h')) == "array('h')"
506
507 a = self.array('i', [1, 2, 3, 1, 2, 1])
508 assert a.count(1) == 3
509 assert a.count(2) == 2
510 assert a.index(3) == 2
511 assert a.index(2) == 1
512 raises(ValueError, a.index, 10)
513
514 a.reverse()
515 assert repr(a) == "array('i', [1, 2, 1, 3, 2, 1])"
516
517 b = self.array('i', [1, 2, 3, 1, 2])
518 b.reverse()
519 assert repr(b) == "array('i', [2, 1, 3, 2, 1])"
520
521 a.remove(3)
522 assert repr(a) == "array('i', [1, 2, 1, 2, 1])"
523 a.remove(1)
524 assert repr(a) == "array('i', [2, 1, 2, 1])"
525
526 a.pop()
527 assert repr(a) == "array('i', [2, 1, 2])"
528
529 a.pop(1)
530 assert repr(a) == "array('i', [2, 2])"
531
532 a.pop(-2)
533 assert repr(a) == "array('i', [2])"
534
535 a.insert(1, 7)
536 assert repr(a) == "array('i', [2, 7])"
537 a.insert(0, 8)
538 a.insert(-1, 9)
539 assert repr(a) == "array('i', [8, 2, 9, 7])"
540
541 a.insert(100, 10)
542 assert repr(a) == "array('i', [8, 2, 9, 7, 10])"
543 a.insert(-100, 20)
544 assert repr(a) == "array('i', [20, 8, 2, 9, 7, 10])"
545
546 def test_compare(self):
547 class comparable(object):
548 def __eq__(self, other):
549 return True
550 class incomparable(object):
551 pass
552
553 for v1, v2, tt in (([1, 2, 3], [1, 3, 2], 'bhilBHIL'),
554 ('abc', 'acb', 'u')):
555 for t in tt:
556 a = self.array(t, v1)
557 b = self.array(t, v1)
558 c = self.array(t, v2)
559
560 assert (a == 7) is False
561 assert (comparable() == a) is True
562 assert (a == comparable()) is True
563 assert (a == incomparable()) is False
564 assert (incomparable() == a) is False
565
566 assert (a == a) is True
567 assert (a == b) is True
568 assert (b == a) is True
569 assert (a == c) is False
570 assert (c == a) is False
571
572 assert (a != a) is False
573 assert (a != b) is False
574 assert (b != a) is False
575 assert (a != c) is True
576 assert (c != a) is True
577
578 assert (a < a) is False
579 assert (a < b) is False
580 assert (b < a) is False
581 assert (a < c) is True
582 assert (c < a) is False
583
584 assert (a > a) is False
585 assert (a > b) is False
586 assert (b > a) is False
587 assert (a > c) is False
588 assert (c > a) is True
589
590 assert (a <= a) is True
591 assert (a <= b) is True
592 assert (b <= a) is True
593 assert (a <= c) is True
594 assert (c <= a) is False
595
596 assert (a >= a) is True
597 assert (a >= b) is True
598 assert (b >= a) is True
599 assert (a >= c) is False
600 assert (c >= a) is True
601
602 a = self.array('i', [-1, 0, 1, 42, 0x7f])
603 assert not a == 2*a
604 assert a != 2*a
605 assert a < 2*a
606 assert a <= 2*a
607 assert not a > 2*a
608 assert not a >= 2*a
609
610 def test_reduce(self):
611 import _pickle as pickle
612 a = self.array('i', [1, 2, 3])
613 s = pickle.dumps(a)
614 b = pickle.loads(s)
615 assert a == b
616
617 a = self.array('l')
618 s = pickle.dumps(a)
619 b = pickle.loads(s)
620 assert len(b) == 0 and b.typecode == 'l'
621
622 a = self.array('i', [1, 2, 4])
623 i = iter(a)
624 #raises(TypeError, pickle.dumps, i)
625
626 def test_copy_swap(self):
627 a = self.array('i', [1, 2, 3])
628 from copy import copy
629 b = copy(a)
630 a[1] = 7
631 assert repr(b) == "array('i', [1, 2, 3])"
632
633 for tc in 'bhilBHIL':
634 a = self.array(tc, [1, 2, 3])
635 a.byteswap()
636 assert len(a) == 3
637 assert a[0] == 1 * (256 ** (a.itemsize - 1))
638 assert a[1] == 2 * (256 ** (a.itemsize - 1))
639 assert a[2] == 3 * (256 ** (a.itemsize - 1))
640 a.byteswap()
641 assert len(a) == 3
642 assert a[0] == 1
643 assert a[1] == 2
644 assert a[2] == 3
645
646 def test_deepcopy(self):
647 a = self.array('u', u'\x01\u263a\x00\ufeff')
648 from copy import deepcopy
649 b = deepcopy(a)
650 assert a == b
651
652 def test_addmul(self):
653 a = self.array('i', [1, 2, 3])
654 assert repr(a + a) == "array('i', [1, 2, 3, 1, 2, 3])"
655 assert 2 * a == a + a
656 assert a * 2 == a + a
657 b = self.array('i', [4, 5, 6, 7])
658 assert repr(a + b) == "array('i', [1, 2, 3, 4, 5, 6, 7])"
659 assert repr(2 * self.array('i')) == "array('i')"
660 assert repr(self.array('i') + self.array('i')) == "array('i')"
661
662 a = self.array('i', [1, 2])
663 assert type(a + a) is self.array
664 assert type(a * 2) is self.array
665 assert type(2 * a) is self.array
666 b = a
667 a += a
668 assert repr(b) == "array('i', [1, 2, 1, 2])"
669 b *= 3
670 assert repr(a) == "array('i', [1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2])"
671 assert a == b
672 a += self.array('i', (7,))
673 assert repr(a) == "array('i', [1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 7])"
674
675 raises(MemoryError, "a * self.maxint")
676 raises(MemoryError, "a *= self.maxint")
677
678 raises(TypeError, "a = self.array('i') + 2")
679 raises(TypeError, "self.array('i') + self.array('b')")
680 a = self.array('i')
681 raises(TypeError, "a += 7")
682
683 # Calling __add__ directly raises TypeError in cpython but
684 # returns NotImplemented in pypy if placed within a
685 # try: except TypeError: construction.
686 #
687 #raises(TypeError, self.array('i').__add__, (2,))
688 #raises(TypeError, self.array('i').__iadd__, (2,))
689 #raises(TypeError, self.array('i').__add__, self.array('b'))
690
691 class addable(object):
692 def __add__(self, other):
693 return "add"
694
695 def __radd__(self, other):
696 return "radd"
697
698 assert addable() + self.array('i') == 'add'
699 assert self.array('i') + addable() == 'radd'
700
701 a = self.array('i')
702 a += addable()
703 assert a == 'radd'
704
705 a = self.array('i', [1, 2])
706 assert a * -1 == self.array('i')
707 b = a
708 a *= -1
709 assert a == self.array('i')
710 assert b == self.array('i')
711
712 a = self.array('i')
713 raises(TypeError, "a * 'hi'")
714 raises(TypeError, "'hi' * a")
715 raises(TypeError, "a *= 'hi'")
716
717 class mulable(object):
718 def __mul__(self, other):
719 return "mul"
720
721 def __rmul__(self, other):
722 return "rmul"
723
724 assert mulable() * self.array('i') == 'mul'
725 assert self.array('i') * mulable() == 'rmul'
726
727 a = self.array('i')
728 a *= mulable()
729 assert a == 'rmul'
730
731 def test_delitem(self):
732 a = self.array('i', [1, 2, 3])
733 del a[1]
734 assert repr(a) == "array('i', [1, 3])"
735
736 a = self.array('i', [1, 2, 3, 4, 5])
737 del a[1:3]
738 assert repr(a) == "array('i', [1, 4, 5])"
739
740 a = self.array('i', [1, 2, 3, 4, 5])
741 del a[3:1]
742 assert repr(a) == "array('i', [1, 2, 3, 4, 5])"
743
744 del a[-100:1]
745 assert repr(a) == "array('i', [2, 3, 4, 5])"
746
747 del a[3:]
748 assert repr(a) == "array('i', [2, 3, 4])"
749
750 del a[-1:]
751 assert repr(a) == "array('i', [2, 3])"
752
753 del a[1:100]
754 assert repr(a) == "array('i', [2])"
755
756 def test_iter(self):
757 a = self.array('i', [1, 2, 3])
758 assert 1 in a
759 b = self.array('i')
760 for i in a:
761 b.append(i)
762 assert repr(b) == "array('i', [1, 2, 3])"
763 assert hasattr(b, '__iter__')
764 assert next(b.__iter__()) == 1
765
766 def test_contains(self):
767 a = self.array('i', [1, 6, 3])
768 assert hasattr(a, '__contains__')
769 assert (1 in a) is True
770 assert 6 in a
771 assert 3 in a
772 assert (0 in a) is False
773 assert 12 not in a
774 assert 'a' not in a
775
776 def test_lying_iterable(self):
777 class lier(object):
778 def __init__(self, n):
779 self.n = n
780
781 def __len__(self):
782 return 3
783
784 def __next__(self):
785 self.n -= 1
786 if self.n < 0:
787 raise StopIteration
788 return self.n
789
790 def __iter__(self):
791 return self
792
793 assert len(lier(2)) == 3
794 assert len(tuple(lier(2))) == 2
795 a = self.array('i', lier(2))
796 assert repr(a) == "array('i', [1, 0])"
797
798 assert len(lier(5)) == 3
799 assert len(tuple(lier(5))) == 5
800 a = self.array('i', lier(5))
801 assert repr(a) == "array('i', [4, 3, 2, 1, 0])"
802
803 def test_type(self):
804 for t in 'bBhHiIlLfduQq':
805 assert type(self.array(t)) is self.array
806 assert isinstance(self.array(t), self.array)
807
808 def test_iterable(self):
809 import collections.abc
810 for t in 'bBhHiIlLfduQq':
811 assert isinstance(self.array(t), collections.abc.Iterable)
812
813 def test_subclass(self):
814 assert len(self.array('b')) == 0
815
816 a = self.array('i')
817 a.append(7)
818 assert len(a) == 1
819
820 array = self.array
821
822 class adder(array):
823 def __getitem__(self, i):
824 return array.__getitem__(self, i) + 1
825
826 a = adder('i', (1, 2, 3))
827 assert len(a) == 3
828 assert a[0] == 2
829
830 def test_subclass_new(self):
831 array = self.array
832 class Image(array):
833 def __new__(cls, width, height, typecode='d'):
834 self = array.__new__(cls, typecode, [0] * (width * height))
835 self.width = width
836 self.height = height
837 return self
838
839 def _index(self, x, y):
840 x = min(max(x, 0), self.width-1)
841 y = min(max(y, 0), self.height-1)
842 return y * self.width + x
843
844 def __getitem__(self, i):
845 return array.__getitem__(self, self._index(*i))
846
847 def __setitem__(self, i, val):
848 return array.__setitem__(self, self._index(*i), val)
849
850 img = Image(5, 10, 'B')
851 for y in range(10):
852 for x in range(5):
853 img[x, y] = x * y
854 for y in range(10):
855 for x in range(5):
856 assert img[x, y] == x * y
857
858 assert img[3, 25] == 3 * 9
859
860 def test_override_from(self):
861 class mya(self.array):
862 def fromlist(self, lst):
863 self.append(7)
864
865 def frombytes(self, lst):
866 self.append(8)
867
868 def fromunicode(self, lst):
869 self.append('9')
870
871 def extend(self, lst):
872 self.append(10)
873
874 assert repr(mya('u', 'hi')) == "mya('u', 'hi')"
875 assert repr(mya('i', [1, 2, 3])) == "mya('i', [1, 2, 3])"
876 assert repr(mya('i', (1, 2, 3))) == "mya('i', [1, 2, 3])"
877
878 a = mya('i')
879 a.fromlist([1, 2, 3])
880 assert repr(a) == "mya('i', [7])"
881
882 a = mya('b')
883 a.frombytes(b'hi')
884 assert repr(a) == "mya('b', [8])"
885
886 a = mya('u')
887 a.fromunicode('hi')
888 assert repr(a) == "mya('u', '9')"
889
890 a = mya('i')
891 a.extend([1, 2, 3])
892 assert repr(a) == "mya('i', [10])"
893
894 def test_override_to(self):
895 class mya(self.array):
896 def tolist(self):
897 return 'list'
898
899 def tobytes(self):
900 return 'str'
901
902 def tounicode(self):
903 return 'unicode'
904
905 assert mya('i', [1, 2, 3]).tolist() == 'list'
906 assert mya('u', 'hi').tobytes() == 'str'
907 assert mya('u', 'hi').tounicode() == 'unicode'
908
909 assert repr(mya('u', 'hi')) == "mya('u', 'hi')"
910 assert repr(mya('i', [1, 2, 3])) == "mya('i', [1, 2, 3])"
911 assert repr(mya('i', (1, 2, 3))) == "mya('i', [1, 2, 3])"
912
913 def test_unicode_outofrange(self):
914 if not self.runappdirect:
915 skip("ll2ctypes cannot represent unichar(sys.maxunicode + 1)")
916 input_unicode = u'\x01\u263a\x00\ufeff'
917 a = self.array('u', input_unicode)
918 b = self.array('u', input_unicode)
919 b.byteswap()
920 assert b[2] == u'\u0000'
921 assert a != b
922 if b.itemsize == 4:
923 e = raises(ValueError, "b[0]") # doesn't work
924 assert str(e.value) == (
925 "cannot operate on this array('u') because it contains"
926 " character U+1000000 not in range [U+0000; U+10ffff]"
927 " at index 0")
928 assert str(b) == ("array('u', <character U+1000000 is not in"
929 " range [U+0000; U+10ffff]>)")
930 raises(ValueError, b.tounicode) # doesn't work
931 elif b.itemsize == 2:
932 assert b[0] == u'\u0100'
933 byteswaped_unicode = u'\u0100\u3a26\x00\ufffe'
934 assert str(b) == "array('u', %r)" % (byteswaped_unicode,)
935 assert b.tounicode() == byteswaped_unicode
936 assert str(a) == "array('u', %r)" % (input_unicode,)
937 assert a.tounicode() == input_unicode
938
939 def test_unicode_surrogate(self):
940 a = self.array('u', u'\ud800')
941 assert a[0] == u'\ud800'
942
943 def test_weakref(self):
944 import weakref
945 a = self.array('u', 'Hi!')
946 r = weakref.ref(a)
947 assert r() is a
948
949 def test_subclass_del(self):
950 import array, gc, weakref
951 l = []
952
953 class A(array.array):
954 pass
955
956 a = A('d')
957 a.append(3.0)
958 r = weakref.ref(a, lambda a: l.append(a()))
959 del a
960 gc.collect(); gc.collect() # XXX needs two of them right now...
961 assert l
962 assert l[0] is None or len(l[0]) == 0
963
964 def test_assign_object_with_special_methods(self):
965 from array import array
966
967 class Num(object):
968 def __float__(self):
969 return 5.25
970
971 def __int__(self):
972 return 7
973
974 class NotNum(object):
975 pass
976
977 class Silly(object):
978 def __float__(self):
979 return None
980
981 def __int__(self):
982 return None
983
984 class OldNum:
985 def __float__(self):
986 return 6.25
987
988 def __int__(self):
989 return 8
990
991 class OldNotNum:
992 pass
993
994 class OldSilly:
995 def __float__(self):
996 return None
997
998 def __int__(self):
999 return None
1000
1001 for tc in 'bBhHiIlL':
1002 a = array(tc, [0])
1003 raises(TypeError, a.__setitem__, 0, 1.0)
1004 a[0] = 1
1005 a[0] = Num()
1006 assert a[0] == 7
1007 raises(TypeError, a.__setitem__, NotNum())
1008 a[0] = OldNum()
1009 assert a[0] == 8
1010 raises(TypeError, a.__setitem__, OldNotNum())
1011 raises(TypeError, a.__setitem__, Silly())
1012 raises(TypeError, a.__setitem__, OldSilly())
1013
1014 for tc in 'fd':
1015 a = array(tc, [0])
1016 a[0] = 1.0
1017 a[0] = 1
1018 a[0] = Num()
1019 assert a[0] == 5.25
1020 raises(TypeError, a.__setitem__, NotNum())
1021 a[0] = OldNum()
1022 assert a[0] == 6.25
1023 raises(TypeError, a.__setitem__, OldNotNum())
1024 raises(TypeError, a.__setitem__, Silly())
1025 raises(TypeError, a.__setitem__, OldSilly())
1026
1027 a = array('u', 'hi')
1028 a[0] = 'b'
1029 assert a[0] == 'b'
1030
1031 a = array('u', u'hi')
1032 a[0] = u'b'
1033 assert a[0] == u'b'
1034
1035 def test_bytearray(self):
1036 a = self.array('u', 'hi')
1037 b = self.array('u')
1038 b.frombytes(bytearray(a.tobytes()))
1039 assert a == b
1040 assert self.array('u', bytearray(a.tobytes())) == a
1041
1042 def test_buffer_info(self):
1043 a = self.array('b', b'Hi!')
1044 bi = a.buffer_info()
1045 assert bi[0] != 0
1046 assert bi[1] == 3
1047
1048 def test_array_reverse_slice_assign_self(self):
1049 a = self.array('b', range(4))
1050 a[::-1] = a
1051 assert a == self.array('b', [3, 2, 1, 0])
1052
1053 def test_array_multiply(self):
1054 a = self.array('b', [0])
1055 b = a * 13
1056 assert b[12] == 0
1057 b = 13 * a
1058 assert b[12] == 0
1059 a *= 13
1060 assert a[12] == 0
1061 a = self.array('b', [1])
1062 b = a * 13
1063 assert b[12] == 1
1064 b = 13 * a
1065 assert b[12] == 1
1066 a *= 13
1067 assert a[12] == 1
1068 a = self.array('i', [0])
1069 b = a * 13
1070 assert b[12] == 0
1071 b = 13 * a
1072 assert b[12] == 0
1073 a *= 13
1074 assert a[12] == 0
1075 a = self.array('i', [1])
1076 b = a * 13
1077 assert b[12] == 1
1078 b = 13 * a
1079 assert b[12] == 1
1080 a *= 13
1081 assert a[12] == 1
1082 a = self.array('i', [0, 0])
1083 b = a * 13
1084 assert len(b) == 26
1085 assert b[22] == 0
1086 b = 13 * a
1087 assert len(b) == 26
1088 assert b[22] == 0
1089 a *= 13
1090 assert a[22] == 0
1091 assert len(a) == 26
1092 a = self.array('f', [-0.0])
1093 b = a * 13
1094 assert len(b) == 13
1095 assert str(b[12]) == "-0.0"
1096 a = self.array('d', [-0.0])
1097 b = a * 13
1098 assert len(b) == 13
1099 assert str(b[12]) == "-0.0"
1100
1101 def test_getitem_only_ints(self):
1102 class MyInt(object):
1103 def __init__(self, x):
1104 self.x = x
1105
1106 def __int__(self):
1107 return self.x
1108
1109 a = self.array('i', [1, 2, 3, 4, 5, 6])
1110 raises(TypeError, "a[MyInt(0)]")
1111 raises(TypeError, "a[MyInt(0):MyInt(5)]")
1112
1113 def test_index_special_method(self):
1114 class MyInt(object):
1115 def __init__(self, x):
1116 self.x = x
1117
1118 def __index__(self):
1119 return self.x
1120
1121 a = self.array('i', [1, 2, 3, 4, 5, 6])
1122 assert a[MyInt(0)] == 1
1123 assert a[MyInt(0):MyInt(5)] == self.array('i', [1, 2, 3, 4, 5])
1124
1125 a[MyInt(0)] = 2
1126 assert a[MyInt(0)] == 2
1127 del a[MyInt(0)]
1128 assert a == self.array('i', [2, 3, 4, 5, 6])
1129
1130 def test_fresh_array_buffer_bytes(self):
1131 assert bytes(memoryview(self.array('i'))) == b''
1132
1133 def test_mview_slice_aswritebuf(self):
1134 import struct
1135 a = self.array('B', b'abcdef')
1136 view = memoryview(a)[1:5]
1137 struct.pack_into('>H', view, 1, 0x1234)
1138 assert a.tobytes() == b'ab\x12\x34ef'
1139
1140 def test_subclass_repr(self):
1141 import array
1142 class subclass(self.array):
1143 pass
1144 assert repr(subclass('i')) == "subclass('i')"
1145
1146 def test_mutate_while_slice(self):
1147 class X:
1148 def __index__(self):
1149 del a[:]
1150 return 1
1151
1152 a = self.array('i', [1, 2, 3, 4, 5, 6])
1153 length = len(a[:X():2])
1154 assert length == 0
1155
1156 a = self.array('i', [1, 2, 3, 4, 5, 6])
1157 length = len(a[:X():2])
1158 assert length == 0
1159
1160 a = self.array('i', [1, 2, 3, 4, 5, 6])
1161 length = len(a[:X():2])
1162 assert length == 0
1163 # make sure array.__del__ is called before the leak check
1164 import gc; gc.collect()
1165
1166 class AppTestArrayReconstructor:
1167 spaceconfig = dict(usemodules=('array', 'struct'))
1168
1169 def test_error(self):
1170 import array
1171 array_reconstructor = array._array_reconstructor
1172 UNKNOWN_FORMAT = -1
1173 raises(TypeError, array_reconstructor,
1174 "", "b", 0, b"")
1175 raises(TypeError, array_reconstructor,
1176 str, "b", 0, b"")
1177 raises(TypeError, array_reconstructor,
1178 array.array, "b", '', b"")
1179 raises(TypeError, array_reconstructor,
1180 array.array, "b", 0, "")
1181 raises(ValueError, array_reconstructor,
1182 array.array, "?", 0, b"")
1183 raises(ValueError, array_reconstructor,
1184 array.array, "b", UNKNOWN_FORMAT, b"")
1185 raises(ValueError, array_reconstructor,
1186 array.array, "b", 22, b"")
1187 raises(ValueError, array_reconstructor,
1188 array.array, "d", 16, b"a")
1189
1190 def test_numbers(self):
1191 import array, struct
1192 array_reconstructor = array._array_reconstructor
1193 UNSIGNED_INT8 = 0
1194 SIGNED_INT8 = 1
1195 UNSIGNED_INT16_LE = 2
1196 UNSIGNED_INT16_BE = 3
1197 SIGNED_INT16_LE = 4
1198 SIGNED_INT16_BE = 5
1199 UNSIGNED_INT32_LE = 6
1200 UNSIGNED_INT32_BE = 7
1201 SIGNED_INT32_LE = 8
1202 SIGNED_INT32_BE = 9
1203 UNSIGNED_INT64_LE = 10
1204 UNSIGNED_INT64_BE = 11
1205 SIGNED_INT64_LE = 12
1206 SIGNED_INT64_BE = 13
1207 IEEE_754_FLOAT_LE = 14
1208 IEEE_754_FLOAT_BE = 15
1209 IEEE_754_DOUBLE_LE = 16
1210 IEEE_754_DOUBLE_BE = 17
1211 testcases = (
1212 (['B', 'H', 'I', 'L'], UNSIGNED_INT8, '=BBBB',
1213 [0x80, 0x7f, 0, 0xff]),
1214 (['b', 'h', 'i', 'l'], SIGNED_INT8, '=bbb',
1215 [-0x80, 0x7f, 0]),
1216 (['H', 'I', 'L'], UNSIGNED_INT16_LE, '<HHHH',
1217 [0x8000, 0x7fff, 0, 0xffff]),
1218 (['H', 'I', 'L'], UNSIGNED_INT16_BE, '>HHHH',
1219 [0x8000, 0x7fff, 0, 0xffff]),
1220 (['h', 'i', 'l'], SIGNED_INT16_LE, '<hhh',
1221 [-0x8000, 0x7fff, 0]),
1222 (['h', 'i', 'l'], SIGNED_INT16_BE, '>hhh',
1223 [-0x8000, 0x7fff, 0]),
1224 (['I', 'L'], UNSIGNED_INT32_LE, '<IIII',
1225 [1<<31, (1<<31)-1, 0, (1<<32)-1]),
1226 (['I', 'L'], UNSIGNED_INT32_BE, '>IIII',
1227 [1<<31, (1<<31)-1, 0, (1<<32)-1]),
1228 (['i', 'l'], SIGNED_INT32_LE, '<iii',
1229 [-1<<31, (1<<31)-1, 0]),
1230 (['i', 'l'], SIGNED_INT32_BE, '>iii',
1231 [-1<<31, (1<<31)-1, 0]),
1232 (['L'], UNSIGNED_INT64_LE, '<QQQQ',
1233 [1<<31, (1<<31)-1, 0, (1<<32)-1]),
1234 (['L'], UNSIGNED_INT64_BE, '>QQQQ',
1235 [1<<31, (1<<31)-1, 0, (1<<32)-1]),
1236 (['l'], SIGNED_INT64_LE, '<qqq',
1237 [-1<<31, (1<<31)-1, 0]),
1238 (['l'], SIGNED_INT64_BE, '>qqq',
1239 [-1<<31, (1<<31)-1, 0]),
1240 # The following tests for INT64 will raise an OverflowError
1241 # when run on a 32-bit machine. The tests are simply skipped
1242 # in that case.
1243 (['L'], UNSIGNED_INT64_LE, '<QQQQ',
1244 [1<<63, (1<<63)-1, 0, (1<<64)-1]),
1245 (['L'], UNSIGNED_INT64_BE, '>QQQQ',
1246 [1<<63, (1<<63)-1, 0, (1<<64)-1]),
1247 (['l'], SIGNED_INT64_LE, '<qqq',
1248 [-1<<63, (1<<63)-1, 0]),
1249 (['l'], SIGNED_INT64_BE, '>qqq',
1250 [-1<<63, (1<<63)-1, 0]),
1251 (['f'], IEEE_754_FLOAT_LE, '<ffff',
1252 [16711938.0, float('inf'), float('-inf'), -0.0]),
1253 (['f'], IEEE_754_FLOAT_BE, '>ffff',
1254 [16711938.0, float('inf'), float('-inf'), -0.0]),
1255 (['d'], IEEE_754_DOUBLE_LE, '<dddd',
1256 [9006104071832581.0, float('inf'), float('-inf'), -0.0]),
1257 (['d'], IEEE_754_DOUBLE_BE, '>dddd',
1258 [9006104071832581.0, float('inf'), float('-inf'), -0.0])
1259 )
1260 for testcase in testcases:
1261 valid_typecodes, mformat_code, struct_fmt, values = testcase
1262 arraystr = struct.pack(struct_fmt, *values)
1263 for typecode in valid_typecodes:
1264 try:
1265 a = array.array(typecode, values)
1266 except OverflowError:
1267 continue # Skip this test case.
1268 b = array_reconstructor(
1269 array.array, typecode, mformat_code, arraystr)
1270 assert a == b
1271
1272 def test_unicode(self):
1273 import array
1274 array_reconstructor = array._array_reconstructor
1275 UTF16_LE = 18
1276 UTF16_BE = 19
1277 UTF32_LE = 20
1278 UTF32_BE = 21
1279 teststr = "Bonne Journ\xe9e \U0002030a\U00020347"
1280 testcases = (
1281 (UTF16_LE, "UTF-16-LE"),
1282 (UTF16_BE, "UTF-16-BE"),
1283 (UTF32_LE, "UTF-32-LE"),
1284 (UTF32_BE, "UTF-32-BE")
1285 )
1286 for testcase in testcases:
1287 mformat_code, encoding = testcase
1288 a = array.array('u', teststr)
1289 b = array_reconstructor(
1290 array.array, 'u', mformat_code, teststr.encode(encoding))
1291 assert a == b
1292
1293 def test_iterate_iterator(self):
1294 import array
1295 it = iter(array.array('b'))
1296 assert list(it) == []
1297 assert list(iter(it)) == []
1298
1299 def test_array_cannot_use_str(self):
1300 import array
1301 e = raises(TypeError, array.array, 'i', 'abcd')
1302 assert str(e.value) == ("cannot use a str to initialize an array"
1303 " with typecode 'i'")