MCPcopy Index your code
hub / github.com/python/cpython / test_memoryview_cast

Method test_memoryview_cast

Lib/test/test_buffer.py:2716–2774  ·  view source on GitHub ↗
(self)

Source from the content-addressed store, hash-verified

2714 [2**10, 2**10, 2**5, 2**3, 2**1])
2715
2716 def test_memoryview_cast(self):
2717 bytespec = (
2718 ('B', lambda ex: list(ex.tobytes())),
2719 ('b', lambda ex: [x-256 if x > 127 else x for x in list(ex.tobytes())]),
2720 ('c', lambda ex: [bytes(chr(x), 'latin-1') for x in list(ex.tobytes())]),
2721 )
2722
2723 def iter_roundtrip(ex, m, items, fmt):
2724 srcsize = struct.calcsize(fmt)
2725 for bytefmt, to_bytelist in bytespec:
2726
2727 m2 = m.cast(bytefmt)
2728 lst = to_bytelist(ex)
2729 self.verify(m2, obj=ex,
2730 itemsize=1, fmt=bytefmt, readonly=False,
2731 ndim=1, shape=[31*srcsize], strides=(1,),
2732 lst=lst, cast=True)
2733
2734 m3 = m2.cast(fmt)
2735 self.assertEqual(m3, ex)
2736 lst = ex.tolist()
2737 self.verify(m3, obj=ex,
2738 itemsize=srcsize, fmt=fmt, readonly=False,
2739 ndim=1, shape=[31], strides=(srcsize,),
2740 lst=lst, cast=True)
2741
2742 # cast from ndim = 0 to ndim = 1
2743 srcsize = struct.calcsize('I')
2744 ex = ndarray(9, shape=[], format='I')
2745 destitems, destshape = cast_items(ex, 'B', 1)
2746 m = memoryview(ex)
2747 m2 = m.cast('B')
2748 self.verify(m2, obj=ex,
2749 itemsize=1, fmt='B', readonly=True,
2750 ndim=1, shape=destshape, strides=(1,),
2751 lst=destitems, cast=True)
2752
2753 # cast from ndim = 1 to ndim = 0
2754 destsize = struct.calcsize('I')
2755 ex = ndarray([9]*destsize, shape=[destsize], format='B')
2756 destitems, destshape = cast_items(ex, 'I', destsize, shape=[])
2757 m = memoryview(ex)
2758 m2 = m.cast('I', shape=[])
2759 self.verify(m2, obj=ex,
2760 itemsize=destsize, fmt='I', readonly=True,
2761 ndim=0, shape=(), strides=(),
2762 lst=destitems, cast=True)
2763
2764 # array.array: roundtrip to/from bytes
2765 for fmt, items, _ in iter_format(31, 'array'):
2766 ex = array.array(fmt, items)
2767 m = memoryview(ex)
2768 iter_roundtrip(ex, m, items, fmt)
2769
2770 # ndarray: roundtrip to/from bytes
2771 for fmt, items, _ in iter_format(31, 'memoryview'):
2772 ex = ndarray(items, shape=[31], format=fmt, flags=ND_WRITABLE)
2773 m = memoryview(ex)

Callers

nothing calls this directly

Calls 5

verifyMethod · 0.95
listClass · 0.85
cast_itemsFunction · 0.85
iter_formatFunction · 0.85
castMethod · 0.80

Tested by

no test coverage detected