1# test handling of failed heap allocation with bytearray
2
3import micropython
4
5
6class GetSlice:
7    def __getitem__(self, idx):
8        return idx
9
10
11sl = GetSlice()[:]
12
13# create bytearray
14micropython.heap_lock()
15try:
16    bytearray(4)
17except MemoryError:
18    print("MemoryError: bytearray create")
19micropython.heap_unlock()
20
21# create bytearray from bytes
22micropython.heap_lock()
23try:
24    bytearray(b"0123")
25except MemoryError:
26    print("MemoryError: bytearray create from bytes")
27micropython.heap_unlock()
28
29# create bytearray from iterator
30r = range(4)
31micropython.heap_lock()
32try:
33    bytearray(r)
34except MemoryError:
35    print("MemoryError: bytearray create from iter")
36micropython.heap_unlock()
37
38# bytearray add
39b = bytearray(4)
40micropython.heap_lock()
41try:
42    b + b"01"
43except MemoryError:
44    print("MemoryError: bytearray.__add__")
45micropython.heap_unlock()
46
47# bytearray iadd
48b = bytearray(4)
49micropython.heap_lock()
50try:
51    b += b"01234567"
52except MemoryError:
53    print("MemoryError: bytearray.__iadd__")
54micropython.heap_unlock()
55print(b)
56
57# bytearray append
58b = bytearray(4)
59micropython.heap_lock()
60try:
61    for i in range(100):
62        b.append(1)
63except MemoryError:
64    print("MemoryError: bytearray.append")
65micropython.heap_unlock()
66
67# bytearray extend
68b = bytearray(4)
69micropython.heap_lock()
70try:
71    b.extend(b"01234567")
72except MemoryError:
73    print("MemoryError: bytearray.extend")
74micropython.heap_unlock()
75
76# bytearray get with slice
77b = bytearray(4)
78micropython.heap_lock()
79try:
80    b[sl]
81except MemoryError:
82    print("MemoryError: bytearray subscr get")
83micropython.heap_unlock()
84
85# extend bytearray using slice subscr
86b = bytearray(4)
87micropython.heap_lock()
88try:
89    b[sl] = b"01234567"
90except MemoryError:
91    print("MemoryError: bytearray subscr grow")
92micropython.heap_unlock()
93print(b)
94