code
stringlengths 1
1.05M
| repo_name
stringlengths 6
83
| path
stringlengths 3
242
| language
stringclasses 222
values | license
stringclasses 20
values | size
int64 1
1.05M
|
|---|---|---|---|---|---|
# test return type of inline asm
@micropython.asm_thumb
def ret_obj(r0) -> object:
pass
ret_obj(print)(1)
@micropython.asm_thumb
def ret_bool(r0) -> bool:
pass
print(ret_bool(0), ret_bool(1))
@micropython.asm_thumb
def ret_int(r0) -> int:
lsl(r0, r0, 29)
print(ret_int(0), hex(ret_int(1)), hex(ret_int(2)), hex(ret_int(4)))
@micropython.asm_thumb
def ret_uint(r0) -> uint:
lsl(r0, r0, 29)
print(ret_uint(0), hex(ret_uint(1)), hex(ret_uint(2)), hex(ret_uint(4)))
|
YifuLiu/AliOS-Things
|
components/py_engine/tests/inlineasm/asmrettype.py
|
Python
|
apache-2.0
| 494
|
@micropython.asm_thumb
def lsl1(r0):
lsl(r0, r0, 1)
print(hex(lsl1(0x123)))
@micropython.asm_thumb
def lsl23(r0):
lsl(r0, r0, 23)
print(hex(lsl23(1)))
@micropython.asm_thumb
def lsr1(r0):
lsr(r0, r0, 1)
print(hex(lsr1(0x123)))
@micropython.asm_thumb
def lsr31(r0):
lsr(r0, r0, 31)
print(hex(lsr31(0x80000000)))
@micropython.asm_thumb
def asr1(r0):
asr(r0, r0, 1)
print(hex(asr1(0x123)))
@micropython.asm_thumb
def asr31(r0):
asr(r0, r0, 31)
print(hex(asr31(0x80000000)))
|
YifuLiu/AliOS-Things
|
components/py_engine/tests/inlineasm/asmshift.py
|
Python
|
apache-2.0
| 517
|
@micropython.asm_thumb
def getIPSR():
mrs(r0, IPSR)
@micropython.asm_thumb
def getBASEPRI():
mrs(r0, BASEPRI)
print(getBASEPRI())
print(getIPSR())
|
YifuLiu/AliOS-Things
|
components/py_engine/tests/inlineasm/asmspecialregs.py
|
Python
|
apache-2.0
| 159
|
@micropython.asm_thumb
def asm_sum_words(r0, r1):
# r0 = len
# r1 = ptr
# r2 = sum
# r3 = dummy
mov(r2, 0)
b(loop_entry)
label(loop1)
ldr(r3, [r1, 0])
add(r2, r2, r3)
add(r1, r1, 4)
sub(r0, r0, 1)
label(loop_entry)
cmp(r0, 0)
bgt(loop1)
mov(r0, r2)
@micropython.asm_thumb
def asm_sum_bytes(r0, r1):
# r0 = len
# r1 = ptr
# r2 = sum
# r3 = dummy
mov(r2, 0)
b(loop_entry)
label(loop1)
ldrb(r3, [r1, 0])
add(r2, r2, r3)
add(r1, r1, 1)
sub(r0, r0, 1)
label(loop_entry)
cmp(r0, 0)
bgt(loop1)
mov(r0, r2)
import uarray as array
b = array.array("l", (100, 200, 300, 400))
n = asm_sum_words(len(b), b)
print(b, n)
b = array.array("b", (10, 20, 30, 40, 50, 60, 70, 80))
n = asm_sum_bytes(len(b), b)
print(b, n)
b = b"\x01\x02\x03\x04"
n = asm_sum_bytes(len(b), b)
print(b, n)
|
YifuLiu/AliOS-Things
|
components/py_engine/tests/inlineasm/asmsum.py
|
Python
|
apache-2.0
| 906
|
# Array operation
# Type: list, inplace operation using for. What's good about this
# method is that it doesn't require any extra memory allocation.
import bench
def test(num):
for i in iter(range(num // 10000)):
arr = [0] * 1000
for i in range(len(arr)):
arr[i] += 1
bench.run(test)
|
YifuLiu/AliOS-Things
|
components/py_engine/tests/internal_bench/arrayop-1-list_inplace.py
|
Python
|
apache-2.0
| 320
|
# Array operation
# Type: list, map() call. This method requires allocation of
# the same amount of memory as original array (to hold result
# array). On the other hand, input array stays intact.
import bench
def test(num):
for i in iter(range(num // 10000)):
arr = [0] * 1000
arr2 = list(map(lambda x: x + 1, arr))
bench.run(test)
|
YifuLiu/AliOS-Things
|
components/py_engine/tests/internal_bench/arrayop-2-list_map.py
|
Python
|
apache-2.0
| 356
|
# Array operation
# Type: bytearray, inplace operation using for. What's good about this
# method is that it doesn't require any extra memory allocation.
import bench
def test(num):
for i in iter(range(num // 10000)):
arr = bytearray(b"\0" * 1000)
for i in range(len(arr)):
arr[i] += 1
bench.run(test)
|
YifuLiu/AliOS-Things
|
components/py_engine/tests/internal_bench/arrayop-3-bytearray_inplace.py
|
Python
|
apache-2.0
| 338
|
# Array operation
# Type: list, map() call. This method requires allocation of
# the same amount of memory as original array (to hold result
# array). On the other hand, input array stays intact.
import bench
def test(num):
for i in iter(range(num // 10000)):
arr = bytearray(b"\0" * 1000)
arr2 = bytearray(map(lambda x: x + 1, arr))
bench.run(test)
|
YifuLiu/AliOS-Things
|
components/py_engine/tests/internal_bench/arrayop-4-bytearray_map.py
|
Python
|
apache-2.0
| 374
|
import time
ITERS = 20000000
def run(f):
t = time.time()
f(ITERS)
t = time.time() - t
print(t)
|
YifuLiu/AliOS-Things
|
components/py_engine/tests/internal_bench/bench.py
|
Python
|
apache-2.0
| 115
|
import bench
def test(num):
for i in iter(range(num // 1000)):
bytes(10000)
bench.run(test)
|
YifuLiu/AliOS-Things
|
components/py_engine/tests/internal_bench/bytealloc-1-bytes_n.py
|
Python
|
apache-2.0
| 108
|
import bench
def test(num):
for i in iter(range(num // 1000)):
b"\0" * 10000
bench.run(test)
|
YifuLiu/AliOS-Things
|
components/py_engine/tests/internal_bench/bytealloc-2-repeat.py
|
Python
|
apache-2.0
| 109
|
# Doing some operation on bytearray
# Inplace - the most memory efficient way
import bench
def test(num):
for i in iter(range(num // 10000)):
ba = bytearray(b"\0" * 1000)
for i in range(len(ba)):
ba[i] += 1
bench.run(test)
|
YifuLiu/AliOS-Things
|
components/py_engine/tests/internal_bench/bytebuf-1-inplace.py
|
Python
|
apache-2.0
| 259
|
# Doing some operation on bytearray
# Pretty weird way - map bytearray thru function, but make sure that
# function return bytes of size 1, then join them together. Surely,
# this is slowest way to do it.
import bench
def test(num):
for i in iter(range(num // 10000)):
ba = bytearray(b"\0" * 1000)
ba2 = b"".join(map(lambda x: bytes([x + 1]), ba))
bench.run(test)
|
YifuLiu/AliOS-Things
|
components/py_engine/tests/internal_bench/bytebuf-2-join_map_bytes.py
|
Python
|
apache-2.0
| 388
|
# Doing some operation on bytearray
# No joins, but still map().
import bench
def test(num):
for i in iter(range(num // 10000)):
ba = bytearray(b"\0" * 1000)
ba2 = bytearray(map(lambda x: x + 1, ba))
bench.run(test)
|
YifuLiu/AliOS-Things
|
components/py_engine/tests/internal_bench/bytebuf-3-bytarray_map.py
|
Python
|
apache-2.0
| 240
|
import bench
def test(num):
for i in iter(range(num // 10000)):
l = [0] * 1000
l2 = list(l)
bench.run(test)
|
YifuLiu/AliOS-Things
|
components/py_engine/tests/internal_bench/from_iter-1-list_bound.py
|
Python
|
apache-2.0
| 132
|
import bench
def test(num):
for i in iter(range(num // 10000)):
l = [0] * 1000
l2 = list(map(lambda x: x, l))
bench.run(test)
|
YifuLiu/AliOS-Things
|
components/py_engine/tests/internal_bench/from_iter-2-list_unbound.py
|
Python
|
apache-2.0
| 150
|
import bench
def test(num):
for i in iter(range(num // 10000)):
l = [0] * 1000
l2 = tuple(l)
bench.run(test)
|
YifuLiu/AliOS-Things
|
components/py_engine/tests/internal_bench/from_iter-3-tuple_bound.py
|
Python
|
apache-2.0
| 133
|
import bench
def test(num):
for i in iter(range(num // 10000)):
l = [0] * 1000
l2 = tuple(map(lambda x: x, l))
bench.run(test)
|
YifuLiu/AliOS-Things
|
components/py_engine/tests/internal_bench/from_iter-4-tuple_unbound.py
|
Python
|
apache-2.0
| 151
|
import bench
def test(num):
for i in iter(range(num // 10000)):
l = [0] * 1000
l2 = bytes(l)
bench.run(test)
|
YifuLiu/AliOS-Things
|
components/py_engine/tests/internal_bench/from_iter-5-bytes_bound.py
|
Python
|
apache-2.0
| 133
|
import bench
def test(num):
for i in iter(range(num // 10000)):
l = [0] * 1000
l2 = bytes(map(lambda x: x, l))
bench.run(test)
|
YifuLiu/AliOS-Things
|
components/py_engine/tests/internal_bench/from_iter-6-bytes_unbound.py
|
Python
|
apache-2.0
| 151
|
import bench
def test(num):
for i in iter(range(num // 10000)):
l = [0] * 1000
l2 = bytearray(l)
bench.run(test)
|
YifuLiu/AliOS-Things
|
components/py_engine/tests/internal_bench/from_iter-7-bytearray_bound.py
|
Python
|
apache-2.0
| 137
|
import bench
def test(num):
for i in iter(range(num // 10000)):
l = [0] * 1000
l2 = bytearray(map(lambda x: x, l))
bench.run(test)
|
YifuLiu/AliOS-Things
|
components/py_engine/tests/internal_bench/from_iter-8-bytearray_unbound.py
|
Python
|
apache-2.0
| 155
|
import bench
def func(a):
pass
def test(num):
for i in iter(range(num)):
func(i)
bench.run(test)
|
YifuLiu/AliOS-Things
|
components/py_engine/tests/internal_bench/func_args-1.1-pos_1.py
|
Python
|
apache-2.0
| 119
|
import bench
def func(a, b, c):
pass
def test(num):
for i in iter(range(num)):
func(i, i, i)
bench.run(test)
|
YifuLiu/AliOS-Things
|
components/py_engine/tests/internal_bench/func_args-1.2-pos_3.py
|
Python
|
apache-2.0
| 131
|
import bench
def func(a, b=1, c=2):
pass
def test(num):
for i in iter(range(num)):
func(i)
bench.run(test)
|
YifuLiu/AliOS-Things
|
components/py_engine/tests/internal_bench/func_args-2-pos_default_2_of_3.py
|
Python
|
apache-2.0
| 129
|
import bench
def func(a):
pass
def test(num):
for i in iter(range(num)):
func(a=i)
bench.run(test)
|
YifuLiu/AliOS-Things
|
components/py_engine/tests/internal_bench/func_args-3.1-kw_1.py
|
Python
|
apache-2.0
| 121
|
import bench
def func(a, b, c):
pass
def test(num):
for i in iter(range(num)):
func(c=i, b=i, a=i)
bench.run(test)
|
YifuLiu/AliOS-Things
|
components/py_engine/tests/internal_bench/func_args-3.2-kw_3.py
|
Python
|
apache-2.0
| 137
|
import bench
def test(num):
for i in iter(range(num // 20)):
enumerate([1, 2], 1)
bench.run(test)
|
YifuLiu/AliOS-Things
|
components/py_engine/tests/internal_bench/func_builtin-1-enum_pos.py
|
Python
|
apache-2.0
| 114
|
import bench
def test(num):
for i in iter(range(num // 20)):
enumerate(iterable=[1, 2], start=1)
bench.run(test)
|
YifuLiu/AliOS-Things
|
components/py_engine/tests/internal_bench/func_builtin-2-enum_kw.py
|
Python
|
apache-2.0
| 129
|
# Function call overhead test
# Establish a baseline for performing a trivial operation inline
import bench
def test(num):
for i in iter(range(num)):
a = i + 1
bench.run(test)
|
YifuLiu/AliOS-Things
|
components/py_engine/tests/internal_bench/funcall-1-inline.py
|
Python
|
apache-2.0
| 192
|
# Function call overhead test
# Perform the same trivial operation as global function call
import bench
def f(x):
return x + 1
def test(num):
for i in iter(range(num)):
a = f(i)
bench.run(test)
|
YifuLiu/AliOS-Things
|
components/py_engine/tests/internal_bench/funcall-2-funcall.py
|
Python
|
apache-2.0
| 216
|
# Function call overhead test
# Perform the same trivial operation as calling function, cached in a
# local variable. This is commonly known optimization for overly dynamic
# languages (the idea is to cut on symbolic look up overhead, as local
# variables are accessed by offset, not by name)
import bench
def f(x):
return x + 1
def test(num):
f_ = f
for i in iter(range(num)):
a = f_(i)
bench.run(test)
|
YifuLiu/AliOS-Things
|
components/py_engine/tests/internal_bench/funcall-3-funcall-local.py
|
Python
|
apache-2.0
| 430
|
import bench
def test(num):
for i in range(num):
pass
bench.run(test)
|
YifuLiu/AliOS-Things
|
components/py_engine/tests/internal_bench/loop_count-1-range.py
|
Python
|
apache-2.0
| 86
|
import bench
def test(num):
for i in iter(range(num)):
pass
bench.run(test)
|
YifuLiu/AliOS-Things
|
components/py_engine/tests/internal_bench/loop_count-2-range_iter.py
|
Python
|
apache-2.0
| 92
|
import bench
def test(num):
i = 0
while i < num:
i += 1
bench.run(test)
|
YifuLiu/AliOS-Things
|
components/py_engine/tests/internal_bench/loop_count-3-while_up.py
|
Python
|
apache-2.0
| 92
|
import bench
def test(num):
while num > 0:
num -= 1
bench.run(test)
|
YifuLiu/AliOS-Things
|
components/py_engine/tests/internal_bench/loop_count-4-while_down_gt.py
|
Python
|
apache-2.0
| 84
|
import bench
def test(num):
while num != 0:
num -= 1
bench.run(test)
|
YifuLiu/AliOS-Things
|
components/py_engine/tests/internal_bench/loop_count-5-while_down_ne.py
|
Python
|
apache-2.0
| 85
|
import bench
def test(num):
zero = 0
while num != zero:
num -= 1
bench.run(test)
|
YifuLiu/AliOS-Things
|
components/py_engine/tests/internal_bench/loop_count-5.1-while_down_ne_localvar.py
|
Python
|
apache-2.0
| 101
|
import bench
def test(num):
i = 0
while i < 20000000:
i += 1
bench.run(test)
|
YifuLiu/AliOS-Things
|
components/py_engine/tests/internal_bench/var-1-constant.py
|
Python
|
apache-2.0
| 97
|
import bench
ITERS = 20000000
def test(num):
i = 0
while i < ITERS:
i += 1
bench.run(test)
|
YifuLiu/AliOS-Things
|
components/py_engine/tests/internal_bench/var-2-global.py
|
Python
|
apache-2.0
| 112
|
import bench
def test(num):
ITERS = 20000000
i = 0
while i < ITERS:
i += 1
bench.run(test)
|
YifuLiu/AliOS-Things
|
components/py_engine/tests/internal_bench/var-3-local.py
|
Python
|
apache-2.0
| 115
|
import bench
def test(num):
i = 0
while i < num:
i += 1
bench.run(lambda n: test(20000000))
|
YifuLiu/AliOS-Things
|
components/py_engine/tests/internal_bench/var-4-arg.py
|
Python
|
apache-2.0
| 112
|
import bench
class Foo:
num = 20000000
def test(num):
i = 0
while i < Foo.num:
i += 1
bench.run(test)
|
YifuLiu/AliOS-Things
|
components/py_engine/tests/internal_bench/var-5-class-attr.py
|
Python
|
apache-2.0
| 128
|
import bench
class Foo:
def __init__(self):
self.num = 20000000
def test(num):
o = Foo()
i = 0
while i < o.num:
i += 1
bench.run(test)
|
YifuLiu/AliOS-Things
|
components/py_engine/tests/internal_bench/var-6-instance-attr.py
|
Python
|
apache-2.0
| 173
|
import bench
class Foo:
def __init__(self):
self.num1 = 0
self.num2 = 0
self.num3 = 0
self.num4 = 0
self.num = 20000000
def test(num):
o = Foo()
i = 0
while i < o.num:
i += 1
bench.run(test)
|
YifuLiu/AliOS-Things
|
components/py_engine/tests/internal_bench/var-6.1-instance-attr-5.py
|
Python
|
apache-2.0
| 261
|
import bench
class Foo:
def __init__(self):
self._num = 20000000
def num(self):
return self._num
def test(num):
o = Foo()
i = 0
while i < o.num():
i += 1
bench.run(test)
|
YifuLiu/AliOS-Things
|
components/py_engine/tests/internal_bench/var-7-instance-meth.py
|
Python
|
apache-2.0
| 221
|
import bench
from ucollections import namedtuple
T = namedtuple("Tup", ["num", "bar"])
def test(num):
t = T(20000000, 0)
i = 0
while i < t.num:
i += 1
bench.run(test)
|
YifuLiu/AliOS-Things
|
components/py_engine/tests/internal_bench/var-8-namedtuple-1st.py
|
Python
|
apache-2.0
| 192
|
import bench
from ucollections import namedtuple
T = namedtuple("Tup", ["foo1", "foo2", "foo3", "foo4", "num"])
def test(num):
t = T(0, 0, 0, 0, 20000000)
i = 0
while i < t.num:
i += 1
bench.run(test)
|
YifuLiu/AliOS-Things
|
components/py_engine/tests/internal_bench/var-8.1-namedtuple-5th.py
|
Python
|
apache-2.0
| 226
|
try:
import usys as sys
except ImportError:
import sys
print(sys.argv)
|
YifuLiu/AliOS-Things
|
components/py_engine/tests/io/argv.py
|
Python
|
apache-2.0
| 80
|
# test builtin print function, using file= argument
try:
import usys as sys
except ImportError:
import sys
try:
sys.stdout
except AttributeError:
print("SKIP")
raise SystemExit
print(file=sys.stdout)
print("test", file=sys.stdout)
try:
print(file=1)
except (AttributeError, OSError): # CPython and uPy differ in error message
print("Error")
|
YifuLiu/AliOS-Things
|
components/py_engine/tests/io/builtin_print_file.py
|
Python
|
apache-2.0
| 374
|
f = open("io/data/file1")
print(f.read(5))
print(f.readline())
print(f.read())
f = open("io/data/file1")
print(f.readlines())
f = open("io/data/file1", "r")
print(f.readlines())
f = open("io/data/file1", "rb")
print(f.readlines())
f = open("io/data/file1", mode="r")
print(f.readlines())
f = open("io/data/file1", mode="rb")
print(f.readlines())
# write() error
f = open("io/data/file1", "r")
try:
f.write("x")
except OSError:
print("OSError")
f.close()
# read(n) error on binary file
f = open("io/data/file1", "ab")
try:
f.read(1)
except OSError:
print("OSError")
f.close()
# read(n) error on text file
f = open("io/data/file1", "at")
try:
f.read(1)
except OSError:
print("OSError")
f.close()
# read() w/o args error
f = open("io/data/file1", "ab")
try:
f.read()
except OSError:
print("OSError")
f.close()
# close() on a closed file
f.close()
|
YifuLiu/AliOS-Things
|
components/py_engine/tests/io/file1.py
|
Python
|
apache-2.0
| 881
|
f = open("io/data/file1")
for l in f:
print(l)
|
YifuLiu/AliOS-Things
|
components/py_engine/tests/io/file_iter.py
|
Python
|
apache-2.0
| 51
|
f = open("io/data/file1")
b = f.read(100)
print(len(b))
|
YifuLiu/AliOS-Things
|
components/py_engine/tests/io/file_long_read.py
|
Python
|
apache-2.0
| 56
|
f = open("io/data/bigfile1")
b = f.read()
print(len(b))
print(b)
|
YifuLiu/AliOS-Things
|
components/py_engine/tests/io/file_long_read2.py
|
Python
|
apache-2.0
| 65
|
f = open("io/data/bigfile1", "rb")
b = f.read(512)
print(len(b))
print(b)
|
YifuLiu/AliOS-Things
|
components/py_engine/tests/io/file_long_read3.py
|
Python
|
apache-2.0
| 74
|
b = bytearray(30)
f = open("io/data/file1", "rb")
print(f.readinto(b))
print(b)
f = open("io/data/file2", "rb")
print(f.readinto(b))
print(b)
# readinto() on writable file
f = open("io/data/file1", "ab")
try:
f.readinto(bytearray(4))
except OSError:
print("OSError")
|
YifuLiu/AliOS-Things
|
components/py_engine/tests/io/file_readinto.py
|
Python
|
apache-2.0
| 276
|
b = bytearray(30)
f = open("io/data/file1", "rb")
# 2nd arg (length to read) is extension to CPython
print(f.readinto(b, 8))
print(b)
b = bytearray(4)
f = open("io/data/file1", "rb")
print(f.readinto(b, 8))
print(b)
|
YifuLiu/AliOS-Things
|
components/py_engine/tests/io/file_readinto_len.py
|
Python
|
apache-2.0
| 217
|
f = open("io/data/file1")
print(f.readline())
print(f.readline(3))
print(f.readline(4))
print(f.readline(5))
print(f.readline())
# readline() on writable file
f = open("io/data/file1", "ab")
try:
f.readline()
except OSError:
print("OSError")
f.close()
|
YifuLiu/AliOS-Things
|
components/py_engine/tests/io/file_readline.py
|
Python
|
apache-2.0
| 261
|
f = open("io/data/file1", "rb")
print(f.seek(6))
print(f.read(5))
print(f.tell())
print(f.seek(0, 1))
print(f.read(4))
print(f.tell())
print(f.seek(-6, 2))
print(f.read(20))
print(f.tell())
print(f.seek(0, 0))
print(f.read(5))
print(f.tell())
f.close()
# test text mode
f = open("io/data/file1", "rt")
print(f.seek(6))
print(f.read(5))
print(f.tell())
f.close()
# seek closed file
f = open("io/data/file1", "r")
f.close()
try:
f.seek(1)
except (OSError, ValueError):
# CPy raises ValueError, uPy raises OSError
print("OSError or ValueError")
|
YifuLiu/AliOS-Things
|
components/py_engine/tests/io/file_seek.py
|
Python
|
apache-2.0
| 560
|
try:
import usys as sys
except ImportError:
import sys
print(sys.stdin.fileno())
print(sys.stdout.fileno())
|
YifuLiu/AliOS-Things
|
components/py_engine/tests/io/file_stdio.py
|
Python
|
apache-2.0
| 117
|
f = open("io/data/file1")
with f as f2:
print(f2.read())
# File should be closed
try:
f.read()
except:
# Note: CPython and us throw different exception trying to read from
# close file.
print("can't read file after with")
# Regression test: test that exception in with initialization properly
# thrown and doesn't crash.
try:
with open("__non_existent", "r"):
pass
except OSError:
print("OSError")
|
YifuLiu/AliOS-Things
|
components/py_engine/tests/io/file_with.py
|
Python
|
apache-2.0
| 438
|
try:
import uos as os
except ImportError:
import os
if not hasattr(os, "remove"):
print("SKIP")
raise SystemExit
# cleanup in case testfile exists
try:
os.remove("testfile")
except OSError:
pass
# Should create a file
f = open("testfile", "a")
f.write("foo")
f.close()
f = open("testfile")
print(f.read())
f.close()
f = open("testfile", "a")
f.write("bar")
f.close()
f = open("testfile")
print(f.read())
f.close()
# cleanup
try:
os.remove("testfile")
except OSError:
pass
|
YifuLiu/AliOS-Things
|
components/py_engine/tests/io/open_append.py
|
Python
|
apache-2.0
| 511
|
try:
import uos as os
except ImportError:
import os
if not hasattr(os, "remove"):
print("SKIP")
raise SystemExit
# cleanup in case testfile exists
try:
os.remove("testfile")
except OSError:
pass
try:
f = open("testfile", "r+b")
print("Unexpectedly opened non-existing file")
except OSError:
print("Expected OSError")
pass
f = open("testfile", "w+b")
f.write(b"1234567890")
f.seek(0)
print(f.read())
f.close()
# Open with truncation
f = open("testfile", "w+b")
f.write(b"abcdefg")
f.seek(0)
print(f.read())
f.close()
# Open without truncation
f = open("testfile", "r+b")
f.write(b"1234")
f.seek(0)
print(f.read())
f.close()
# cleanup
try:
os.remove("testfile")
except OSError:
pass
|
YifuLiu/AliOS-Things
|
components/py_engine/tests/io/open_plus.py
|
Python
|
apache-2.0
| 736
|
import uio
import usys
try:
uio.resource_stream
except AttributeError:
print("SKIP")
raise SystemExit
buf = uio.resource_stream("data", "file2")
print(buf.read())
# resource_stream(None, ...) look ups from current dir, hence sys.path[0] hack
buf = uio.resource_stream(None, usys.path[0] + "/data/file2")
print(buf.read())
|
YifuLiu/AliOS-Things
|
components/py_engine/tests/io/resource_stream.py
|
Python
|
apache-2.0
| 337
|
import jni
try:
ArrayList = jni.cls("java/util/ArrayList")
except:
print("SKIP")
raise SystemExit
l = ArrayList()
print(l)
l.add("one")
l.add("two")
print(l.toString())
print(l)
print(l[0], l[1])
|
YifuLiu/AliOS-Things
|
components/py_engine/tests/jni/list.py
|
Python
|
apache-2.0
| 211
|
import jni
try:
Integer = jni.cls("java/lang/Integer")
except:
print("SKIP")
raise SystemExit
# Create object
i = Integer(42)
print(i)
# Call object method
print(i.hashCode())
# Pass object to another method
System = jni.cls("java/lang/System")
System.out.println(i)
|
YifuLiu/AliOS-Things
|
components/py_engine/tests/jni/object.py
|
Python
|
apache-2.0
| 281
|
try:
import jni
System = jni.cls("java/lang/System")
except:
print("SKIP")
raise SystemExit
System.out.println("Hello, Java!")
|
YifuLiu/AliOS-Things
|
components/py_engine/tests/jni/system_out.py
|
Python
|
apache-2.0
| 145
|
# test constant optimisation
from micropython import const
X = const(123)
Y = const(X + 456)
print(X, Y + 1)
def f():
print(X, Y + 1)
f()
_X = const(12)
_Y = const(_X + 34)
print(_X, _Y)
class A:
Z = const(1)
_Z = const(2)
print(Z, _Z)
print(hasattr(A, "Z"), hasattr(A, "_Z"))
|
YifuLiu/AliOS-Things
|
components/py_engine/tests/micropython/const.py
|
Python
|
apache-2.0
| 306
|
# check that consts are not replaced in anything except standalone identifiers
from micropython import const
X = const(1)
Y = const(2)
Z = const(3)
# import that uses a constant
import micropython as X
print(globals()["X"])
# function name that matches a constant
def X():
print("function X", X)
globals()["X"]()
# arguments that match a constant
def f(X, *Y, **Z):
pass
f(1)
# class name that matches a constant
class X:
def f(self):
print("class X", X)
globals()["X"]().f()
# constant within a class
class A:
C1 = const(4)
def X(self):
print("method X", Y, C1, self.C1)
A().X()
|
YifuLiu/AliOS-Things
|
components/py_engine/tests/micropython/const2.py
|
Python
|
apache-2.0
| 633
|
# make sure syntax error works correctly for bad const definition
from micropython import const
def test_syntax(code):
try:
exec(code)
except SyntaxError:
print("SyntaxError")
# argument not a constant
test_syntax("a = const(x)")
# redefined constant
test_syntax("A = const(1); A = const(2)")
# these operations are not supported within const
test_syntax("A = const(1 @ 2)")
test_syntax("A = const(1 / 2)")
test_syntax("A = const(1 ** -2)")
test_syntax("A = const(1 << -2)")
test_syntax("A = const(1 >> -2)")
test_syntax("A = const(1 % 0)")
test_syntax("A = const(1 // 0)")
|
YifuLiu/AliOS-Things
|
components/py_engine/tests/micropython/const_error.py
|
Python
|
apache-2.0
| 605
|
# test constant optimisation, with consts that are bignums
from micropython import const
# check we can make consts from bignums
Z1 = const(0xFFFFFFFF)
Z2 = const(0xFFFFFFFFFFFFFFFF)
print(hex(Z1), hex(Z2))
# check arithmetic with bignum
Z3 = const(Z1 + Z2)
Z4 = const((1 << 100) + Z1)
print(hex(Z3), hex(Z4))
|
YifuLiu/AliOS-Things
|
components/py_engine/tests/micropython/const_intbig.py
|
Python
|
apache-2.0
| 313
|
# test micropython-specific decorators
@micropython.bytecode
def f():
return "bytecode"
print(f())
|
YifuLiu/AliOS-Things
|
components/py_engine/tests/micropython/decorator.py
|
Python
|
apache-2.0
| 107
|
# test syntax errors for uPy-specific decorators
def test_syntax(code):
try:
exec(code)
except SyntaxError:
print("SyntaxError")
# invalid micropython decorators
test_syntax("@micropython.a\ndef f(): pass")
test_syntax("@micropython.a.b\ndef f(): pass")
|
YifuLiu/AliOS-Things
|
components/py_engine/tests/micropython/decorator_error.py
|
Python
|
apache-2.0
| 282
|
# test that emergency exceptions work
import micropython
import usys
try:
import uio
except ImportError:
print("SKIP")
raise SystemExit
# some ports need to allocate heap for the emg exc
try:
micropython.alloc_emergency_exception_buf(256)
except AttributeError:
pass
def f():
micropython.heap_lock()
try:
raise ValueError(1)
except ValueError as er:
exc = er
micropython.heap_unlock()
# print the exception
buf = uio.StringIO()
usys.print_exception(exc, buf)
for l in buf.getvalue().split("\n"):
if l.startswith(" File "):
print(l.split('"')[2])
else:
print(l)
f()
|
YifuLiu/AliOS-Things
|
components/py_engine/tests/micropython/emg_exc.py
|
Python
|
apache-2.0
| 682
|
# test some extreme cases of allocating exceptions and tracebacks
import micropython
# Check for stackless build, which can't call functions without
# allocating a frame on the heap.
try:
def stackless():
pass
micropython.heap_lock()
stackless()
micropython.heap_unlock()
except RuntimeError:
print("SKIP")
raise SystemExit
# some ports need to allocate heap for the emergency exception
try:
micropython.alloc_emergency_exception_buf(256)
except AttributeError:
pass
def main():
# create an exception with many args while heap is locked
# should revert to empty tuple for args
micropython.heap_lock()
e = Exception(
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
)
micropython.heap_unlock()
print(repr(e))
# create an exception with a long formatted error message while heap is locked
# should use emergency exception buffer and truncate the message
def f():
pass
micropython.heap_lock()
try:
f(
abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz=1
)
except Exception as er:
e = er
micropython.heap_unlock()
print(repr(e)[:10])
# create an exception with a long formatted error message while heap is low
# should use the heap and truncate the message
lst = []
while 1:
try:
lst = [lst]
except MemoryError:
break
try:
f(
abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz=1
)
except Exception as er:
e = er
lst[0][0] = None
lst = None
print(repr(e)[:10])
# raise a deep exception with the heap locked
# should use emergency exception and be unable to resize traceback array
def g():
g()
micropython.heap_lock()
try:
g()
except Exception as er:
e = er
micropython.heap_unlock()
print(repr(e)[:13])
# create an exception on the heap with some traceback on the heap, but then
# raise it with the heap locked so it can't allocate any more traceback
exc = Exception("my exception")
try:
raise exc
except:
pass
def h(e):
raise e
micropython.heap_lock()
try:
h(exc)
except Exception as er:
e = er
micropython.heap_unlock()
print(repr(e))
main()
|
YifuLiu/AliOS-Things
|
components/py_engine/tests/micropython/extreme_exc.py
|
Python
|
apache-2.0
| 3,386
|
# check that heap_lock/heap_unlock work as expected
import micropython
l = []
l2 = list(range(100))
micropython.heap_lock()
micropython.heap_lock()
# general allocation on the heap
try:
print([])
except MemoryError:
print("MemoryError")
# expansion of a heap block
try:
l.extend(l2)
except MemoryError:
print("MemoryError")
print(micropython.heap_unlock())
# Should still fail
try:
print([])
except MemoryError:
print("MemoryError")
micropython.heap_unlock()
# check that allocation works after an unlock
print([])
|
YifuLiu/AliOS-Things
|
components/py_engine/tests/micropython/heap_lock.py
|
Python
|
apache-2.0
| 548
|
# test micropython.heap_locked()
import micropython
if not hasattr(micropython, "heap_locked"):
print("SKIP")
raise SystemExit
micropython.heap_lock()
print(micropython.heap_locked())
micropython.heap_unlock()
print(micropython.heap_locked())
|
YifuLiu/AliOS-Things
|
components/py_engine/tests/micropython/heap_locked.py
|
Python
|
apache-2.0
| 254
|
# check that we can do certain things without allocating heap memory
import micropython
# Check for stackless build, which can't call functions without
# allocating a frame on heap.
try:
def stackless():
pass
micropython.heap_lock()
stackless()
micropython.heap_unlock()
except RuntimeError:
print("SKIP")
raise SystemExit
def f1(a):
print(a)
def f2(a, b=2):
print(a, b)
def f3(a, b, c, d):
x1 = x2 = a
x3 = x4 = b
x5 = x6 = c
x7 = x8 = d
print(x1, x3, x5, x7, x2 + x4 + x6 + x8)
global_var = 1
def test():
global global_var, global_exc
global_var = 2 # set an existing global variable
for i in range(2): # for loop
f1(i) # function call
f1(i * 2 + 1) # binary operation with small ints
f1(a=i) # keyword arguments
f2(i) # default arg (second one)
f2(i, i) # 2 args
f3(1, 2, 3, 4) # function with lots of local state
# call test() with heap allocation disabled
micropython.heap_lock()
test()
micropython.heap_unlock()
|
YifuLiu/AliOS-Things
|
components/py_engine/tests/micropython/heapalloc.py
|
Python
|
apache-2.0
| 1,058
|
try:
import uio
except ImportError:
print("SKIP")
raise SystemExit
import micropython
data = b"1234" * 16
buf = uio.BytesIO(64)
micropython.heap_lock()
buf.write(data)
micropython.heap_unlock()
print(buf.getvalue())
|
YifuLiu/AliOS-Things
|
components/py_engine/tests/micropython/heapalloc_bytesio.py
|
Python
|
apache-2.0
| 234
|
# Creating BytesIO from immutable object should not immediately
# copy its content.
try:
import uio
import micropython
micropython.mem_total
except (ImportError, AttributeError):
print("SKIP")
raise SystemExit
data = b"1234" * 256
before = micropython.mem_total()
buf = uio.BytesIO(data)
after = micropython.mem_total()
print(after - before < len(data))
|
YifuLiu/AliOS-Things
|
components/py_engine/tests/micropython/heapalloc_bytesio2.py
|
Python
|
apache-2.0
| 381
|
import micropython
# Tests both code paths for built-in exception raising.
# mp_obj_new_exception_msg_varg (exception requires decompression at raise-time to format)
# mp_obj_new_exception_msg (decompression can be deferred)
# NameError uses mp_obj_new_exception_msg_varg for NameError("name '%q' isn't defined")
# set.pop uses mp_obj_new_exception_msg for KeyError("pop from an empty set")
# Tests that deferred decompression works both via print(e) and accessing the message directly via e.args.
a = set()
# First test the regular case (can use heap for allocating the decompression buffer).
try:
name()
except NameError as e:
print(type(e).__name__, e)
try:
a.pop()
except KeyError as e:
print(type(e).__name__, e)
try:
name()
except NameError as e:
print(e.args[0])
try:
a.pop()
except KeyError as e:
print(e.args[0])
# Then test that it still works when the heap is locked (i.e. in ISR context).
micropython.heap_lock()
try:
name()
except NameError as e:
print(type(e).__name__)
try:
a.pop()
except KeyError as e:
print(type(e).__name__)
micropython.heap_unlock()
|
YifuLiu/AliOS-Things
|
components/py_engine/tests/micropython/heapalloc_exc_compressed.py
|
Python
|
apache-2.0
| 1,129
|
import micropython
# Does the full test from heapalloc_exc_compressed.py but while the heap is
# locked (this can only work when the emergency exception buf is enabled).
# Some ports need to allocate heap for the emgergency exception buffer.
try:
micropython.alloc_emergency_exception_buf(256)
except AttributeError:
pass
a = set()
def test():
micropython.heap_lock()
try:
name()
except NameError as e:
print(type(e).__name__, e)
try:
a.pop()
except KeyError as e:
print(type(e).__name__, e)
try:
name()
except NameError as e:
print(e.args[0])
try:
a.pop()
except KeyError as e:
print(e.args[0])
micropython.heap_unlock()
test()
|
YifuLiu/AliOS-Things
|
components/py_engine/tests/micropython/heapalloc_exc_compressed_emg_exc.py
|
Python
|
apache-2.0
| 753
|
# Test that we can raise and catch (preallocated) exception
# without memory allocation.
import micropython
e = ValueError("error")
def func():
micropython.heap_lock()
try:
# This works as is because traceback is not allocated
# if not possible (heap is locked, no memory). If heap
# is not locked, this would allocate a traceback entry.
# To avoid that, traceback should be warmed up (by raising
# it once after creation) and then cleared before each
# raise with:
# e.__traceback__ = None
raise e
except Exception as e2:
print(e2)
micropython.heap_unlock()
func()
print("ok")
|
YifuLiu/AliOS-Things
|
components/py_engine/tests/micropython/heapalloc_exc_raise.py
|
Python
|
apache-2.0
| 671
|
# test handling of failed heap allocation with bytearray
import micropython
class GetSlice:
def __getitem__(self, idx):
return idx
sl = GetSlice()[:]
# create bytearray
micropython.heap_lock()
try:
bytearray(4)
except MemoryError:
print("MemoryError: bytearray create")
micropython.heap_unlock()
# create bytearray from bytes
micropython.heap_lock()
try:
bytearray(b"0123")
except MemoryError:
print("MemoryError: bytearray create from bytes")
micropython.heap_unlock()
# create bytearray from iterator
r = range(4)
micropython.heap_lock()
try:
bytearray(r)
except MemoryError:
print("MemoryError: bytearray create from iter")
micropython.heap_unlock()
# bytearray add
b = bytearray(4)
micropython.heap_lock()
try:
b + b"01"
except MemoryError:
print("MemoryError: bytearray.__add__")
micropython.heap_unlock()
# bytearray iadd
b = bytearray(4)
micropython.heap_lock()
try:
b += b"01234567"
except MemoryError:
print("MemoryError: bytearray.__iadd__")
micropython.heap_unlock()
print(b)
# bytearray append
b = bytearray(4)
micropython.heap_lock()
try:
for i in range(100):
b.append(1)
except MemoryError:
print("MemoryError: bytearray.append")
micropython.heap_unlock()
# bytearray extend
b = bytearray(4)
micropython.heap_lock()
try:
b.extend(b"01234567")
except MemoryError:
print("MemoryError: bytearray.extend")
micropython.heap_unlock()
# bytearray get with slice
b = bytearray(4)
micropython.heap_lock()
try:
b[sl]
except MemoryError:
print("MemoryError: bytearray subscr get")
micropython.heap_unlock()
# extend bytearray using slice subscr
b = bytearray(4)
micropython.heap_lock()
try:
b[sl] = b"01234567"
except MemoryError:
print("MemoryError: bytearray subscr grow")
micropython.heap_unlock()
print(b)
|
YifuLiu/AliOS-Things
|
components/py_engine/tests/micropython/heapalloc_fail_bytearray.py
|
Python
|
apache-2.0
| 1,819
|
# test handling of failed heap allocation with dict
import micropython
# create dict
x = 1
micropython.heap_lock()
try:
{x: x}
except MemoryError:
print("MemoryError: create dict")
micropython.heap_unlock()
# create dict view
x = {1: 1}
micropython.heap_lock()
try:
x.items()
except MemoryError:
print("MemoryError: dict.items")
micropython.heap_unlock()
|
YifuLiu/AliOS-Things
|
components/py_engine/tests/micropython/heapalloc_fail_dict.py
|
Python
|
apache-2.0
| 374
|
# test handling of failed heap allocation with list
import micropython
class GetSlice:
def __getitem__(self, idx):
return idx
sl = GetSlice()[:]
# create slice in VM
l = [1, 2, 3]
micropython.heap_lock()
try:
print(l[0:1])
except MemoryError:
print("MemoryError: list index")
micropython.heap_unlock()
# get from list using slice
micropython.heap_lock()
try:
l[sl]
except MemoryError:
print("MemoryError: list get slice")
micropython.heap_unlock()
# extend list using slice subscr
l = [1, 2]
l2 = [3, 4, 5, 6, 7, 8, 9, 10]
micropython.heap_lock()
try:
l[sl] = l2
except MemoryError:
print("MemoryError: list extend slice")
micropython.heap_unlock()
print(l)
|
YifuLiu/AliOS-Things
|
components/py_engine/tests/micropython/heapalloc_fail_list.py
|
Python
|
apache-2.0
| 702
|
# test handling of failed heap allocation with memoryview
import micropython
class GetSlice:
def __getitem__(self, idx):
return idx
sl = GetSlice()[:]
# create memoryview
micropython.heap_lock()
try:
memoryview(b"")
except MemoryError:
print("MemoryError: memoryview create")
micropython.heap_unlock()
# memoryview get with slice
m = memoryview(b"")
micropython.heap_lock()
try:
m[sl]
except MemoryError:
print("MemoryError: memoryview subscr get")
micropython.heap_unlock()
|
YifuLiu/AliOS-Things
|
components/py_engine/tests/micropython/heapalloc_fail_memoryview.py
|
Python
|
apache-2.0
| 510
|
# test handling of failed heap allocation with set
import micropython
# create set
x = 1
micropython.heap_lock()
try:
{x}
except MemoryError:
print("MemoryError: set create")
micropython.heap_unlock()
# set copy
s = {1, 2}
micropython.heap_lock()
try:
s.copy()
except MemoryError:
print("MemoryError: set copy")
micropython.heap_unlock()
|
YifuLiu/AliOS-Things
|
components/py_engine/tests/micropython/heapalloc_fail_set.py
|
Python
|
apache-2.0
| 357
|
# test handling of failed heap allocation with tuple
import micropython
# create tuple
x = 1
micropython.heap_lock()
try:
(x,)
except MemoryError:
print("MemoryError: tuple create")
micropython.heap_unlock()
|
YifuLiu/AliOS-Things
|
components/py_engine/tests/micropython/heapalloc_fail_tuple.py
|
Python
|
apache-2.0
| 218
|
# Test that calling clazz.__call__() with up to at least 3 arguments
# doesn't require heap allocation.
import micropython
class Foo0:
def __call__(self):
print("__call__")
class Foo1:
def __call__(self, a):
print("__call__", a)
class Foo2:
def __call__(self, a, b):
print("__call__", a, b)
class Foo3:
def __call__(self, a, b, c):
print("__call__", a, b, c)
f0 = Foo0()
f1 = Foo1()
f2 = Foo2()
f3 = Foo3()
micropython.heap_lock()
f0()
f1(1)
f2(1, 2)
f3(1, 2, 3)
micropython.heap_unlock()
|
YifuLiu/AliOS-Things
|
components/py_engine/tests/micropython/heapalloc_inst_call.py
|
Python
|
apache-2.0
| 548
|
# Test that int.from_bytes() for small number of bytes generates
# small int.
import micropython
micropython.heap_lock()
print(int.from_bytes(b"1", "little"))
print(int.from_bytes(b"12", "little"))
print(int.from_bytes(b"2\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00", "little"))
micropython.heap_unlock()
|
YifuLiu/AliOS-Things
|
components/py_engine/tests/micropython/heapalloc_int_from_bytes.py
|
Python
|
apache-2.0
| 307
|
# test that iterating doesn't use the heap
try:
frozenset
except NameError:
print("SKIP")
raise SystemExit
try:
import uarray as array
except ImportError:
try:
import array
except ImportError:
print("SKIP")
raise SystemExit
try:
from micropython import heap_lock, heap_unlock
except (ImportError, AttributeError):
heap_lock = heap_unlock = lambda: 0
def do_iter(l):
heap_lock()
for i in l:
print(i)
heap_unlock()
def gen_func():
yield 1
yield 2
# pre-create collections to iterate over
ba = bytearray(b"123")
ar = array.array("H", (123, 456))
t = (1, 2, 3)
l = [1, 2]
d = {1: 2}
s = set((1,))
fs = frozenset((1,))
g1 = (100 + x for x in range(2))
g2 = gen_func()
# test containment (both success and failure) with the heap locked
heap_lock()
print(49 in b"123", 255 in b"123")
print(1 in t, -1 in t)
print(1 in l, -1 in l)
print(1 in d, -1 in d)
print(1 in s, -1 in s)
heap_unlock()
# test unpacking with the heap locked
unp0 = unp1 = unp2 = None # preallocate slots for globals
heap_lock()
unp0, unp1, unp2 = t
print(unp0, unp1, unp2)
heap_unlock()
# test certain builtins with the heap locked
heap_lock()
print(all(t))
print(any(t))
print(min(t))
print(max(t))
print(sum(t))
heap_unlock()
# test iterating over collections with the heap locked
do_iter(b"123")
do_iter(ba)
do_iter(ar)
do_iter(t)
do_iter(l)
do_iter(d)
do_iter(s)
do_iter(fs)
do_iter(g1)
do_iter(g2)
|
YifuLiu/AliOS-Things
|
components/py_engine/tests/micropython/heapalloc_iter.py
|
Python
|
apache-2.0
| 1,462
|
# String operations which don't require allocation
import micropython
micropython.heap_lock()
# Concatenating empty string returns original string
b"" + b""
b"" + b"1"
b"2" + b""
"" + ""
"" + "1"
"2" + ""
# If no replacements done, returns original string
"foo".replace(",", "_")
micropython.heap_unlock()
|
YifuLiu/AliOS-Things
|
components/py_engine/tests/micropython/heapalloc_str.py
|
Python
|
apache-2.0
| 311
|
# test super() operations which don't require allocation
import micropython
# Check for stackless build, which can't call functions without
# allocating a frame on heap.
try:
def stackless():
pass
micropython.heap_lock()
stackless()
micropython.heap_unlock()
except RuntimeError:
print("SKIP")
raise SystemExit
class A:
def foo(self):
print("A foo")
return 42
class B(A):
def foo(self):
print("B foo")
print(super().foo())
b = B()
micropython.heap_lock()
b.foo()
micropython.heap_unlock()
|
YifuLiu/AliOS-Things
|
components/py_engine/tests/micropython/heapalloc_super.py
|
Python
|
apache-2.0
| 571
|
# test that we can generate a traceback without allocating
import micropython
import usys
try:
import uio
except ImportError:
print("SKIP")
raise SystemExit
# preallocate exception instance with some room for a traceback
global_exc = StopIteration()
try:
raise global_exc
except:
pass
def test():
micropython.heap_lock()
global global_exc
global_exc.__traceback__ = None
try:
raise global_exc
except StopIteration:
print("StopIteration")
micropython.heap_unlock()
# call test() with heap allocation disabled
test()
# print the exception that was raised
buf = uio.StringIO()
usys.print_exception(global_exc, buf)
for l in buf.getvalue().split("\n"):
# uPy on pyboard prints <stdin> as file, so remove filename.
if l.startswith(" File "):
l = l.split('"')
print(l[0], l[2])
else:
print(l)
|
YifuLiu/AliOS-Things
|
components/py_engine/tests/micropython/heapalloc_traceback.py
|
Python
|
apache-2.0
| 892
|
# Check that yield-from can work without heap allocation
import micropython
# Yielding from a function generator
def sub_gen(a):
for i in range(a):
yield i
def gen(g):
yield from g
g = gen(sub_gen(4))
micropython.heap_lock()
print(next(g))
print(next(g))
micropython.heap_unlock()
# Yielding from a user iterator
class G:
def __init__(self):
self.value = 0
def __iter__(self):
return self
def __next__(self):
v = self.value
self.value += 1
return v
g = gen(G())
micropython.heap_lock()
print(next(g))
print(next(g))
micropython.heap_unlock()
|
YifuLiu/AliOS-Things
|
components/py_engine/tests/micropython/heapalloc_yield_from.py
|
Python
|
apache-2.0
| 621
|
# test importing of invalid .mpy files
try:
import usys, uio, uos
uio.IOBase
uos.mount
except (ImportError, AttributeError):
print("SKIP")
raise SystemExit
class UserFile(uio.IOBase):
def __init__(self, data):
self.data = memoryview(data)
self.pos = 0
def readinto(self, buf):
n = min(len(buf), len(self.data) - self.pos)
buf[:n] = self.data[self.pos : self.pos + n]
self.pos += n
return n
def ioctl(self, req, arg):
return 0
class UserFS:
def __init__(self, files):
self.files = files
def mount(self, readonly, mksfs):
pass
def umount(self):
pass
def stat(self, path):
if path in self.files:
return (32768, 0, 0, 0, 0, 0, 0, 0, 0, 0)
raise OSError
def open(self, path, mode):
return UserFile(self.files[path])
# these are the test .mpy files
user_files = {
"/mod0.mpy": b"", # empty file
"/mod1.mpy": b"M", # too short header
"/mod2.mpy": b"M\x00\x00\x00", # bad version
"/mod3.mpy": b"M\x00\x00\x00\x7f", # qstr window too large
}
# create and mount a user filesystem
uos.mount(UserFS(user_files), "/userfs")
usys.path.append("/userfs")
# import .mpy files from the user filesystem
for i in range(len(user_files)):
mod = "mod%u" % i
try:
__import__(mod)
except ValueError as er:
print(mod, "ValueError", er)
# unmount and undo path addition
uos.umount("/userfs")
usys.path.pop()
|
YifuLiu/AliOS-Things
|
components/py_engine/tests/micropython/import_mpy_invalid.py
|
Python
|
apache-2.0
| 1,514
|
# Test that native code loaded from a .mpy file is retained after a GC.
try:
import gc, sys, uio, uos
sys.implementation.mpy
uio.IOBase
uos.mount
except (ImportError, AttributeError):
print("SKIP")
raise SystemExit
class UserFile(uio.IOBase):
def __init__(self, data):
self.data = memoryview(data)
self.pos = 0
def readinto(self, buf):
n = min(len(buf), len(self.data) - self.pos)
buf[:n] = self.data[self.pos : self.pos + n]
self.pos += n
return n
def ioctl(self, req, arg):
return 0
class UserFS:
def __init__(self, files):
self.files = files
def mount(self, readonly, mksfs):
pass
def umount(self):
pass
def stat(self, path):
if path in self.files:
return (32768, 0, 0, 0, 0, 0, 0, 0, 0, 0)
raise OSError
def open(self, path, mode):
return UserFile(self.files[path])
# Pre-compiled examples/natmod/features0 example for various architectures, keyed
# by the required value of sys.implementation.mpy.
features0_file_contents = {
# -march=x64 -mcache-lookup-bc
0xB05: b'M\x05\x0b\x1f \x84b\xe9/\x00\x00\x00SH\x8b\x1ds\x00\x00\x00\xbe\x02\x00\x00\x00\xffS\x18\xbf\x01\x00\x00\x00H\x85\xc0u\x0cH\x8bC \xbe\x02\x00\x00\x00[\xff\xe0H\x0f\xaf\xf8H\xff\xc8\xeb\xe6ATUSH\x8b\x1dA\x00\x00\x00H\x8b\x7f\x08L\x8bc(A\xff\xd4H\x8d5\x1f\x00\x00\x00H\x89\xc5H\x8b\x05-\x00\x00\x00\x0f\xb78\xffShH\x89\xefA\xff\xd4H\x8b\x03[]A\\\xc3\x00\x00\x00\x00\x00\x00\x00\x00\x00\x05\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x90\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x01\x84@\x12factorial\x10\x00\x00\r \x01"\x9f\x1c\x01\x1e\xff',
# -march=armv7m
0x1605: b"M\x05\x16\x1f \x84\x12\x1a\xe0\x00\x00\x13\xb5\nK\nJ{D\x9cX\x02!\xe3h\x98G\x03F\x01 3\xb9\x02!#i\x01\x93\x02\xb0\xbd\xe8\x10@\x18GXC\x01;\xf4\xe7\x00\xbfj\x00\x00\x00\x00\x00\x00\x00\xf8\xb5\tN\tK~D\xf4X@hgi\xb8G\x05F\x07K\x07I\xf2XyD\x10\x88ck\x98G(F\xb8G h\xf8\xbd6\x00\x00\x00\x00\x00\x00\x00\x04\x00\x00\x00\x1c\x00\x00\x00\x00\x00\x00\x00\x05\x00\x00\x00\x00\x00\x00\x00\x80\x00\x00\x00\x00\x00\x00\x00\x01\x84\x00\x12factorial\x10\x00\x00\r<\x01>\x9f8\x01:\xff",
}
# Populate other armv7m-derived archs based on armv7m.
for arch in (0x1A05, 0x1E05, 0x2205):
features0_file_contents[arch] = features0_file_contents[0x1605]
if sys.implementation.mpy not in features0_file_contents:
print("SKIP")
raise SystemExit
# These are the test .mpy files.
user_files = {"/features0.mpy": features0_file_contents[sys.implementation.mpy]}
# Create and mount a user filesystem.
uos.mount(UserFS(user_files), "/userfs")
sys.path.append("/userfs")
# Import the native function.
gc.collect()
from features0 import factorial
# Free the module that contained the function.
del sys.modules["features0"]
# Run a GC cycle which should reclaim the module but not the function.
gc.collect()
# Allocate lots of fragmented memory to overwrite anything that was just freed by the GC.
for i in range(1000):
[]
# Run the native function, it should not have been freed or overwritten.
print(factorial(10))
# Unmount and undo path addition.
uos.umount("/userfs")
sys.path.pop()
|
YifuLiu/AliOS-Things
|
components/py_engine/tests/micropython/import_mpy_native_gc.py
|
Python
|
apache-2.0
| 3,253
|
# test importing of .mpy files with native code (x64 only)
try:
import usys, uio, uos
uio.IOBase
uos.mount
except (ImportError, AttributeError):
print("SKIP")
raise SystemExit
if not (usys.platform == "linux" and usys.maxsize > 2 ** 32):
print("SKIP")
raise SystemExit
class UserFile(uio.IOBase):
def __init__(self, data):
self.data = memoryview(data)
self.pos = 0
def readinto(self, buf):
n = min(len(buf), len(self.data) - self.pos)
buf[:n] = self.data[self.pos : self.pos + n]
self.pos += n
return n
def ioctl(self, req, arg):
return 0
class UserFS:
def __init__(self, files):
self.files = files
def mount(self, readonly, mksfs):
pass
def umount(self):
pass
def stat(self, path):
if path in self.files:
return (32768, 0, 0, 0, 0, 0, 0, 0, 0, 0)
raise OSError
def open(self, path, mode):
return UserFile(self.files[path])
# these are the test .mpy files
# fmt: off
user_files = {
# bad architecture
'/mod0.mpy': b'M\x05\xff\x00\x10',
# test loading of viper and asm
'/mod1.mpy': (
b'M\x05\x0b\x1f\x20' # header
b'\x20' # n bytes, bytecode
b'\x00\x08\x02m\x02m' # prelude
b'\x51' # LOAD_CONST_NONE
b'\x63' # RETURN_VALUE
b'\x00\x02' # n_obj, n_raw_code
b'\x22' # n bytes, viper code
b'\x00\x00\x00\x00\x00\x00' # dummy machine code
b'\x00\x00' # qstr0
b'\x01\x0c\x0aprint' # n_qstr, qstr0
b'\x00\x00\x00' # scope_flags, n_obj, n_raw_code
b'\x23' # n bytes, asm code
b'\x00\x00\x00\x00\x00\x00\x00\x00' # dummy machine code
b'\x00\x00\x00' # scope_flags, n_pos_args, type_sig
),
# test loading viper with additional scope flags and relocation
'/mod2.mpy': (
b'M\x05\x0b\x1f\x20' # header
b'\x20' # n bytes, bytecode
b'\x00\x08\x02m\x02m' # prelude
b'\x51' # LOAD_CONST_NONE
b'\x63' # RETURN_VALUE
b'\x00\x01' # n_obj, n_raw_code
b'\x12' # n bytes(=4), viper code
b'\x00\x00\x00\x00' # dummy machine code
b'\x00' # n_qstr
b'\x70' # scope_flags: VIPERBSS | VIPERRODATA | VIPERRELOC
b'\x00\x00' # n_obj, n_raw_code
b'\x06rodata' # rodata, 6 bytes
b'\x04' # bss, 4 bytes
b'\x03\x01\x00' # dummy relocation of rodata
),
}
# fmt: on
# create and mount a user filesystem
uos.mount(UserFS(user_files), "/userfs")
usys.path.append("/userfs")
# import .mpy files from the user filesystem
for i in range(len(user_files)):
mod = "mod%u" % i
try:
__import__(mod)
print(mod, "OK")
except ValueError as er:
print(mod, "ValueError", er)
# unmount and undo path addition
uos.umount("/userfs")
usys.path.pop()
|
YifuLiu/AliOS-Things
|
components/py_engine/tests/micropython/import_mpy_native_x64.py
|
Python
|
apache-2.0
| 2,971
|
# test the micropython.kbd_intr() function
import micropython
try:
micropython.kbd_intr
except AttributeError:
print("SKIP")
raise SystemExit
# just check we can actually call it
micropython.kbd_intr(3)
|
YifuLiu/AliOS-Things
|
components/py_engine/tests/micropython/kbd_intr.py
|
Python
|
apache-2.0
| 218
|