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
|
|---|---|---|---|---|---|
# Copyright (c) 2019 Project Nayuki. (MIT License)
# https://www.nayuki.io/page/free-small-fft-in-multiple-languages
import math, cmath
def transform_radix2(vector, inverse):
# Returns the integer whose value is the reverse of the lowest 'bits' bits of the integer 'x'.
def reverse(x, bits):
y = 0
for i in range(bits):
y = (y << 1) | (x & 1)
x >>= 1
return y
# Initialization
n = len(vector)
levels = int(math.log2(n))
coef = (2 if inverse else -2) * cmath.pi / n
exptable = [cmath.rect(1, i * coef) for i in range(n // 2)]
vector = [vector[reverse(i, levels)] for i in range(n)] # Copy with bit-reversed permutation
# Radix-2 decimation-in-time FFT
size = 2
while size <= n:
halfsize = size // 2
tablestep = n // size
for i in range(0, n, size):
k = 0
for j in range(i, i + halfsize):
temp = vector[j + halfsize] * exptable[k]
vector[j + halfsize] = vector[j] - temp
vector[j] += temp
k += tablestep
size *= 2
return vector
###########################################################################
# Benchmark interface
bm_params = {
(50, 25): (2, 128),
(100, 100): (3, 256),
(1000, 1000): (20, 512),
(5000, 1000): (100, 512),
}
def bm_setup(params):
state = None
signal = [math.cos(2 * math.pi * i / params[1]) + 0j for i in range(params[1])]
fft = None
fft_inv = None
def run():
nonlocal fft, fft_inv
for _ in range(params[0]):
fft = transform_radix2(signal, False)
fft_inv = transform_radix2(fft, True)
def result():
nonlocal fft, fft_inv
fft[1] -= 0.5 * params[1]
fft[-1] -= 0.5 * params[1]
fft_ok = all(abs(f) < 1e-3 for f in fft)
for i in range(len(fft_inv)):
fft_inv[i] -= params[1] * signal[i]
fft_inv_ok = all(abs(f) < 1e-3 for f in fft_inv)
return params[0] * params[1], (fft_ok, fft_inv_ok)
return run, result
|
YifuLiu/AliOS-Things
|
components/py_engine/tests/perf_bench/bm_fft.py
|
Python
|
apache-2.0
| 2,107
|
# Source: https://github.com/python/pyperformance
# License: MIT
# Artificial, floating point-heavy benchmark originally used by Factor.
from math import sin, cos, sqrt
class Point(object):
__slots__ = ("x", "y", "z")
def __init__(self, i):
self.x = x = sin(i)
self.y = cos(i) * 3
self.z = (x * x) / 2
def __repr__(self):
return "<Point: x=%s, y=%s, z=%s>" % (self.x, self.y, self.z)
def normalize(self):
x = self.x
y = self.y
z = self.z
norm = sqrt(x * x + y * y + z * z)
self.x /= norm
self.y /= norm
self.z /= norm
def maximize(self, other):
self.x = self.x if self.x > other.x else other.x
self.y = self.y if self.y > other.y else other.y
self.z = self.z if self.z > other.z else other.z
return self
def maximize(points):
next = points[0]
for p in points[1:]:
next = next.maximize(p)
return next
def benchmark(n):
points = [None] * n
for i in range(n):
points[i] = Point(i)
for p in points:
p.normalize()
return maximize(points)
###########################################################################
# Benchmark interface
bm_params = {
(50, 25): (1, 150),
(100, 100): (1, 250),
(1000, 1000): (10, 1500),
(5000, 1000): (20, 3000),
}
def bm_setup(params):
state = None
def run():
nonlocal state
for _ in range(params[0]):
state = benchmark(params[1])
def result():
return params[0] * params[1], "Point(%.4f, %.4f, %.4f)" % (state.x, state.y, state.z)
return run, result
|
YifuLiu/AliOS-Things
|
components/py_engine/tests/perf_bench/bm_float.py
|
Python
|
apache-2.0
| 1,657
|
# Source: https://github.com/python/pyperformance
# License: MIT
# Solver of Hexiom board game.
# Benchmark from Laurent Vaucher.
# Source: https://github.com/slowfrog/hexiom : hexiom2.py, level36.txt
# (Main function tweaked by Armin Rigo.)
##################################
class Dir(object):
def __init__(self, x, y):
self.x = x
self.y = y
DIRS = [Dir(1, 0), Dir(-1, 0), Dir(0, 1), Dir(0, -1), Dir(1, 1), Dir(-1, -1)]
EMPTY = 7
##################################
class Done(object):
MIN_CHOICE_STRATEGY = 0
MAX_CHOICE_STRATEGY = 1
HIGHEST_VALUE_STRATEGY = 2
FIRST_STRATEGY = 3
MAX_NEIGHBORS_STRATEGY = 4
MIN_NEIGHBORS_STRATEGY = 5
def __init__(self, count, empty=False):
self.count = count
self.cells = None if empty else [[0, 1, 2, 3, 4, 5, 6, EMPTY] for i in range(count)]
def clone(self):
ret = Done(self.count, True)
ret.cells = [self.cells[i][:] for i in range(self.count)]
return ret
def __getitem__(self, i):
return self.cells[i]
def set_done(self, i, v):
self.cells[i] = [v]
def already_done(self, i):
return len(self.cells[i]) == 1
def remove(self, i, v):
if v in self.cells[i]:
self.cells[i].remove(v)
return True
else:
return False
def remove_all(self, v):
for i in range(self.count):
self.remove(i, v)
def remove_unfixed(self, v):
changed = False
for i in range(self.count):
if not self.already_done(i):
if self.remove(i, v):
changed = True
return changed
def filter_tiles(self, tiles):
for v in range(8):
if tiles[v] == 0:
self.remove_all(v)
def next_cell_min_choice(self):
minlen = 10
mini = -1
for i in range(self.count):
if 1 < len(self.cells[i]) < minlen:
minlen = len(self.cells[i])
mini = i
return mini
def next_cell_max_choice(self):
maxlen = 1
maxi = -1
for i in range(self.count):
if maxlen < len(self.cells[i]):
maxlen = len(self.cells[i])
maxi = i
return maxi
def next_cell_highest_value(self):
maxval = -1
maxi = -1
for i in range(self.count):
if not self.already_done(i):
maxvali = max(k for k in self.cells[i] if k != EMPTY)
if maxval < maxvali:
maxval = maxvali
maxi = i
return maxi
def next_cell_first(self):
for i in range(self.count):
if not self.already_done(i):
return i
return -1
def next_cell_max_neighbors(self, pos):
maxn = -1
maxi = -1
for i in range(self.count):
if not self.already_done(i):
cells_around = pos.hex.get_by_id(i).links
n = sum(
1 if (self.already_done(nid) and (self[nid][0] != EMPTY)) else 0
for nid in cells_around
)
if n > maxn:
maxn = n
maxi = i
return maxi
def next_cell_min_neighbors(self, pos):
minn = 7
mini = -1
for i in range(self.count):
if not self.already_done(i):
cells_around = pos.hex.get_by_id(i).links
n = sum(
1 if (self.already_done(nid) and (self[nid][0] != EMPTY)) else 0
for nid in cells_around
)
if n < minn:
minn = n
mini = i
return mini
def next_cell(self, pos, strategy=HIGHEST_VALUE_STRATEGY):
if strategy == Done.HIGHEST_VALUE_STRATEGY:
return self.next_cell_highest_value()
elif strategy == Done.MIN_CHOICE_STRATEGY:
return self.next_cell_min_choice()
elif strategy == Done.MAX_CHOICE_STRATEGY:
return self.next_cell_max_choice()
elif strategy == Done.FIRST_STRATEGY:
return self.next_cell_first()
elif strategy == Done.MAX_NEIGHBORS_STRATEGY:
return self.next_cell_max_neighbors(pos)
elif strategy == Done.MIN_NEIGHBORS_STRATEGY:
return self.next_cell_min_neighbors(pos)
else:
raise Exception("Wrong strategy: %d" % strategy)
##################################
class Node(object):
def __init__(self, pos, id, links):
self.pos = pos
self.id = id
self.links = links
##################################
class Hex(object):
def __init__(self, size):
self.size = size
self.count = 3 * size * (size - 1) + 1
self.nodes_by_id = self.count * [None]
self.nodes_by_pos = {}
id = 0
for y in range(size):
for x in range(size + y):
pos = (x, y)
node = Node(pos, id, [])
self.nodes_by_pos[pos] = node
self.nodes_by_id[node.id] = node
id += 1
for y in range(1, size):
for x in range(y, size * 2 - 1):
ry = size + y - 1
pos = (x, ry)
node = Node(pos, id, [])
self.nodes_by_pos[pos] = node
self.nodes_by_id[node.id] = node
id += 1
def link_nodes(self):
for node in self.nodes_by_id:
(x, y) = node.pos
for dir in DIRS:
nx = x + dir.x
ny = y + dir.y
if self.contains_pos((nx, ny)):
node.links.append(self.nodes_by_pos[(nx, ny)].id)
def contains_pos(self, pos):
return pos in self.nodes_by_pos
def get_by_pos(self, pos):
return self.nodes_by_pos[pos]
def get_by_id(self, id):
return self.nodes_by_id[id]
##################################
class Pos(object):
def __init__(self, hex, tiles, done=None):
self.hex = hex
self.tiles = tiles
self.done = Done(hex.count) if done is None else done
def clone(self):
return Pos(self.hex, self.tiles, self.done.clone())
##################################
def constraint_pass(pos, last_move=None):
changed = False
left = pos.tiles[:]
done = pos.done
# Remove impossible values from free cells
free_cells = range(done.count) if last_move is None else pos.hex.get_by_id(last_move).links
for i in free_cells:
if not done.already_done(i):
vmax = 0
vmin = 0
cells_around = pos.hex.get_by_id(i).links
for nid in cells_around:
if done.already_done(nid):
if done[nid][0] != EMPTY:
vmin += 1
vmax += 1
else:
vmax += 1
for num in range(7):
if (num < vmin) or (num > vmax):
if done.remove(i, num):
changed = True
# Computes how many of each value is still free
for cell in done.cells:
if len(cell) == 1:
left[cell[0]] -= 1
for v in range(8):
# If there is none, remove the possibility from all tiles
if (pos.tiles[v] > 0) and (left[v] == 0):
if done.remove_unfixed(v):
changed = True
else:
possible = sum((1 if v in cell else 0) for cell in done.cells)
# If the number of possible cells for a value is exactly the number of available tiles
# put a tile in each cell
if pos.tiles[v] == possible:
for i in range(done.count):
cell = done.cells[i]
if (not done.already_done(i)) and (v in cell):
done.set_done(i, v)
changed = True
# Force empty or non-empty around filled cells
filled_cells = range(done.count) if last_move is None else [last_move]
for i in filled_cells:
if done.already_done(i):
num = done[i][0]
empties = 0
filled = 0
unknown = []
cells_around = pos.hex.get_by_id(i).links
for nid in cells_around:
if done.already_done(nid):
if done[nid][0] == EMPTY:
empties += 1
else:
filled += 1
else:
unknown.append(nid)
if len(unknown) > 0:
if num == filled:
for u in unknown:
if EMPTY in done[u]:
done.set_done(u, EMPTY)
changed = True
# else:
# raise Exception("Houston, we've got a problem")
elif num == filled + len(unknown):
for u in unknown:
if done.remove(u, EMPTY):
changed = True
return changed
ASCENDING = 1
DESCENDING = -1
def find_moves(pos, strategy, order):
done = pos.done
cell_id = done.next_cell(pos, strategy)
if cell_id < 0:
return []
if order == ASCENDING:
return [(cell_id, v) for v in done[cell_id]]
else:
# Try higher values first and EMPTY last
moves = list(reversed([(cell_id, v) for v in done[cell_id] if v != EMPTY]))
if EMPTY in done[cell_id]:
moves.append((cell_id, EMPTY))
return moves
def play_move(pos, move):
(cell_id, i) = move
pos.done.set_done(cell_id, i)
def print_pos(pos, output):
hex = pos.hex
done = pos.done
size = hex.size
for y in range(size):
print(" " * (size - y - 1), end="", file=output)
for x in range(size + y):
pos2 = (x, y)
id = hex.get_by_pos(pos2).id
if done.already_done(id):
c = done[id][0] if done[id][0] != EMPTY else "."
else:
c = "?"
print("%s " % c, end="", file=output)
print(end="\n", file=output)
for y in range(1, size):
print(" " * y, end="", file=output)
for x in range(y, size * 2 - 1):
ry = size + y - 1
pos2 = (x, ry)
id = hex.get_by_pos(pos2).id
if done.already_done(id):
c = done[id][0] if done[id][0] != EMPTY else "."
else:
c = "?"
print("%s " % c, end="", file=output)
print(end="\n", file=output)
OPEN = 0
SOLVED = 1
IMPOSSIBLE = -1
def solved(pos, output, verbose=False):
hex = pos.hex
tiles = pos.tiles[:]
done = pos.done
exact = True
all_done = True
for i in range(hex.count):
if len(done[i]) == 0:
return IMPOSSIBLE
elif done.already_done(i):
num = done[i][0]
tiles[num] -= 1
if tiles[num] < 0:
return IMPOSSIBLE
vmax = 0
vmin = 0
if num != EMPTY:
cells_around = hex.get_by_id(i).links
for nid in cells_around:
if done.already_done(nid):
if done[nid][0] != EMPTY:
vmin += 1
vmax += 1
else:
vmax += 1
if (num < vmin) or (num > vmax):
return IMPOSSIBLE
if num != vmin:
exact = False
else:
all_done = False
if (not all_done) or (not exact):
return OPEN
print_pos(pos, output)
return SOLVED
def solve_step(prev, strategy, order, output, first=False):
if first:
pos = prev.clone()
while constraint_pass(pos):
pass
else:
pos = prev
moves = find_moves(pos, strategy, order)
if len(moves) == 0:
return solved(pos, output)
else:
for move in moves:
# print("Trying (%d, %d)" % (move[0], move[1]))
ret = OPEN
new_pos = pos.clone()
play_move(new_pos, move)
# print_pos(new_pos)
while constraint_pass(new_pos, move[0]):
pass
cur_status = solved(new_pos, output)
if cur_status != OPEN:
ret = cur_status
else:
ret = solve_step(new_pos, strategy, order, output)
if ret == SOLVED:
return SOLVED
return IMPOSSIBLE
def check_valid(pos):
hex = pos.hex
tiles = pos.tiles
# fill missing entries in tiles
tot = 0
for i in range(8):
if tiles[i] > 0:
tot += tiles[i]
else:
tiles[i] = 0
# check total
if tot != hex.count:
raise Exception("Invalid input. Expected %d tiles, got %d." % (hex.count, tot))
def solve(pos, strategy, order, output):
check_valid(pos)
return solve_step(pos, strategy, order, output, first=True)
# TODO Write an 'iterator' to go over all x,y positions
def read_file(file):
lines = [line.strip("\r\n") for line in file.splitlines()]
size = int(lines[0])
hex = Hex(size)
linei = 1
tiles = 8 * [0]
done = Done(hex.count)
for y in range(size):
line = lines[linei][size - y - 1 :]
p = 0
for x in range(size + y):
tile = line[p : p + 2]
p += 2
if tile[1] == ".":
inctile = EMPTY
else:
inctile = int(tile)
tiles[inctile] += 1
# Look for locked tiles
if tile[0] == "+":
# print("Adding locked tile: %d at pos %d, %d, id=%d" %
# (inctile, x, y, hex.get_by_pos((x, y)).id))
done.set_done(hex.get_by_pos((x, y)).id, inctile)
linei += 1
for y in range(1, size):
ry = size - 1 + y
line = lines[linei][y:]
p = 0
for x in range(y, size * 2 - 1):
tile = line[p : p + 2]
p += 2
if tile[1] == ".":
inctile = EMPTY
else:
inctile = int(tile)
tiles[inctile] += 1
# Look for locked tiles
if tile[0] == "+":
# print("Adding locked tile: %d at pos %d, %d, id=%d" %
# (inctile, x, ry, hex.get_by_pos((x, ry)).id))
done.set_done(hex.get_by_pos((x, ry)).id, inctile)
linei += 1
hex.link_nodes()
done.filter_tiles(tiles)
return Pos(hex, tiles, done)
def solve_file(file, strategy, order, output):
pos = read_file(file)
solve(pos, strategy, order, output)
LEVELS = {}
LEVELS[2] = (
"""
2
. 1
. 1 1
1 .
""",
"""\
1 1
. . .
1 1
""",
)
LEVELS[10] = (
"""
3
+.+. .
+. 0 . 2
. 1+2 1 .
2 . 0+.
.+.+.
""",
"""\
. . 1
. 1 . 2
0 . 2 2 .
. . . .
0 . .
""",
)
LEVELS[20] = (
"""
3
. 5 4
. 2+.+1
. 3+2 3 .
+2+. 5 .
. 3 .
""",
"""\
3 3 2
4 5 . 1
3 5 2 . .
2 . . .
. . .
""",
)
LEVELS[25] = (
"""
3
4 . .
. . 2 .
4 3 2 . 4
2 2 3 .
4 2 4
""",
"""\
3 4 2
2 4 4 .
. . . 4 2
. 2 4 3
. 2 .
""",
)
LEVELS[30] = (
"""
4
5 5 . .
3 . 2+2 6
3 . 2 . 5 .
. 3 3+4 4 . 3
4 5 4 . 5 4
5+2 . . 3
4 . . .
""",
"""\
3 4 3 .
4 6 5 2 .
2 5 5 . . 2
. . 5 4 . 4 3
. 3 5 4 5 4
. 2 . 3 3
. . . .
""",
)
LEVELS[36] = (
"""
4
2 1 1 2
3 3 3 . .
2 3 3 . 4 .
. 2 . 2 4 3 2
2 2 . . . 2
4 3 4 . .
3 2 3 3
""",
"""\
3 4 3 2
3 4 4 . 3
2 . . 3 4 3
2 . 1 . 3 . 2
3 3 . 2 . 2
3 . 2 . 2
2 2 . 1
""",
)
###########################################################################
# Benchmark interface
bm_params = {
(100, 100): (1, 10, DESCENDING, Done.FIRST_STRATEGY),
(1000, 1000): (1, 25, DESCENDING, Done.FIRST_STRATEGY),
(5000, 1000): (10, 25, DESCENDING, Done.FIRST_STRATEGY),
}
def bm_setup(params):
try:
import uio as io
except ImportError:
import io
loops, level, order, strategy = params
board, solution = LEVELS[level]
board = board.strip()
expected = solution.rstrip()
output = None
def run():
nonlocal output
for _ in range(loops):
stream = io.StringIO()
solve_file(board, strategy, order, stream)
output = stream.getvalue()
stream = None
def result():
norm = params[0] * params[1]
out = "\n".join(line.rstrip() for line in output.splitlines())
return norm, ((out == expected), out)
return run, result
|
YifuLiu/AliOS-Things
|
components/py_engine/tests/perf_bench/bm_hexiom.py
|
Python
|
apache-2.0
| 16,870
|
# Source: https://github.com/python/pyperformance
# License: MIT
# Simple, brute-force N-Queens solver.
# author: collinwinter@google.com (Collin Winter)
# n_queens function: Copyright 2009 Raymond Hettinger
# Pure-Python implementation of itertools.permutations().
def permutations(iterable, r=None):
"""permutations(range(3), 2) --> (0,1) (0,2) (1,0) (1,2) (2,0) (2,1)"""
pool = tuple(iterable)
n = len(pool)
if r is None:
r = n
indices = list(range(n))
cycles = list(range(n - r + 1, n + 1))[::-1]
yield tuple(pool[i] for i in indices[:r])
while n:
for i in reversed(range(r)):
cycles[i] -= 1
if cycles[i] == 0:
indices[i:] = indices[i + 1 :] + indices[i : i + 1]
cycles[i] = n - i
else:
j = cycles[i]
indices[i], indices[-j] = indices[-j], indices[i]
yield tuple(pool[i] for i in indices[:r])
break
else:
return
# From http://code.activestate.com/recipes/576647/
def n_queens(queen_count):
"""N-Queens solver.
Args: queen_count: the number of queens to solve for, same as board size.
Yields: Solutions to the problem, each yielded value is a N-tuple.
"""
cols = range(queen_count)
for vec in permutations(cols):
if queen_count == len(set(vec[i] + i for i in cols)) == len(set(vec[i] - i for i in cols)):
yield vec
###########################################################################
# Benchmark interface
bm_params = {
(50, 25): (1, 5),
(100, 25): (1, 6),
(1000, 100): (1, 7),
(5000, 100): (1, 8),
}
def bm_setup(params):
res = None
def run():
nonlocal res
for _ in range(params[0]):
res = len(list(n_queens(params[1])))
def result():
return params[0] * 10 ** (params[1] - 3), res
return run, result
|
YifuLiu/AliOS-Things
|
components/py_engine/tests/perf_bench/bm_nqueens.py
|
Python
|
apache-2.0
| 1,935
|
# Source: https://github.com/python/pyperformance
# License: MIT
# Calculating some of the digits of π.
# This benchmark stresses big integer arithmetic.
# Adapted from code on: http://benchmarksgame.alioth.debian.org/
def compose(a, b):
aq, ar, as_, at = a
bq, br, bs, bt = b
return (aq * bq, aq * br + ar * bt, as_ * bq + at * bs, as_ * br + at * bt)
def extract(z, j):
q, r, s, t = z
return (q * j + r) // (s * j + t)
def gen_pi_digits(n):
z = (1, 0, 0, 1)
k = 1
digs = []
for _ in range(n):
y = extract(z, 3)
while y != extract(z, 4):
z = compose(z, (k, 4 * k + 2, 0, 2 * k + 1))
k += 1
y = extract(z, 3)
z = compose((10, -10 * y, 0, 1), z)
digs.append(y)
return digs
###########################################################################
# Benchmark interface
bm_params = {
(50, 25): (1, 35),
(100, 100): (1, 65),
(1000, 1000): (2, 250),
(5000, 1000): (3, 350),
}
def bm_setup(params):
state = None
def run():
nonlocal state
nloop, ndig = params
ndig = params[1]
for _ in range(nloop):
state = None # free previous result
state = gen_pi_digits(ndig)
def result():
return params[0] * params[1], "".join(str(d) for d in state)
return run, result
|
YifuLiu/AliOS-Things
|
components/py_engine/tests/perf_bench/bm_pidigits.py
|
Python
|
apache-2.0
| 1,375
|
# Pure Python AES encryption routines.
#
# AES is integer based and inplace so doesn't use the heap. It is therefore
# a good test of raw performance and correctness of the VM/runtime.
#
# The AES code comes first (code originates from a C version authored by D.P.George)
# and then the test harness at the bottom.
#
# MIT license; Copyright (c) 2016 Damien P. George on behalf of Pycom Ltd
##################################################################
# discrete arithmetic routines, mostly from a precomputed table
# non-linear, invertible, substitution box
# fmt: off
aes_s_box_table = bytes((
0x63,0x7c,0x77,0x7b,0xf2,0x6b,0x6f,0xc5,0x30,0x01,0x67,0x2b,0xfe,0xd7,0xab,0x76,
0xca,0x82,0xc9,0x7d,0xfa,0x59,0x47,0xf0,0xad,0xd4,0xa2,0xaf,0x9c,0xa4,0x72,0xc0,
0xb7,0xfd,0x93,0x26,0x36,0x3f,0xf7,0xcc,0x34,0xa5,0xe5,0xf1,0x71,0xd8,0x31,0x15,
0x04,0xc7,0x23,0xc3,0x18,0x96,0x05,0x9a,0x07,0x12,0x80,0xe2,0xeb,0x27,0xb2,0x75,
0x09,0x83,0x2c,0x1a,0x1b,0x6e,0x5a,0xa0,0x52,0x3b,0xd6,0xb3,0x29,0xe3,0x2f,0x84,
0x53,0xd1,0x00,0xed,0x20,0xfc,0xb1,0x5b,0x6a,0xcb,0xbe,0x39,0x4a,0x4c,0x58,0xcf,
0xd0,0xef,0xaa,0xfb,0x43,0x4d,0x33,0x85,0x45,0xf9,0x02,0x7f,0x50,0x3c,0x9f,0xa8,
0x51,0xa3,0x40,0x8f,0x92,0x9d,0x38,0xf5,0xbc,0xb6,0xda,0x21,0x10,0xff,0xf3,0xd2,
0xcd,0x0c,0x13,0xec,0x5f,0x97,0x44,0x17,0xc4,0xa7,0x7e,0x3d,0x64,0x5d,0x19,0x73,
0x60,0x81,0x4f,0xdc,0x22,0x2a,0x90,0x88,0x46,0xee,0xb8,0x14,0xde,0x5e,0x0b,0xdb,
0xe0,0x32,0x3a,0x0a,0x49,0x06,0x24,0x5c,0xc2,0xd3,0xac,0x62,0x91,0x95,0xe4,0x79,
0xe7,0xc8,0x37,0x6d,0x8d,0xd5,0x4e,0xa9,0x6c,0x56,0xf4,0xea,0x65,0x7a,0xae,0x08,
0xba,0x78,0x25,0x2e,0x1c,0xa6,0xb4,0xc6,0xe8,0xdd,0x74,0x1f,0x4b,0xbd,0x8b,0x8a,
0x70,0x3e,0xb5,0x66,0x48,0x03,0xf6,0x0e,0x61,0x35,0x57,0xb9,0x86,0xc1,0x1d,0x9e,
0xe1,0xf8,0x98,0x11,0x69,0xd9,0x8e,0x94,0x9b,0x1e,0x87,0xe9,0xce,0x55,0x28,0xdf,
0x8c,0xa1,0x89,0x0d,0xbf,0xe6,0x42,0x68,0x41,0x99,0x2d,0x0f,0xb0,0x54,0xbb,0x16,
))
# fmt: on
# multiplication of polynomials modulo x^8 + x^4 + x^3 + x + 1 = 0x11b
def aes_gf8_mul_2(x):
if x & 0x80:
return (x << 1) ^ 0x11B
else:
return x << 1
def aes_gf8_mul_3(x):
return x ^ aes_gf8_mul_2(x)
# non-linear, invertible, substitution box
def aes_s_box(a):
return aes_s_box_table[a & 0xFF]
# return 0x02^(a-1) in GF(2^8)
def aes_r_con(a):
ans = 1
while a > 1:
ans <<= 1
if ans & 0x100:
ans ^= 0x11B
a -= 1
return ans
##################################################################
# basic AES algorithm; see FIPS-197
# all inputs must be size 16
def aes_add_round_key(state, w):
for i in range(16):
state[i] ^= w[i]
# combined sub_bytes, shift_rows, mix_columns, add_round_key
# all inputs must be size 16
def aes_sb_sr_mc_ark(state, w, w_idx, temp):
temp_idx = 0
for i in range(4):
x0 = aes_s_box_table[state[i * 4]]
x1 = aes_s_box_table[state[1 + ((i + 1) & 3) * 4]]
x2 = aes_s_box_table[state[2 + ((i + 2) & 3) * 4]]
x3 = aes_s_box_table[state[3 + ((i + 3) & 3) * 4]]
temp[temp_idx] = aes_gf8_mul_2(x0) ^ aes_gf8_mul_3(x1) ^ x2 ^ x3 ^ w[w_idx]
temp[temp_idx + 1] = x0 ^ aes_gf8_mul_2(x1) ^ aes_gf8_mul_3(x2) ^ x3 ^ w[w_idx + 1]
temp[temp_idx + 2] = x0 ^ x1 ^ aes_gf8_mul_2(x2) ^ aes_gf8_mul_3(x3) ^ w[w_idx + 2]
temp[temp_idx + 3] = aes_gf8_mul_3(x0) ^ x1 ^ x2 ^ aes_gf8_mul_2(x3) ^ w[w_idx + 3]
w_idx += 4
temp_idx += 4
for i in range(16):
state[i] = temp[i]
# combined sub_bytes, shift_rows, add_round_key
# all inputs must be size 16
def aes_sb_sr_ark(state, w, w_idx, temp):
temp_idx = 0
for i in range(4):
x0 = aes_s_box_table[state[i * 4]]
x1 = aes_s_box_table[state[1 + ((i + 1) & 3) * 4]]
x2 = aes_s_box_table[state[2 + ((i + 2) & 3) * 4]]
x3 = aes_s_box_table[state[3 + ((i + 3) & 3) * 4]]
temp[temp_idx] = x0 ^ w[w_idx]
temp[temp_idx + 1] = x1 ^ w[w_idx + 1]
temp[temp_idx + 2] = x2 ^ w[w_idx + 2]
temp[temp_idx + 3] = x3 ^ w[w_idx + 3]
w_idx += 4
temp_idx += 4
for i in range(16):
state[i] = temp[i]
# take state as input and change it to the next state in the sequence
# state and temp have size 16, w has size 16 * (Nr + 1), Nr >= 1
def aes_state(state, w, temp, nr):
aes_add_round_key(state, w)
w_idx = 16
for i in range(nr - 1):
aes_sb_sr_mc_ark(state, w, w_idx, temp)
w_idx += 16
aes_sb_sr_ark(state, w, w_idx, temp)
# expand 'key' to 'w' for use with aes_state
# key has size 4 * Nk, w has size 16 * (Nr + 1), temp has size 16
def aes_key_expansion(key, w, temp, nk, nr):
for i in range(4 * nk):
w[i] = key[i]
w_idx = 4 * nk - 4
for i in range(nk, 4 * (nr + 1)):
t = temp
t_idx = 0
if i % nk == 0:
t[0] = aes_s_box(w[w_idx + 1]) ^ aes_r_con(i // nk)
for j in range(1, 4):
t[j] = aes_s_box(w[w_idx + (j + 1) % 4])
elif nk > 6 and i % nk == 4:
for j in range(0, 4):
t[j] = aes_s_box(w[w_idx + j])
else:
t = w
t_idx = w_idx
w_idx += 4
for j in range(4):
w[w_idx + j] = w[w_idx + j - 4 * nk] ^ t[t_idx + j]
##################################################################
# simple use of AES algorithm, using output feedback (OFB) mode
class AES:
def __init__(self, keysize):
if keysize == 128:
self.nk = 4
self.nr = 10
elif keysize == 192:
self.nk = 6
self.nr = 12
else:
assert keysize == 256
self.nk = 8
self.nr = 14
self.state = bytearray(16)
self.w = bytearray(16 * (self.nr + 1))
self.temp = bytearray(16)
self.state_pos = 16
def set_key(self, key):
aes_key_expansion(key, self.w, self.temp, self.nk, self.nr)
self.state_pos = 16
def set_iv(self, iv):
for i in range(16):
self.state[i] = iv[i]
self.state_pos = 16
def get_some_state(self, n_needed):
if self.state_pos >= 16:
aes_state(self.state, self.w, self.temp, self.nr)
self.state_pos = 0
n = 16 - self.state_pos
if n > n_needed:
n = n_needed
return n
def apply_to(self, data):
idx = 0
n = len(data)
while n > 0:
ln = self.get_some_state(n)
n -= ln
for i in range(ln):
data[idx + i] ^= self.state[self.state_pos + i]
idx += ln
self.state_pos += n
###########################################################################
# Benchmark interface
bm_params = {
(50, 25): (1, 16),
(100, 100): (1, 32),
(1000, 1000): (4, 256),
(5000, 1000): (20, 256),
}
def bm_setup(params):
nloop, datalen = params
aes = AES(256)
key = bytearray(256 // 8)
iv = bytearray(16)
data = bytearray(datalen)
# from now on we don't use the heap
def run():
for loop in range(nloop):
# encrypt
aes.set_key(key)
aes.set_iv(iv)
for i in range(2):
aes.apply_to(data)
# decrypt
aes.set_key(key)
aes.set_iv(iv)
for i in range(2):
aes.apply_to(data)
# verify
for i in range(len(data)):
assert data[i] == 0
def result():
return params[0] * params[1], True
return run, result
|
YifuLiu/AliOS-Things
|
components/py_engine/tests/perf_bench/misc_aes.py
|
Python
|
apache-2.0
| 7,652
|
# Compute the Mandelbrot set, to test complex numbers
def mandelbrot(w, h):
def in_set(c):
z = 0
for i in range(32):
z = z * z + c
if abs(z) > 100:
return i
return 0
img = bytearray(w * h)
xscale = (w - 1) / 2.4
yscale = (h - 1) / 3.2
for v in range(h):
line = memoryview(img)[v * w : v * w + w]
for u in range(w):
c = in_set(complex(v / yscale - 2.3, u / xscale - 1.2))
line[u] = c
return img
bm_params = {
(100, 100): (20, 20),
(1000, 1000): (80, 80),
(5000, 1000): (150, 150),
}
def bm_setup(ps):
return lambda: mandelbrot(ps[0], ps[1]), lambda: (ps[0] * ps[1], None)
|
YifuLiu/AliOS-Things
|
components/py_engine/tests/perf_bench/misc_mandel.py
|
Python
|
apache-2.0
| 724
|
"""
"PYSTONE" Benchmark Program
Version: Python/1.2 (corresponds to C/1.1 plus 3 Pystone fixes)
Author: Reinhold P. Weicker, CACM Vol 27, No 10, 10/84 pg. 1013.
Translated from ADA to C by Rick Richardson.
Every method to preserve ADA-likeness has been used,
at the expense of C-ness.
Translated from C to Python by Guido van Rossum.
"""
__version__ = "1.2"
[Ident1, Ident2, Ident3, Ident4, Ident5] = range(1, 6)
class Record:
def __init__(self, PtrComp=None, Discr=0, EnumComp=0, IntComp=0, StringComp=0):
self.PtrComp = PtrComp
self.Discr = Discr
self.EnumComp = EnumComp
self.IntComp = IntComp
self.StringComp = StringComp
def copy(self):
return Record(self.PtrComp, self.Discr, self.EnumComp, self.IntComp, self.StringComp)
TRUE = 1
FALSE = 0
def Setup():
global IntGlob
global BoolGlob
global Char1Glob
global Char2Glob
global Array1Glob
global Array2Glob
IntGlob = 0
BoolGlob = FALSE
Char1Glob = "\0"
Char2Glob = "\0"
Array1Glob = [0] * 51
Array2Glob = [x[:] for x in [Array1Glob] * 51]
def Proc0(loops):
global IntGlob
global BoolGlob
global Char1Glob
global Char2Glob
global Array1Glob
global Array2Glob
global PtrGlb
global PtrGlbNext
PtrGlbNext = Record()
PtrGlb = Record()
PtrGlb.PtrComp = PtrGlbNext
PtrGlb.Discr = Ident1
PtrGlb.EnumComp = Ident3
PtrGlb.IntComp = 40
PtrGlb.StringComp = "DHRYSTONE PROGRAM, SOME STRING"
String1Loc = "DHRYSTONE PROGRAM, 1'ST STRING"
Array2Glob[8][7] = 10
for i in range(loops):
Proc5()
Proc4()
IntLoc1 = 2
IntLoc2 = 3
String2Loc = "DHRYSTONE PROGRAM, 2'ND STRING"
EnumLoc = Ident2
BoolGlob = not Func2(String1Loc, String2Loc)
while IntLoc1 < IntLoc2:
IntLoc3 = 5 * IntLoc1 - IntLoc2
IntLoc3 = Proc7(IntLoc1, IntLoc2)
IntLoc1 = IntLoc1 + 1
Proc8(Array1Glob, Array2Glob, IntLoc1, IntLoc3)
PtrGlb = Proc1(PtrGlb)
CharIndex = "A"
while CharIndex <= Char2Glob:
if EnumLoc == Func1(CharIndex, "C"):
EnumLoc = Proc6(Ident1)
CharIndex = chr(ord(CharIndex) + 1)
IntLoc3 = IntLoc2 * IntLoc1
IntLoc2 = IntLoc3 // IntLoc1
IntLoc2 = 7 * (IntLoc3 - IntLoc2) - IntLoc1
IntLoc1 = Proc2(IntLoc1)
def Proc1(PtrParIn):
PtrParIn.PtrComp = NextRecord = PtrGlb.copy()
PtrParIn.IntComp = 5
NextRecord.IntComp = PtrParIn.IntComp
NextRecord.PtrComp = PtrParIn.PtrComp
NextRecord.PtrComp = Proc3(NextRecord.PtrComp)
if NextRecord.Discr == Ident1:
NextRecord.IntComp = 6
NextRecord.EnumComp = Proc6(PtrParIn.EnumComp)
NextRecord.PtrComp = PtrGlb.PtrComp
NextRecord.IntComp = Proc7(NextRecord.IntComp, 10)
else:
PtrParIn = NextRecord.copy()
NextRecord.PtrComp = None
return PtrParIn
def Proc2(IntParIO):
IntLoc = IntParIO + 10
while 1:
if Char1Glob == "A":
IntLoc = IntLoc - 1
IntParIO = IntLoc - IntGlob
EnumLoc = Ident1
if EnumLoc == Ident1:
break
return IntParIO
def Proc3(PtrParOut):
global IntGlob
if PtrGlb is not None:
PtrParOut = PtrGlb.PtrComp
else:
IntGlob = 100
PtrGlb.IntComp = Proc7(10, IntGlob)
return PtrParOut
def Proc4():
global Char2Glob
BoolLoc = Char1Glob == "A"
BoolLoc = BoolLoc or BoolGlob
Char2Glob = "B"
def Proc5():
global Char1Glob
global BoolGlob
Char1Glob = "A"
BoolGlob = FALSE
def Proc6(EnumParIn):
EnumParOut = EnumParIn
if not Func3(EnumParIn):
EnumParOut = Ident4
if EnumParIn == Ident1:
EnumParOut = Ident1
elif EnumParIn == Ident2:
if IntGlob > 100:
EnumParOut = Ident1
else:
EnumParOut = Ident4
elif EnumParIn == Ident3:
EnumParOut = Ident2
elif EnumParIn == Ident4:
pass
elif EnumParIn == Ident5:
EnumParOut = Ident3
return EnumParOut
def Proc7(IntParI1, IntParI2):
IntLoc = IntParI1 + 2
IntParOut = IntParI2 + IntLoc
return IntParOut
def Proc8(Array1Par, Array2Par, IntParI1, IntParI2):
global IntGlob
IntLoc = IntParI1 + 5
Array1Par[IntLoc] = IntParI2
Array1Par[IntLoc + 1] = Array1Par[IntLoc]
Array1Par[IntLoc + 30] = IntLoc
for IntIndex in range(IntLoc, IntLoc + 2):
Array2Par[IntLoc][IntIndex] = IntLoc
Array2Par[IntLoc][IntLoc - 1] = Array2Par[IntLoc][IntLoc - 1] + 1
Array2Par[IntLoc + 20][IntLoc] = Array1Par[IntLoc]
IntGlob = 5
def Func1(CharPar1, CharPar2):
CharLoc1 = CharPar1
CharLoc2 = CharLoc1
if CharLoc2 != CharPar2:
return Ident1
else:
return Ident2
def Func2(StrParI1, StrParI2):
IntLoc = 1
while IntLoc <= 1:
if Func1(StrParI1[IntLoc], StrParI2[IntLoc + 1]) == Ident1:
CharLoc = "A"
IntLoc = IntLoc + 1
if CharLoc >= "W" and CharLoc <= "Z":
IntLoc = 7
if CharLoc == "X":
return TRUE
else:
if StrParI1 > StrParI2:
IntLoc = IntLoc + 7
return TRUE
else:
return FALSE
def Func3(EnumParIn):
EnumLoc = EnumParIn
if EnumLoc == Ident3:
return TRUE
return FALSE
###########################################################################
# Benchmark interface
bm_params = {
(50, 10): (80,),
(100, 10): (300,),
(1000, 10): (4000,),
(5000, 10): (20000,),
}
def bm_setup(params):
Setup()
return lambda: Proc0(params[0]), lambda: (params[0], 0)
|
YifuLiu/AliOS-Things
|
components/py_engine/tests/perf_bench/misc_pystone.py
|
Python
|
apache-2.0
| 5,799
|
# A simple ray tracer
# MIT license; Copyright (c) 2019 Damien P. George
INF = 1e30
EPS = 1e-6
class Vec:
def __init__(self, x, y, z):
self.x, self.y, self.z = x, y, z
def __neg__(self):
return Vec(-self.x, -self.y, -self.z)
def __add__(self, rhs):
return Vec(self.x + rhs.x, self.y + rhs.y, self.z + rhs.z)
def __sub__(self, rhs):
return Vec(self.x - rhs.x, self.y - rhs.y, self.z - rhs.z)
def __mul__(self, rhs):
return Vec(self.x * rhs, self.y * rhs, self.z * rhs)
def length(self):
return (self.x ** 2 + self.y ** 2 + self.z ** 2) ** 0.5
def normalise(self):
l = self.length()
return Vec(self.x / l, self.y / l, self.z / l)
def dot(self, rhs):
return self.x * rhs.x + self.y * rhs.y + self.z * rhs.z
RGB = Vec
class Ray:
def __init__(self, p, d):
self.p, self.d = p, d
class View:
def __init__(self, width, height, depth, pos, xdir, ydir, zdir):
self.width = width
self.height = height
self.depth = depth
self.pos = pos
self.xdir = xdir
self.ydir = ydir
self.zdir = zdir
def calc_dir(self, dx, dy):
return (self.xdir * dx + self.ydir * dy + self.zdir * self.depth).normalise()
class Light:
def __init__(self, pos, colour, casts_shadows):
self.pos = pos
self.colour = colour
self.casts_shadows = casts_shadows
class Surface:
def __init__(self, diffuse, specular, spec_idx, reflect, transp, colour):
self.diffuse = diffuse
self.specular = specular
self.spec_idx = spec_idx
self.reflect = reflect
self.transp = transp
self.colour = colour
@staticmethod
def dull(colour):
return Surface(0.7, 0.0, 1, 0.0, 0.0, colour * 0.6)
@staticmethod
def shiny(colour):
return Surface(0.2, 0.9, 32, 0.8, 0.0, colour * 0.3)
@staticmethod
def transparent(colour):
return Surface(0.2, 0.9, 32, 0.0, 0.8, colour * 0.3)
class Sphere:
def __init__(self, surface, centre, radius):
self.surface = surface
self.centre = centre
self.radsq = radius ** 2
def intersect(self, ray):
v = self.centre - ray.p
b = v.dot(ray.d)
det = b ** 2 - v.dot(v) + self.radsq
if det > 0:
det **= 0.5
t1 = b - det
if t1 > EPS:
return t1
t2 = b + det
if t2 > EPS:
return t2
return INF
def surface_at(self, v):
return self.surface, (v - self.centre).normalise()
class Plane:
def __init__(self, surface, centre, normal):
self.surface = surface
self.normal = normal.normalise()
self.cdotn = centre.dot(normal)
def intersect(self, ray):
ddotn = ray.d.dot(self.normal)
if abs(ddotn) > EPS:
t = (self.cdotn - ray.p.dot(self.normal)) / ddotn
if t > 0:
return t
return INF
def surface_at(self, p):
return self.surface, self.normal
class Scene:
def __init__(self, ambient, light, objs):
self.ambient = ambient
self.light = light
self.objs = objs
def trace_scene(canvas, view, scene, max_depth):
for v in range(canvas.height):
y = (-v + 0.5 * (canvas.height - 1)) * view.height / canvas.height
for u in range(canvas.width):
x = (u - 0.5 * (canvas.width - 1)) * view.width / canvas.width
ray = Ray(view.pos, view.calc_dir(x, y))
c = trace_ray(scene, ray, max_depth)
canvas.put_pix(u, v, c)
def trace_ray(scene, ray, depth):
# Find closest intersecting object
hit_t = INF
hit_obj = None
for obj in scene.objs:
t = obj.intersect(ray)
if t < hit_t:
hit_t = t
hit_obj = obj
# Check if any objects hit
if hit_obj is None:
return RGB(0, 0, 0)
# Compute location of ray intersection
point = ray.p + ray.d * hit_t
surf, surf_norm = hit_obj.surface_at(point)
if ray.d.dot(surf_norm) > 0:
surf_norm = -surf_norm
# Compute reflected ray
reflected = ray.d - surf_norm * (surf_norm.dot(ray.d) * 2)
# Ambient light
col = surf.colour * scene.ambient
# Diffuse, specular and shadow from light source
light_vec = scene.light.pos - point
light_dist = light_vec.length()
light_vec = light_vec.normalise()
ndotl = surf_norm.dot(light_vec)
ldotv = light_vec.dot(reflected)
if ndotl > 0 or ldotv > 0:
light_ray = Ray(point + light_vec * EPS, light_vec)
light_col = trace_to_light(scene, light_ray, light_dist)
if ndotl > 0:
col += light_col * surf.diffuse * ndotl
if ldotv > 0:
col += light_col * surf.specular * ldotv ** surf.spec_idx
# Reflections
if depth > 0 and surf.reflect > 0:
col += trace_ray(scene, Ray(point + reflected * EPS, reflected), depth - 1) * surf.reflect
# Transparency
if depth > 0 and surf.transp > 0:
col += trace_ray(scene, Ray(point + ray.d * EPS, ray.d), depth - 1) * surf.transp
return col
def trace_to_light(scene, ray, light_dist):
col = scene.light.colour
for obj in scene.objs:
t = obj.intersect(ray)
if t < light_dist:
col *= obj.surface.transp
return col
class Canvas:
def __init__(self, width, height):
self.width = width
self.height = height
self.data = bytearray(3 * width * height)
def put_pix(self, x, y, c):
off = 3 * (y * self.width + x)
self.data[off] = min(255, max(0, int(255 * c.x)))
self.data[off + 1] = min(255, max(0, int(255 * c.y)))
self.data[off + 2] = min(255, max(0, int(255 * c.z)))
def write_ppm(self, filename):
with open(filename, "wb") as f:
f.write(bytes("P6 %d %d 255\n" % (self.width, self.height), "ascii"))
f.write(self.data)
def main(w, h, d):
canvas = Canvas(w, h)
view = View(32, 32, 64, Vec(0, 0, 50), Vec(1, 0, 0), Vec(0, 1, 0), Vec(0, 0, -1))
scene = Scene(
0.5,
Light(Vec(0, 8, 0), RGB(1, 1, 1), True),
[
Plane(Surface.dull(RGB(1, 0, 0)), Vec(-10, 0, 0), Vec(1, 0, 0)),
Plane(Surface.dull(RGB(0, 1, 0)), Vec(10, 0, 0), Vec(-1, 0, 0)),
Plane(Surface.dull(RGB(1, 1, 1)), Vec(0, 0, -10), Vec(0, 0, 1)),
Plane(Surface.dull(RGB(1, 1, 1)), Vec(0, -10, 0), Vec(0, 1, 0)),
Plane(Surface.dull(RGB(1, 1, 1)), Vec(0, 10, 0), Vec(0, -1, 0)),
Sphere(Surface.shiny(RGB(1, 1, 1)), Vec(-5, -4, 3), 4),
Sphere(Surface.dull(RGB(0, 0, 1)), Vec(4, -5, 0), 4),
Sphere(Surface.transparent(RGB(0.2, 0.2, 0.2)), Vec(6, -1, 8), 4),
],
)
trace_scene(canvas, view, scene, d)
return canvas
# For testing
# main(256, 256, 4).write_ppm('rt.ppm')
###########################################################################
# Benchmark interface
bm_params = {
(100, 100): (5, 5, 2),
(1000, 100): (18, 18, 3),
(5000, 100): (40, 40, 3),
}
def bm_setup(params):
return lambda: main(*params), lambda: (params[0] * params[1] * params[2], None)
|
YifuLiu/AliOS-Things
|
components/py_engine/tests/perf_bench/misc_raytrace.py
|
Python
|
apache-2.0
| 7,296
|
@micropython.viper
def f0():
pass
@micropython.native
def call(r):
f = f0
for _ in r:
f()
bm_params = {
(50, 10): (15000,),
(100, 10): (30000,),
(1000, 10): (300000,),
(5000, 10): (1500000,),
}
def bm_setup(params):
return lambda: call(range(params[0])), lambda: (params[0] // 1000, None)
|
YifuLiu/AliOS-Things
|
components/py_engine/tests/perf_bench/viper_call0.py
|
Python
|
apache-2.0
| 335
|
@micropython.viper
def f1a(x):
return x
@micropython.native
def call(r):
f = f1a
for _ in r:
f(1)
bm_params = {
(50, 10): (15000,),
(100, 10): (30000,),
(1000, 10): (300000,),
(5000, 10): (1500000,),
}
def bm_setup(params):
return lambda: call(range(params[0])), lambda: (params[0] // 1000, None)
|
YifuLiu/AliOS-Things
|
components/py_engine/tests/perf_bench/viper_call1a.py
|
Python
|
apache-2.0
| 343
|
@micropython.viper
def f1b(x) -> int:
return int(x)
@micropython.native
def call(r):
f = f1b
for _ in r:
f(1)
bm_params = {
(50, 10): (15000,),
(100, 10): (30000,),
(1000, 10): (300000,),
(5000, 10): (1500000,),
}
def bm_setup(params):
return lambda: call(range(params[0])), lambda: (params[0] // 1000, None)
|
YifuLiu/AliOS-Things
|
components/py_engine/tests/perf_bench/viper_call1b.py
|
Python
|
apache-2.0
| 355
|
@micropython.viper
def f1c(x: int) -> int:
return x
@micropython.native
def call(r):
f = f1c
for _ in r:
f(1)
bm_params = {
(50, 10): (15000,),
(100, 10): (30000,),
(1000, 10): (300000,),
(5000, 10): (1500000,),
}
def bm_setup(params):
return lambda: call(range(params[0])), lambda: (params[0] // 1000, None)
|
YifuLiu/AliOS-Things
|
components/py_engine/tests/perf_bench/viper_call1c.py
|
Python
|
apache-2.0
| 355
|
@micropython.viper
def f2a(x, y):
return x
@micropython.native
def call(r):
f = f2a
for _ in r:
f(1, 2)
bm_params = {
(50, 10): (15000,),
(100, 10): (30000,),
(1000, 10): (300000,),
(5000, 10): (1500000,),
}
def bm_setup(params):
return lambda: call(range(params[0])), lambda: (params[0] // 1000, None)
|
YifuLiu/AliOS-Things
|
components/py_engine/tests/perf_bench/viper_call2a.py
|
Python
|
apache-2.0
| 349
|
@micropython.viper
def f2b(x: int, y: int) -> int:
return x + y
@micropython.native
def call(r):
f = f2b
for _ in r:
f(1, 2)
bm_params = {
(50, 10): (15000,),
(100, 10): (30000,),
(1000, 10): (300000,),
(5000, 10): (1500000,),
}
def bm_setup(params):
return lambda: call(range(params[0])), lambda: (params[0] // 1000, None)
|
YifuLiu/AliOS-Things
|
components/py_engine/tests/perf_bench/viper_call2b.py
|
Python
|
apache-2.0
| 370
|
import pyb
if not hasattr(pyb, "Accel"):
print("SKIP")
raise SystemExit
accel = pyb.Accel()
print(accel)
accel.x()
accel.y()
accel.z()
accel.tilt()
accel.filtered_xyz()
|
YifuLiu/AliOS-Things
|
components/py_engine/tests/pyb/accel.py
|
Python
|
apache-2.0
| 179
|
from pyb import ADC, Timer
adct = ADC(16) # Temperature 930 -> 20C
print(str(adct)[:19])
adcv = ADC(17) # Voltage 1500 -> 3.3V
print(adcv)
# read single sample; 2.5V-5V is pass range
val = adcv.read()
assert val > 1000 and val < 2000
# timer for read_timed
tim = Timer(5, freq=500)
# read into bytearray
buf = bytearray(b"\xff" * 50)
adcv.read_timed(buf, tim)
print(len(buf))
for i in buf:
assert i > 50 and i < 150
# read into arrays with different element sizes
import array
arv = array.array("h", 25 * [0x7FFF])
adcv.read_timed(arv, tim)
print(len(arv))
for i in arv:
assert i > 1000 and i < 2000
arv = array.array("i", 30 * [-1])
adcv.read_timed(arv, tim)
print(len(arv))
for i in arv:
assert i > 1000 and i < 2000
# Test read_timed_multi
arv = bytearray(b"\xff" * 50)
art = bytearray(b"\xff" * 50)
ADC.read_timed_multi((adcv, adct), (arv, art), tim)
for i in arv:
assert i > 60 and i < 125
# Wide range: unsure of accuracy of temp sensor.
for i in art:
assert i > 15 and i < 200
arv = array.array("i", 25 * [-1])
art = array.array("i", 25 * [-1])
ADC.read_timed_multi((adcv, adct), (arv, art), tim)
for i in arv:
assert i > 1000 and i < 2000
# Wide range: unsure of accuracy of temp sensor.
for i in art:
assert i > 50 and i < 2000
arv = array.array("h", 25 * [0x7FFF])
art = array.array("h", 25 * [0x7FFF])
ADC.read_timed_multi((adcv, adct), (arv, art), tim)
for i in arv:
assert i > 1000 and i < 2000
# Wide range: unsure of accuracy of temp sensor.
for i in art:
assert i > 50 and i < 2000
|
YifuLiu/AliOS-Things
|
components/py_engine/tests/pyb/adc.py
|
Python
|
apache-2.0
| 1,546
|
from pyb import Pin, ADCAll
pins = [Pin.cpu.A0, Pin.cpu.A1, Pin.cpu.A2, Pin.cpu.A3]
# set pins to IN mode, init ADCAll, then check pins are ANALOG
for p in pins:
p.init(p.IN)
adc = ADCAll(12)
for p in pins:
print(p)
# set pins to IN mode, init ADCAll with mask, then check some pins are ANALOG
for p in pins:
p.init(p.IN)
adc = ADCAll(12, 0x70003)
for p in pins:
print(p)
# init all pins to ANALOG
adc = ADCAll(12)
print(adc)
# read all channels
for c in range(19):
print(type(adc.read_channel(c)))
# call special reading functions
print(0 < adc.read_core_temp() < 100)
print(0 < adc.read_core_vbat() < 4)
print(0 < adc.read_core_vref() < 2)
print(0 < adc.read_vref() < 4)
|
YifuLiu/AliOS-Things
|
components/py_engine/tests/pyb/adcall.py
|
Python
|
apache-2.0
| 699
|
# Test board-specific items on PYBv1.x
import os, pyb
if not "PYBv1." in os.uname().machine:
print("SKIP")
raise SystemExit
# test creating UART by id/name
for bus in (1, 2, 3, 4, 5, 6, 7, "XA", "XB", "YA", "YB", "Z"):
try:
pyb.UART(bus, 9600)
print("UART", bus)
except ValueError:
print("ValueError", bus)
# test creating SPI by id/name
for bus in (1, 2, 3, "X", "Y", "Z"):
try:
pyb.SPI(bus)
print("SPI", bus)
except ValueError:
print("ValueError", bus)
# test creating I2C by id/name
for bus in (2, 3, "X", "Y", "Z"):
try:
pyb.I2C(bus)
print("I2C", bus)
except ValueError:
print("ValueError", bus)
# test creating CAN by id/name
for bus in (1, 2, 3, "YA", "YB", "YC"):
try:
pyb.CAN(bus, pyb.CAN.LOOPBACK)
print("CAN", bus)
except ValueError:
print("ValueError", bus)
|
YifuLiu/AliOS-Things
|
components/py_engine/tests/pyb/board_pybv1x.py
|
Python
|
apache-2.0
| 911
|
try:
from pyb import CAN
except ImportError:
print("SKIP")
raise SystemExit
from array import array
import micropython
import pyb
# test we can correctly create by id (2 handled in can2.py test)
for bus in (-1, 0, 1, 3):
try:
CAN(bus, CAN.LOOPBACK)
print("CAN", bus)
except ValueError:
print("ValueError", bus)
CAN(1).deinit()
CAN.initfilterbanks(14)
can = CAN(1)
print(can)
# Test state when de-init'd
print(can.state() == can.STOPPED)
can.init(CAN.LOOPBACK)
print(can)
print(can.any(0))
# Test state when freshly created
print(can.state() == can.ERROR_ACTIVE)
# Test that restart can be called
can.restart()
# Test info returns a sensible value
print(can.info())
# Catch all filter
can.setfilter(0, CAN.MASK16, 0, (0, 0, 0, 0))
can.send("abcd", 123, timeout=5000)
print(can.any(0), can.info())
print(can.recv(0))
can.send("abcd", -1, timeout=5000)
print(can.recv(0))
can.send("abcd", 0x7FF + 1, timeout=5000)
print(can.recv(0))
# Test too long message
try:
can.send("abcdefghi", 0x7FF, timeout=5000)
except ValueError:
print("passed")
else:
print("failed")
# Test that recv can work without allocating memory on the heap
buf = bytearray(10)
l = [0, 0, 0, memoryview(buf)]
l2 = None
micropython.heap_lock()
can.send("", 42)
l2 = can.recv(0, l)
assert l is l2
print(l, len(l[3]), buf)
can.send("1234", 42)
l2 = can.recv(0, l)
assert l is l2
print(l, len(l[3]), buf)
can.send("01234567", 42)
l2 = can.recv(0, l)
assert l is l2
print(l, len(l[3]), buf)
can.send("abc", 42)
l2 = can.recv(0, l)
assert l is l2
print(l, len(l[3]), buf)
micropython.heap_unlock()
# Test that recv can work with different arrays behind the memoryview
can.send("abc", 1)
print(bytes(can.recv(0, [0, 0, 0, memoryview(array("B", range(8)))])[3]))
can.send("def", 1)
print(bytes(can.recv(0, [0, 0, 0, memoryview(array("b", range(8)))])[3]))
# Test for non-list passed as second arg to recv
can.send("abc", 1)
try:
can.recv(0, 1)
except TypeError:
print("TypeError")
# Test for too-short-list passed as second arg to recv
can.send("abc", 1)
try:
can.recv(0, [0, 0, 0])
except ValueError:
print("ValueError")
# Test for non-memoryview passed as 4th element to recv
can.send("abc", 1)
try:
can.recv(0, [0, 0, 0, 0])
except TypeError:
print("TypeError")
# Test for read-only-memoryview passed as 4th element to recv
can.send("abc", 1)
try:
can.recv(0, [0, 0, 0, memoryview(bytes(8))])
except ValueError:
print("ValueError")
# Test for bad-typecode-memoryview passed as 4th element to recv
can.send("abc", 1)
try:
can.recv(0, [0, 0, 0, memoryview(array("i", range(8)))])
except ValueError:
print("ValueError")
del can
# Testing extended IDs
can = CAN(1, CAN.LOOPBACK, extframe=True)
# Catch all filter
can.setfilter(0, CAN.MASK32, 0, (0, 0))
print(can)
try:
can.send("abcde", 0x7FF + 1, timeout=5000)
except ValueError:
print("failed")
else:
r = can.recv(0)
if r[0] == 0x7FF + 1 and r[3] == b"abcde":
print("passed")
else:
print("failed, wrong data received")
# Test filters
for n in [0, 8, 16, 24]:
filter_id = 0b00001000 << n
filter_mask = 0b00011100 << n
id_ok = 0b00001010 << n
id_fail = 0b00011010 << n
can.clearfilter(0)
can.setfilter(0, pyb.CAN.MASK32, 0, (filter_id, filter_mask))
can.send("ok", id_ok, timeout=3)
if can.any(0):
msg = can.recv(0)
print((hex(filter_id), hex(filter_mask), hex(msg[0]), msg[3]))
can.send("fail", id_fail, timeout=3)
if can.any(0):
msg = can.recv(0)
print((hex(filter_id), hex(filter_mask), hex(msg[0]), msg[3]))
del can
# Test RxCallbacks
can = CAN(1, CAN.LOOPBACK)
can.setfilter(0, CAN.LIST16, 0, (1, 2, 3, 4))
can.setfilter(1, CAN.LIST16, 1, (5, 6, 7, 8))
def cb0(bus, reason):
print("cb0")
if reason == 0:
print("pending")
if reason == 1:
print("full")
if reason == 2:
print("overflow")
def cb1(bus, reason):
print("cb1")
if reason == 0:
print("pending")
if reason == 1:
print("full")
if reason == 2:
print("overflow")
def cb0a(bus, reason):
print("cb0a")
if reason == 0:
print("pending")
if reason == 1:
print("full")
if reason == 2:
print("overflow")
def cb1a(bus, reason):
print("cb1a")
if reason == 0:
print("pending")
if reason == 1:
print("full")
if reason == 2:
print("overflow")
can.rxcallback(0, cb0)
can.rxcallback(1, cb1)
can.send("11111111", 1, timeout=5000)
can.send("22222222", 2, timeout=5000)
can.send("33333333", 3, timeout=5000)
can.rxcallback(0, cb0a)
can.send("44444444", 4, timeout=5000)
can.send("55555555", 5, timeout=5000)
can.send("66666666", 6, timeout=5000)
can.send("77777777", 7, timeout=5000)
can.rxcallback(1, cb1a)
can.send("88888888", 8, timeout=5000)
print(can.recv(0))
print(can.recv(0))
print(can.recv(0))
print(can.recv(1))
print(can.recv(1))
print(can.recv(1))
can.send("11111111", 1, timeout=5000)
can.send("55555555", 5, timeout=5000)
print(can.recv(0))
print(can.recv(1))
del can
# Testing asynchronous send
can = CAN(1, CAN.LOOPBACK)
can.setfilter(0, CAN.MASK16, 0, (0, 0, 0, 0))
while can.any(0):
can.recv(0)
can.send("abcde", 1, timeout=0)
print(can.any(0))
while not can.any(0):
pass
print(can.recv(0))
try:
can.send("abcde", 2, timeout=0)
can.send("abcde", 3, timeout=0)
can.send("abcde", 4, timeout=0)
can.send("abcde", 5, timeout=0)
except OSError as e:
if str(e) == "16":
print("passed")
else:
print("failed")
pyb.delay(500)
while can.any(0):
print(can.recv(0))
# Testing rtr messages
bus1 = CAN(1, CAN.LOOPBACK)
while bus1.any(0):
bus1.recv(0)
bus1.setfilter(0, CAN.LIST16, 0, (1, 2, 3, 4))
bus1.setfilter(1, CAN.LIST16, 0, (5, 6, 7, 8), rtr=(True, True, True, True))
bus1.setfilter(2, CAN.MASK16, 0, (64, 64, 32, 32), rtr=(False, True))
bus1.send("", 1, rtr=True)
print(bus1.any(0))
bus1.send("", 5, rtr=True)
print(bus1.recv(0))
bus1.send("", 6, rtr=True)
print(bus1.recv(0))
bus1.send("", 7, rtr=True)
print(bus1.recv(0))
bus1.send("", 16, rtr=True)
print(bus1.any(0))
bus1.send("", 32, rtr=True)
print(bus1.recv(0))
# test HAL error, timeout
can = pyb.CAN(1, pyb.CAN.NORMAL)
try:
can.send("1", 1, timeout=50)
except OSError as e:
print(repr(e))
|
YifuLiu/AliOS-Things
|
components/py_engine/tests/pyb/can.py
|
Python
|
apache-2.0
| 6,398
|
try:
from pyb import CAN
CAN(2)
except (ImportError, ValueError):
print("SKIP")
raise SystemExit
# Testing rtr messages
bus2 = CAN(2, CAN.LOOPBACK, extframe=True)
while bus2.any(0):
bus2.recv(0)
bus2.setfilter(0, CAN.LIST32, 0, (1, 2), rtr=(True, True))
bus2.setfilter(1, CAN.LIST32, 0, (3, 4), rtr=(True, False))
bus2.setfilter(2, CAN.MASK32, 0, (16, 16), rtr=(False,))
bus2.setfilter(2, CAN.MASK32, 0, (32, 32), rtr=(True,))
bus2.send("", 1, rtr=True)
print(bus2.recv(0))
bus2.send("", 2, rtr=True)
print(bus2.recv(0))
bus2.send("", 3, rtr=True)
print(bus2.recv(0))
bus2.send("", 4, rtr=True)
print(bus2.any(0))
|
YifuLiu/AliOS-Things
|
components/py_engine/tests/pyb/can2.py
|
Python
|
apache-2.0
| 637
|
import pyb
if not hasattr(pyb, "DAC"):
print("SKIP")
raise SystemExit
dac = pyb.DAC(1)
print(dac)
dac.noise(100)
dac.triangle(100)
dac.write(0)
dac.write_timed(bytearray(10), 100, mode=pyb.DAC.NORMAL)
pyb.delay(20)
dac.write(0)
# test buffering arg
dac = pyb.DAC(1, buffering=True)
dac.write(0)
|
YifuLiu/AliOS-Things
|
components/py_engine/tests/pyb/dac.py
|
Python
|
apache-2.0
| 306
|
import pyb
# test basic functionality
ext = pyb.ExtInt("X5", pyb.ExtInt.IRQ_RISING, pyb.Pin.PULL_DOWN, lambda l: print("line:", l))
ext.disable()
ext.enable()
print(ext.line())
ext.swint()
# test swint while disabled, then again after re-enabled
ext.disable()
ext.swint()
ext.enable()
ext.swint()
# disable now that the test is finished
ext.disable()
|
YifuLiu/AliOS-Things
|
components/py_engine/tests/pyb/extint.py
|
Python
|
apache-2.0
| 354
|
import pyb
from pyb import I2C
# test we can correctly create by id
for bus in (-1, 0, 1):
try:
I2C(bus)
print("I2C", bus)
except ValueError:
print("ValueError", bus)
i2c = I2C(1)
i2c.init(I2C.CONTROLLER, baudrate=400000)
print(i2c.scan())
i2c.deinit()
|
YifuLiu/AliOS-Things
|
components/py_engine/tests/pyb/i2c.py
|
Python
|
apache-2.0
| 288
|
# use accelerometer to test i2c bus
import pyb
from pyb import I2C
if not hasattr(pyb, "Accel"):
print("SKIP")
raise SystemExit
accel_addr = 76
pyb.Accel() # this will init the MMA for us
i2c = I2C(1, I2C.CONTROLLER, baudrate=400000)
print(i2c.scan())
print(i2c.is_ready(accel_addr))
print(i2c.mem_read(1, accel_addr, 7, timeout=500))
i2c.mem_write(0, accel_addr, 0, timeout=500)
i2c.send(7, addr=accel_addr)
i2c.recv(1, addr=accel_addr)
|
YifuLiu/AliOS-Things
|
components/py_engine/tests/pyb/i2c_accel.py
|
Python
|
apache-2.0
| 455
|
# test I2C errors, with polling (disabled irqs) and DMA
import pyb
from pyb import I2C
if not hasattr(pyb, "Accel"):
print("SKIP")
raise SystemExit
# init accelerometer
pyb.Accel()
# get I2C bus
i2c = I2C(1, I2C.CONTROLLER, dma=True)
# test polling mem_read
pyb.disable_irq()
i2c.mem_read(1, 76, 0x0A) # should succeed
pyb.enable_irq()
try:
pyb.disable_irq()
i2c.mem_read(1, 77, 0x0A) # should fail
except OSError as e:
pyb.enable_irq()
print(repr(e))
i2c.mem_read(1, 76, 0x0A) # should succeed
# test polling mem_write
pyb.disable_irq()
i2c.mem_write(1, 76, 0x0A) # should succeed
pyb.enable_irq()
try:
pyb.disable_irq()
i2c.mem_write(1, 77, 0x0A) # should fail
except OSError as e:
pyb.enable_irq()
print(repr(e))
i2c.mem_write(1, 76, 0x0A) # should succeed
# test DMA mem_read
i2c.mem_read(1, 76, 0x0A) # should succeed
try:
i2c.mem_read(1, 77, 0x0A) # should fail
except OSError as e:
print(repr(e))
i2c.mem_read(1, 76, 0x0A) # should succeed
# test DMA mem_write
i2c.mem_write(1, 76, 0x0A) # should succeed
try:
i2c.mem_write(1, 77, 0x0A) # should fail
except OSError as e:
print(repr(e))
i2c.mem_write(1, 76, 0x0A) # should succeed
|
YifuLiu/AliOS-Things
|
components/py_engine/tests/pyb/i2c_error.py
|
Python
|
apache-2.0
| 1,214
|
import pyb
def test_irq():
# test basic disable/enable
i1 = pyb.disable_irq()
print(i1)
pyb.enable_irq() # by default should enable IRQ
# check that interrupts are enabled by waiting for ticks
pyb.delay(10)
# check nested disable/enable
i1 = pyb.disable_irq()
i2 = pyb.disable_irq()
print(i1, i2)
pyb.enable_irq(i2)
pyb.enable_irq(i1)
# check that interrupts are enabled by waiting for ticks
pyb.delay(10)
test_irq()
|
YifuLiu/AliOS-Things
|
components/py_engine/tests/pyb/irq.py
|
Python
|
apache-2.0
| 481
|
import os, pyb
machine = os.uname().machine
if "PYBv1." in machine or "PYBLITEv1." in machine:
leds = [pyb.LED(i) for i in range(1, 5)]
pwm_leds = leds[2:]
elif "PYBD" in machine:
leds = [pyb.LED(i) for i in range(1, 4)]
pwm_leds = []
else:
print("SKIP")
raise SystemExit
# test printing
for i in range(3):
print(leds[i])
# test on and off
for l in leds:
l.on()
assert l.intensity() == 255
pyb.delay(100)
l.off()
assert l.intensity() == 0
pyb.delay(100)
# test toggle
for l in 2 * leds:
l.toggle()
assert l.intensity() in (0, 255)
pyb.delay(100)
# test intensity
for l in pwm_leds:
for i in range(256):
l.intensity(i)
assert l.intensity() == i
pyb.delay(1)
for i in range(255, -1, -1):
l.intensity(i)
assert l.intensity() == i
pyb.delay(1)
|
YifuLiu/AliOS-Things
|
components/py_engine/tests/pyb/led.py
|
Python
|
apache-2.0
| 865
|
# test stm module
import stm
import pyb
# test storing a full 32-bit number
# turn on then off the A15(=yellow) LED
BSRR = 0x18
stm.mem32[stm.GPIOA + BSRR] = 0x00008000
pyb.delay(100)
print(hex(stm.mem32[stm.GPIOA + stm.GPIO_ODR] & 0x00008000))
stm.mem32[stm.GPIOA + BSRR] = 0x80000000
print(hex(stm.mem32[stm.GPIOA + stm.GPIO_ODR] & 0x00008000))
|
YifuLiu/AliOS-Things
|
components/py_engine/tests/pyb/modstm.py
|
Python
|
apache-2.0
| 349
|
import time
DAYS_PER_MONTH = [0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
def is_leap(year):
return (year % 4) == 0
def test():
seconds = 0
wday = 5 # Jan 1, 2000 was a Saturday
for year in range(2000, 2034):
print("Testing %d" % year)
yday = 1
for month in range(1, 13):
if month == 2 and is_leap(year):
DAYS_PER_MONTH[2] = 29
else:
DAYS_PER_MONTH[2] = 28
for day in range(1, DAYS_PER_MONTH[month] + 1):
secs = time.mktime((year, month, day, 0, 0, 0, 0, 0))
if secs != seconds:
print(
"mktime failed for %d-%02d-%02d got %d expected %d"
% (year, month, day, secs, seconds)
)
tuple = time.localtime(seconds)
secs = time.mktime(tuple)
if secs != seconds:
print(
"localtime failed for %d-%02d-%02d got %d expected %d"
% (year, month, day, secs, seconds)
)
return
seconds += 86400
if yday != tuple[7]:
print(
"locatime for %d-%02d-%02d got yday %d, expecting %d"
% (year, month, day, tuple[7], yday)
)
return
if wday != tuple[6]:
print(
"locatime for %d-%02d-%02d got wday %d, expecting %d"
% (year, month, day, tuple[6], wday)
)
return
yday += 1
wday = (wday + 1) % 7
def spot_test(seconds, expected_time):
actual_time = time.localtime(seconds)
for i in range(len(actual_time)):
if actual_time[i] != expected_time[i]:
print(
"time.localtime(", seconds, ") returned", actual_time, "expecting", expected_time
)
return
print("time.localtime(", seconds, ") returned", actual_time, "(pass)")
test()
# fmt: off
spot_test( 0, (2000, 1, 1, 0, 0, 0, 5, 1))
spot_test( 1, (2000, 1, 1, 0, 0, 1, 5, 1))
spot_test( 59, (2000, 1, 1, 0, 0, 59, 5, 1))
spot_test( 60, (2000, 1, 1, 0, 1, 0, 5, 1))
spot_test( 3599, (2000, 1, 1, 0, 59, 59, 5, 1))
spot_test( 3600, (2000, 1, 1, 1, 0, 0, 5, 1))
spot_test( -1, (1999, 12, 31, 23, 59, 59, 4, 365))
spot_test( 447549467, (2014, 3, 7, 23, 17, 47, 4, 66))
spot_test( -940984933, (1970, 3, 7, 23, 17, 47, 5, 66))
spot_test(-1072915199, (1966, 1, 1, 0, 0, 1, 5, 1))
spot_test(-1072915200, (1966, 1, 1, 0, 0, 0, 5, 1))
spot_test(-1072915201, (1965, 12, 31, 23, 59, 59, 4, 365))
# fmt: on
|
YifuLiu/AliOS-Things
|
components/py_engine/tests/pyb/modtime.py
|
Python
|
apache-2.0
| 2,902
|
from pyb import Pin
p = Pin("X8", Pin.IN)
print(p)
print(p.name())
print(p.pin())
print(p.port())
p = Pin("X8", Pin.IN, Pin.PULL_UP)
p = Pin("X8", Pin.IN, pull=Pin.PULL_UP)
p = Pin("X8", mode=Pin.IN, pull=Pin.PULL_UP)
print(p)
print(p.value())
p.init(p.IN, p.PULL_DOWN)
p.init(p.IN, pull=p.PULL_DOWN)
p.init(mode=p.IN, pull=p.PULL_DOWN)
print(p)
print(p.value())
p.init(p.OUT_PP)
p.low()
print(p.value())
p.high()
print(p.value())
p.value(0)
print(p.value())
p.value(1)
print(p.value())
p.value(False)
print(p.value())
p.value(True)
print(p.value())
|
YifuLiu/AliOS-Things
|
components/py_engine/tests/pyb/pin.py
|
Python
|
apache-2.0
| 554
|
# basic tests of pyb module
import pyb
# test delay
pyb.delay(-1)
pyb.delay(0)
pyb.delay(1)
start = pyb.millis()
pyb.delay(17)
print((pyb.millis() - start) // 5) # should print 3
# test udelay
pyb.udelay(-1)
pyb.udelay(0)
pyb.udelay(1)
start = pyb.millis()
pyb.udelay(17000)
print((pyb.millis() - start) // 5) # should print 3
# other
pyb.disable_irq()
pyb.enable_irq()
print(pyb.have_cdc())
pyb.sync()
print(len(pyb.unique_id()))
pyb.wfi()
pyb.fault_debug(True)
pyb.fault_debug(False)
|
YifuLiu/AliOS-Things
|
components/py_engine/tests/pyb/pyb1.py
|
Python
|
apache-2.0
| 502
|
# test pyb module on F405 MCUs
import os, pyb
if not "STM32F405" in os.uname().machine:
print("SKIP")
raise SystemExit
print(pyb.freq())
print(type(pyb.rng()))
# test HAL error specific to F405
i2c = pyb.I2C(2, pyb.I2C.CONTROLLER)
try:
i2c.recv(1, 1)
except OSError as e:
print(repr(e))
|
YifuLiu/AliOS-Things
|
components/py_engine/tests/pyb/pyb_f405.py
|
Python
|
apache-2.0
| 307
|
# test pyb module on F411 MCUs
import os, pyb
if not "STM32F411" in os.uname().machine:
print("SKIP")
raise SystemExit
print(pyb.freq())
|
YifuLiu/AliOS-Things
|
components/py_engine/tests/pyb/pyb_f411.py
|
Python
|
apache-2.0
| 148
|
import pyb, stm
from pyb import RTC
rtc = RTC()
rtc.init()
print(rtc)
# make sure that 1 second passes correctly
rtc.datetime((2014, 1, 1, 1, 0, 0, 0, 0))
pyb.delay(1002)
print(rtc.datetime()[:7])
def set_and_print(datetime):
rtc.datetime(datetime)
print(rtc.datetime()[:7])
# make sure that setting works correctly
set_and_print((2000, 1, 1, 1, 0, 0, 0, 0))
set_and_print((2000, 1, 31, 1, 0, 0, 0, 0))
set_and_print((2000, 12, 31, 1, 0, 0, 0, 0))
set_and_print((2016, 12, 31, 1, 0, 0, 0, 0))
set_and_print((2016, 12, 31, 7, 0, 0, 0, 0))
set_and_print((2016, 12, 31, 7, 1, 0, 0, 0))
set_and_print((2016, 12, 31, 7, 12, 0, 0, 0))
set_and_print((2016, 12, 31, 7, 13, 0, 0, 0))
set_and_print((2016, 12, 31, 7, 23, 0, 0, 0))
set_and_print((2016, 12, 31, 7, 23, 1, 0, 0))
set_and_print((2016, 12, 31, 7, 23, 59, 0, 0))
set_and_print((2016, 12, 31, 7, 23, 59, 1, 0))
set_and_print((2016, 12, 31, 7, 23, 59, 59, 0))
set_and_print((2099, 12, 31, 7, 23, 59, 59, 0))
# check that calibration works correctly
# save existing calibration value:
cal_tmp = rtc.calibration()
def set_and_print_calib(cal):
rtc.calibration(cal)
print(rtc.calibration())
set_and_print_calib(512)
set_and_print_calib(511)
set_and_print_calib(345)
set_and_print_calib(1)
set_and_print_calib(0)
set_and_print_calib(-1)
set_and_print_calib(-123)
set_and_print_calib(-510)
set_and_print_calib(-511)
# restore existing calibration value
rtc.calibration(cal_tmp)
# Check register settings for wakeup
def set_and_print_wakeup(ms):
try:
rtc.wakeup(ms)
wucksel = stm.mem32[stm.RTC + stm.RTC_CR] & 7
wut = stm.mem32[stm.RTC + stm.RTC_WUTR] & 0xFFFF
except ValueError:
wucksel = -1
wut = -1
print((wucksel, wut))
set_and_print_wakeup(0)
set_and_print_wakeup(1)
set_and_print_wakeup(4000)
set_and_print_wakeup(4001)
set_and_print_wakeup(8000)
set_and_print_wakeup(8001)
set_and_print_wakeup(16000)
set_and_print_wakeup(16001)
set_and_print_wakeup(32000)
set_and_print_wakeup(32001)
set_and_print_wakeup(0x10000 * 1000)
set_and_print_wakeup(0x10001 * 1000)
set_and_print_wakeup(0x1FFFF * 1000)
set_and_print_wakeup(0x20000 * 1000)
set_and_print_wakeup(0x20001 * 1000) # exception
|
YifuLiu/AliOS-Things
|
components/py_engine/tests/pyb/rtc.py
|
Python
|
apache-2.0
| 2,216
|
from pyb import Servo
servo = Servo(1)
print(servo)
servo.angle(0)
servo.angle(10, 100)
servo.speed(-10)
servo.speed(10, 100)
servo.pulse_width(1500)
print(servo.pulse_width())
servo.calibration(630, 2410, 1490, 2460, 2190)
print(servo.calibration())
|
YifuLiu/AliOS-Things
|
components/py_engine/tests/pyb/servo.py
|
Python
|
apache-2.0
| 256
|
from pyb import SPI
# test we can correctly create by id
for bus in (-1, 0, 1, 2):
try:
SPI(bus)
print("SPI", bus)
except ValueError:
print("ValueError", bus)
spi = SPI(1)
print(spi)
spi = SPI(1, SPI.CONTROLLER)
spi = SPI(1, SPI.CONTROLLER, baudrate=500000)
spi = SPI(
1, SPI.CONTROLLER, 500000, polarity=1, phase=0, bits=8, firstbit=SPI.MSB, ti=False, crc=None
)
print(str(spi)[:32], str(spi)[53:]) # don't print baudrate/prescaler
spi.init(SPI.PERIPHERAL, phase=1)
print(spi)
try:
# need to flush input before we get an error (error is what we want to test)
for i in range(10):
spi.recv(1, timeout=100)
except OSError:
print("OSError")
spi.init(SPI.CONTROLLER)
spi.send(1, timeout=100)
print(spi.recv(1, timeout=100))
print(spi.send_recv(1, timeout=100))
spi.deinit()
|
YifuLiu/AliOS-Things
|
components/py_engine/tests/pyb/spi.py
|
Python
|
apache-2.0
| 833
|
from pyb import Switch
sw = Switch()
print(sw())
sw.callback(print)
sw.callback(None)
|
YifuLiu/AliOS-Things
|
components/py_engine/tests/pyb/switch.py
|
Python
|
apache-2.0
| 87
|
# check basic functionality of the timer class
import pyb
from pyb import Timer
tim = Timer(4)
tim = Timer(4, prescaler=100, period=200)
print(tim.prescaler())
print(tim.period())
tim.prescaler(300)
print(tim.prescaler())
tim.period(400)
print(tim.period())
# Setting and printing frequency
tim = Timer(2, freq=100)
print(tim.freq())
tim.freq(0.001)
print("{:.3f}".format(tim.freq()))
|
YifuLiu/AliOS-Things
|
components/py_engine/tests/pyb/timer.py
|
Python
|
apache-2.0
| 388
|
# check callback feature of the timer class
import pyb
from pyb import Timer
# callback function that disables the callback when called
def cb1(t):
print("cb1")
t.callback(None)
# callback function that disables the timer when called
def cb2(t):
print("cb2")
t.deinit()
# callback where cb4 closes over cb3.y
def cb3(x):
y = x
def cb4(t):
print("cb4", y)
t.callback(None)
return cb4
# create a timer with a callback, using callback(None) to stop
tim = Timer(1, freq=100, callback=cb1)
pyb.delay(5)
print("before cb1")
pyb.delay(15)
# create a timer with a callback, using deinit to stop
tim = Timer(2, freq=100, callback=cb2)
pyb.delay(5)
print("before cb2")
pyb.delay(15)
# create a timer, then set the freq, then set the callback
tim = Timer(4)
tim.init(freq=100)
tim.callback(cb1)
pyb.delay(5)
print("before cb1")
pyb.delay(15)
# test callback with a closure
tim.init(freq=100)
tim.callback(cb3(3))
pyb.delay(5)
print("before cb4")
pyb.delay(15)
|
YifuLiu/AliOS-Things
|
components/py_engine/tests/pyb/timer_callback.py
|
Python
|
apache-2.0
| 1,006
|
from pyb import UART
# test we can correctly create by id
for bus in (-1, 0, 1, 2, 5, 6):
try:
UART(bus, 9600)
print("UART", bus)
except ValueError:
print("ValueError", bus)
uart = UART(1)
uart = UART(1, 9600)
uart = UART(1, 9600, bits=8, parity=None, stop=1)
print(uart)
uart.init(2400)
print(uart)
print(uart.any())
print(uart.write("123"))
print(uart.write(b"abcd"))
print(uart.writechar(1))
# make sure this method exists
uart.sendbreak()
# non-blocking mode
uart = UART(1, 9600, timeout=0)
print(uart.write(b"1"))
print(uart.write(b"abcd"))
print(uart.writechar(1))
print(uart.read(100))
# set rxbuf
uart.init(9600, rxbuf=8)
print(uart)
uart.init(9600, rxbuf=0)
print(uart)
# set read_buf_len (legacy, use rxbuf instead)
uart.init(9600, read_buf_len=4)
print(uart)
uart.init(9600, read_buf_len=0)
print(uart)
|
YifuLiu/AliOS-Things
|
components/py_engine/tests/pyb/uart.py
|
Python
|
apache-2.0
| 854
|
import time, pyb
@micropython.native
def f(led, n, d):
led.off()
i = 0
while i < n:
print(i)
led.toggle()
time.sleep_ms(d)
i += 1
led.off()
f(pyb.LED(1), 2, 150)
f(pyb.LED(2), 4, 50)
|
YifuLiu/AliOS-Things
|
components/py_engine/tests/pybnative/while.py
|
Python
|
apache-2.0
| 235
|
import native_frozen_align
native_frozen_align.native_x(1)
native_frozen_align.native_y(2)
native_frozen_align.native_z(3)
|
YifuLiu/AliOS-Things
|
components/py_engine/tests/qemu-arm/native_test.py
|
Python
|
apache-2.0
| 124
|
#! /usr/bin/env python3
import os
import subprocess
import sys
import argparse
import re
from glob import glob
from collections import defaultdict
# Tests require at least CPython 3.3. If your default python3 executable
# is of lower version, you can point MICROPY_CPYTHON3 environment var
# to the correct executable.
if os.name == "nt":
CPYTHON3 = os.getenv("MICROPY_CPYTHON3", "python3.exe")
MICROPYTHON = os.getenv("MICROPY_MICROPYTHON", "../ports/windows/micropython.exe")
else:
CPYTHON3 = os.getenv("MICROPY_CPYTHON3", "python3")
MICROPYTHON = os.getenv("MICROPY_MICROPYTHON", "../ports/unix/micropython")
def run_tests(pyb, test_dict):
test_count = 0
testcase_count = 0
for base_test, tests in sorted(test_dict.items()):
print(base_test + ":")
for test_file in tests:
# run MicroPython
if pyb is None:
# run on PC
try:
output_mupy = subprocess.check_output(
[MICROPYTHON, "-X", "emit=bytecode", test_file[0]]
)
except subprocess.CalledProcessError:
output_mupy = b"CRASH"
else:
# run on pyboard
pyb.enter_raw_repl()
try:
output_mupy = pyb.execfile(test_file).replace(b"\r\n", b"\n")
except pyboard.PyboardError:
output_mupy = b"CRASH"
output_mupy = float(output_mupy.strip())
test_file[1] = output_mupy
testcase_count += 1
test_count += 1
baseline = None
for t in tests:
if baseline is None:
baseline = t[1]
print(" %.3fs (%+06.2f%%) %s" % (t[1], (t[1] * 100 / baseline) - 100, t[0]))
print("{} tests performed ({} individual testcases)".format(test_count, testcase_count))
# all tests succeeded
return True
def main():
cmd_parser = argparse.ArgumentParser(description="Run tests for MicroPython.")
cmd_parser.add_argument("--pyboard", action="store_true", help="run the tests on the pyboard")
cmd_parser.add_argument("files", nargs="*", help="input test files")
args = cmd_parser.parse_args()
# Note pyboard support is copied over from run-tests.py, not tests, and likely needs revamping
if args.pyboard:
import pyboard
pyb = pyboard.Pyboard("/dev/ttyACM0")
pyb.enter_raw_repl()
else:
pyb = None
if len(args.files) == 0:
if pyb is None:
# run PC tests
test_dirs = ("internal_bench",)
else:
# run pyboard tests
test_dirs = ("basics", "float", "pyb")
tests = sorted(
test_file
for test_files in (glob("{}/*.py".format(dir)) for dir in test_dirs)
for test_file in test_files
)
else:
# tests explicitly given
tests = sorted(args.files)
test_dict = defaultdict(lambda: [])
for t in tests:
m = re.match(r"(.+?)-(.+)\.py", t)
if not m:
continue
test_dict[m.group(1)].append([t, None])
if not run_tests(pyb, test_dict):
sys.exit(1)
if __name__ == "__main__":
main()
|
YifuLiu/AliOS-Things
|
components/py_engine/tests/run-internalbench.py
|
Python
|
apache-2.0
| 3,276
|
#!/usr/bin/env python3
# This file is part of the MicroPython project, http://micropython.org/
# The MIT License (MIT)
# Copyright (c) 2020 Damien P. George
import sys, os, time, re, select
import argparse
import itertools
import subprocess
import tempfile
sys.path.append("../tools")
import pyboard
if os.name == "nt":
CPYTHON3 = os.getenv("MICROPY_CPYTHON3", "python3.exe")
MICROPYTHON = os.getenv("MICROPY_MICROPYTHON", "../ports/windows/micropython.exe")
else:
CPYTHON3 = os.getenv("MICROPY_CPYTHON3", "python3")
MICROPYTHON = os.getenv("MICROPY_MICROPYTHON", "../ports/unix/micropython")
# For diff'ing test output
DIFF = os.getenv("MICROPY_DIFF", "diff -u")
PYTHON_TRUTH = CPYTHON3
INSTANCE_READ_TIMEOUT_S = 10
APPEND_CODE_TEMPLATE = """
import sys
class multitest:
@staticmethod
def flush():
try:
sys.stdout.flush()
except AttributeError:
pass
@staticmethod
def skip():
print("SKIP")
multitest.flush()
raise SystemExit
@staticmethod
def next():
print("NEXT")
multitest.flush()
@staticmethod
def broadcast(msg):
print("BROADCAST", msg)
multitest.flush()
@staticmethod
def wait(msg):
msg = "BROADCAST " + msg
while True:
if sys.stdin.readline().rstrip() == msg:
return
@staticmethod
def globals(**gs):
for g in gs:
print("SET {{}} = {{!r}}".format(g, gs[g]))
multitest.flush()
@staticmethod
def get_network_ip():
try:
import network
ip = network.WLAN().ifconfig()[0]
except:
ip = "127.0.0.1"
return ip
{}
instance{}()
multitest.flush()
"""
# The btstack implementation on Unix generates some spurious output that we
# can't control.
IGNORE_OUTPUT_MATCHES = (
"libusb: error ", # It tries to open devices that it doesn't have access to (libusb prints unconditionally).
"hci_transport_h2_libusb.c", # Same issue. We enable LOG_ERROR in btstack.
"USB Path: ", # Hardcoded in btstack's libusb transport.
"hci_number_completed_packet", # Warning from btstack.
)
class PyInstance:
def __init__(self):
pass
def close(self):
pass
def prepare_script_from_file(self, filename, prepend, append):
with open(filename, "rb") as f:
script = f.read()
if prepend:
script = bytes(prepend, "ascii") + b"\n" + script
if append:
script += b"\n" + bytes(append, "ascii")
return script
def run_file(self, filename, prepend="", append=""):
return self.run_script(self.prepare_script_from_file(filename, prepend, append))
def start_file(self, filename, prepend="", append=""):
return self.start_script(self.prepare_script_from_file(filename, prepend, append))
class PyInstanceSubProcess(PyInstance):
def __init__(self, argv, env=None):
self.argv = argv
self.env = {n: v for n, v in (i.split("=") for i in env)} if env else None
self.popen = None
self.finished = True
def __str__(self):
return self.argv[0].rsplit("/")[-1]
def run_script(self, script):
output = b""
err = None
try:
p = subprocess.run(
self.argv,
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT,
input=script,
env=self.env,
)
output = p.stdout
except subprocess.CalledProcessError as er:
err = er
return str(output.strip(), "ascii"), err
def start_script(self, script):
self.popen = subprocess.Popen(
self.argv + ["-c", script],
stdin=subprocess.PIPE,
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT,
env=self.env,
)
self.finished = False
def stop(self):
if self.popen and self.popen.poll() is None:
self.popen.terminate()
def readline(self):
sel = select.select([self.popen.stdout.raw], [], [], 0.001)
if not sel[0]:
self.finished = self.popen.poll() is not None
return None, None
out = self.popen.stdout.raw.readline()
if out == b"":
self.finished = self.popen.poll() is not None
return None, None
else:
return str(out.rstrip(), "ascii"), None
def write(self, data):
self.popen.stdin.write(data)
self.popen.stdin.flush()
def is_finished(self):
return self.finished
def wait_finished(self):
self.popen.wait()
out = self.popen.stdout.read()
return str(out, "ascii"), ""
class PyInstancePyboard(PyInstance):
@staticmethod
def map_device_shortcut(device):
if device[0] == "a" and device[1:].isdigit():
return "/dev/ttyACM" + device[1:]
elif device[0] == "u" and device[1:].isdigit():
return "/dev/ttyUSB" + device[1:]
else:
return device
def __init__(self, device):
device = self.map_device_shortcut(device)
self.device = device
self.pyb = pyboard.Pyboard(device)
self.pyb.enter_raw_repl()
self.finished = True
def __str__(self):
return self.device.rsplit("/")[-1]
def close(self):
self.pyb.exit_raw_repl()
self.pyb.close()
def run_script(self, script):
output = b""
err = None
try:
self.pyb.enter_raw_repl()
output = self.pyb.exec_(script)
except pyboard.PyboardError as er:
err = er
return str(output.strip(), "ascii"), err
def start_script(self, script):
self.pyb.enter_raw_repl()
self.pyb.exec_raw_no_follow(script)
self.finished = False
def stop(self):
self.pyb.serial.write(b"\r\x03")
def readline(self):
if self.finished:
return None, None
if self.pyb.serial.inWaiting() == 0:
return None, None
out = self.pyb.read_until(1, (b"\r\n", b"\x04"))
if out.endswith(b"\x04"):
self.finished = True
out = out[:-1]
err = str(self.pyb.read_until(1, b"\x04"), "ascii")
err = err[:-1]
if not out and not err:
return None, None
else:
err = None
return str(out.rstrip(), "ascii"), err
def write(self, data):
self.pyb.serial.write(data)
def is_finished(self):
return self.finished
def wait_finished(self):
out, err = self.pyb.follow(10, None)
return str(out, "ascii"), str(err, "ascii")
def prepare_test_file_list(test_files):
test_files2 = []
for test_file in sorted(test_files):
num_instances = 0
with open(test_file) as f:
for line in f:
m = re.match(r"def instance([0-9]+)\(\):", line)
if m:
num_instances = max(num_instances, int(m.group(1)) + 1)
test_files2.append((test_file, num_instances))
return test_files2
def trace_instance_output(instance_idx, line):
if cmd_args.trace_output:
t_ms = round((time.time() - trace_t0) * 1000)
print("{:6} i{} :".format(t_ms, instance_idx), line)
sys.stdout.flush()
def run_test_on_instances(test_file, num_instances, instances):
global trace_t0
trace_t0 = time.time()
error = False
skip = False
injected_globals = ""
output = [[] for _ in range(num_instances)]
if cmd_args.trace_output:
print("TRACE {}:".format("|".join(str(i) for i in instances)))
# Start all instances running, in order, waiting until they signal they are ready
for idx in range(num_instances):
append_code = APPEND_CODE_TEMPLATE.format(injected_globals, idx)
instance = instances[idx]
instance.start_file(test_file, append=append_code)
last_read_time = time.time()
while True:
if instance.is_finished():
break
out, err = instance.readline()
if out is None and err is None:
if time.time() > last_read_time + INSTANCE_READ_TIMEOUT_S:
output[idx].append("TIMEOUT")
error = True
break
time.sleep(0.1)
continue
last_read_time = time.time()
if out is not None and not any(m in out for m in IGNORE_OUTPUT_MATCHES):
trace_instance_output(idx, out)
if out.startswith("SET "):
injected_globals += out[4:] + "\n"
elif out == "SKIP":
skip = True
break
elif out == "NEXT":
break
else:
output[idx].append(out)
if err is not None:
trace_instance_output(idx, err)
output[idx].append(err)
error = True
if error or skip:
break
if not error and not skip:
# Capture output and wait for all instances to finish running
last_read_time = [time.time() for _ in range(num_instances)]
while True:
num_running = 0
num_output = 0
for idx in range(num_instances):
instance = instances[idx]
if instance.is_finished():
continue
num_running += 1
out, err = instance.readline()
if out is None and err is None:
if time.time() > last_read_time[idx] + INSTANCE_READ_TIMEOUT_S:
output[idx].append("TIMEOUT")
error = True
continue
num_output += 1
last_read_time[idx] = time.time()
if out is not None and not any(m in out for m in IGNORE_OUTPUT_MATCHES):
trace_instance_output(idx, out)
if out.startswith("BROADCAST "):
for instance2 in instances:
if instance2 is not instance:
instance2.write(bytes(out, "ascii") + b"\r\n")
else:
output[idx].append(out)
if err is not None:
trace_instance_output(idx, err)
output[idx].append(err)
error = True
if not num_output:
time.sleep(0.1)
if not num_running or error:
break
# Stop all instances
for idx in range(num_instances):
instances[idx].stop()
output_str = ""
for idx, lines in enumerate(output):
output_str += "--- instance{} ---\n".format(idx)
output_str += "\n".join(lines) + "\n"
return error, skip, output_str
def print_diff(a, b):
a_fd, a_path = tempfile.mkstemp(text=True)
b_fd, b_path = tempfile.mkstemp(text=True)
os.write(a_fd, a.encode())
os.write(b_fd, b.encode())
os.close(a_fd)
os.close(b_fd)
subprocess.run(DIFF.split(" ") + [a_path, b_path])
os.unlink(a_path)
os.unlink(b_path)
def run_tests(test_files, instances_truth, instances_test):
skipped_tests = []
passed_tests = []
failed_tests = []
for test_file, num_instances in test_files:
instances_str = "|".join(str(instances_test[i]) for i in range(num_instances))
print("{} on {}: ".format(test_file, instances_str), end="")
if cmd_args.show_output or cmd_args.trace_output:
print()
sys.stdout.flush()
# Run test on test instances
error, skip, output_test = run_test_on_instances(test_file, num_instances, instances_test)
if not skip:
# Check if truth exists in a file, and read it in
test_file_expected = test_file + ".exp"
if os.path.isfile(test_file_expected):
with open(test_file_expected) as f:
output_truth = f.read()
else:
# Run test on truth instances to get expected output
_, _, output_truth = run_test_on_instances(
test_file, num_instances, instances_truth
)
if cmd_args.show_output:
print("### TEST ###")
print(output_test, end="")
if not skip:
print("### TRUTH ###")
print(output_truth, end="")
# Print result of test
if skip:
print("skip")
skipped_tests.append(test_file)
elif output_test == output_truth:
print("pass")
passed_tests.append(test_file)
else:
print("FAIL")
failed_tests.append(test_file)
if not cmd_args.show_output:
print("### TEST ###")
print(output_test, end="")
print("### TRUTH ###")
print(output_truth, end="")
print("### DIFF ###")
print_diff(output_truth, output_test)
if cmd_args.show_output:
print()
print("{} tests performed".format(len(skipped_tests) + len(passed_tests) + len(failed_tests)))
print("{} tests passed".format(len(passed_tests)))
if skipped_tests:
print("{} tests skipped: {}".format(len(skipped_tests), " ".join(skipped_tests)))
if failed_tests:
print("{} tests failed: {}".format(len(failed_tests), " ".join(failed_tests)))
return not failed_tests
def main():
global cmd_args
cmd_parser = argparse.ArgumentParser(description="Run network tests for MicroPython")
cmd_parser.add_argument(
"-s", "--show-output", action="store_true", help="show test output after running"
)
cmd_parser.add_argument(
"-t", "--trace-output", action="store_true", help="trace test output while running"
)
cmd_parser.add_argument(
"-i", "--instance", action="append", default=[], help="instance(s) to run the tests on"
)
cmd_parser.add_argument(
"-p",
"--permutations",
type=int,
default=1,
help="repeat the test with this many permutations of the instance order",
)
cmd_parser.add_argument("files", nargs="+", help="input test files")
cmd_args = cmd_parser.parse_args()
# clear search path to make sure tests use only builtin modules and those in extmod
os.environ["MICROPYPATH"] = os.pathsep + "../extmod"
test_files = prepare_test_file_list(cmd_args.files)
max_instances = max(t[1] for t in test_files)
instances_truth = [PyInstanceSubProcess([PYTHON_TRUTH]) for _ in range(max_instances)]
instances_test = []
for i in cmd_args.instance:
# Each instance arg is <cmd>,ENV=VAR,ENV=VAR...
i = i.split(",")
cmd = i[0]
env = i[1:]
if cmd.startswith("exec:"):
instances_test.append(PyInstanceSubProcess([cmd[len("exec:") :]], env))
elif cmd == "micropython":
instances_test.append(PyInstanceSubProcess([MICROPYTHON], env))
elif cmd == "cpython":
instances_test.append(PyInstanceSubProcess([CPYTHON3], env))
elif cmd.startswith("pyb:"):
instances_test.append(PyInstancePyboard(cmd[len("pyb:") :]))
else:
print("unknown instance string: {}".format(cmd), file=sys.stderr)
sys.exit(1)
for _ in range(max_instances - len(instances_test)):
instances_test.append(PyInstanceSubProcess([MICROPYTHON]))
all_pass = True
try:
for i, instances_test_permutation in enumerate(itertools.permutations(instances_test)):
if i >= cmd_args.permutations:
break
all_pass &= run_tests(test_files, instances_truth, instances_test_permutation)
finally:
for i in instances_truth:
i.close()
for i in instances_test:
i.close()
if not all_pass:
sys.exit(1)
if __name__ == "__main__":
main()
|
YifuLiu/AliOS-Things
|
components/py_engine/tests/run-multitests.py
|
Python
|
apache-2.0
| 16,235
|
#!/usr/bin/env python3
# This file is part of the MicroPython project, http://micropython.org/
# The MIT License (MIT)
# Copyright (c) 2019 Damien P. George
import os
import subprocess
import sys
import argparse
sys.path.append("../tools")
import pyboard
# Paths for host executables
CPYTHON3 = os.getenv("MICROPY_CPYTHON3", "python3")
MICROPYTHON = os.getenv("MICROPY_MICROPYTHON", "../ports/unix/micropython-coverage")
NATMOD_EXAMPLE_DIR = "../examples/natmod/"
# Supported tests and their corresponding mpy module
TEST_MAPPINGS = {
"btree": "btree/btree_$(ARCH).mpy",
"framebuf": "framebuf/framebuf_$(ARCH).mpy",
"uheapq": "uheapq/uheapq_$(ARCH).mpy",
"urandom": "urandom/urandom_$(ARCH).mpy",
"ure": "ure/ure_$(ARCH).mpy",
"uzlib": "uzlib/uzlib_$(ARCH).mpy",
}
# Code to allow a target MicroPython to import an .mpy from RAM
injected_import_hook_code = """\
import usys, uos, uio
class __File(uio.IOBase):
def __init__(self):
self.off = 0
def ioctl(self, request, arg):
return 0
def readinto(self, buf):
buf[:] = memoryview(__buf)[self.off:self.off + len(buf)]
self.off += len(buf)
return len(buf)
class __FS:
def mount(self, readonly, mkfs):
pass
def chdir(self, path):
pass
def stat(self, path):
if path == '__injected.mpy':
return tuple(0 for _ in range(10))
else:
raise OSError(-2) # ENOENT
def open(self, path, mode):
return __File()
uos.mount(__FS(), '/__remote')
uos.chdir('/__remote')
usys.modules['{}'] = __import__('__injected')
"""
class TargetSubprocess:
def __init__(self, cmd):
self.cmd = cmd
def close(self):
pass
def run_script(self, script):
try:
p = subprocess.run(
self.cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, input=script
)
return p.stdout, None
except subprocess.CalledProcessError as er:
return b"", er
class TargetPyboard:
def __init__(self, pyb):
self.pyb = pyb
self.pyb.enter_raw_repl()
def close(self):
self.pyb.exit_raw_repl()
self.pyb.close()
def run_script(self, script):
try:
self.pyb.enter_raw_repl()
output = self.pyb.exec_(script)
output = output.replace(b"\r\n", b"\n")
return output, None
except pyboard.PyboardError as er:
return b"", er
def run_tests(target_truth, target, args, stats):
for test_file in args.files:
# Find supported test
for k, v in TEST_MAPPINGS.items():
if test_file.find(k) != -1:
test_module = k
test_mpy = v.replace("$(ARCH)", args.arch)
break
else:
print("---- {} - no matching mpy".format(test_file))
continue
# Read test script
with open(test_file, "rb") as f:
test_file_data = f.read()
# Create full test with embedded .mpy
try:
with open(NATMOD_EXAMPLE_DIR + test_mpy, "rb") as f:
test_script = b"__buf=" + bytes(repr(f.read()), "ascii") + b"\n"
except OSError:
print("---- {} - mpy file not compiled".format(test_file))
continue
test_script += bytes(injected_import_hook_code.format(test_module), "ascii")
test_script += test_file_data
# Run test under MicroPython
result_out, error = target.run_script(test_script)
# Work out result of test
extra = ""
if error is None and result_out == b"SKIP\n":
result = "SKIP"
elif error is not None:
result = "FAIL"
extra = " - " + str(error)
else:
# Check result against truth
try:
with open(test_file + ".exp", "rb") as f:
result_exp = f.read()
error = None
except OSError:
result_exp, error = target_truth.run_script(test_file_data)
if error is not None:
result = "TRUTH FAIL"
elif result_out != result_exp:
result = "FAIL"
print(result_out)
else:
result = "pass"
# Accumulate statistics
stats["total"] += 1
if result == "pass":
stats["pass"] += 1
elif result == "SKIP":
stats["skip"] += 1
else:
stats["fail"] += 1
# Print result
print("{:4} {}{}".format(result, test_file, extra))
def main():
cmd_parser = argparse.ArgumentParser(
description="Run dynamic-native-module tests under MicroPython"
)
cmd_parser.add_argument(
"-p", "--pyboard", action="store_true", help="run tests via pyboard.py"
)
cmd_parser.add_argument(
"-d", "--device", default="/dev/ttyACM0", help="the device for pyboard.py"
)
cmd_parser.add_argument(
"-a", "--arch", default="x64", help="native architecture of the target"
)
cmd_parser.add_argument("files", nargs="*", help="input test files")
args = cmd_parser.parse_args()
target_truth = TargetSubprocess([CPYTHON3])
if args.pyboard:
target = TargetPyboard(pyboard.Pyboard(args.device))
else:
target = TargetSubprocess([MICROPYTHON])
stats = {"total": 0, "pass": 0, "fail": 0, "skip": 0}
run_tests(target_truth, target, args, stats)
target.close()
target_truth.close()
print("{} tests performed".format(stats["total"]))
print("{} tests passed".format(stats["pass"]))
if stats["fail"]:
print("{} tests failed".format(stats["fail"]))
if stats["skip"]:
print("{} tests skipped".format(stats["skip"]))
if stats["fail"]:
sys.exit(1)
if __name__ == "__main__":
main()
|
YifuLiu/AliOS-Things
|
components/py_engine/tests/run-natmodtests.py
|
Python
|
apache-2.0
| 5,851
|
#!/usr/bin/env python3
# This file is part of the MicroPython project, http://micropython.org/
# The MIT License (MIT)
# Copyright (c) 2019 Damien P. George
import os
import subprocess
import sys
import argparse
from glob import glob
sys.path.append("../tools")
import pyboard
# Paths for host executables
if os.name == "nt":
CPYTHON3 = os.getenv("MICROPY_CPYTHON3", "python3.exe")
MICROPYTHON = os.getenv("MICROPY_MICROPYTHON", "../ports/windows/micropython.exe")
else:
CPYTHON3 = os.getenv("MICROPY_CPYTHON3", "python3")
MICROPYTHON = os.getenv("MICROPY_MICROPYTHON", "../ports/unix/micropython")
PYTHON_TRUTH = CPYTHON3
BENCH_SCRIPT_DIR = "perf_bench/"
def compute_stats(lst):
avg = 0
var = 0
for x in lst:
avg += x
var += x * x
avg /= len(lst)
var = max(0, var / len(lst) - avg ** 2)
return avg, var ** 0.5
def run_script_on_target(target, script):
output = b""
err = None
if isinstance(target, pyboard.Pyboard):
# Run via pyboard interface
try:
target.enter_raw_repl()
output = target.exec_(script)
except pyboard.PyboardError as er:
err = er
else:
# Run local executable
try:
p = subprocess.run(
target, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, input=script
)
output = p.stdout
except subprocess.CalledProcessError as er:
err = er
return str(output.strip(), "ascii"), err
def run_feature_test(target, test):
with open("feature_check/" + test + ".py", "rb") as f:
script = f.read()
output, err = run_script_on_target(target, script)
if err is None:
return output
else:
return "CRASH: %r" % err
def run_benchmark_on_target(target, script):
output, err = run_script_on_target(target, script)
if err is None:
time, norm, result = output.split(None, 2)
try:
return int(time), int(norm), result
except ValueError:
return -1, -1, "CRASH: %r" % output
else:
return -1, -1, "CRASH: %r" % err
def run_benchmarks(target, param_n, param_m, n_average, test_list):
skip_complex = run_feature_test(target, "complex") != "complex"
skip_native = run_feature_test(target, "native_check") != "native"
for test_file in sorted(test_list):
print(test_file + ": ", end="")
# Check if test should be skipped
skip = (
skip_complex
and test_file.find("bm_fft") != -1
or skip_native
and test_file.find("viper_") != -1
)
if skip:
print("skip")
continue
# Create test script
with open(test_file, "rb") as f:
test_script = f.read()
with open(BENCH_SCRIPT_DIR + "benchrun.py", "rb") as f:
test_script += f.read()
test_script += b"bm_run(%u, %u)\n" % (param_n, param_m)
# Write full test script if needed
if 0:
with open("%s.full" % test_file, "wb") as f:
f.write(test_script)
# Run MicroPython a given number of times
times = []
scores = []
error = None
result_out = None
for _ in range(n_average):
time, norm, result = run_benchmark_on_target(target, test_script)
if time < 0 or norm < 0:
error = result
break
if result_out is None:
result_out = result
elif result != result_out:
error = "FAIL self"
break
times.append(time)
scores.append(1e6 * norm / time)
# Check result against truth if needed
if error is None and result_out != "None":
_, _, result_exp = run_benchmark_on_target(PYTHON_TRUTH, test_script)
if result_out != result_exp:
error = "FAIL truth"
if error is not None:
print(error)
else:
t_avg, t_sd = compute_stats(times)
s_avg, s_sd = compute_stats(scores)
print(
"{:.2f} {:.4f} {:.2f} {:.4f}".format(
t_avg, 100 * t_sd / t_avg, s_avg, 100 * s_sd / s_avg
)
)
if 0:
print(" times: ", times)
print(" scores:", scores)
sys.stdout.flush()
def parse_output(filename):
with open(filename) as f:
params = f.readline()
n, m, _ = params.strip().split()
n = int(n.split("=")[1])
m = int(m.split("=")[1])
data = []
for l in f:
if l.find(": ") != -1 and l.find(": skip") == -1 and l.find("CRASH: ") == -1:
name, values = l.strip().split(": ")
values = tuple(float(v) for v in values.split())
data.append((name,) + values)
return n, m, data
def compute_diff(file1, file2, diff_score):
# Parse output data from previous runs
n1, m1, d1 = parse_output(file1)
n2, m2, d2 = parse_output(file2)
# Print header
if diff_score:
print("diff of scores (higher is better)")
else:
print("diff of microsecond times (lower is better)")
if n1 == n2 and m1 == m2:
hdr = "N={} M={}".format(n1, m1)
else:
hdr = "N={} M={} vs N={} M={}".format(n1, m1, n2, m2)
print(
"{:24} {:>10} -> {:>10} {:>10} {:>7}% (error%)".format(
hdr, file1, file2, "diff", "diff"
)
)
# Print entries
while d1 and d2:
if d1[0][0] == d2[0][0]:
# Found entries with matching names
entry1 = d1.pop(0)
entry2 = d2.pop(0)
name = entry1[0].rsplit("/")[-1]
av1, sd1 = entry1[1 + 2 * diff_score], entry1[2 + 2 * diff_score]
av2, sd2 = entry2[1 + 2 * diff_score], entry2[2 + 2 * diff_score]
sd1 *= av1 / 100 # convert from percent sd to absolute sd
sd2 *= av2 / 100 # convert from percent sd to absolute sd
av_diff = av2 - av1
sd_diff = (sd1 ** 2 + sd2 ** 2) ** 0.5
percent = 100 * av_diff / av1
percent_sd = 100 * sd_diff / av1
print(
"{:24} {:10.2f} -> {:10.2f} : {:+10.2f} = {:+7.3f}% (+/-{:.2f}%)".format(
name, av1, av2, av_diff, percent, percent_sd
)
)
elif d1[0][0] < d2[0][0]:
d1.pop(0)
else:
d2.pop(0)
def main():
cmd_parser = argparse.ArgumentParser(description="Run benchmarks for MicroPython")
cmd_parser.add_argument(
"-t", "--diff-time", action="store_true", help="diff time outputs from a previous run"
)
cmd_parser.add_argument(
"-s", "--diff-score", action="store_true", help="diff score outputs from a previous run"
)
cmd_parser.add_argument(
"-p", "--pyboard", action="store_true", help="run tests via pyboard.py"
)
cmd_parser.add_argument(
"-d", "--device", default="/dev/ttyACM0", help="the device for pyboard.py"
)
cmd_parser.add_argument("-a", "--average", default="8", help="averaging number")
cmd_parser.add_argument(
"--emit", default="bytecode", help="MicroPython emitter to use (bytecode or native)"
)
cmd_parser.add_argument("N", nargs=1, help="N parameter (approximate target CPU frequency)")
cmd_parser.add_argument("M", nargs=1, help="M parameter (approximate target heap in kbytes)")
cmd_parser.add_argument("files", nargs="*", help="input test files")
args = cmd_parser.parse_args()
if args.diff_time or args.diff_score:
compute_diff(args.N[0], args.M[0], args.diff_score)
sys.exit(0)
# N, M = 50, 25 # esp8266
# N, M = 100, 100 # pyboard, esp32
# N, M = 1000, 1000 # PC
N = int(args.N[0])
M = int(args.M[0])
n_average = int(args.average)
if args.pyboard:
target = pyboard.Pyboard(args.device)
target.enter_raw_repl()
else:
target = [MICROPYTHON, "-X", "emit=" + args.emit]
if len(args.files) == 0:
tests_skip = ("benchrun.py",)
if M <= 25:
# These scripts are too big to be compiled by the target
tests_skip += ("bm_chaos.py", "bm_hexiom.py", "misc_raytrace.py")
tests = sorted(
BENCH_SCRIPT_DIR + test_file
for test_file in os.listdir(BENCH_SCRIPT_DIR)
if test_file.endswith(".py") and test_file not in tests_skip
)
else:
tests = sorted(args.files)
print("N={} M={} n_average={}".format(N, M, n_average))
run_benchmarks(target, N, M, n_average, tests)
if isinstance(target, pyboard.Pyboard):
target.exit_raw_repl()
target.close()
if __name__ == "__main__":
main()
|
YifuLiu/AliOS-Things
|
components/py_engine/tests/run-perfbench.py
|
Python
|
apache-2.0
| 8,890
|
#! /usr/bin/env python3
import os
import subprocess
import sys
import platform
import argparse
import inspect
import re
from glob import glob
import multiprocessing
from multiprocessing.pool import ThreadPool
import threading
import tempfile
# See stackoverflow.com/questions/2632199: __file__ nor sys.argv[0]
# are guaranteed to always work, this one should though.
BASEPATH = os.path.dirname(os.path.abspath(inspect.getsourcefile(lambda: None)))
def base_path(*p):
return os.path.abspath(os.path.join(BASEPATH, *p)).replace("\\", "/")
# Tests require at least CPython 3.3. If your default python3 executable
# is of lower version, you can point MICROPY_CPYTHON3 environment var
# to the correct executable.
if os.name == "nt":
CPYTHON3 = os.getenv("MICROPY_CPYTHON3", "python")
MICROPYTHON = os.getenv("MICROPY_MICROPYTHON", base_path("../ports/windows/micropython.exe"))
else:
CPYTHON3 = os.getenv("MICROPY_CPYTHON3", "python3")
MICROPYTHON = os.getenv("MICROPY_MICROPYTHON", base_path("../ports/unix/micropython"))
# Use CPython options to not save .pyc files, to only access the core standard library
# (not site packages which may clash with u-module names), and improve start up time.
CPYTHON3_CMD = [CPYTHON3, "-BS"]
# mpy-cross is only needed if --via-mpy command-line arg is passed
MPYCROSS = os.getenv("MICROPY_MPYCROSS", base_path("../mpy-cross/mpy-cross"))
# For diff'ing test output
DIFF = os.getenv("MICROPY_DIFF", "diff -u")
# Set PYTHONIOENCODING so that CPython will use utf-8 on systems which set another encoding in the locale
os.environ["PYTHONIOENCODING"] = "utf-8"
def rm_f(fname):
if os.path.exists(fname):
os.remove(fname)
# unescape wanted regex chars and escape unwanted ones
def convert_regex_escapes(line):
cs = []
escape = False
for c in str(line, "utf8"):
if escape:
escape = False
cs.append(c)
elif c == "\\":
escape = True
elif c in ("(", ")", "[", "]", "{", "}", ".", "*", "+", "^", "$"):
cs.append("\\" + c)
else:
cs.append(c)
# accept carriage-return(s) before final newline
if cs[-1] == "\n":
cs[-1] = "\r*\n"
return bytes("".join(cs), "utf8")
def run_micropython(pyb, args, test_file, is_special=False):
special_tests = (
"micropython/meminfo.py",
"basics/bytes_compare3.py",
"basics/builtin_help.py",
"thread/thread_exc2.py",
"esp32/partition_ota.py",
)
had_crash = False
if pyb is None:
# run on PC
if (
test_file.startswith(("cmdline/", base_path("feature_check/")))
or test_file in special_tests
):
# special handling for tests of the unix cmdline program
is_special = True
if is_special:
# check for any cmdline options needed for this test
args = [MICROPYTHON]
with open(test_file, "rb") as f:
line = f.readline()
if line.startswith(b"# cmdline:"):
# subprocess.check_output on Windows only accepts strings, not bytes
args += [str(c, "utf-8") for c in line[10:].strip().split()]
# run the test, possibly with redirected input
try:
if "repl_" in test_file:
# Need to use a PTY to test command line editing
try:
import pty
except ImportError:
# in case pty module is not available, like on Windows
return b"SKIP\n"
import select
def get(required=False):
rv = b""
while True:
ready = select.select([master], [], [], 0.02)
if ready[0] == [master]:
rv += os.read(master, 1024)
else:
if not required or rv:
return rv
def send_get(what):
os.write(master, what)
return get()
with open(test_file, "rb") as f:
# instead of: output_mupy = subprocess.check_output(args, stdin=f)
master, slave = pty.openpty()
p = subprocess.Popen(
args, stdin=slave, stdout=slave, stderr=subprocess.STDOUT, bufsize=0
)
banner = get(True)
output_mupy = banner + b"".join(send_get(line) for line in f)
send_get(b"\x04") # exit the REPL, so coverage info is saved
# At this point the process might have exited already, but trying to
# kill it 'again' normally doesn't result in exceptions as Python and/or
# the OS seem to try to handle this nicely. When running Linux on WSL
# though, the situation differs and calling Popen.kill after the process
# terminated results in a ProcessLookupError. Just catch that one here
# since we just want the process to be gone and that's the case.
try:
p.kill()
except ProcessLookupError:
pass
os.close(master)
os.close(slave)
else:
output_mupy = subprocess.check_output(
args + [test_file], stderr=subprocess.STDOUT
)
except subprocess.CalledProcessError:
return b"CRASH"
else:
# a standard test run on PC
# create system command
cmdlist = [MICROPYTHON, "-X", "emit=" + args.emit]
if args.heapsize is not None:
cmdlist.extend(["-X", "heapsize=" + args.heapsize])
# if running via .mpy, first compile the .py file
if args.via_mpy:
mpy_modname = tempfile.mktemp(dir="")
mpy_filename = mpy_modname + ".mpy"
subprocess.check_output(
[MPYCROSS]
+ args.mpy_cross_flags.split()
+ ["-o", mpy_filename, "-X", "emit=" + args.emit, test_file]
)
cmdlist.extend(["-m", mpy_modname])
else:
cmdlist.append(test_file)
# run the actual test
try:
output_mupy = subprocess.check_output(cmdlist, stderr=subprocess.STDOUT)
except subprocess.CalledProcessError as er:
had_crash = True
output_mupy = er.output + b"CRASH"
# clean up if we had an intermediate .mpy file
if args.via_mpy:
rm_f(mpy_filename)
else:
# run on pyboard
pyb.enter_raw_repl()
try:
output_mupy = pyb.execfile(test_file)
except pyboard.PyboardError as e:
had_crash = True
if not is_special and e.args[0] == "exception":
output_mupy = e.args[1] + e.args[2] + b"CRASH"
else:
output_mupy = bytes(e.args[0], "ascii") + b"\nCRASH"
# canonical form for all ports/platforms is to use \n for end-of-line
output_mupy = output_mupy.replace(b"\r\n", b"\n")
# don't try to convert the output if we should skip this test
if had_crash or output_mupy in (b"SKIP\n", b"CRASH"):
return output_mupy
if is_special or test_file in special_tests:
# convert parts of the output that are not stable across runs
with open(test_file + ".exp", "rb") as f:
lines_exp = []
for line in f.readlines():
if line == b"########\n":
line = (line,)
else:
line = (line, re.compile(convert_regex_escapes(line)))
lines_exp.append(line)
lines_mupy = [line + b"\n" for line in output_mupy.split(b"\n")]
if output_mupy.endswith(b"\n"):
lines_mupy = lines_mupy[:-1] # remove erroneous last empty line
i_mupy = 0
for i in range(len(lines_exp)):
if lines_exp[i][0] == b"########\n":
# 8x #'s means match 0 or more whole lines
line_exp = lines_exp[i + 1]
skip = 0
while i_mupy + skip < len(lines_mupy) and not line_exp[1].match(
lines_mupy[i_mupy + skip]
):
skip += 1
if i_mupy + skip >= len(lines_mupy):
lines_mupy[i_mupy] = b"######## FAIL\n"
break
del lines_mupy[i_mupy : i_mupy + skip]
lines_mupy.insert(i_mupy, b"########\n")
i_mupy += 1
else:
# a regex
if lines_exp[i][1].match(lines_mupy[i_mupy]):
lines_mupy[i_mupy] = lines_exp[i][0]
else:
# print("don't match: %r %s" % (lines_exp[i][1], lines_mupy[i_mupy])) # DEBUG
pass
i_mupy += 1
if i_mupy >= len(lines_mupy):
break
output_mupy = b"".join(lines_mupy)
return output_mupy
def run_feature_check(pyb, args, base_path, test_file):
if pyb is not None and test_file.startswith("repl_"):
# REPL feature tests will not run via pyboard because they require prompt interactivity
return b""
return run_micropython(pyb, args, base_path("feature_check", test_file), is_special=True)
class ThreadSafeCounter:
def __init__(self, start=0):
self._value = start
self._lock = threading.Lock()
def increment(self):
self.add(1)
def add(self, to_add):
with self._lock:
self._value += to_add
def append(self, arg):
self.add([arg])
@property
def value(self):
return self._value
def run_tests(pyb, tests, args, result_dir, num_threads=1):
test_count = ThreadSafeCounter()
testcase_count = ThreadSafeCounter()
passed_count = ThreadSafeCounter()
failed_tests = ThreadSafeCounter([])
skipped_tests = ThreadSafeCounter([])
skip_tests = set()
skip_native = False
skip_int_big = False
skip_bytearray = False
skip_set_type = False
skip_slice = False
skip_async = False
skip_const = False
skip_revops = False
skip_io_module = False
skip_fstring = False
skip_endian = False
has_complex = True
has_coverage = False
upy_float_precision = 32
# If we're asked to --list-tests, we can't assume that there's a
# connection to target, so we can't run feature checks usefully.
if not (args.list_tests or args.write_exp):
# Even if we run completely different tests in a different directory,
# we need to access feature_checks from the same directory as the
# run-tests.py script itself so use base_path.
# Check if micropython.native is supported, and skip such tests if it's not
output = run_feature_check(pyb, args, base_path, "native_check.py")
if output != b"native\n":
skip_native = True
# Check if arbitrary-precision integers are supported, and skip such tests if it's not
output = run_feature_check(pyb, args, base_path, "int_big.py")
if output != b"1000000000000000000000000000000000000000000000\n":
skip_int_big = True
# Check if bytearray is supported, and skip such tests if it's not
output = run_feature_check(pyb, args, base_path, "bytearray.py")
if output != b"bytearray\n":
skip_bytearray = True
# Check if set type (and set literals) is supported, and skip such tests if it's not
output = run_feature_check(pyb, args, base_path, "set_check.py")
if output != b"{1}\n":
skip_set_type = True
# Check if slice is supported, and skip such tests if it's not
output = run_feature_check(pyb, args, base_path, "slice.py")
if output != b"slice\n":
skip_slice = True
# Check if async/await keywords are supported, and skip such tests if it's not
output = run_feature_check(pyb, args, base_path, "async_check.py")
if output != b"async\n":
skip_async = True
# Check if const keyword (MicroPython extension) is supported, and skip such tests if it's not
output = run_feature_check(pyb, args, base_path, "const.py")
if output != b"1\n":
skip_const = True
# Check if __rOP__ special methods are supported, and skip such tests if it's not
output = run_feature_check(pyb, args, base_path, "reverse_ops.py")
if output == b"TypeError\n":
skip_revops = True
# Check if uio module exists, and skip such tests if it doesn't
output = run_feature_check(pyb, args, base_path, "uio_module.py")
if output != b"uio\n":
skip_io_module = True
# Check if fstring feature is enabled, and skip such tests if it doesn't
output = run_feature_check(pyb, args, base_path, "fstring.py")
if output != b"a=1\n":
skip_fstring = True
# Check if emacs repl is supported, and skip such tests if it's not
t = run_feature_check(pyb, args, base_path, "repl_emacs_check.py")
if "True" not in str(t, "ascii"):
skip_tests.add("cmdline/repl_emacs_keys.py")
# Check if words movement in repl is supported, and skip such tests if it's not
t = run_feature_check(pyb, args, base_path, "repl_words_move_check.py")
if "True" not in str(t, "ascii"):
skip_tests.add("cmdline/repl_words_move.py")
upy_byteorder = run_feature_check(pyb, args, base_path, "byteorder.py")
upy_float_precision = run_feature_check(pyb, args, base_path, "float.py")
try:
upy_float_precision = int(upy_float_precision)
except ValueError:
upy_float_precision = 0
has_complex = run_feature_check(pyb, args, base_path, "complex.py") == b"complex\n"
has_coverage = run_feature_check(pyb, args, base_path, "coverage.py") == b"coverage\n"
cpy_byteorder = subprocess.check_output(
CPYTHON3_CMD + [base_path("feature_check/byteorder.py")]
)
skip_endian = upy_byteorder != cpy_byteorder
# These tests don't test slice explicitly but rather use it to perform the test
misc_slice_tests = (
"builtin_range",
"class_super",
"containment",
"errno1",
"fun_str",
"generator1",
"globals_del",
"memoryview1",
"memoryview_gc",
"object1",
"python34",
"struct_endian",
)
# Some tests shouldn't be run on GitHub Actions
if os.getenv("GITHUB_ACTIONS") == "true":
skip_tests.add("thread/stress_schedule.py") # has reliability issues
if upy_float_precision == 0:
skip_tests.add("extmod/uctypes_le_float.py")
skip_tests.add("extmod/uctypes_native_float.py")
skip_tests.add("extmod/uctypes_sizeof_float.py")
skip_tests.add("extmod/ujson_dumps_float.py")
skip_tests.add("extmod/ujson_loads_float.py")
skip_tests.add("extmod/urandom_extra_float.py")
skip_tests.add("misc/rge_sm.py")
if upy_float_precision < 32:
skip_tests.add(
"float/float2int_intbig.py"
) # requires fp32, there's float2int_fp30_intbig.py instead
skip_tests.add(
"float/string_format.py"
) # requires fp32, there's string_format_fp30.py instead
skip_tests.add("float/bytes_construct.py") # requires fp32
skip_tests.add("float/bytearray_construct.py") # requires fp32
if upy_float_precision < 64:
skip_tests.add("float/float_divmod.py") # tested by float/float_divmod_relaxed.py instead
skip_tests.add("float/float2int_doubleprec_intbig.py")
skip_tests.add("float/float_parse_doubleprec.py")
if not has_complex:
skip_tests.add("float/complex1.py")
skip_tests.add("float/complex1_intbig.py")
skip_tests.add("float/complex_special_methods.py")
skip_tests.add("float/int_big_float.py")
skip_tests.add("float/true_value.py")
skip_tests.add("float/types.py")
if not has_coverage:
skip_tests.add("cmdline/cmd_parsetree.py")
# Some tests shouldn't be run on a PC
if args.target == "unix":
# unix build does not have the GIL so can't run thread mutation tests
for t in tests:
if t.startswith("thread/mutate_"):
skip_tests.add(t)
# Some tests shouldn't be run on pyboard
if args.target != "unix":
skip_tests.add("basics/exception_chain.py") # warning is not printed
skip_tests.add("micropython/meminfo.py") # output is very different to PC output
skip_tests.add("extmod/machine_mem.py") # raw memory access not supported
if args.target == "wipy":
skip_tests.add("misc/print_exception.py") # requires error reporting full
skip_tests.update(
{
"extmod/uctypes_%s.py" % t
for t in "bytearray le native_le ptr_le ptr_native_le sizeof sizeof_native array_assign_le array_assign_native_le".split()
}
) # requires uctypes
skip_tests.add("extmod/zlibd_decompress.py") # requires zlib
skip_tests.add("extmod/uheapq1.py") # uheapq not supported by WiPy
skip_tests.add("extmod/urandom_basic.py") # requires urandom
skip_tests.add("extmod/urandom_extra.py") # requires urandom
elif args.target == "esp8266":
skip_tests.add("misc/rge_sm.py") # too large
elif args.target == "minimal":
skip_tests.add("basics/class_inplace_op.py") # all special methods not supported
skip_tests.add(
"basics/subclass_native_init.py"
) # native subclassing corner cases not support
skip_tests.add("misc/rge_sm.py") # too large
skip_tests.add("micropython/opt_level.py") # don't assume line numbers are stored
elif args.target == "nrf":
skip_tests.add("basics/memoryview1.py") # no item assignment for memoryview
skip_tests.add("extmod/urandom_basic.py") # unimplemented: urandom.seed
skip_tests.add("micropython/opt_level.py") # no support for line numbers
skip_tests.add("misc/non_compliant.py") # no item assignment for bytearray
for t in tests:
if t.startswith("basics/io_"):
skip_tests.add(t)
elif args.target == "qemu-arm":
skip_tests.add("misc/print_exception.py") # requires sys stdfiles
# Some tests are known to fail on 64-bit machines
if pyb is None and platform.architecture()[0] == "64bit":
pass
# Some tests use unsupported features on Windows
if os.name == "nt":
skip_tests.add("import/import_file.py") # works but CPython prints forward slashes
# Some tests are known to fail with native emitter
# Remove them from the below when they work
if args.emit == "native":
skip_tests.update(
{"basics/%s.py" % t for t in "gen_yield_from_close generator_name".split()}
) # require raise_varargs, generator name
skip_tests.update(
{"basics/async_%s.py" % t for t in "with with2 with_break with_return".split()}
) # require async_with
skip_tests.update(
{"basics/%s.py" % t for t in "try_reraise try_reraise2".split()}
) # require raise_varargs
skip_tests.add("basics/annotate_var.py") # requires checking for unbound local
skip_tests.add("basics/del_deref.py") # requires checking for unbound local
skip_tests.add("basics/del_local.py") # requires checking for unbound local
skip_tests.add("basics/exception_chain.py") # raise from is not supported
skip_tests.add("basics/scope_implicit.py") # requires checking for unbound local
skip_tests.add("basics/try_finally_return2.py") # requires raise_varargs
skip_tests.add("basics/unboundlocal.py") # requires checking for unbound local
skip_tests.add("extmod/uasyncio_event.py") # unknown issue
skip_tests.add("extmod/uasyncio_lock.py") # requires async with
skip_tests.add("extmod/uasyncio_micropython.py") # unknown issue
skip_tests.add("extmod/uasyncio_wait_for.py") # unknown issue
skip_tests.add("misc/features.py") # requires raise_varargs
skip_tests.add(
"misc/print_exception.py"
) # because native doesn't have proper traceback info
skip_tests.add("misc/sys_exc_info.py") # sys.exc_info() is not supported for native
skip_tests.add(
"micropython/emg_exc.py"
) # because native doesn't have proper traceback info
skip_tests.add(
"micropython/heapalloc_traceback.py"
) # because native doesn't have proper traceback info
skip_tests.add(
"micropython/opt_level_lineno.py"
) # native doesn't have proper traceback info
skip_tests.add("micropython/schedule.py") # native code doesn't check pending events
def run_one_test(test_file):
test_file = test_file.replace("\\", "/")
if args.filters:
# Default verdict is the opposit of the first action
verdict = "include" if args.filters[0][0] == "exclude" else "exclude"
for action, pat in args.filters:
if pat.search(test_file):
verdict = action
if verdict == "exclude":
return
test_basename = test_file.replace("..", "_").replace("./", "").replace("/", "_")
test_name = os.path.splitext(os.path.basename(test_file))[0]
is_native = (
test_name.startswith("native_")
or test_name.startswith("viper_")
or args.emit == "native"
)
is_endian = test_name.endswith("_endian")
is_int_big = test_name.startswith("int_big") or test_name.endswith("_intbig")
is_bytearray = test_name.startswith("bytearray") or test_name.endswith("_bytearray")
is_set_type = test_name.startswith("set_") or test_name.startswith("frozenset")
is_slice = test_name.find("slice") != -1 or test_name in misc_slice_tests
is_async = test_name.startswith(("async_", "uasyncio_"))
is_const = test_name.startswith("const")
is_io_module = test_name.startswith("io_")
is_fstring = test_name.startswith("string_fstring")
skip_it = test_file in skip_tests
skip_it |= skip_native and is_native
skip_it |= skip_endian and is_endian
skip_it |= skip_int_big and is_int_big
skip_it |= skip_bytearray and is_bytearray
skip_it |= skip_set_type and is_set_type
skip_it |= skip_slice and is_slice
skip_it |= skip_async and is_async
skip_it |= skip_const and is_const
skip_it |= skip_revops and "reverse_op" in test_name
skip_it |= skip_io_module and is_io_module
skip_it |= skip_fstring and is_fstring
if args.list_tests:
if not skip_it:
print(test_file)
return
if skip_it:
print("skip ", test_file)
skipped_tests.append(test_name)
return
# get expected output
test_file_expected = test_file + ".exp"
if os.path.isfile(test_file_expected):
# expected output given by a file, so read that in
with open(test_file_expected, "rb") as f:
output_expected = f.read()
else:
# run CPython to work out expected output
try:
output_expected = subprocess.check_output(CPYTHON3_CMD + [test_file])
if args.write_exp:
with open(test_file_expected, "wb") as f:
f.write(output_expected)
except subprocess.CalledProcessError:
output_expected = b"CPYTHON3 CRASH"
# canonical form for all host platforms is to use \n for end-of-line
output_expected = output_expected.replace(b"\r\n", b"\n")
if args.write_exp:
return
# run MicroPython
output_mupy = run_micropython(pyb, args, test_file)
if output_mupy == b"SKIP\n":
print("skip ", test_file)
skipped_tests.append(test_name)
return
testcase_count.add(len(output_expected.splitlines()))
filename_expected = os.path.join(result_dir, test_basename + ".exp")
filename_mupy = os.path.join(result_dir, test_basename + ".out")
if output_expected == output_mupy:
print("pass ", test_file)
passed_count.increment()
rm_f(filename_expected)
rm_f(filename_mupy)
else:
with open(filename_expected, "wb") as f:
f.write(output_expected)
with open(filename_mupy, "wb") as f:
f.write(output_mupy)
print("FAIL ", test_file)
failed_tests.append(test_name)
test_count.increment()
if pyb or args.list_tests:
num_threads = 1
if num_threads > 1:
pool = ThreadPool(num_threads)
pool.map(run_one_test, tests)
else:
for test in tests:
run_one_test(test)
if args.list_tests:
return True
print(
"{} tests performed ({} individual testcases)".format(
test_count.value, testcase_count.value
)
)
print("{} tests passed".format(passed_count.value))
skipped_tests = sorted(skipped_tests.value)
if len(skipped_tests) > 0:
print("{} tests skipped: {}".format(len(skipped_tests), " ".join(skipped_tests)))
failed_tests = sorted(failed_tests.value)
if len(failed_tests) > 0:
print("{} tests failed: {}".format(len(failed_tests), " ".join(failed_tests)))
return False
# all tests succeeded
return True
class append_filter(argparse.Action):
def __init__(self, option_strings, dest, **kwargs):
super().__init__(option_strings, dest, default=[], **kwargs)
def __call__(self, parser, args, value, option):
if not hasattr(args, self.dest):
args.filters = []
if option.startswith(("-e", "--e")):
option = "exclude"
else:
option = "include"
args.filters.append((option, re.compile(value)))
def main():
cmd_parser = argparse.ArgumentParser(
formatter_class=argparse.RawDescriptionHelpFormatter,
description="""Run and manage tests for MicroPython.
Tests are discovered by scanning test directories for .py files or using the
specified test files. If test files nor directories are specified, the script
expects to be ran in the tests directory (where this file is located) and the
builtin tests suitable for the target platform are ran.
When running tests, run-tests.py compares the MicroPython output of the test with the output
produced by running the test through CPython unless a <test>.exp file is found, in which
case it is used as comparison.
If a test fails, run-tests.py produces a pair of <test>.out and <test>.exp files in the result
directory with the MicroPython output and the expectations, respectively.
""",
epilog="""\
Options -i and -e can be multiple and processed in the order given. Regex
"search" (vs "match") operation is used. An action (include/exclude) of
the last matching regex is used:
run-tests.py -i async - exclude all, then include tests containing "async" anywhere
run-tests.py -e '/big.+int' - include all, then exclude by regex
run-tests.py -e async -i async_foo - include all, exclude async, yet still include async_foo
""",
)
cmd_parser.add_argument("--target", default="unix", help="the target platform")
cmd_parser.add_argument(
"--device",
default="/dev/ttyACM0",
help="the serial device or the IP address of the pyboard",
)
cmd_parser.add_argument(
"-b", "--baudrate", default=115200, help="the baud rate of the serial device"
)
cmd_parser.add_argument("-u", "--user", default="micro", help="the telnet login username")
cmd_parser.add_argument("-p", "--password", default="python", help="the telnet login password")
cmd_parser.add_argument(
"-d", "--test-dirs", nargs="*", help="input test directories (if no files given)"
)
cmd_parser.add_argument(
"-r", "--result-dir", default=base_path("results"), help="directory for test results"
)
cmd_parser.add_argument(
"-e",
"--exclude",
action=append_filter,
metavar="REGEX",
dest="filters",
help="exclude test by regex on path/name.py",
)
cmd_parser.add_argument(
"-i",
"--include",
action=append_filter,
metavar="REGEX",
dest="filters",
help="include test by regex on path/name.py",
)
cmd_parser.add_argument(
"--write-exp",
action="store_true",
help="use CPython to generate .exp files to run tests w/o CPython",
)
cmd_parser.add_argument(
"--list-tests", action="store_true", help="list tests instead of running them"
)
cmd_parser.add_argument(
"--emit", default="bytecode", help="MicroPython emitter to use (bytecode or native)"
)
cmd_parser.add_argument("--heapsize", help="heapsize to use (use default if not specified)")
cmd_parser.add_argument(
"--via-mpy", action="store_true", help="compile .py files to .mpy first"
)
cmd_parser.add_argument(
"--mpy-cross-flags", default="-mcache-lookup-bc", help="flags to pass to mpy-cross"
)
cmd_parser.add_argument(
"--keep-path", action="store_true", help="do not clear MICROPYPATH when running tests"
)
cmd_parser.add_argument(
"-j",
"--jobs",
default=multiprocessing.cpu_count(),
metavar="N",
type=int,
help="Number of tests to run simultaneously",
)
cmd_parser.add_argument("files", nargs="*", help="input test files")
cmd_parser.add_argument(
"--print-failures",
action="store_true",
help="print the diff of expected vs. actual output for failed tests and exit",
)
cmd_parser.add_argument(
"--clean-failures",
action="store_true",
help="delete the .exp and .out files from failed tests and exit",
)
args = cmd_parser.parse_args()
if args.print_failures:
for exp in glob(os.path.join(args.result_dir, "*.exp")):
testbase = exp[:-4]
print()
print("FAILURE {0}".format(testbase))
os.system("{0} {1}.exp {1}.out".format(DIFF, testbase))
sys.exit(0)
if args.clean_failures:
for f in glob(os.path.join(args.result_dir, "*.exp")) + glob(
os.path.join(args.result_dir, "*.out")
):
os.remove(f)
sys.exit(0)
LOCAL_TARGETS = (
"unix",
"qemu-arm",
)
EXTERNAL_TARGETS = ("pyboard", "wipy", "esp8266", "esp32", "minimal", "nrf")
if args.target in LOCAL_TARGETS or args.list_tests:
pyb = None
elif args.target in EXTERNAL_TARGETS:
global pyboard
sys.path.append(base_path("../tools"))
import pyboard
pyb = pyboard.Pyboard(args.device, args.baudrate, args.user, args.password)
pyb.enter_raw_repl()
else:
raise ValueError("target must be one of %s" % ", ".join(LOCAL_TARGETS + EXTERNAL_TARGETS))
if len(args.files) == 0:
if args.test_dirs is None:
test_dirs = (
"basics",
"micropython",
"misc",
"extmod",
)
if args.target == "pyboard":
# run pyboard tests
test_dirs += ("float", "stress", "pyb", "pybnative", "inlineasm")
elif args.target in ("esp8266", "esp32", "minimal", "nrf"):
test_dirs += ("float",)
elif args.target == "wipy":
# run WiPy tests
test_dirs += ("wipy",)
elif args.target == "unix":
# run PC tests
test_dirs += (
"float",
"import",
"io",
"stress",
"unicode",
"unix",
"cmdline",
)
elif args.target == "qemu-arm":
if not args.write_exp:
raise ValueError("--target=qemu-arm must be used with --write-exp")
# Generate expected output files for qemu run.
# This list should match the test_dirs tuple in tinytest-codegen.py.
test_dirs += (
"float",
"inlineasm",
"qemu-arm",
)
else:
# run tests from these directories
test_dirs = args.test_dirs
tests = sorted(
test_file
for test_files in (glob("{}/*.py".format(dir)) for dir in test_dirs)
for test_file in test_files
)
else:
# tests explicitly given
tests = args.files
if not args.keep_path:
# clear search path to make sure tests use only builtin modules and those in extmod
os.environ["MICROPYPATH"] = os.pathsep + base_path("../extmod")
try:
os.makedirs(args.result_dir, exist_ok=True)
res = run_tests(pyb, tests, args, args.result_dir, args.jobs)
finally:
if pyb:
pyb.close()
if not res:
sys.exit(1)
if __name__ == "__main__":
main()
|
YifuLiu/AliOS-Things
|
components/py_engine/tests/run-tests.py
|
Python
|
apache-2.0
| 34,439
|
# copying a large dictionary
a = {i: 2 * i for i in range(1000)}
b = a.copy()
for i in range(1000):
print(i, b[i])
print(len(b))
|
YifuLiu/AliOS-Things
|
components/py_engine/tests/stress/dict_copy.py
|
Python
|
apache-2.0
| 134
|
# create a large dictionary
d = {}
x = 1
while x < 1000:
d[x] = x
x += 1
print(d[500])
|
YifuLiu/AliOS-Things
|
components/py_engine/tests/stress/dict_create.py
|
Python
|
apache-2.0
| 96
|
# The aim with this test is to hit the maximum resize/rehash size of a dict,
# where there are no more primes in the table of growing allocation sizes.
# This value is 54907 items.
d = {}
try:
for i in range(54908):
d[i] = i
except MemoryError:
pass
# Just check the dict still has the first value
print(d[0])
|
YifuLiu/AliOS-Things
|
components/py_engine/tests/stress/dict_create_max.py
|
Python
|
apache-2.0
| 328
|
# test that the GC can trace nested objects
try:
import gc
except ImportError:
print("SKIP")
raise SystemExit
# test a big shallow object pointing to many unique objects
lst = [[i] for i in range(200)]
gc.collect()
print(lst)
# test a deep object
lst = [
[[[[(i, j, k, l)] for i in range(3)] for j in range(3)] for k in range(3)] for l in range(3)
]
gc.collect()
print(lst)
|
YifuLiu/AliOS-Things
|
components/py_engine/tests/stress/gc_trace.py
|
Python
|
apache-2.0
| 393
|
# test large list sorting (should not stack overflow)
l = list(range(2000))
l.sort()
print(l[0], l[-1])
l.sort(reverse=True)
print(l[0], l[-1])
|
YifuLiu/AliOS-Things
|
components/py_engine/tests/stress/list_sort.py
|
Python
|
apache-2.0
| 144
|
# Test interning qstrs that go over the limit of the maximum qstr length
# (which is 255 bytes for the default configuration)
def make_id(n, base="a"):
return "".join(chr(ord(base) + i % 26) for i in range(n))
# identifiers in parser
for l in range(254, 259):
g = {}
var = make_id(l)
try:
exec(var + "=1", g)
except RuntimeError:
print("RuntimeError", l)
continue
print(var in g)
# calling a function with kwarg
def f(**k):
print(k)
for l in range(254, 259):
try:
exec("f({}=1)".format(make_id(l)))
except RuntimeError:
print("RuntimeError", l)
# type construction
for l in range(254, 259):
id = make_id(l)
try:
print(type(id, (), {}).__name__)
except RuntimeError:
print("RuntimeError", l)
# hasattr, setattr, getattr
class A:
pass
for l in range(254, 259):
id = make_id(l)
a = A()
try:
setattr(a, id, 123)
except RuntimeError:
print("RuntimeError", l)
try:
print(hasattr(a, id), getattr(a, id))
except RuntimeError:
print("RuntimeError", l)
# format with keys
for l in range(254, 259):
id = make_id(l)
try:
print(("{" + id + "}").format(**{id: l}))
except RuntimeError:
print("RuntimeError", l)
# modulo format with keys
for l in range(254, 259):
id = make_id(l)
try:
print(("%(" + id + ")d") % {id: l})
except RuntimeError:
print("RuntimeError", l)
# import module
# (different OS's have different results so only run those that are consistent)
for l in (100, 101, 256, 257, 258):
try:
__import__(make_id(l))
except ImportError:
print("ok", l)
except RuntimeError:
print("RuntimeError", l)
# import package
for l in (100, 101, 102, 128, 129):
try:
exec("import " + make_id(l) + "." + make_id(l, "A"))
except ImportError:
print("ok", l)
except RuntimeError:
print("RuntimeError", l)
|
YifuLiu/AliOS-Things
|
components/py_engine/tests/stress/qstr_limit.py
|
Python
|
apache-2.0
| 1,992
|
def foo():
foo()
try:
foo()
except RuntimeError:
print("RuntimeError")
|
YifuLiu/AliOS-Things
|
components/py_engine/tests/stress/recursion.py
|
Python
|
apache-2.0
| 85
|
# This tests that printing recursive data structure doesn't lead to segfault.
try:
import uio as io
except ImportError:
print("SKIP")
raise SystemExit
l = [1, 2, 3, None]
l[-1] = l
try:
print(l, file=io.StringIO())
except RuntimeError:
print("RuntimeError")
|
YifuLiu/AliOS-Things
|
components/py_engine/tests/stress/recursive_data.py
|
Python
|
apache-2.0
| 279
|
# test deeply recursive generators
# simple "yield from" recursion
def gen():
yield from gen()
try:
list(gen())
except RuntimeError:
print("RuntimeError")
# recursion via an iterator over a generator
def gen2():
for x in gen2():
yield x
try:
next(gen2())
except RuntimeError:
print("RuntimeError")
|
YifuLiu/AliOS-Things
|
components/py_engine/tests/stress/recursive_gen.py
|
Python
|
apache-2.0
| 336
|
# This tests that recursion with iternext doesn't lead to segfault.
try:
enumerate
filter
map
max
zip
except:
print("SKIP")
raise SystemExit
# We need to pick an N that is large enough to hit the recursion
# limit, but not too large that we run out of heap memory.
try:
# large stack/heap, eg unix
[0] * 80000
N = 5000
except:
try:
# medium, eg pyboard
[0] * 10000
N = 1000
except:
# small, eg esp8266
N = 100
try:
x = (1, 2)
for i in range(N):
x = enumerate(x)
tuple(x)
except RuntimeError:
print("RuntimeError")
try:
x = (1, 2)
for i in range(N):
x = filter(None, x)
tuple(x)
except RuntimeError:
print("RuntimeError")
try:
x = (1, 2)
for i in range(N):
x = map(max, x, ())
tuple(x)
except RuntimeError:
print("RuntimeError")
try:
x = (1, 2)
for i in range(N):
x = zip(x)
tuple(x)
except RuntimeError:
print("RuntimeError")
|
YifuLiu/AliOS-Things
|
components/py_engine/tests/stress/recursive_iternext.py
|
Python
|
apache-2.0
| 1,015
|
# test concurrent mutating access to a shared bytearray object
#
# MIT license; Copyright (c) 2016 Damien P. George on behalf of Pycom Ltd
import _thread
# the shared bytearray
ba = bytearray()
# main thread function
def th(n, lo, hi):
for repeat in range(n):
for i in range(lo, hi):
l = len(ba)
ba.append(i)
assert len(ba) >= l + 1
l = len(ba)
ba.extend(bytearray([i]))
assert len(ba) >= l + 1
with lock:
global n_finished
n_finished += 1
lock = _thread.allocate_lock()
n_thread = 4
n_finished = 0
n_repeat = 4 # use 40 for more stressful test (uses more heap)
# spawn threads
for i in range(n_thread):
_thread.start_new_thread(th, (n_repeat, i * 256 // n_thread, (i + 1) * 256 // n_thread))
# busy wait for threads to finish
while n_finished < n_thread:
pass
# check bytearray has correct contents
print(len(ba))
count = [0 for _ in range(256)]
for b in ba:
count[b] += 1
print(count)
|
YifuLiu/AliOS-Things
|
components/py_engine/tests/thread/mutate_bytearray.py
|
Python
|
apache-2.0
| 1,014
|
# test concurrent mutating access to a shared dict object
#
# MIT license; Copyright (c) 2016 Damien P. George on behalf of Pycom Ltd
import _thread
# the shared dict
di = {"a": "A", "b": "B", "c": "C", "d": "D"}
# main thread function
def th(n, lo, hi):
for repeat in range(n):
for i in range(lo, hi):
di[i] = repeat + i
assert di[i] == repeat + i
del di[i]
assert i not in di
di[i] = repeat + i
assert di[i] == repeat + i
assert di.pop(i) == repeat + i
with lock:
global n_finished
n_finished += 1
lock = _thread.allocate_lock()
n_thread = 4
n_finished = 0
# spawn threads
for i in range(n_thread):
_thread.start_new_thread(th, (30, i * 300, (i + 1) * 300))
# busy wait for threads to finish
while n_finished < n_thread:
pass
# check dict has correct contents
print(sorted(di.items()))
|
YifuLiu/AliOS-Things
|
components/py_engine/tests/thread/mutate_dict.py
|
Python
|
apache-2.0
| 924
|
# test concurrent mutating access to a shared user instance
#
# MIT license; Copyright (c) 2016 Damien P. George on behalf of Pycom Ltd
import _thread
# the shared user class and instance
class User:
def __init__(self):
self.a = "A"
self.b = "B"
self.c = "C"
user = User()
# main thread function
def th(n, lo, hi):
for repeat in range(n):
for i in range(lo, hi):
setattr(user, "attr_%u" % i, repeat + i)
assert getattr(user, "attr_%u" % i) == repeat + i
with lock:
global n_finished
n_finished += 1
lock = _thread.allocate_lock()
n_repeat = 30
n_range = 50 # 300 for stressful test (uses more heap)
n_thread = 4
n_finished = 0
# spawn threads
for i in range(n_thread):
_thread.start_new_thread(th, (n_repeat, i * n_range, (i + 1) * n_range))
# busy wait for threads to finish
while n_finished < n_thread:
pass
# check user instance has correct contents
print(user.a, user.b, user.c)
for i in range(n_thread * n_range):
assert getattr(user, "attr_%u" % i) == n_repeat - 1 + i
|
YifuLiu/AliOS-Things
|
components/py_engine/tests/thread/mutate_instance.py
|
Python
|
apache-2.0
| 1,083
|
# test concurrent mutating access to a shared list object
#
# MIT license; Copyright (c) 2016 Damien P. George on behalf of Pycom Ltd
import _thread
# the shared list
li = list()
# main thread function
def th(n, lo, hi):
for repeat in range(n):
for i in range(lo, hi):
li.append(i)
assert li.count(i) == repeat + 1
li.extend([i, i])
assert li.count(i) == repeat + 3
li.remove(i)
assert li.count(i) == repeat + 2
li.remove(i)
assert li.count(i) == repeat + 1
with lock:
global n_finished
n_finished += 1
lock = _thread.allocate_lock()
n_thread = 4
n_finished = 0
# spawn threads
for i in range(n_thread):
_thread.start_new_thread(th, (4, i * 60, (i + 1) * 60))
# busy wait for threads to finish
while n_finished < n_thread:
pass
# check list has correct contents
li.sort()
print(li)
|
YifuLiu/AliOS-Things
|
components/py_engine/tests/thread/mutate_list.py
|
Python
|
apache-2.0
| 930
|
# test concurrent mutating access to a shared set object
#
# MIT license; Copyright (c) 2016 Damien P. George on behalf of Pycom Ltd
import _thread
# the shared set
se = set([-1, -2, -3, -4])
# main thread function
def th(n, lo, hi):
for repeat in range(n):
for i in range(lo, hi):
se.add(i)
assert i in se
se.remove(i)
assert i not in se
with lock:
global n_finished
n_finished += 1
lock = _thread.allocate_lock()
n_thread = 4
n_finished = 0
# spawn threads
for i in range(n_thread):
_thread.start_new_thread(th, (50, i * 500, (i + 1) * 500))
# busy wait for threads to finish
while n_finished < n_thread:
pass
# check set has correct contents
print(sorted(se))
|
YifuLiu/AliOS-Things
|
components/py_engine/tests/thread/mutate_set.py
|
Python
|
apache-2.0
| 761
|
# Stress test for threads using AES encryption routines.
#
# AES was chosen because it is integer based and inplace so doesn't use the
# heap. It is therefore a good test of raw performance and correctness of the
# VM/runtime. It can be used to measure threading performance (concurrency is
# in principle possible) and correctness (it's non trivial for the encryption/
# decryption to give the correct answer).
#
# The AES code comes first (code originates from a C version authored by D.P.George)
# and then the test harness at the bottom. It can be tuned to be more/less
# aggressive by changing the amount of data to encrypt, the number of loops and
# the number of threads.
#
# MIT license; Copyright (c) 2016 Damien P. George on behalf of Pycom Ltd
##################################################################
# discrete arithmetic routines, mostly from a precomputed table
# non-linear, invertible, substitution box
# fmt: off
aes_s_box_table = bytes((
0x63,0x7c,0x77,0x7b,0xf2,0x6b,0x6f,0xc5,0x30,0x01,0x67,0x2b,0xfe,0xd7,0xab,0x76,
0xca,0x82,0xc9,0x7d,0xfa,0x59,0x47,0xf0,0xad,0xd4,0xa2,0xaf,0x9c,0xa4,0x72,0xc0,
0xb7,0xfd,0x93,0x26,0x36,0x3f,0xf7,0xcc,0x34,0xa5,0xe5,0xf1,0x71,0xd8,0x31,0x15,
0x04,0xc7,0x23,0xc3,0x18,0x96,0x05,0x9a,0x07,0x12,0x80,0xe2,0xeb,0x27,0xb2,0x75,
0x09,0x83,0x2c,0x1a,0x1b,0x6e,0x5a,0xa0,0x52,0x3b,0xd6,0xb3,0x29,0xe3,0x2f,0x84,
0x53,0xd1,0x00,0xed,0x20,0xfc,0xb1,0x5b,0x6a,0xcb,0xbe,0x39,0x4a,0x4c,0x58,0xcf,
0xd0,0xef,0xaa,0xfb,0x43,0x4d,0x33,0x85,0x45,0xf9,0x02,0x7f,0x50,0x3c,0x9f,0xa8,
0x51,0xa3,0x40,0x8f,0x92,0x9d,0x38,0xf5,0xbc,0xb6,0xda,0x21,0x10,0xff,0xf3,0xd2,
0xcd,0x0c,0x13,0xec,0x5f,0x97,0x44,0x17,0xc4,0xa7,0x7e,0x3d,0x64,0x5d,0x19,0x73,
0x60,0x81,0x4f,0xdc,0x22,0x2a,0x90,0x88,0x46,0xee,0xb8,0x14,0xde,0x5e,0x0b,0xdb,
0xe0,0x32,0x3a,0x0a,0x49,0x06,0x24,0x5c,0xc2,0xd3,0xac,0x62,0x91,0x95,0xe4,0x79,
0xe7,0xc8,0x37,0x6d,0x8d,0xd5,0x4e,0xa9,0x6c,0x56,0xf4,0xea,0x65,0x7a,0xae,0x08,
0xba,0x78,0x25,0x2e,0x1c,0xa6,0xb4,0xc6,0xe8,0xdd,0x74,0x1f,0x4b,0xbd,0x8b,0x8a,
0x70,0x3e,0xb5,0x66,0x48,0x03,0xf6,0x0e,0x61,0x35,0x57,0xb9,0x86,0xc1,0x1d,0x9e,
0xe1,0xf8,0x98,0x11,0x69,0xd9,0x8e,0x94,0x9b,0x1e,0x87,0xe9,0xce,0x55,0x28,0xdf,
0x8c,0xa1,0x89,0x0d,0xbf,0xe6,0x42,0x68,0x41,0x99,0x2d,0x0f,0xb0,0x54,0xbb,0x16,
))
# fmt: on
# multiplication of polynomials modulo x^8 + x^4 + x^3 + x + 1 = 0x11b
def aes_gf8_mul_2(x):
if x & 0x80:
return (x << 1) ^ 0x11B
else:
return x << 1
def aes_gf8_mul_3(x):
return x ^ aes_gf8_mul_2(x)
# non-linear, invertible, substitution box
def aes_s_box(a):
return aes_s_box_table[a & 0xFF]
# return 0x02^(a-1) in GF(2^8)
def aes_r_con(a):
ans = 1
while a > 1:
ans <<= 1
if ans & 0x100:
ans ^= 0x11B
a -= 1
return ans
##################################################################
# basic AES algorithm; see FIPS-197
#
# Think of it as a pseudo random number generator, with each
# symbol in the sequence being a 16 byte block (the state). The
# key is a parameter of the algorithm and tells which particular
# sequence of random symbols you want. The initial vector, IV,
# sets the start of the sequence. The idea of a strong cipher
# is that it's very difficult to guess the key even if you know
# a large part of the sequence. The basic AES algorithm simply
# provides such a sequence. En/de-cryption is implemented here
# using OCB, where the sequence is xored against the plaintext.
# Care must be taken to (almost) always choose a different IV.
# all inputs must be size 16
def aes_add_round_key(state, w):
for i in range(16):
state[i] ^= w[i]
# combined sub_bytes, shift_rows, mix_columns, add_round_key
# all inputs must be size 16
def aes_sb_sr_mc_ark(state, w, w_idx, temp):
temp_idx = 0
for i in range(4):
x0 = aes_s_box_table[state[i * 4]]
x1 = aes_s_box_table[state[1 + ((i + 1) & 3) * 4]]
x2 = aes_s_box_table[state[2 + ((i + 2) & 3) * 4]]
x3 = aes_s_box_table[state[3 + ((i + 3) & 3) * 4]]
temp[temp_idx] = aes_gf8_mul_2(x0) ^ aes_gf8_mul_3(x1) ^ x2 ^ x3 ^ w[w_idx]
temp[temp_idx + 1] = x0 ^ aes_gf8_mul_2(x1) ^ aes_gf8_mul_3(x2) ^ x3 ^ w[w_idx + 1]
temp[temp_idx + 2] = x0 ^ x1 ^ aes_gf8_mul_2(x2) ^ aes_gf8_mul_3(x3) ^ w[w_idx + 2]
temp[temp_idx + 3] = aes_gf8_mul_3(x0) ^ x1 ^ x2 ^ aes_gf8_mul_2(x3) ^ w[w_idx + 3]
w_idx += 4
temp_idx += 4
for i in range(16):
state[i] = temp[i]
# combined sub_bytes, shift_rows, add_round_key
# all inputs must be size 16
def aes_sb_sr_ark(state, w, w_idx, temp):
temp_idx = 0
for i in range(4):
x0 = aes_s_box_table[state[i * 4]]
x1 = aes_s_box_table[state[1 + ((i + 1) & 3) * 4]]
x2 = aes_s_box_table[state[2 + ((i + 2) & 3) * 4]]
x3 = aes_s_box_table[state[3 + ((i + 3) & 3) * 4]]
temp[temp_idx] = x0 ^ w[w_idx]
temp[temp_idx + 1] = x1 ^ w[w_idx + 1]
temp[temp_idx + 2] = x2 ^ w[w_idx + 2]
temp[temp_idx + 3] = x3 ^ w[w_idx + 3]
w_idx += 4
temp_idx += 4
for i in range(16):
state[i] = temp[i]
# take state as input and change it to the next state in the sequence
# state and temp have size 16, w has size 16 * (Nr + 1), Nr >= 1
def aes_state(state, w, temp, nr):
aes_add_round_key(state, w)
w_idx = 16
for i in range(nr - 1):
aes_sb_sr_mc_ark(state, w, w_idx, temp)
w_idx += 16
aes_sb_sr_ark(state, w, w_idx, temp)
# expand 'key' to 'w' for use with aes_state
# key has size 4 * Nk, w has size 16 * (Nr + 1), temp has size 16
def aes_key_expansion(key, w, temp, nk, nr):
for i in range(4 * nk):
w[i] = key[i]
w_idx = 4 * nk - 4
for i in range(nk, 4 * (nr + 1)):
t = temp
t_idx = 0
if i % nk == 0:
t[0] = aes_s_box(w[w_idx + 1]) ^ aes_r_con(i // nk)
for j in range(1, 4):
t[j] = aes_s_box(w[w_idx + (j + 1) % 4])
elif nk > 6 and i % nk == 4:
for j in range(0, 4):
t[j] = aes_s_box(w[w_idx + j])
else:
t = w
t_idx = w_idx
w_idx += 4
for j in range(4):
w[w_idx + j] = w[w_idx + j - 4 * nk] ^ t[t_idx + j]
##################################################################
# simple use of AES algorithm, using output feedback (OFB) mode
class AES:
def __init__(self, keysize):
if keysize == 128:
self.nk = 4
self.nr = 10
elif keysize == 192:
self.nk = 6
self.nr = 12
else:
assert keysize == 256
self.nk = 8
self.nr = 14
self.state = bytearray(16)
self.w = bytearray(16 * (self.nr + 1))
self.temp = bytearray(16)
self.state_pos = 16
def set_key(self, key):
aes_key_expansion(key, self.w, self.temp, self.nk, self.nr)
self.state_pos = 16
def set_iv(self, iv):
for i in range(16):
self.state[i] = iv[i]
self.state_pos = 16
def get_some_state(self, n_needed):
if self.state_pos >= 16:
aes_state(self.state, self.w, self.temp, self.nr)
self.state_pos = 0
n = 16 - self.state_pos
if n > n_needed:
n = n_needed
return n
def apply_to(self, data):
idx = 0
n = len(data)
while n > 0:
ln = self.get_some_state(n)
n -= ln
for i in range(ln):
data[idx + i] ^= self.state[self.state_pos + i]
idx += ln
self.state_pos += n
##################################################################
# test code
try:
import utime as time
except ImportError:
import time
import _thread
class LockedCounter:
def __init__(self):
self.lock = _thread.allocate_lock()
self.value = 0
def add(self, val):
self.lock.acquire()
self.value += val
self.lock.release()
count = LockedCounter()
def thread_entry(n_loop):
global count
aes = AES(256)
key = bytearray(256 // 8)
iv = bytearray(16)
data = bytearray(128)
# from now on we don't use the heap
for loop in range(n_loop):
# encrypt
aes.set_key(key)
aes.set_iv(iv)
for i in range(8):
aes.apply_to(data)
# decrypt
aes.set_key(key)
aes.set_iv(iv)
for i in range(8):
aes.apply_to(data)
# verify
for i in range(len(data)):
assert data[i] == 0
count.add(1)
if __name__ == "__main__":
import sys
if sys.platform == "rp2":
n_thread = 1
n_loop = 2
elif sys.platform in ("esp32", "pyboard"):
n_thread = 2
n_loop = 2
else:
n_thread = 20
n_loop = 5
for i in range(n_thread):
_thread.start_new_thread(thread_entry, (n_loop,))
thread_entry(n_loop)
while count.value < n_thread:
time.sleep(1)
print("done")
|
YifuLiu/AliOS-Things
|
components/py_engine/tests/thread/stress_aes.py
|
Python
|
apache-2.0
| 9,136
|
# stress test for creating many threads
try:
import utime
sleep_ms = utime.sleep_ms
except ImportError:
import time
sleep_ms = lambda t: time.sleep(t / 1000)
import _thread
def thread_entry(n):
pass
thread_num = 0
while thread_num < 500:
try:
_thread.start_new_thread(thread_entry, (thread_num,))
thread_num += 1
except (MemoryError, OSError) as er:
# Cannot create a new thead at this stage, yield for a bit to
# let existing threads run to completion and free up resources.
sleep_ms(50)
# wait for the last threads to terminate
sleep_ms(500)
print("done")
|
YifuLiu/AliOS-Things
|
components/py_engine/tests/thread/stress_create.py
|
Python
|
apache-2.0
| 634
|
# stress test for the heap by allocating lots of objects within threads
# allocates about 5mb on the heap
#
# MIT license; Copyright (c) 2016 Damien P. George on behalf of Pycom Ltd
try:
import utime as time
except ImportError:
import time
import _thread
def last(l):
return l[-1]
def thread_entry(n):
# allocate a bytearray and fill it
data = bytearray(i for i in range(256))
# run a loop which allocates a small list and uses it each iteration
lst = 8 * [0]
sum = 0
for i in range(n):
sum += last(lst)
lst = [0, 0, 0, 0, 0, 0, 0, i + 1]
# check that the bytearray still has the right data
for i, b in enumerate(data):
assert i == b
# print the result of the loop and indicate we are finished
with lock:
print(sum, lst[-1])
global n_finished
n_finished += 1
lock = _thread.allocate_lock()
n_thread = 10
n_finished = 0
# spawn threads
for i in range(n_thread):
_thread.start_new_thread(thread_entry, (10000,))
# wait for threads to finish
while n_finished < n_thread:
time.sleep(1)
|
YifuLiu/AliOS-Things
|
components/py_engine/tests/thread/stress_heap.py
|
Python
|
apache-2.0
| 1,102
|
# test hitting the function recursion limit within a thread
#
# MIT license; Copyright (c) 2016 Damien P. George on behalf of Pycom Ltd
import _thread
def foo():
foo()
def thread_entry():
try:
foo()
except RuntimeError:
print("RuntimeError")
global finished
finished = True
finished = False
_thread.start_new_thread(thread_entry, ())
# busy wait for thread to finish
while not finished:
pass
print("done")
|
YifuLiu/AliOS-Things
|
components/py_engine/tests/thread/stress_recurse.py
|
Python
|
apache-2.0
| 455
|
# This test ensures that the scheduler doesn't trigger any assertions
# while dealing with concurrent access from multiple threads.
import _thread
import utime
import micropython
import gc
try:
micropython.schedule
except AttributeError:
print("SKIP")
raise SystemExit
gc.disable()
_NUM_TASKS = 10000
_TIMEOUT_MS = 10000
n = 0 # How many times the task successfully ran.
t = None # Start time of test, assigned here to preallocate entry in globals dict.
def task(x):
global n
n += 1
def thread():
while True:
try:
micropython.schedule(task, None)
except RuntimeError:
# Queue full, back off.
utime.sleep_ms(10)
for i in range(8):
_thread.start_new_thread(thread, ())
# Wait up to 10 seconds for 10000 tasks to be scheduled.
t = utime.ticks_ms()
while n < _NUM_TASKS and utime.ticks_diff(utime.ticks_ms(), t) < _TIMEOUT_MS:
pass
if n < _NUM_TASKS:
# Not all the tasks were scheduled, likely the scheduler stopped working.
print(n)
else:
print("PASS")
|
YifuLiu/AliOS-Things
|
components/py_engine/tests/thread/stress_schedule.py
|
Python
|
apache-2.0
| 1,061
|
# test raising and catching an exception within a thread
#
# MIT license; Copyright (c) 2016 Damien P. George on behalf of Pycom Ltd
import _thread
def foo():
raise ValueError
def thread_entry():
try:
foo()
except ValueError:
pass
with lock:
global n_finished
n_finished += 1
lock = _thread.allocate_lock()
n_thread = 4
n_finished = 0
# spawn threads
for i in range(n_thread):
while True:
try:
_thread.start_new_thread(thread_entry, ())
break
except OSError:
pass
# busy wait for threads to finish
while n_finished < n_thread:
pass
print("done")
|
YifuLiu/AliOS-Things
|
components/py_engine/tests/thread/thread_exc1.py
|
Python
|
apache-2.0
| 663
|
# test raising exception within thread which is not caught
import utime
import _thread
def thread_entry():
raise ValueError
_thread.start_new_thread(thread_entry, ())
utime.sleep(1)
print("done")
|
YifuLiu/AliOS-Things
|
components/py_engine/tests/thread/thread_exc2.py
|
Python
|
apache-2.0
| 204
|
# test _thread.exit() function
#
# MIT license; Copyright (c) 2016 Damien P. George on behalf of Pycom Ltd
try:
import utime as time
except ImportError:
import time
import _thread
def thread_entry():
_thread.exit()
for i in range(2):
while True:
try:
_thread.start_new_thread(thread_entry, ())
break
except OSError:
pass
# wait for threads to finish
time.sleep(1)
print("done")
|
YifuLiu/AliOS-Things
|
components/py_engine/tests/thread/thread_exit1.py
|
Python
|
apache-2.0
| 452
|
# test raising SystemExit to finish a thread
#
# MIT license; Copyright (c) 2016 Damien P. George on behalf of Pycom Ltd
try:
import utime as time
except ImportError:
import time
import _thread
def thread_entry():
raise SystemExit
for i in range(2):
while True:
try:
_thread.start_new_thread(thread_entry, ())
break
except OSError:
pass
# wait for threads to finish
time.sleep(1)
print("done")
|
YifuLiu/AliOS-Things
|
components/py_engine/tests/thread/thread_exit2.py
|
Python
|
apache-2.0
| 468
|
# test that we can run the garbage collector within threads
#
# MIT license; Copyright (c) 2016 Damien P. George on behalf of Pycom Ltd
import gc
import _thread
def thread_entry(n):
# allocate a bytearray and fill it
data = bytearray(i for i in range(256))
# do some work and call gc.collect() a few times
for i in range(n):
for i in range(len(data)):
data[i] = data[i]
gc.collect()
# print whether the data remains intact and indicate we are finished
with lock:
print(list(data) == list(range(256)))
global n_finished
n_finished += 1
lock = _thread.allocate_lock()
n_thread = 4
n_finished = 0
# spawn threads
for i in range(n_thread):
_thread.start_new_thread(thread_entry, (10,))
# busy wait for threads to finish
while n_finished < n_thread:
pass
|
YifuLiu/AliOS-Things
|
components/py_engine/tests/thread/thread_gc1.py
|
Python
|
apache-2.0
| 843
|
# test interaction of micropython.heap_lock with threads
import _thread, micropython
lock1 = _thread.allocate_lock()
lock2 = _thread.allocate_lock()
def thread_entry():
lock1.acquire()
print([1, 2, 3])
lock2.release()
lock1.acquire()
lock2.acquire()
_thread.start_new_thread(thread_entry, ())
micropython.heap_lock()
lock1.release()
lock2.acquire()
micropython.heap_unlock()
lock1.release()
lock2.release()
|
YifuLiu/AliOS-Things
|
components/py_engine/tests/thread/thread_heap_lock.py
|
Python
|
apache-2.0
| 428
|
# test _thread.get_ident() function
#
# MIT license; Copyright (c) 2016 Damien P. George on behalf of Pycom Ltd
import _thread
def thread_entry():
tid = _thread.get_ident()
print("thread", type(tid) == int, tid != 0, tid != tid_main)
global finished
finished = True
tid_main = _thread.get_ident()
print("main", type(tid_main) == int, tid_main != 0)
finished = False
_thread.start_new_thread(thread_entry, ())
while not finished:
pass
print("done")
|
YifuLiu/AliOS-Things
|
components/py_engine/tests/thread/thread_ident1.py
|
Python
|
apache-2.0
| 475
|
# test _thread lock object using a single thread
#
# MIT license; Copyright (c) 2016 Damien P. George on behalf of Pycom Ltd
import _thread
# create lock
lock = _thread.allocate_lock()
print(type(lock) == _thread.LockType)
# should be unlocked
print(lock.locked())
# basic acquire and release
print(lock.acquire())
print(lock.locked())
lock.release()
print(lock.locked())
# try acquire twice (second should fail)
print(lock.acquire())
print(lock.locked())
print(lock.acquire(0))
print(lock.locked())
lock.release()
print(lock.locked())
# test with capabilities of lock
with lock:
print(lock.locked())
# test that lock is unlocked if an error is rasied
try:
with lock:
print(lock.locked())
raise KeyError
except KeyError:
print("KeyError")
print(lock.locked())
# test that we can't release an unlocked lock
try:
lock.release()
except RuntimeError:
print("RuntimeError")
|
YifuLiu/AliOS-Things
|
components/py_engine/tests/thread/thread_lock1.py
|
Python
|
apache-2.0
| 918
|
# test _thread lock objects with multiple threads
#
# MIT license; Copyright (c) 2016 Damien P. George on behalf of Pycom Ltd
try:
import utime as time
except ImportError:
import time
import _thread
lock = _thread.allocate_lock()
def thread_entry():
lock.acquire()
print("have it")
lock.release()
# spawn the threads
for i in range(4):
_thread.start_new_thread(thread_entry, ())
# wait for threads to finish
time.sleep(1)
print("done")
|
YifuLiu/AliOS-Things
|
components/py_engine/tests/thread/thread_lock2.py
|
Python
|
apache-2.0
| 467
|
# test thread coordination using a lock object
#
# MIT license; Copyright (c) 2016 Damien P. George on behalf of Pycom Ltd
import _thread
lock = _thread.allocate_lock()
n_thread = 10
n_finished = 0
def thread_entry(idx):
global n_finished
while True:
with lock:
if n_finished == idx:
break
print("my turn:", idx)
with lock:
n_finished += 1
# spawn threads
for i in range(n_thread):
_thread.start_new_thread(thread_entry, (i,))
# busy wait for threads to finish
while n_finished < n_thread:
pass
|
YifuLiu/AliOS-Things
|
components/py_engine/tests/thread/thread_lock3.py
|
Python
|
apache-2.0
| 570
|
# test using lock to coordinate access to global mutable objects
#
# MIT license; Copyright (c) 2016 Damien P. George on behalf of Pycom Ltd
try:
import utime as time
except ImportError:
import time
import _thread
def fac(n):
x = 1
for i in range(1, n + 1):
x *= i
return x
def thread_entry():
while True:
with jobs_lock:
try:
f, arg = jobs.pop(0)
except IndexError:
return
ans = f(arg)
with output_lock:
output.append((arg, ans))
# create a list of jobs
jobs = [(fac, i) for i in range(20, 80)]
jobs_lock = _thread.allocate_lock()
n_jobs = len(jobs)
# create a list to store the results
output = []
output_lock = _thread.allocate_lock()
# spawn threads to do the jobs
for i in range(4):
_thread.start_new_thread(thread_entry, ())
# wait for the jobs to complete
while True:
with jobs_lock:
if len(output) == n_jobs:
break
time.sleep(1)
# sort and print the results
output.sort(key=lambda x: x[0])
for arg, ans in output:
print(arg, ans)
|
YifuLiu/AliOS-Things
|
components/py_engine/tests/thread/thread_lock4.py
|
Python
|
apache-2.0
| 1,109
|
# test _thread lock objects where a lock is acquired/released by a different thread
import _thread
def thread_entry():
print("thread about to release lock")
lock.release()
lock = _thread.allocate_lock()
lock.acquire()
_thread.start_new_thread(thread_entry, ())
lock.acquire()
print("main has lock")
lock.release()
|
YifuLiu/AliOS-Things
|
components/py_engine/tests/thread/thread_lock5.py
|
Python
|
apache-2.0
| 327
|
# test concurrent interning of strings
#
# MIT license; Copyright (c) 2016 Damien P. George on behalf of Pycom Ltd
try:
import utime as time
except ImportError:
import time
import _thread
# function to check the interned string
def check(s, val):
assert type(s) == str
assert int(s) == val
# main thread function
def th(base, n):
for i in range(n):
# this will intern the string and check it
exec("check('%u', %u)" % (base + i, base + i))
with lock:
global n_finished
n_finished += 1
lock = _thread.allocate_lock()
n_thread = 4
n_finished = 0
n_qstr_per_thread = 100 # make 1000 for a more stressful test (uses more heap)
# spawn threads
for i in range(n_thread):
_thread.start_new_thread(th, (i * n_qstr_per_thread, n_qstr_per_thread))
# wait for threads to finish
while n_finished < n_thread:
time.sleep(1)
print("pass")
|
YifuLiu/AliOS-Things
|
components/py_engine/tests/thread/thread_qstr1.py
|
Python
|
apache-2.0
| 898
|
# test capability for threads to access a shared immutable data structure
#
# MIT license; Copyright (c) 2016 Damien P. George on behalf of Pycom Ltd
import _thread
def foo(i):
pass
def thread_entry(n, tup):
for i in tup:
foo(i)
with lock:
global n_finished
n_finished += 1
lock = _thread.allocate_lock()
n_thread = 2
n_finished = 0
# the shared data structure
tup = (1, 2, 3, 4)
# spawn threads
for i in range(n_thread):
_thread.start_new_thread(thread_entry, (100, tup))
# busy wait for threads to finish
while n_finished < n_thread:
pass
print(tup)
|
YifuLiu/AliOS-Things
|
components/py_engine/tests/thread/thread_shared1.py
|
Python
|
apache-2.0
| 606
|
# test capability for threads to access a shared mutable data structure
# (without contention because they access different parts of the structure)
#
# MIT license; Copyright (c) 2016 Damien P. George on behalf of Pycom Ltd
import _thread
def foo(lst, i):
lst[i] += 1
def thread_entry(n, lst, idx):
for i in range(n):
foo(lst, idx)
with lock:
global n_finished
n_finished += 1
lock = _thread.allocate_lock()
n_thread = 2
n_finished = 0
# the shared data structure
lst = [0, 0]
# spawn threads
for i in range(n_thread):
_thread.start_new_thread(thread_entry, ((i + 1) * 10, lst, i))
# busy wait for threads to finish
while n_finished < n_thread:
pass
print(lst)
|
YifuLiu/AliOS-Things
|
components/py_engine/tests/thread/thread_shared2.py
|
Python
|
apache-2.0
| 715
|
# test threads sleeping
#
# MIT license; Copyright (c) 2016 Damien P. George on behalf of Pycom Ltd
try:
import utime
sleep_ms = utime.sleep_ms
except ImportError:
import time
sleep_ms = lambda t: time.sleep(t / 1000)
import _thread
lock = _thread.allocate_lock()
n_thread = 4
n_finished = 0
def thread_entry(t):
global n_finished
sleep_ms(t)
sleep_ms(2 * t)
with lock:
n_finished += 1
for i in range(n_thread):
_thread.start_new_thread(thread_entry, (10 * i,))
# wait for threads to finish
while n_finished < n_thread:
sleep_ms(100)
print("done", n_thread)
|
YifuLiu/AliOS-Things
|
components/py_engine/tests/thread/thread_sleep1.py
|
Python
|
apache-2.0
| 616
|
# test setting the thread stack size
#
# MIT license; Copyright (c) 2016 Damien P. George on behalf of Pycom Ltd
try:
import usys as sys
except ImportError:
import sys
import _thread
# different implementations have different minimum sizes
if sys.implementation.name == "micropython":
sz = 2 * 1024
else:
sz = 512 * 1024
def foo():
pass
def thread_entry():
foo()
with lock:
global n_finished
n_finished += 1
# reset stack size to default
_thread.stack_size()
# test set/get of stack size
print(_thread.stack_size())
print(_thread.stack_size(sz))
print(_thread.stack_size() == sz)
print(_thread.stack_size())
lock = _thread.allocate_lock()
n_thread = 2
n_finished = 0
# set stack size and spawn a few threads
_thread.stack_size(sz)
for i in range(n_thread):
while True:
try:
_thread.start_new_thread(thread_entry, ())
break
except OSError:
pass
# reset stack size to default (for subsequent scripts on baremetal)
_thread.stack_size()
# busy wait for threads to finish
while n_finished < n_thread:
pass
print("done")
|
YifuLiu/AliOS-Things
|
components/py_engine/tests/thread/thread_stacksize1.py
|
Python
|
apache-2.0
| 1,131
|
# test basic capability to start a new thread
#
# MIT license; Copyright (c) 2016 Damien P. George on behalf of Pycom Ltd
try:
import utime as time
except ImportError:
import time
import _thread
def foo():
pass
def thread_entry(n):
for i in range(n):
foo()
for i in range(2):
while True:
try:
_thread.start_new_thread(thread_entry, ((i + 1) * 10,))
break
except OSError:
pass
# wait for threads to finish
time.sleep(1)
print("done")
|
YifuLiu/AliOS-Things
|
components/py_engine/tests/thread/thread_start1.py
|
Python
|
apache-2.0
| 521
|
# test capability to start a thread with keyword args
#
# MIT license; Copyright (c) 2016 Damien P. George on behalf of Pycom Ltd
try:
import utime as time
except ImportError:
import time
import _thread
def thread_entry(a0, a1, a2, a3):
print("thread", a0, a1, a2, a3)
# spawn thread using kw args
_thread.start_new_thread(thread_entry, (10, 20), {"a2": 0, "a3": 1})
# wait for thread to finish
time.sleep(1)
# incorrect argument where dictionary is needed for keyword args
try:
_thread.start_new_thread(thread_entry, (), ())
except TypeError:
print("TypeError")
print("done")
|
YifuLiu/AliOS-Things
|
components/py_engine/tests/thread/thread_start2.py
|
Python
|
apache-2.0
| 605
|
f = open("unicode/data/utf-8_1.txt", encoding="utf-8")
l = f.readline()
print(l)
print(len(l))
|
YifuLiu/AliOS-Things
|
components/py_engine/tests/unicode/file1.py
|
Python
|
apache-2.0
| 95
|
# test reading a given number of characters
def do(mode):
if mode == "rb":
enc = None
else:
enc = "utf-8"
f = open("unicode/data/utf-8_2.txt", mode=mode, encoding=enc)
print(f.read(1))
print(f.read(1))
print(f.read(2))
print(f.read(4))
# skip to end of line
f.readline()
# check 3-byte utf-8 char
print(f.read(1 if mode == "rt" else 3))
# check 4-byte utf-8 char
print(f.read(1 if mode == "rt" else 4))
f.close()
do("rb")
do("rt")
|
YifuLiu/AliOS-Things
|
components/py_engine/tests/unicode/file2.py
|
Python
|
apache-2.0
| 511
|
# Test a UTF-8 encoded literal
s = "asdf©qwer"
for i in range(len(s)):
print("s[%d]: %s %X" % (i, s[i], ord(s[i])))
# Test all three forms of Unicode escape, and
# all blocks of UTF-8 byte patterns
s = "a\xA9\xFF\u0123\u0800\uFFEE\U0001F44C"
for i in range(-len(s), len(s)):
print("s[%d]: %s %X" % (i, s[i], ord(s[i])))
print("s[:%d]: %d chars, '%s'" % (i, len(s[:i]), s[:i]))
for j in range(i, len(s)):
print("s[%d:%d]: %d chars, '%s'" % (i, j, len(s[i:j]), s[i:j]))
print("s[%d:]: %d chars, '%s'" % (i, len(s[i:]), s[i:]))
# Test UTF-8 encode and decode
enc = s.encode()
print(enc, enc.decode() == s)
# printing of unicode chars using repr
# NOTE: for some characters (eg \u10ff) we differ to CPython
print(repr("a\uffff"))
print(repr("a\U0001ffff"))
# test invalid escape code
try:
eval('"\\U00110000"')
except SyntaxError:
print("SyntaxError")
# test unicode string given to int
try:
int("\u0200")
except ValueError:
print("ValueError")
# test invalid UTF-8 string
try:
str(b"ab\xa1", "utf8")
except UnicodeError:
print("UnicodeError")
try:
str(b"ab\xf8", "utf8")
except UnicodeError:
print("UnicodeError")
try:
str(bytearray(b"ab\xc0a"), "utf8")
except UnicodeError:
print("UnicodeError")
try:
str(b"\xf0\xe0\xed\xe8", "utf8")
except UnicodeError:
print("UnicodeError")
|
YifuLiu/AliOS-Things
|
components/py_engine/tests/unicode/unicode.py
|
Python
|
apache-2.0
| 1,362
|
# test builtin chr with unicode characters
print(chr(945))
print(chr(0x800))
print(chr(0x10000))
|
YifuLiu/AliOS-Things
|
components/py_engine/tests/unicode/unicode_chr.py
|
Python
|
apache-2.0
| 98
|
# test unicode in identifiers
# comment
# αβγδϵφζ
# global identifiers
α = 1
αβγ = 2
bβ = 3
βb = 4
print(α, αβγ, bβ, βb)
# function, argument, local identifiers
def α(β, γ):
δ = β + γ
print(β, γ, δ)
α(1, 2)
# class, method identifiers
class φ:
def __init__(self):
pass
def δ(self, ϵ):
print(ϵ)
zζzζz = φ()
if hasattr(zζzζz, "δ"):
zζzζz.δ(ϵ=123)
|
YifuLiu/AliOS-Things
|
components/py_engine/tests/unicode/unicode_id.py
|
Python
|
apache-2.0
| 433
|
print("Привет".find("т"))
print("Привет".find("П"))
print("Привет".rfind("т"))
print("Привет".rfind("П"))
print("Привет".index("т"))
print("Привет".index("П"))
|
YifuLiu/AliOS-Things
|
components/py_engine/tests/unicode/unicode_index.py
|
Python
|
apache-2.0
| 202
|
for c in "Hello":
print(c)
for c in "Привет":
print(c)
|
YifuLiu/AliOS-Things
|
components/py_engine/tests/unicode/unicode_iter.py
|
Python
|
apache-2.0
| 69
|
# test builtin ord with unicode characters
print(ord("α"))
|
YifuLiu/AliOS-Things
|
components/py_engine/tests/unicode/unicode_ord.py
|
Python
|
apache-2.0
| 61
|
# str methods with explicit start/end pos
print("Привет".startswith("П"))
print("Привет".startswith("р", 1))
print("абвба".find("а", 1))
print("абвба".find("а", 1, -1))
|
YifuLiu/AliOS-Things
|
components/py_engine/tests/unicode/unicode_pos.py
|
Python
|
apache-2.0
| 195
|
# Test slicing of Unicode strings
s = "Привет"
print(s[:])
print(s[2:])
print(s[:5])
print(s[2:5])
print(s[2:5:1])
print(s[2:10])
print(s[-3:10])
print(s[-4:10])
|
YifuLiu/AliOS-Things
|
components/py_engine/tests/unicode/unicode_slice.py
|
Python
|
apache-2.0
| 170
|
# test handling of unicode chars in format strings
print("α".format())
print("{α}".format(α=1))
|
YifuLiu/AliOS-Things
|
components/py_engine/tests/unicode/unicode_str_format.py
|
Python
|
apache-2.0
| 100
|
# test handling of unicode chars in string % formatting
print("α" % ())
|
YifuLiu/AliOS-Things
|
components/py_engine/tests/unicode/unicode_str_modulo.py
|
Python
|
apache-2.0
| 74
|
a = "¢пр"
print(a[0], a[0:1])
print(a[1], a[1:2])
print(a[2], a[2:3])
try:
print(a[3])
except IndexError:
print("IndexError")
print(a[3:4])
print(a[-1])
print(a[-2], a[-2:-1])
print(a[-3], a[-3:-2])
try:
print(a[-4])
except IndexError:
print("IndexError")
print(a[-4:-3])
print(a[0:2])
print(a[1:3])
print(a[2:4])
|
YifuLiu/AliOS-Things
|
components/py_engine/tests/unicode/unicode_subscr.py
|
Python
|
apache-2.0
| 336
|