blob: ddd5b9a8e2f25052d8aae06ee7e44cf1a1d5483e [file] [log] [blame]
Christian Heimes7b6fc8e2007-11-08 02:28:11 +00001"""Unit tests for the memoryview
2
Stefan Krahaaf8e2e2012-08-19 12:50:24 +02003 Some tests are in test_bytes. Many tests that require _testbuffer.ndarray
4 are in test_buffer.
Christian Heimes7b6fc8e2007-11-08 02:28:11 +00005"""
6
7import unittest
Benjamin Petersonee8712c2008-05-20 21:35:26 +00008import test.support
Antoine Pitrou616d2852008-08-19 22:09:34 +00009import sys
Antoine Pitrouc6b09eb2008-09-01 15:10:14 +000010import gc
11import weakref
Antoine Pitrouc3b39242009-01-03 16:59:18 +000012import array
Antoine Pitrouad62b032011-01-18 18:57:52 +000013import io
Serhiy Storchakaf81be8a2015-12-25 21:04:29 +020014import copy
15import pickle
Christian Heimes7b6fc8e2007-11-08 02:28:11 +000016
Antoine Pitrou616d2852008-08-19 22:09:34 +000017
Antoine Pitrouc3b39242009-01-03 16:59:18 +000018class AbstractMemoryTests:
19 source_bytes = b"abcdef"
Antoine Pitrou616d2852008-08-19 22:09:34 +000020
Antoine Pitrouc3b39242009-01-03 16:59:18 +000021 @property
22 def _source(self):
23 return self.source_bytes
24
25 @property
26 def _types(self):
27 return filter(None, [self.ro_type, self.rw_type])
Antoine Pitrou616d2852008-08-19 22:09:34 +000028
29 def check_getitem_with_type(self, tp):
Antoine Pitrouc3b39242009-01-03 16:59:18 +000030 b = tp(self._source)
Antoine Pitrou616d2852008-08-19 22:09:34 +000031 oldrefcount = sys.getrefcount(b)
32 m = self._view(b)
Stefan Krah9a2d99e2012-02-25 12:24:21 +010033 self.assertEqual(m[0], ord(b"a"))
34 self.assertIsInstance(m[0], int)
35 self.assertEqual(m[5], ord(b"f"))
36 self.assertEqual(m[-1], ord(b"f"))
37 self.assertEqual(m[-6], ord(b"a"))
Antoine Pitrou616d2852008-08-19 22:09:34 +000038 # Bounds checking
39 self.assertRaises(IndexError, lambda: m[6])
40 self.assertRaises(IndexError, lambda: m[-7])
41 self.assertRaises(IndexError, lambda: m[sys.maxsize])
42 self.assertRaises(IndexError, lambda: m[-sys.maxsize])
43 # Type checking
44 self.assertRaises(TypeError, lambda: m[None])
45 self.assertRaises(TypeError, lambda: m[0.0])
46 self.assertRaises(TypeError, lambda: m["a"])
47 m = None
Ezio Melottib3aedd42010-11-20 19:04:17 +000048 self.assertEqual(sys.getrefcount(b), oldrefcount)
Antoine Pitrou616d2852008-08-19 22:09:34 +000049
Antoine Pitrouc3b39242009-01-03 16:59:18 +000050 def test_getitem(self):
51 for tp in self._types:
52 self.check_getitem_with_type(tp)
Antoine Pitrou616d2852008-08-19 22:09:34 +000053
Raymond Hettinger159eac92009-06-23 20:38:54 +000054 def test_iter(self):
55 for tp in self._types:
56 b = tp(self._source)
57 m = self._view(b)
58 self.assertEqual(list(m), [m[i] for i in range(len(m))])
59
Antoine Pitrou616d2852008-08-19 22:09:34 +000060 def test_setitem_readonly(self):
Antoine Pitrouc3b39242009-01-03 16:59:18 +000061 if not self.ro_type:
Zachary Ware9fe6d862013-12-08 00:20:35 -060062 self.skipTest("no read-only type to test")
Antoine Pitrouc3b39242009-01-03 16:59:18 +000063 b = self.ro_type(self._source)
Antoine Pitrou616d2852008-08-19 22:09:34 +000064 oldrefcount = sys.getrefcount(b)
65 m = self._view(b)
66 def setitem(value):
67 m[0] = value
68 self.assertRaises(TypeError, setitem, b"a")
69 self.assertRaises(TypeError, setitem, 65)
70 self.assertRaises(TypeError, setitem, memoryview(b"a"))
71 m = None
Ezio Melottib3aedd42010-11-20 19:04:17 +000072 self.assertEqual(sys.getrefcount(b), oldrefcount)
Antoine Pitrou616d2852008-08-19 22:09:34 +000073
74 def test_setitem_writable(self):
Antoine Pitrouc3b39242009-01-03 16:59:18 +000075 if not self.rw_type:
Zachary Ware9fe6d862013-12-08 00:20:35 -060076 self.skipTest("no writable type to test")
Antoine Pitrouc3b39242009-01-03 16:59:18 +000077 tp = self.rw_type
78 b = self.rw_type(self._source)
Antoine Pitrou616d2852008-08-19 22:09:34 +000079 oldrefcount = sys.getrefcount(b)
80 m = self._view(b)
Stefan Krah9a2d99e2012-02-25 12:24:21 +010081 m[0] = ord(b'1')
82 self._check_contents(tp, b, b"1bcdef")
83 m[0:1] = tp(b"0")
Antoine Pitrouc3b39242009-01-03 16:59:18 +000084 self._check_contents(tp, b, b"0bcdef")
85 m[1:3] = tp(b"12")
86 self._check_contents(tp, b, b"012def")
87 m[1:1] = tp(b"")
88 self._check_contents(tp, b, b"012def")
89 m[:] = tp(b"abcdef")
90 self._check_contents(tp, b, b"abcdef")
Antoine Pitrou616d2852008-08-19 22:09:34 +000091
92 # Overlapping copies of a view into itself
93 m[0:3] = m[2:5]
Antoine Pitrouc3b39242009-01-03 16:59:18 +000094 self._check_contents(tp, b, b"cdedef")
95 m[:] = tp(b"abcdef")
Antoine Pitrou616d2852008-08-19 22:09:34 +000096 m[2:5] = m[0:3]
Antoine Pitrouc3b39242009-01-03 16:59:18 +000097 self._check_contents(tp, b, b"ababcf")
Antoine Pitrou616d2852008-08-19 22:09:34 +000098
99 def setitem(key, value):
Antoine Pitrouc3b39242009-01-03 16:59:18 +0000100 m[key] = tp(value)
Antoine Pitrou616d2852008-08-19 22:09:34 +0000101 # Bounds checking
102 self.assertRaises(IndexError, setitem, 6, b"a")
103 self.assertRaises(IndexError, setitem, -7, b"a")
104 self.assertRaises(IndexError, setitem, sys.maxsize, b"a")
105 self.assertRaises(IndexError, setitem, -sys.maxsize, b"a")
106 # Wrong index/slice types
107 self.assertRaises(TypeError, setitem, 0.0, b"a")
108 self.assertRaises(TypeError, setitem, (0,), b"a")
Stefan Krah9a2d99e2012-02-25 12:24:21 +0100109 self.assertRaises(TypeError, setitem, (slice(0,1,1), 0), b"a")
110 self.assertRaises(TypeError, setitem, (0, slice(0,1,1)), b"a")
111 self.assertRaises(TypeError, setitem, (0,), b"a")
Antoine Pitrou616d2852008-08-19 22:09:34 +0000112 self.assertRaises(TypeError, setitem, "a", b"a")
Stefan Krah9a2d99e2012-02-25 12:24:21 +0100113 # Not implemented: multidimensional slices
114 slices = (slice(0,1,1), slice(0,1,2))
115 self.assertRaises(NotImplementedError, setitem, slices, b"a")
Antoine Pitrou616d2852008-08-19 22:09:34 +0000116 # Trying to resize the memory object
Stefan Krah9a2d99e2012-02-25 12:24:21 +0100117 exc = ValueError if m.format == 'c' else TypeError
118 self.assertRaises(exc, setitem, 0, b"")
119 self.assertRaises(exc, setitem, 0, b"ab")
Antoine Pitrou616d2852008-08-19 22:09:34 +0000120 self.assertRaises(ValueError, setitem, slice(1,1), b"a")
121 self.assertRaises(ValueError, setitem, slice(0,2), b"a")
122
123 m = None
Ezio Melottib3aedd42010-11-20 19:04:17 +0000124 self.assertEqual(sys.getrefcount(b), oldrefcount)
Antoine Pitrou616d2852008-08-19 22:09:34 +0000125
Antoine Pitroue0793ba2010-09-01 21:14:16 +0000126 def test_delitem(self):
127 for tp in self._types:
128 b = tp(self._source)
129 m = self._view(b)
130 with self.assertRaises(TypeError):
131 del m[1]
132 with self.assertRaises(TypeError):
133 del m[1:4]
134
Antoine Pitrou616d2852008-08-19 22:09:34 +0000135 def test_tobytes(self):
Antoine Pitrouc3b39242009-01-03 16:59:18 +0000136 for tp in self._types:
137 m = self._view(tp(self._source))
138 b = m.tobytes()
139 # This calls self.getitem_type() on each separate byte of b"abcdef"
140 expected = b"".join(
141 self.getitem_type(bytes([c])) for c in b"abcdef")
Ezio Melottib3aedd42010-11-20 19:04:17 +0000142 self.assertEqual(b, expected)
Ezio Melottie9615932010-01-24 19:26:24 +0000143 self.assertIsInstance(b, bytes)
Antoine Pitrou616d2852008-08-19 22:09:34 +0000144
145 def test_tolist(self):
Antoine Pitrouc3b39242009-01-03 16:59:18 +0000146 for tp in self._types:
147 m = self._view(tp(self._source))
148 l = m.tolist()
Ezio Melottib3aedd42010-11-20 19:04:17 +0000149 self.assertEqual(l, list(b"abcdef"))
Antoine Pitrou616d2852008-08-19 22:09:34 +0000150
151 def test_compare(self):
152 # memoryviews can compare for equality with other objects
153 # having the buffer interface.
Antoine Pitrouc3b39242009-01-03 16:59:18 +0000154 for tp in self._types:
155 m = self._view(tp(self._source))
156 for tp_comp in self._types:
157 self.assertTrue(m == tp_comp(b"abcdef"))
158 self.assertFalse(m != tp_comp(b"abcdef"))
159 self.assertFalse(m == tp_comp(b"abcde"))
160 self.assertTrue(m != tp_comp(b"abcde"))
161 self.assertFalse(m == tp_comp(b"abcde1"))
162 self.assertTrue(m != tp_comp(b"abcde1"))
163 self.assertTrue(m == m)
164 self.assertTrue(m == m[:])
165 self.assertTrue(m[0:6] == m[:])
166 self.assertFalse(m[0:5] == m)
Antoine Pitrou616d2852008-08-19 22:09:34 +0000167
Antoine Pitrouc3b39242009-01-03 16:59:18 +0000168 # Comparison with objects which don't support the buffer API
169 self.assertFalse(m == "abcdef")
170 self.assertTrue(m != "abcdef")
171 self.assertFalse("abcdef" == m)
172 self.assertTrue("abcdef" != m)
Antoine Pitrou616d2852008-08-19 22:09:34 +0000173
Antoine Pitrouc3b39242009-01-03 16:59:18 +0000174 # Unordered comparisons
175 for c in (m, b"abcdef"):
176 self.assertRaises(TypeError, lambda: m < c)
177 self.assertRaises(TypeError, lambda: c <= m)
178 self.assertRaises(TypeError, lambda: m >= c)
179 self.assertRaises(TypeError, lambda: c > m)
Antoine Pitrou616d2852008-08-19 22:09:34 +0000180
181 def check_attributes_with_type(self, tp):
Antoine Pitrouc3b39242009-01-03 16:59:18 +0000182 m = self._view(tp(self._source))
Ezio Melottib3aedd42010-11-20 19:04:17 +0000183 self.assertEqual(m.format, self.format)
184 self.assertEqual(m.itemsize, self.itemsize)
185 self.assertEqual(m.ndim, 1)
186 self.assertEqual(m.shape, (6,))
187 self.assertEqual(len(m), 6)
188 self.assertEqual(m.strides, (self.itemsize,))
Stefan Krah9a2d99e2012-02-25 12:24:21 +0100189 self.assertEqual(m.suboffsets, ())
Antoine Pitrou616d2852008-08-19 22:09:34 +0000190 return m
191
192 def test_attributes_readonly(self):
Antoine Pitrouc3b39242009-01-03 16:59:18 +0000193 if not self.ro_type:
Zachary Ware9fe6d862013-12-08 00:20:35 -0600194 self.skipTest("no read-only type to test")
Antoine Pitrouc3b39242009-01-03 16:59:18 +0000195 m = self.check_attributes_with_type(self.ro_type)
Ezio Melottib3aedd42010-11-20 19:04:17 +0000196 self.assertEqual(m.readonly, True)
Antoine Pitrou616d2852008-08-19 22:09:34 +0000197
198 def test_attributes_writable(self):
Antoine Pitrouc3b39242009-01-03 16:59:18 +0000199 if not self.rw_type:
Zachary Ware9fe6d862013-12-08 00:20:35 -0600200 self.skipTest("no writable type to test")
Antoine Pitrouc3b39242009-01-03 16:59:18 +0000201 m = self.check_attributes_with_type(self.rw_type)
Ezio Melottib3aedd42010-11-20 19:04:17 +0000202 self.assertEqual(m.readonly, False)
Antoine Pitrou616d2852008-08-19 22:09:34 +0000203
Antoine Pitrouc6b09eb2008-09-01 15:10:14 +0000204 def test_getbuffer(self):
205 # Test PyObject_GetBuffer() on a memoryview object.
Antoine Pitrouc3b39242009-01-03 16:59:18 +0000206 for tp in self._types:
207 b = tp(self._source)
208 oldrefcount = sys.getrefcount(b)
209 m = self._view(b)
210 oldviewrefcount = sys.getrefcount(m)
211 s = str(m, "utf-8")
212 self._check_contents(tp, b, s.encode("utf-8"))
Ezio Melottib3aedd42010-11-20 19:04:17 +0000213 self.assertEqual(sys.getrefcount(m), oldviewrefcount)
Antoine Pitrouc3b39242009-01-03 16:59:18 +0000214 m = None
Ezio Melottib3aedd42010-11-20 19:04:17 +0000215 self.assertEqual(sys.getrefcount(b), oldrefcount)
Antoine Pitrouc6b09eb2008-09-01 15:10:14 +0000216
217 def test_gc(self):
Antoine Pitrouc3b39242009-01-03 16:59:18 +0000218 for tp in self._types:
219 if not isinstance(tp, type):
220 # If tp is a factory rather than a plain type, skip
221 continue
Antoine Pitrouc6b09eb2008-09-01 15:10:14 +0000222
Stefan Krah9a2d99e2012-02-25 12:24:21 +0100223 class MyView():
224 def __init__(self, base):
225 self.m = memoryview(base)
Antoine Pitrouc3b39242009-01-03 16:59:18 +0000226 class MySource(tp):
227 pass
228 class MyObject:
229 pass
230
Stefan Krah9a2d99e2012-02-25 12:24:21 +0100231 # Create a reference cycle through a memoryview object.
232 # This exercises mbuf_clear().
Antoine Pitrouc3b39242009-01-03 16:59:18 +0000233 b = MySource(tp(b'abc'))
234 m = self._view(b)
235 o = MyObject()
236 b.m = m
237 b.o = o
238 wr = weakref.ref(o)
239 b = m = o = None
240 # The cycle must be broken
241 gc.collect()
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000242 self.assertTrue(wr() is None, wr())
Antoine Pitrouc6b09eb2008-09-01 15:10:14 +0000243
Stefan Krah9a2d99e2012-02-25 12:24:21 +0100244 # This exercises memory_clear().
245 m = MyView(tp(b'abc'))
246 o = MyObject()
247 m.x = m
248 m.o = o
249 wr = weakref.ref(o)
250 m = o = None
251 # The cycle must be broken
252 gc.collect()
253 self.assertTrue(wr() is None, wr())
254
Antoine Pitrou6e6cc832010-09-09 12:59:39 +0000255 def _check_released(self, m, tp):
Ezio Melottied3a7d22010-12-01 02:32:32 +0000256 check = self.assertRaisesRegex(ValueError, "released")
Antoine Pitrou6e6cc832010-09-09 12:59:39 +0000257 with check: bytes(m)
258 with check: m.tobytes()
259 with check: m.tolist()
260 with check: m[0]
261 with check: m[0] = b'x'
262 with check: len(m)
263 with check: m.format
264 with check: m.itemsize
265 with check: m.ndim
266 with check: m.readonly
267 with check: m.shape
268 with check: m.strides
269 with check:
270 with m:
271 pass
272 # str() and repr() still function
273 self.assertIn("released memory", str(m))
274 self.assertIn("released memory", repr(m))
275 self.assertEqual(m, m)
276 self.assertNotEqual(m, memoryview(tp(self._source)))
277 self.assertNotEqual(m, tp(self._source))
278
279 def test_contextmanager(self):
280 for tp in self._types:
281 b = tp(self._source)
282 m = self._view(b)
283 with m as cm:
284 self.assertIs(cm, m)
285 self._check_released(m, tp)
286 m = self._view(b)
287 # Can release explicitly inside the context manager
288 with m:
289 m.release()
290
291 def test_release(self):
292 for tp in self._types:
293 b = tp(self._source)
294 m = self._view(b)
295 m.release()
296 self._check_released(m, tp)
297 # Can be called a second time (it's a no-op)
298 m.release()
299 self._check_released(m, tp)
Antoine Pitrou616d2852008-08-19 22:09:34 +0000300
Antoine Pitrouad62b032011-01-18 18:57:52 +0000301 def test_writable_readonly(self):
302 # Issue #10451: memoryview incorrectly exposes a readonly
303 # buffer as writable causing a segfault if using mmap
304 tp = self.ro_type
305 if tp is None:
Zachary Ware9fe6d862013-12-08 00:20:35 -0600306 self.skipTest("no read-only type to test")
Antoine Pitrouad62b032011-01-18 18:57:52 +0000307 b = tp(self._source)
308 m = self._view(b)
309 i = io.BytesIO(b'ZZZZ')
310 self.assertRaises(TypeError, i.readinto, m)
311
Stefan Krah9a2d99e2012-02-25 12:24:21 +0100312 def test_getbuf_fail(self):
313 self.assertRaises(TypeError, self._view, {})
314
Antoine Pitrouce4a9da2011-11-21 20:46:33 +0100315 def test_hash(self):
316 # Memoryviews of readonly (hashable) types are hashable, and they
Stefan Krah9a2d99e2012-02-25 12:24:21 +0100317 # hash as hash(obj.tobytes()).
Antoine Pitrouce4a9da2011-11-21 20:46:33 +0100318 tp = self.ro_type
319 if tp is None:
320 self.skipTest("no read-only type to test")
321 b = tp(self._source)
322 m = self._view(b)
323 self.assertEqual(hash(m), hash(b"abcdef"))
324 # Releasing the memoryview keeps the stored hash value (as with weakrefs)
325 m.release()
326 self.assertEqual(hash(m), hash(b"abcdef"))
327 # Hashing a memoryview for the first time after it is released
328 # results in an error (as with weakrefs).
329 m = self._view(b)
330 m.release()
331 self.assertRaises(ValueError, hash, m)
332
333 def test_hash_writable(self):
334 # Memoryviews of writable types are unhashable
335 tp = self.rw_type
336 if tp is None:
337 self.skipTest("no writable type to test")
338 b = tp(self._source)
339 m = self._view(b)
340 self.assertRaises(ValueError, hash, m)
341
Richard Oudkerk3e0a1eb2012-05-28 21:35:09 +0100342 def test_weakref(self):
343 # Check memoryviews are weakrefable
344 for tp in self._types:
345 b = tp(self._source)
346 m = self._view(b)
347 L = []
348 def callback(wr, b=b):
349 L.append(b)
350 wr = weakref.ref(m, callback)
351 self.assertIs(wr(), m)
352 del m
353 test.support.gc_collect()
354 self.assertIs(wr(), None)
355 self.assertIs(L[0], b)
356
Nick Coghlana0f169c2013-10-02 22:06:54 +1000357 def test_reversed(self):
358 for tp in self._types:
359 b = tp(self._source)
360 m = self._view(b)
361 aslist = list(reversed(m.tolist()))
362 self.assertEqual(list(reversed(m)), aslist)
363 self.assertEqual(list(reversed(m)), list(m[::-1]))
364
Stefan Krahfa5d6a52015-01-29 14:27:23 +0100365 def test_issue22668(self):
Stefan Krah3c0cf052015-01-29 17:33:31 +0100366 a = array.array('H', [256, 256, 256, 256])
367 x = memoryview(a)
368 m = x.cast('B')
Stefan Krahfa5d6a52015-01-29 14:27:23 +0100369 b = m.cast('H')
370 c = b[0:2]
371 d = memoryview(b)
372
373 del b
Stefan Krahfc341bd2015-01-29 14:33:37 +0100374
Stefan Krahfa5d6a52015-01-29 14:27:23 +0100375 self.assertEqual(c[0], 256)
376 self.assertEqual(d[0], 256)
377 self.assertEqual(c.format, "H")
378 self.assertEqual(d.format, "H")
Stefan Krahfc341bd2015-01-29 14:33:37 +0100379
Stefan Krahfa5d6a52015-01-29 14:27:23 +0100380 _ = m.cast('I')
381 self.assertEqual(c[0], 256)
382 self.assertEqual(d[0], 256)
383 self.assertEqual(c.format, "H")
384 self.assertEqual(d.format, "H")
385
Nick Coghlana0f169c2013-10-02 22:06:54 +1000386
Antoine Pitrouc3b39242009-01-03 16:59:18 +0000387# Variations on source objects for the buffer: bytes-like objects, then arrays
388# with itemsize > 1.
389# NOTE: support for multi-dimensional objects is unimplemented.
Antoine Pitrou616d2852008-08-19 22:09:34 +0000390
Antoine Pitrouc3b39242009-01-03 16:59:18 +0000391class BaseBytesMemoryTests(AbstractMemoryTests):
392 ro_type = bytes
393 rw_type = bytearray
394 getitem_type = bytes
395 itemsize = 1
396 format = 'B'
397
398class BaseArrayMemoryTests(AbstractMemoryTests):
399 ro_type = None
400 rw_type = lambda self, b: array.array('i', list(b))
Antoine Pitrou1ce3eb52010-09-01 20:29:34 +0000401 getitem_type = lambda self, b: array.array('i', list(b)).tobytes()
Antoine Pitrouc3b39242009-01-03 16:59:18 +0000402 itemsize = array.array('i').itemsize
403 format = 'i'
404
Zachary Ware9fe6d862013-12-08 00:20:35 -0600405 @unittest.skip('XXX test should be adapted for non-byte buffers')
Antoine Pitrouc3b39242009-01-03 16:59:18 +0000406 def test_getbuffer(self):
Antoine Pitrouc3b39242009-01-03 16:59:18 +0000407 pass
408
Zachary Ware9fe6d862013-12-08 00:20:35 -0600409 @unittest.skip('XXX NotImplementedError: tolist() only supports byte views')
Antoine Pitrouc3b39242009-01-03 16:59:18 +0000410 def test_tolist(self):
Antoine Pitrouc3b39242009-01-03 16:59:18 +0000411 pass
412
413
414# Variations on indirection levels: memoryview, slice of memoryview,
415# slice of slice of memoryview.
416# This is important to test allocation subtleties.
417
418class BaseMemoryviewTests:
Antoine Pitrou616d2852008-08-19 22:09:34 +0000419 def _view(self, obj):
420 return memoryview(obj)
421
Antoine Pitrouc3b39242009-01-03 16:59:18 +0000422 def _check_contents(self, tp, obj, contents):
Ezio Melottib3aedd42010-11-20 19:04:17 +0000423 self.assertEqual(obj, tp(contents))
Christian Heimes7b6fc8e2007-11-08 02:28:11 +0000424
Antoine Pitrouc3b39242009-01-03 16:59:18 +0000425class BaseMemorySliceTests:
426 source_bytes = b"XabcdefY"
Antoine Pitrou616d2852008-08-19 22:09:34 +0000427
428 def _view(self, obj):
429 m = memoryview(obj)
430 return m[1:7]
431
Antoine Pitrouc3b39242009-01-03 16:59:18 +0000432 def _check_contents(self, tp, obj, contents):
Ezio Melottib3aedd42010-11-20 19:04:17 +0000433 self.assertEqual(obj[1:7], tp(contents))
Antoine Pitrou616d2852008-08-19 22:09:34 +0000434
435 def test_refs(self):
Antoine Pitrouc3b39242009-01-03 16:59:18 +0000436 for tp in self._types:
437 m = memoryview(tp(self._source))
438 oldrefcount = sys.getrefcount(m)
439 m[1:2]
Ezio Melottib3aedd42010-11-20 19:04:17 +0000440 self.assertEqual(sys.getrefcount(m), oldrefcount)
Antoine Pitrou616d2852008-08-19 22:09:34 +0000441
Antoine Pitrouc3b39242009-01-03 16:59:18 +0000442class BaseMemorySliceSliceTests:
443 source_bytes = b"XabcdefY"
Antoine Pitrou616d2852008-08-19 22:09:34 +0000444
445 def _view(self, obj):
446 m = memoryview(obj)
447 return m[:7][1:]
448
Antoine Pitrouc3b39242009-01-03 16:59:18 +0000449 def _check_contents(self, tp, obj, contents):
Ezio Melottib3aedd42010-11-20 19:04:17 +0000450 self.assertEqual(obj[1:7], tp(contents))
Antoine Pitrouc3b39242009-01-03 16:59:18 +0000451
452
453# Concrete test classes
454
455class BytesMemoryviewTest(unittest.TestCase,
456 BaseMemoryviewTests, BaseBytesMemoryTests):
457
458 def test_constructor(self):
459 for tp in self._types:
460 ob = tp(self._source)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000461 self.assertTrue(memoryview(ob))
462 self.assertTrue(memoryview(object=ob))
Antoine Pitrouc3b39242009-01-03 16:59:18 +0000463 self.assertRaises(TypeError, memoryview)
464 self.assertRaises(TypeError, memoryview, ob, ob)
465 self.assertRaises(TypeError, memoryview, argument=ob)
466 self.assertRaises(TypeError, memoryview, ob, argument=True)
467
468class ArrayMemoryviewTest(unittest.TestCase,
469 BaseMemoryviewTests, BaseArrayMemoryTests):
470
471 def test_array_assign(self):
472 # Issue #4569: segfault when mutating a memoryview with itemsize != 1
473 a = array.array('i', range(10))
474 m = memoryview(a)
475 new_a = array.array('i', range(9, -1, -1))
476 m[:] = new_a
Ezio Melottib3aedd42010-11-20 19:04:17 +0000477 self.assertEqual(a, new_a)
Antoine Pitrouc3b39242009-01-03 16:59:18 +0000478
479
480class BytesMemorySliceTest(unittest.TestCase,
481 BaseMemorySliceTests, BaseBytesMemoryTests):
482 pass
483
484class ArrayMemorySliceTest(unittest.TestCase,
485 BaseMemorySliceTests, BaseArrayMemoryTests):
486 pass
487
488class BytesMemorySliceSliceTest(unittest.TestCase,
489 BaseMemorySliceSliceTests, BaseBytesMemoryTests):
490 pass
491
492class ArrayMemorySliceSliceTest(unittest.TestCase,
493 BaseMemorySliceSliceTests, BaseArrayMemoryTests):
494 pass
Antoine Pitrou616d2852008-08-19 22:09:34 +0000495
496
Stefan Krah0c515952015-08-08 13:38:10 +0200497class OtherTest(unittest.TestCase):
498 def test_ctypes_cast(self):
499 # Issue 15944: Allow all source formats when casting to bytes.
500 ctypes = test.support.import_module("ctypes")
501 p6 = bytes(ctypes.c_double(0.6))
502
503 d = ctypes.c_double()
504 m = memoryview(d).cast("B")
505 m[:2] = p6[:2]
506 m[2:] = p6[2:]
507 self.assertEqual(d.value, 0.6)
508
509 for format in "Bbc":
510 with self.subTest(format):
511 d = ctypes.c_double()
512 m = memoryview(d).cast(format)
513 m[:2] = memoryview(p6).cast(format)[:2]
514 m[2:] = memoryview(p6).cast(format)[2:]
515 self.assertEqual(d.value, 0.6)
516
Stefan Krah0ce5b6e2015-11-10 18:17:22 +0100517 def test_memoryview_hex(self):
518 # Issue #9951: memoryview.hex() segfaults with non-contiguous buffers.
519 x = b'0' * 200000
520 m1 = memoryview(x)
521 m2 = m1[::-1]
522 self.assertEqual(m2.hex(), '30' * 200000)
523
Serhiy Storchakaf81be8a2015-12-25 21:04:29 +0200524 def test_copy(self):
525 m = memoryview(b'abc')
526 with self.assertRaises(TypeError):
527 copy.copy(m)
528
529 def test_pickle(self):
530 m = memoryview(b'abc')
531 for proto in range(pickle.HIGHEST_PROTOCOL + 1):
532 with self.assertRaises(TypeError):
533 pickle.dumps(m, proto)
534
Stefan Krah0c515952015-08-08 13:38:10 +0200535
Christian Heimes7b6fc8e2007-11-08 02:28:11 +0000536if __name__ == "__main__":
Zachary Ware38c707e2015-04-13 15:00:43 -0500537 unittest.main()