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
|
|---|---|---|---|---|---|
"""
categories: Syntax,Operators
description: MicroPython allows using := to assign to the variable of a comprehension, CPython raises a SyntaxError.
cause: MicroPython is optimised for code size and doesn't check this case.
workaround: Do not rely on this behaviour if writing CPython compatible code.
"""
print([i := -1 for i in range(4)])
|
YifuLiu/AliOS-Things
|
components/py_engine/tests/cpydiff/syntax_assign_expr.py
|
Python
|
apache-2.0
| 342
|
"""
categories: Syntax,Spaces
description: uPy requires spaces between literal numbers and keywords, CPy doesn't
cause: Unknown
workaround: Unknown
"""
try:
print(eval("1and 0"))
except SyntaxError:
print("Should have worked")
try:
print(eval("1or 0"))
except SyntaxError:
print("Should have worked")
try:
print(eval("1if 1else 0"))
except SyntaxError:
print("Should have worked")
|
YifuLiu/AliOS-Things
|
components/py_engine/tests/cpydiff/syntax_spaces.py
|
Python
|
apache-2.0
| 405
|
"""
categories: Syntax,Unicode
description: Unicode name escapes are not implemented
cause: Unknown
workaround: Unknown
"""
print("\N{LATIN SMALL LETTER A}")
|
YifuLiu/AliOS-Things
|
components/py_engine/tests/cpydiff/syntax_unicode_nameesc.py
|
Python
|
apache-2.0
| 158
|
"""
categories: Types,bytearray
description: Array slice assignment with unsupported RHS
cause: Unknown
workaround: Unknown
"""
b = bytearray(4)
b[0:1] = [1, 2]
print(b)
|
YifuLiu/AliOS-Things
|
components/py_engine/tests/cpydiff/types_bytearray_sliceassign.py
|
Python
|
apache-2.0
| 170
|
"""
categories: Types,bytes
description: bytes objects support .format() method
cause: MicroPython strives to be a more regular implementation, so if both `str` and `bytes` support ``__mod__()`` (the % operator), it makes sense to support ``format()`` for both too. Support for ``__mod__`` can also be compiled out, which leaves only ``format()`` for bytes formatting.
workaround: If you are interested in CPython compatibility, don't use ``.format()`` on bytes objects.
"""
print(b"{}".format(1))
|
YifuLiu/AliOS-Things
|
components/py_engine/tests/cpydiff/types_bytes_format.py
|
Python
|
apache-2.0
| 498
|
"""
categories: Types,bytes
description: bytes() with keywords not implemented
cause: Unknown
workaround: Pass the encoding as a positional parameter, e.g. ``print(bytes('abc', 'utf-8'))``
"""
print(bytes("abc", encoding="utf8"))
|
YifuLiu/AliOS-Things
|
components/py_engine/tests/cpydiff/types_bytes_keywords.py
|
Python
|
apache-2.0
| 230
|
"""
categories: Types,bytes
description: Bytes subscription with step != 1 not implemented
cause: MicroPython is highly optimized for memory usage.
workaround: Use explicit loop for this very rare operation.
"""
print(b"123"[0:3:2])
|
YifuLiu/AliOS-Things
|
components/py_engine/tests/cpydiff/types_bytes_subscrstep.py
|
Python
|
apache-2.0
| 233
|
"""
categories: Types,dict
description: Dictionary keys view does not behave as a set.
cause: Not implemented.
workaround: Explicitly convert keys to a set before using set operations.
"""
print({1: 2, 3: 4}.keys() & {1})
|
YifuLiu/AliOS-Things
|
components/py_engine/tests/cpydiff/types_dict_keys_set.py
|
Python
|
apache-2.0
| 222
|
"""
categories: Types,Exception
description: All exceptions have readable ``value`` and ``errno`` attributes, not just ``StopIteration`` and ``OSError``.
cause: MicroPython is optimised to reduce code size.
workaround: Only use ``value`` on ``StopIteration`` exceptions, and ``errno`` on ``OSError`` exceptions. Do not use or rely on these attributes on other exceptions.
"""
e = Exception(1)
print(e.value)
print(e.errno)
|
YifuLiu/AliOS-Things
|
components/py_engine/tests/cpydiff/types_exception_attrs.py
|
Python
|
apache-2.0
| 424
|
"""
categories: Types,Exception
description: Exception chaining not implemented
cause: Unknown
workaround: Unknown
"""
try:
raise TypeError
except TypeError:
raise ValueError
|
YifuLiu/AliOS-Things
|
components/py_engine/tests/cpydiff/types_exception_chaining.py
|
Python
|
apache-2.0
| 183
|
"""
categories: Types,Exception
description: User-defined attributes for builtin exceptions are not supported
cause: MicroPython is highly optimized for memory usage.
workaround: Use user-defined exception subclasses.
"""
e = Exception()
e.x = 0
print(e.x)
|
YifuLiu/AliOS-Things
|
components/py_engine/tests/cpydiff/types_exception_instancevar.py
|
Python
|
apache-2.0
| 257
|
"""
categories: Types,Exception
description: Exception in while loop condition may have unexpected line number
cause: Condition checks are optimized to happen at the end of loop body, and that line number is reported.
workaround: Unknown
"""
l = ["-foo", "-bar"]
i = 0
while l[i][0] == "-":
print("iter")
i += 1
|
YifuLiu/AliOS-Things
|
components/py_engine/tests/cpydiff/types_exception_loops.py
|
Python
|
apache-2.0
| 321
|
"""
categories: Types,Exception
description: Exception.__init__ method does not exist.
cause: Subclassing native classes is not fully supported in MicroPython.
workaround: Call using ``super()`` instead::
class A(Exception):
def __init__(self):
super().__init__()
"""
class A(Exception):
def __init__(self):
Exception.__init__(self)
a = A()
|
YifuLiu/AliOS-Things
|
components/py_engine/tests/cpydiff/types_exception_subclassinit.py
|
Python
|
apache-2.0
| 382
|
"""
categories: Types,float
description: uPy and CPython outputs formats may differ
cause: Unknown
workaround: Unknown
"""
print("%.1g" % -9.9)
|
YifuLiu/AliOS-Things
|
components/py_engine/tests/cpydiff/types_float_rounding.py
|
Python
|
apache-2.0
| 144
|
"""
categories: Types,int
description: ``bit_length`` method doesn't exist.
cause: bit_length method is not implemented.
workaround: Avoid using this method on MicroPython.
"""
x = 255
print("{} is {} bits long.".format(x, x.bit_length()))
|
YifuLiu/AliOS-Things
|
components/py_engine/tests/cpydiff/types_int_bit_length.py
|
Python
|
apache-2.0
| 241
|
"""
categories: Types,int
description: No int conversion for int-derived types available
cause: Unknown
workaround: Avoid subclassing builtin types unless really needed. Prefer https://en.wikipedia.org/wiki/Composition_over_inheritance .
"""
class A(int):
__add__ = lambda self, other: A(int(self) + other)
a = A(42)
print(a + a)
|
YifuLiu/AliOS-Things
|
components/py_engine/tests/cpydiff/types_int_subclassconv.py
|
Python
|
apache-2.0
| 338
|
"""
categories: Types,list
description: List delete with step != 1 not implemented
cause: Unknown
workaround: Use explicit loop for this rare operation.
"""
l = [1, 2, 3, 4]
del l[0:4:2]
print(l)
|
YifuLiu/AliOS-Things
|
components/py_engine/tests/cpydiff/types_list_delete_subscrstep.py
|
Python
|
apache-2.0
| 196
|
"""
categories: Types,list
description: List slice-store with non-iterable on RHS is not implemented
cause: RHS is restricted to be a tuple or list
workaround: Use ``list(<iter>)`` on RHS to convert the iterable to a list
"""
l = [10, 20]
l[0:1] = range(4)
print(l)
|
YifuLiu/AliOS-Things
|
components/py_engine/tests/cpydiff/types_list_store_noniter.py
|
Python
|
apache-2.0
| 266
|
"""
categories: Types,list
description: List store with step != 1 not implemented
cause: Unknown
workaround: Use explicit loop for this rare operation.
"""
l = [1, 2, 3, 4]
l[0:4:2] = [5, 6]
print(l)
|
YifuLiu/AliOS-Things
|
components/py_engine/tests/cpydiff/types_list_store_subscrstep.py
|
Python
|
apache-2.0
| 200
|
"""
categories: Types,str
description: Start/end indices such as str.endswith(s, start) not implemented
cause: Unknown
workaround: Unknown
"""
print("abc".endswith("c", 1))
|
YifuLiu/AliOS-Things
|
components/py_engine/tests/cpydiff/types_str_endswith.py
|
Python
|
apache-2.0
| 173
|
"""
categories: Types,str
description: Attributes/subscr not implemented
cause: Unknown
workaround: Unknown
"""
print("{a[0]}".format(a=[1, 2]))
|
YifuLiu/AliOS-Things
|
components/py_engine/tests/cpydiff/types_str_formatsubscr.py
|
Python
|
apache-2.0
| 145
|
"""
categories: Types,str
description: str(...) with keywords not implemented
cause: Unknown
workaround: Input the encoding format directly. eg ``print(bytes('abc', 'utf-8'))``
"""
print(str(b"abc", encoding="utf8"))
|
YifuLiu/AliOS-Things
|
components/py_engine/tests/cpydiff/types_str_keywords.py
|
Python
|
apache-2.0
| 217
|
"""
categories: Types,str
description: str.ljust() and str.rjust() not implemented
cause: MicroPython is highly optimized for memory usage. Easy workarounds available.
workaround: Instead of ``s.ljust(10)`` use ``"%-10s" % s``, instead of ``s.rjust(10)`` use ``"% 10s" % s``. Alternatively, ``"{:<10}".format(s)`` or ``"{:>10}".format(s)``.
"""
print("abc".ljust(10))
|
YifuLiu/AliOS-Things
|
components/py_engine/tests/cpydiff/types_str_ljust_rjust.py
|
Python
|
apache-2.0
| 368
|
"""
categories: Types,str
description: None as first argument for rsplit such as str.rsplit(None, n) not implemented
cause: Unknown
workaround: Unknown
"""
print("a a a".rsplit(None, 1))
|
YifuLiu/AliOS-Things
|
components/py_engine/tests/cpydiff/types_str_rsplitnone.py
|
Python
|
apache-2.0
| 187
|
"""
categories: Types,str
description: Subscript with step != 1 is not yet implemented
cause: Unknown
workaround: Unknown
"""
print("abcdefghi"[0:9:2])
|
YifuLiu/AliOS-Things
|
components/py_engine/tests/cpydiff/types_str_subscrstep.py
|
Python
|
apache-2.0
| 152
|
"""
categories: Types,tuple
description: Tuple load with step != 1 not implemented
cause: Unknown
workaround: Unknown
"""
print((1, 2, 3, 4)[0:4:2])
|
YifuLiu/AliOS-Things
|
components/py_engine/tests/cpydiff/types_tuple_subscrstep.py
|
Python
|
apache-2.0
| 149
|
try:
from esp32 import Partition as p
import micropython
except ImportError:
print("SKIP")
raise SystemExit
# try some vanilla OSError to get std error code
try:
open("this filedoesnotexist", "r")
print("FAILED TO RAISE")
except OSError as e:
print(e)
# try to make nvs partition bootable, which ain't gonna work
part = p.find(type=p.TYPE_DATA)[0]
fun = p.set_boot
try:
fun(part)
print("FAILED TO RAISE")
except OSError as e:
print(e)
# same but with out of memory condition by locking the heap
exc = "FAILED TO RAISE"
micropython.heap_lock()
try:
fun(part)
except OSError as e:
exc = e
micropython.heap_unlock()
print("exc:", exc) # exc empty due to no memory
# same again but having an emergency buffer
micropython.alloc_emergency_exception_buf(256)
exc = "FAILED TO RAISE"
micropython.heap_lock()
try:
fun(part)
except Exception as e:
exc = e
micropython.heap_unlock()
print(exc)
|
YifuLiu/AliOS-Things
|
components/py_engine/tests/esp32/check_err_str.py
|
Python
|
apache-2.0
| 944
|
# Test the esp32's esp32.idf_heap_info to return sane data
try:
import esp32
except ImportError:
print("SKIP")
raise SystemExit
# region tuple is: (size, free, largest free, min free)
# we check that each region's size is > 0 and that the free amounts are smaller than the size
def chk_heap(kind, regions):
chk = [True, True, True, True]
for r in regions:
chk = [
chk[0] and r[0] > 0,
chk[1] and r[1] <= r[0],
chk[2] and r[2] <= r[0],
chk[3] and r[3] <= r[0],
]
print(kind, chk)
# try getting heap regions
regions = esp32.idf_heap_info(esp32.HEAP_DATA)
print("HEAP_DATA >2:", len(regions) > 2)
chk_heap("HEAP_DATA", regions)
# try getting code regions
regions = esp32.idf_heap_info(esp32.HEAP_EXEC)
print("HEAP_EXEC >2:", len(regions) > 2)
chk_heap("HEAP_EXEC", regions)
# try invalid param
print(esp32.idf_heap_info(-1))
|
YifuLiu/AliOS-Things
|
components/py_engine/tests/esp32/esp32_idf_heap_info.py
|
Python
|
apache-2.0
| 915
|
# Test the esp32 NVS class - access to esp-idf's Non-Volatile-Storage
from esp32 import NVS
nvs = NVS("mp-test")
# test setting and gettin an integer kv
nvs.set_i32("key1", 1234)
print(nvs.get_i32("key1"))
nvs.set_i32("key2", -503)
print(nvs.get_i32("key2"))
print(nvs.get_i32("key1"))
# test setting and getting a blob kv using a bytearray
blob1 = "testing a string as a blob"
nvs.set_blob("blob1", blob1)
buf1 = bytearray(len(blob1))
len1 = nvs.get_blob("blob1", buf1)
print(buf1)
print(len(blob1), len1)
# test setting and getting a blob kv using a string
blob2 = b"testing a bytearray"
nvs.set_blob("blob2", blob2)
buf2 = bytearray(len(blob2))
len2 = nvs.get_blob("blob2", buf2)
print(buf2)
print(len(blob2), len2)
# test raising of error exceptions
nvs.erase_key("key1")
try:
nvs.erase_key("key1") # not found
except OSError as e:
print(e)
try:
nvs.get_i32("key1") # not found
except OSError as e:
print(e)
try:
nvs.get_i32("blob1") # not found (blob1 exists but diff type)
except OSError as e:
print(e)
try:
buf3 = bytearray(10)
nvs.get_blob("blob1", buf3) # invalid length (too short)
except OSError as e:
print(e)
nvs.commit() # we're not verifying that this does anything, just doesn't error
# test using a second namespace and that it doesn't interfere with first
nvs2 = NVS("mp-test2")
try:
print(nvs2.get_i32("key2"))
except OSError as e:
print(e)
nvs2.set_i32("key2", 7654)
print(nvs.get_i32("key2"))
print(nvs2.get_i32("key2"))
# clean-up (the namespaces will remain)
nvs.erase_key("key2")
nvs.erase_key("blob1")
nvs.erase_key("blob2")
nvs2.erase_key("key2")
nvs.commit()
|
YifuLiu/AliOS-Things
|
components/py_engine/tests/esp32/esp32_nvs.py
|
Python
|
apache-2.0
| 1,644
|
# Test ESP32 OTA updates, including automatic roll-back.
# Running this test requires firmware with an OTA Partition, such as the GENERIC_OTA "board".
# This test also requires patience as it copies the boot partition into the other OTA slot.
import machine
from esp32 import Partition
# start by checking that the running partition table has OTA partitions, 'cause if
# it doesn't there's nothing we can test
cur = Partition(Partition.RUNNING)
cur_name = cur.info()[4]
if not cur_name.startswith("ota_"):
print("SKIP")
raise SystemExit
DEBUG = True
def log(*args):
if DEBUG:
print(*args)
# replace boot.py with the test code that will run on each reboot
import uos
try:
uos.rename("boot.py", "boot-orig.py")
except:
pass
with open("boot.py", "w") as f:
f.write("DEBUG=" + str(DEBUG))
f.write(
"""
import machine
from esp32 import Partition
cur = Partition(Partition.RUNNING)
cur_name = cur.info()[4]
def log(*args):
if DEBUG: print(*args)
from step import STEP, EXPECT
log("Running partition: " + cur_name + " STEP=" + str(STEP) + " EXPECT=" + EXPECT)
if cur_name != EXPECT:
print("\\x04FAILED: step " + str(STEP) + " expected " + EXPECT + " got " + cur_name + "\\x04")
if STEP == 0:
log("Not confirming boot ok and resetting back into first")
nxt = cur.get_next_update()
with open("step.py", "w") as f:
f.write("STEP=1\\nEXPECT=\\"" + nxt.info()[4] + "\\"\\n")
machine.reset()
elif STEP == 1:
log("Booting into second partition again")
nxt = cur.get_next_update()
nxt.set_boot()
with open("step.py", "w") as f:
f.write("STEP=2\\nEXPECT=\\"" + nxt.info()[4] + "\\"\\n")
machine.reset()
elif STEP == 2:
log("Confirming boot ok and rebooting into same partition")
Partition.mark_app_valid_cancel_rollback()
with open("step.py", "w") as f:
f.write("STEP=3\\nEXPECT=\\"" + cur_name + "\\"\\n")
machine.reset()
elif STEP == 3:
log("Booting into original partition")
nxt = cur.get_next_update()
nxt.set_boot()
with open("step.py", "w") as f:
f.write("STEP=4\\nEXPECT=\\"" + nxt.info()[4] + "\\"\\n")
machine.reset()
elif STEP == 4:
log("Confirming boot ok and DONE!")
Partition.mark_app_valid_cancel_rollback()
import uos
uos.remove("step.py")
uos.remove("boot.py")
uos.rename("boot-orig.py", "boot.py")
print("\\nSUCCESS!\\n\\x04\\x04")
"""
)
def copy_partition(src, dest):
log("Partition copy: {} --> {}".format(src.info(), dest.info()))
sz = src.info()[3]
if dest.info()[3] != sz:
raise ValueError("Sizes don't match: {} vs {}".format(sz, dest.info()[3]))
addr = 0
blk = bytearray(4096)
while addr < sz:
if sz - addr < 4096:
blk = blk[: sz - addr]
if addr & 0xFFFF == 0:
# need to show progress to run-tests.py else it times out
print(" ... 0x{:06x}".format(addr))
src.readblocks(addr >> 12, blk)
dest.writeblocks(addr >> 12, blk)
addr += len(blk)
# get things started by copying the current partition into the next slot and rebooting
print("Copying current to next partition")
nxt = cur.get_next_update()
copy_partition(cur, nxt)
print("Partition copied, booting into it")
nxt.set_boot()
# the step.py file is used to keep track of state across reboots
# EXPECT is the name of the partition we expect to reboot into
with open("step.py", "w") as f:
f.write('STEP=0\nEXPECT="' + nxt.info()[4] + '"\n')
machine.reset()
|
YifuLiu/AliOS-Things
|
components/py_engine/tests/esp32/partition_ota.py
|
Python
|
apache-2.0
| 3,535
|
# Test that the esp32's socket module performs DNS resolutions on bind and connect
import sys
if sys.implementation.name == "micropython" and sys.platform != "esp32":
print("SKIP")
raise SystemExit
try:
import usocket as socket, sys
except:
import socket, sys
def test_bind_resolves_0_0_0_0():
s = socket.socket()
try:
s.bind(("0.0.0.0", 31245))
print("bind actually bound")
s.close()
except Exception as e:
print("bind raised", e)
def test_bind_resolves_localhost():
s = socket.socket()
try:
s.bind(("localhost", 31245))
print("bind actually bound")
s.close()
except Exception as e:
print("bind raised", e)
def test_connect_resolves():
s = socket.socket()
try:
s.connect(("micropython.org", 80))
print("connect actually connected")
s.close()
except Exception as e:
print("connect raised", e)
def test_connect_non_existent():
s = socket.socket()
try:
s.connect(("nonexistent.example.com", 80))
print("connect actually connected")
s.close()
except OSError as e:
print("connect raised OSError")
except Exception as e:
print("connect raised", e)
test_funs = [n for n in dir() if n.startswith("test_")]
for f in sorted(test_funs):
print("--", f, end=": ")
eval(f + "()")
|
YifuLiu/AliOS-Things
|
components/py_engine/tests/esp32/resolve_on_connect.py
|
Python
|
apache-2.0
| 1,391
|
try:
import btree
import uio
import uerrno
except ImportError:
print("SKIP")
raise SystemExit
# f = open("_test.db", "w+b")
f = uio.BytesIO()
db = btree.open(f, pagesize=512)
db[b"foo3"] = b"bar3"
db[b"foo1"] = b"bar1"
db[b"foo2"] = b"bar2"
db[b"bar1"] = b"foo1"
dbstr = str(db)
print(dbstr[:7], dbstr[-1:])
print(db[b"foo2"])
try:
print(db[b"foo"])
except KeyError:
print("KeyError")
print(db.get(b"foo"))
print(db.get(b"foo", b"dflt"))
del db[b"foo2"]
try:
del db[b"foo"]
except KeyError:
print("KeyError")
for k, v in db.items():
print((k, v))
print("---")
for k, v in db.items(None, None):
print((k, v))
print("---")
for k, v in db.items(b"f"):
print((k, v))
print("---")
for k, v in db.items(b"f", b"foo3"):
print((k, v))
print("---")
for k, v in db.items(None, b"foo3"):
print((k, v))
print("---")
for k, v in db.items(b"f", b"foo3", btree.INCL):
print((k, v))
print("---")
for k, v in db.items(None, None, btree.DESC):
print((k, v))
print(db.seq(1, b"foo1"))
print(db.seq(1, b"qux"))
try:
db.seq(b"foo1")
except OSError as e:
print(e.errno == uerrno.EINVAL)
print(list(db.keys()))
print(list(db.values()))
for k in db:
print(k)
db.put(b"baz1", b"qux1")
print("foo1", "foo1" in db)
print("foo2", "foo2" in db)
print("baz1", "baz1" in db)
try:
print(db + db[b"foo1"])
except TypeError:
print("TypeError")
db.flush()
db.close()
f.close()
|
YifuLiu/AliOS-Things
|
components/py_engine/tests/extmod/btree1.py
|
Python
|
apache-2.0
| 1,446
|
# Test that errno's propagate correctly through btree module.
try:
import btree, uio, uerrno
uio.IOBase
except (ImportError, AttributeError):
print("SKIP")
raise SystemExit
class Device(uio.IOBase):
def __init__(self, read_ret=0, ioctl_ret=0):
self.read_ret = read_ret
self.ioctl_ret = ioctl_ret
def readinto(self, buf):
print("read", len(buf))
return self.read_ret
def ioctl(self, cmd, arg):
print("ioctl", cmd)
return self.ioctl_ret
# Invalid pagesize; errno comes from btree library
try:
db = btree.open(Device(), pagesize=511)
except OSError as er:
print("OSError", er.errno == uerrno.EINVAL)
# Valid pagesize, device returns error on read; errno comes from Device.readinto
try:
db = btree.open(Device(-1000), pagesize=512)
except OSError as er:
print(repr(er))
# Valid pagesize, device returns error on seek; errno comes from Device.ioctl
try:
db = btree.open(Device(0, -1001), pagesize=512)
except OSError as er:
print(repr(er))
|
YifuLiu/AliOS-Things
|
components/py_engine/tests/extmod/btree_error.py
|
Python
|
apache-2.0
| 1,045
|
# Test btree interaction with the garbage collector.
try:
import btree, uio, gc
except ImportError:
print("SKIP")
raise SystemExit
N = 80
# Create a BytesIO but don't keep a reference to it.
db = btree.open(uio.BytesIO(), pagesize=512)
# Overwrite lots of the Python stack to make sure no reference to the BytesIO remains.
x = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
# Write lots of key/value pairs, which fill up the DB and also allocate temporary heap
# memory due to the string addition, and do a GC collect to verify that the BytesIO
# is not collected.
for i in range(N):
db[b"thekey" + str(i)] = b"thelongvalue" + str(i)
print(db[b"thekey" + str(i)])
gc.collect()
# Reclaim memory allocated by the db object.
db.close()
|
YifuLiu/AliOS-Things
|
components/py_engine/tests/extmod/btree_gc.py
|
Python
|
apache-2.0
| 747
|
try:
import framebuf
except ImportError:
print("SKIP")
raise SystemExit
w = 5
h = 16
size = w * h // 8
buf = bytearray(size)
maps = {
framebuf.MONO_VLSB: "MONO_VLSB",
framebuf.MONO_HLSB: "MONO_HLSB",
framebuf.MONO_HMSB: "MONO_HMSB",
}
for mapping in maps.keys():
for x in range(size):
buf[x] = 0
fbuf = framebuf.FrameBuffer(buf, w, h, mapping)
print(maps[mapping])
# access as buffer
print(memoryview(fbuf)[0])
# fill
fbuf.fill(1)
print(buf)
fbuf.fill(0)
print(buf)
# put pixel
fbuf.pixel(0, 0, 1)
fbuf.pixel(4, 0, 1)
fbuf.pixel(0, 15, 1)
fbuf.pixel(4, 15, 1)
print(buf)
# clear pixel
fbuf.pixel(4, 15, 0)
print(buf)
# get pixel
print(fbuf.pixel(0, 0), fbuf.pixel(1, 1))
# hline
fbuf.fill(0)
fbuf.hline(0, 1, w, 1)
print("hline", buf)
# vline
fbuf.fill(0)
fbuf.vline(1, 0, h, 1)
print("vline", buf)
# rect
fbuf.fill(0)
fbuf.rect(1, 1, 3, 3, 1)
print("rect", buf)
# fill rect
fbuf.fill(0)
fbuf.fill_rect(0, 0, 0, 3, 1) # zero width, no-operation
fbuf.fill_rect(1, 1, 3, 3, 1)
print("fill_rect", buf)
# line
fbuf.fill(0)
fbuf.line(1, 1, 3, 3, 1)
print("line", buf)
# line steep negative gradient
fbuf.fill(0)
fbuf.line(3, 3, 2, 1, 1)
print("line", buf)
# scroll
fbuf.fill(0)
fbuf.pixel(2, 7, 1)
fbuf.scroll(0, 1)
print(buf)
fbuf.scroll(0, -2)
print(buf)
fbuf.scroll(1, 0)
print(buf)
fbuf.scroll(-1, 0)
print(buf)
fbuf.scroll(2, 2)
print(buf)
# print text
fbuf.fill(0)
fbuf.text("hello", 0, 0, 1)
print(buf)
fbuf.text("hello", 0, 0, 0) # clear
print(buf)
# char out of font range set to chr(127)
fbuf.text(str(chr(31)), 0, 0)
print(buf)
print()
# test invalid constructor, and stride argument
try:
fbuf = framebuf.FrameBuffer(buf, w, h, -1, w)
except ValueError:
print("ValueError")
# test legacy constructor
fbuf = framebuf.FrameBuffer1(buf, w, h)
fbuf = framebuf.FrameBuffer1(buf, w, h, w)
print(framebuf.MVLSB == framebuf.MONO_VLSB)
|
YifuLiu/AliOS-Things
|
components/py_engine/tests/extmod/framebuf1.py
|
Python
|
apache-2.0
| 2,168
|
try:
import framebuf, usys
except ImportError:
print("SKIP")
raise SystemExit
# This test and its .exp file is based on a little-endian architecture.
if usys.byteorder != "little":
print("SKIP")
raise SystemExit
def printbuf():
print("--8<--")
for y in range(h):
print(buf[y * w * 2 : (y + 1) * w * 2])
print("-->8--")
w = 4
h = 5
buf = bytearray(w * h * 2)
fbuf = framebuf.FrameBuffer(buf, w, h, framebuf.RGB565)
# fill
fbuf.fill(0xFFFF)
printbuf()
fbuf.fill(0x0000)
printbuf()
# put pixel
fbuf.pixel(0, 0, 0xEEEE)
fbuf.pixel(3, 0, 0xEE00)
fbuf.pixel(0, 4, 0x00EE)
fbuf.pixel(3, 4, 0x0EE0)
printbuf()
# get pixel
print(fbuf.pixel(0, 4), fbuf.pixel(1, 1))
# scroll
fbuf.fill(0x0000)
fbuf.pixel(2, 2, 0xFFFF)
printbuf()
fbuf.scroll(0, 1)
printbuf()
fbuf.scroll(1, 0)
printbuf()
fbuf.scroll(-1, -2)
printbuf()
w2 = 2
h2 = 3
buf2 = bytearray(w2 * h2 * 2)
fbuf2 = framebuf.FrameBuffer(buf2, w2, h2, framebuf.RGB565)
fbuf2.fill(0x0000)
fbuf2.pixel(0, 0, 0x0EE0)
fbuf2.pixel(0, 2, 0xEE00)
fbuf2.pixel(1, 0, 0x00EE)
fbuf2.pixel(1, 2, 0xE00E)
fbuf.fill(0xFFFF)
fbuf.blit(fbuf2, 3, 3, 0x0000)
fbuf.blit(fbuf2, -1, -1, 0x0000)
fbuf.blit(fbuf2, 16, 16, 0x0000)
printbuf()
|
YifuLiu/AliOS-Things
|
components/py_engine/tests/extmod/framebuf16.py
|
Python
|
apache-2.0
| 1,212
|
try:
import framebuf
except ImportError:
print("SKIP")
raise SystemExit
def printbuf():
print("--8<--")
for y in range(h):
for x in range(w):
print("%u" % ((buf[(x + y * w) // 4] >> ((x & 3) << 1)) & 3), end="")
print()
print("-->8--")
w = 8
h = 5
buf = bytearray(w * h // 4)
fbuf = framebuf.FrameBuffer(buf, w, h, framebuf.GS2_HMSB)
# fill
fbuf.fill(3)
printbuf()
fbuf.fill(0)
printbuf()
# put pixel
fbuf.pixel(0, 0, 1)
fbuf.pixel(3, 0, 2)
fbuf.pixel(0, 4, 3)
fbuf.pixel(3, 4, 2)
printbuf()
# get pixel
print(fbuf.pixel(0, 4), fbuf.pixel(1, 1))
# scroll
fbuf.fill(0)
fbuf.pixel(2, 2, 3)
printbuf()
fbuf.scroll(0, 1)
printbuf()
fbuf.scroll(1, 0)
printbuf()
fbuf.scroll(-1, -2)
printbuf()
w2 = 2
h2 = 3
buf2 = bytearray(w2 * h2 // 4)
fbuf2 = framebuf.FrameBuffer(buf2, w2, h2, framebuf.GS2_HMSB)
# blit
fbuf2.fill(0)
fbuf2.pixel(0, 0, 1)
fbuf2.pixel(0, 2, 2)
fbuf2.pixel(1, 0, 1)
fbuf2.pixel(1, 2, 2)
fbuf.fill(3)
fbuf.blit(fbuf2, 3, 3, 0)
fbuf.blit(fbuf2, -1, -1, 0)
fbuf.blit(fbuf2, 16, 16, 0)
printbuf()
|
YifuLiu/AliOS-Things
|
components/py_engine/tests/extmod/framebuf2.py
|
Python
|
apache-2.0
| 1,068
|
try:
import framebuf
except ImportError:
print("SKIP")
raise SystemExit
def printbuf():
print("--8<--")
for y in range(h):
print(buf[y * w // 2 : (y + 1) * w // 2])
print("-->8--")
w = 16
h = 8
buf = bytearray(w * h // 2)
fbuf = framebuf.FrameBuffer(buf, w, h, framebuf.GS4_HMSB)
# fill
fbuf.fill(0x0F)
printbuf()
fbuf.fill(0xA0)
printbuf()
# put pixel
fbuf.pixel(0, 0, 0x01)
printbuf()
fbuf.pixel(w - 1, 0, 0x02)
printbuf()
fbuf.pixel(w - 1, h - 1, 0x03)
printbuf()
fbuf.pixel(0, h - 1, 0x04)
printbuf()
# get pixel
print(fbuf.pixel(0, 0), fbuf.pixel(w - 1, 0), fbuf.pixel(w - 1, h - 1), fbuf.pixel(0, h - 1))
print(fbuf.pixel(1, 0), fbuf.pixel(w - 2, 0), fbuf.pixel(w - 2, h - 1), fbuf.pixel(1, h - 1))
# fill rect
fbuf.fill_rect(0, 0, w, h, 0x0F)
printbuf()
fbuf.fill_rect(0, 0, w, h, 0xF0)
fbuf.fill_rect(1, 0, w // 2 + 1, 1, 0xF1)
printbuf()
fbuf.fill_rect(1, 0, w // 2 + 1, 1, 0x10)
fbuf.fill_rect(1, 0, w // 2, 1, 0xF1)
printbuf()
fbuf.fill_rect(1, 0, w // 2, 1, 0x10)
fbuf.fill_rect(0, h - 4, w // 2 + 1, 4, 0xAF)
printbuf()
fbuf.fill_rect(0, h - 4, w // 2 + 1, 4, 0xB0)
fbuf.fill_rect(0, h - 4, w // 2, 4, 0xAF)
printbuf()
fbuf.fill_rect(0, h - 4, w // 2, 4, 0xB0)
|
YifuLiu/AliOS-Things
|
components/py_engine/tests/extmod/framebuf4.py
|
Python
|
apache-2.0
| 1,214
|
try:
import framebuf
except ImportError:
print("SKIP")
raise SystemExit
def printbuf():
print("--8<--")
for y in range(h):
for x in range(w):
print("%02x" % buf[(x + y * w)], end="")
print()
print("-->8--")
w = 8
h = 5
buf = bytearray(w * h)
fbuf = framebuf.FrameBuffer(buf, w, h, framebuf.GS8)
# fill
fbuf.fill(0x55)
printbuf()
# put pixel
fbuf.pixel(0, 0, 0x11)
fbuf.pixel(w - 1, 0, 0x22)
fbuf.pixel(0, h - 1, 0x33)
fbuf.pixel(w - 1, h - 1, 0xFF)
printbuf()
# get pixel
print(hex(fbuf.pixel(0, h - 1)), hex(fbuf.pixel(1, 1)))
|
YifuLiu/AliOS-Things
|
components/py_engine/tests/extmod/framebuf8.py
|
Python
|
apache-2.0
| 587
|
# Test blit between different color spaces
try:
import framebuf, usys
except ImportError:
print("SKIP")
raise SystemExit
# Monochrome glyph/icon
w = 8
h = 8
cbuf = bytearray(w * h // 8)
fbc = framebuf.FrameBuffer(cbuf, w, h, framebuf.MONO_HLSB)
fbc.line(0, 0, 7, 7, 1)
# RGB565 destination
wd = 16
hd = 16
dest = bytearray(wd * hd * 2)
fbd = framebuf.FrameBuffer(dest, wd, hd, framebuf.RGB565)
wp = 2
bg = 0x1234
fg = 0xF800
pal = bytearray(wp * 2)
palette = framebuf.FrameBuffer(pal, wp, 1, framebuf.RGB565)
palette.pixel(0, 0, bg)
palette.pixel(1, 0, fg)
fbd.blit(fbc, 0, 0, -1, palette)
print(fbd.pixel(0, 0) == fg)
print(fbd.pixel(7, 7) == fg)
print(fbd.pixel(8, 8) == 0) # Ouside blit
print(fbd.pixel(0, 1) == bg)
print(fbd.pixel(1, 0) == bg)
|
YifuLiu/AliOS-Things
|
components/py_engine/tests/extmod/framebuf_palette.py
|
Python
|
apache-2.0
| 766
|
# test subclassing framebuf.FrameBuffer
try:
import framebuf, usys
except ImportError:
print("SKIP")
raise SystemExit
# This test and its .exp file is based on a little-endian architecture.
if usys.byteorder != "little":
print("SKIP")
raise SystemExit
class FB(framebuf.FrameBuffer):
def __init__(self, n):
self.n = n
super().__init__(bytearray(2 * n * n), n, n, framebuf.RGB565)
def foo(self):
self.hline(0, 2, self.n, 0x0304)
fb = FB(n=3)
fb.pixel(0, 0, 0x0102)
fb.foo()
print(bytes(fb))
# Test that blitting a subclass works.
fb2 = framebuf.FrameBuffer(bytearray(2 * 3 * 3), 3, 3, framebuf.RGB565)
fb.fill(0)
fb.pixel(0, 0, 0x0506)
fb.pixel(2, 2, 0x0708)
fb2.blit(fb, 0, 0)
print(bytes(fb2))
# Test that blitting something that isn't a subclass fails with TypeError.
class NotAFrameBuf:
pass
try:
fb.blit(NotAFrameBuf(), 0, 0)
except TypeError:
print("TypeError")
try:
fb.blit(None, 0, 0)
except TypeError:
print("TypeError")
|
YifuLiu/AliOS-Things
|
components/py_engine/tests/extmod/framebuf_subclass.py
|
Python
|
apache-2.0
| 1,013
|
# test machine module
try:
try:
import umachine as machine
except ImportError:
import machine
machine.mem8
except:
print("SKIP")
raise SystemExit
print(machine.mem8)
try:
machine.mem16[1]
except ValueError:
print("ValueError")
try:
machine.mem16[1] = 1
except ValueError:
print("ValueError")
try:
del machine.mem8[0]
except TypeError:
print("TypeError")
try:
machine.mem8[0:1]
except TypeError:
print("TypeError")
try:
machine.mem8[0:1] = 10
except TypeError:
print("TypeError")
try:
machine.mem8["hello"]
except TypeError:
print("TypeError")
try:
machine.mem8["hello"] = 10
except TypeError:
print("TypeError")
|
YifuLiu/AliOS-Things
|
components/py_engine/tests/extmod/machine1.py
|
Python
|
apache-2.0
| 713
|
try:
try:
import umachine as machine
except ImportError:
import machine
machine.PinBase
except:
print("SKIP")
raise SystemExit
class MyPin(machine.PinBase):
def __init__(self):
print("__init__")
self.v = False
def value(self, v=None):
print("value:", v)
if v is None:
self.v = not self.v
return int(self.v)
p = MyPin()
print(p.value())
print(p.value())
print(p.value())
p.value(1)
p.value(0)
|
YifuLiu/AliOS-Things
|
components/py_engine/tests/extmod/machine_pinbase.py
|
Python
|
apache-2.0
| 498
|
try:
try:
import umachine as machine
except ImportError:
import machine
machine.PinBase
machine.time_pulse_us
except:
print("SKIP")
raise SystemExit
class ConstPin(machine.PinBase):
def __init__(self, value):
self.v = value
def value(self, v=None):
if v is None:
return self.v
else:
self.v = v
class TogglePin(machine.PinBase):
def __init__(self):
self.v = 0
def value(self, v=None):
if v is None:
self.v = 1 - self.v
print("value:", self.v)
return self.v
p = TogglePin()
t = machine.time_pulse_us(p, 1)
print(type(t))
t = machine.time_pulse_us(p, 0)
print(type(t))
p = ConstPin(0)
print(machine.time_pulse_us(p, 1, 10))
print(machine.time_pulse_us(p, 0, 10))
|
YifuLiu/AliOS-Things
|
components/py_engine/tests/extmod/machine_pulse.py
|
Python
|
apache-2.0
| 826
|
# test machine.Signal class
try:
try:
import umachine as machine
except ImportError:
import machine
machine.PinBase
machine.Signal
except:
print("SKIP")
raise SystemExit
class Pin(machine.PinBase):
def __init__(self):
self.v = 0
def value(self, v=None):
if v is None:
return self.v
else:
self.v = int(v)
# test non-inverted
p = Pin()
s = machine.Signal(p)
s.value(0)
print(p.value(), s.value())
s.value(1)
print(p.value(), s.value())
# test inverted, and using on/off methods
p = Pin()
s = machine.Signal(p, invert=True)
s.off()
print(p.value(), s.value())
s.on()
print(p.value(), s.value())
|
YifuLiu/AliOS-Things
|
components/py_engine/tests/extmod/machine_signal.py
|
Python
|
apache-2.0
| 695
|
# test machine.Timer
try:
import utime, umachine as machine
machine.Timer
except:
print("SKIP")
raise SystemExit
# create and deinit
t = machine.Timer(freq=1)
t.deinit()
# deinit again
t.deinit()
# create 2 and deinit
t = machine.Timer(freq=1)
t2 = machine.Timer(freq=1)
t.deinit()
t2.deinit()
# create 2 and deinit in different order
t = machine.Timer(freq=1)
t2 = machine.Timer(freq=1)
t2.deinit()
t.deinit()
# create one-shot timer with callback and wait for it to print (should be just once)
t = machine.Timer(period=1, mode=machine.Timer.ONE_SHOT, callback=lambda t: print("one-shot"))
utime.sleep_ms(5)
t.deinit()
# create periodic timer with callback and wait for it to print
t = machine.Timer(period=4, mode=machine.Timer.PERIODIC, callback=lambda t: print("periodic"))
utime.sleep_ms(14)
t.deinit()
|
YifuLiu/AliOS-Things
|
components/py_engine/tests/extmod/machine_timer.py
|
Python
|
apache-2.0
| 832
|
try:
from utime import ticks_diff, ticks_add
except ImportError:
print("SKIP")
raise SystemExit
MAX = ticks_add(0, -1)
# Should be done like this to avoid small int overflow
MODULO_HALF = MAX // 2 + 1
# Invariants:
# if ticks_diff(a, b) = c,
# then ticks_diff(b, a) = -c
assert ticks_diff(1, 0) == 1, ticks_diff(1, 0)
assert ticks_diff(0, 1) == -1
assert ticks_diff(0, MAX) == 1
assert ticks_diff(MAX, 0) == -1
assert ticks_diff(0, MAX - 1) == 2
# Maximum "positive" distance
assert ticks_diff(MODULO_HALF, 1) == MODULO_HALF - 1, ticks_diff(MODULO_HALF, 1)
# Step further, and it becomes a negative distance
assert ticks_diff(MODULO_HALF, 0) == -MODULO_HALF
# Offsetting that in either direction doesn't affect the result
off = 100
# Cheating and skipping to use ticks_add() when we know there's no wraparound
# Real apps should use always it.
assert ticks_diff(MODULO_HALF + off, 1 + off) == MODULO_HALF - 1
assert ticks_diff(MODULO_HALF + off, 0 + off) == -MODULO_HALF
assert ticks_diff(MODULO_HALF - off, ticks_add(1, -off)) == MODULO_HALF - 1
assert ticks_diff(MODULO_HALF - off, ticks_add(0, -off)) == -MODULO_HALF
print("OK")
|
YifuLiu/AliOS-Things
|
components/py_engine/tests/extmod/ticks_diff.py
|
Python
|
apache-2.0
| 1,152
|
try:
import utime
utime.sleep_ms, utime.sleep_us, utime.ticks_diff, utime.ticks_ms, utime.ticks_us, utime.ticks_cpu
except (ImportError, AttributeError):
print("SKIP")
raise SystemExit
utime.sleep_ms(1)
utime.sleep_us(1)
t0 = utime.ticks_ms()
t1 = utime.ticks_ms()
print(0 <= utime.ticks_diff(t1, t0) <= 1)
t0 = utime.ticks_us()
t1 = utime.ticks_us()
print(0 <= utime.ticks_diff(t1, t0) <= 500)
# ticks_cpu may not be implemented, at least make sure it doesn't decrease
t0 = utime.ticks_cpu()
t1 = utime.ticks_cpu()
print(utime.ticks_diff(t1, t0) >= 0)
|
YifuLiu/AliOS-Things
|
components/py_engine/tests/extmod/time_ms_us.py
|
Python
|
apache-2.0
| 574
|
# Test that tasks return their value correctly to the caller
try:
import uasyncio as asyncio
except ImportError:
try:
import asyncio
except ImportError:
print("SKIP")
raise SystemExit
async def foo():
return 42
async def main():
# Call function directly via an await
print(await foo())
# Create a task and await on it
task = asyncio.create_task(foo())
print(await task)
asyncio.run(main())
|
YifuLiu/AliOS-Things
|
components/py_engine/tests/extmod/uasyncio_await_return.py
|
Python
|
apache-2.0
| 458
|
try:
import uasyncio as asyncio
except ImportError:
try:
import asyncio
except ImportError:
print("SKIP")
raise SystemExit
try:
import utime
ticks = utime.ticks_ms
ticks_diff = utime.ticks_diff
except:
import time
ticks = lambda: int(time.time() * 1000)
ticks_diff = lambda t1, t0: t1 - t0
async def delay_print(t, s):
await asyncio.sleep(t)
print(s)
async def main():
print("start")
await asyncio.sleep(0.001)
print("after sleep")
t0 = ticks()
await delay_print(0.02, "short")
t1 = ticks()
await delay_print(0.04, "long")
t2 = ticks()
await delay_print(-1, "negative")
t3 = ticks()
print(
"took {} {} {}".format(
round(ticks_diff(t1, t0), -1),
round(ticks_diff(t2, t1), -1),
round(ticks_diff(t3, t2), -1),
)
)
asyncio.run(main())
|
YifuLiu/AliOS-Things
|
components/py_engine/tests/extmod/uasyncio_basic.py
|
Python
|
apache-2.0
| 912
|
try:
import uasyncio as asyncio
except ImportError:
try:
import asyncio
except ImportError:
print("SKIP")
raise SystemExit
async def forever():
print("forever start")
await asyncio.sleep(10)
async def main():
print("main start")
asyncio.create_task(forever())
await asyncio.sleep(0.001)
print("main done")
return 42
print(asyncio.run(main()))
|
YifuLiu/AliOS-Things
|
components/py_engine/tests/extmod/uasyncio_basic2.py
|
Python
|
apache-2.0
| 413
|
# Test fairness of cancelling a task
# That tasks which continuously cancel each other don't take over the scheduler
try:
import uasyncio as asyncio
except ImportError:
try:
import asyncio
except ImportError:
print("SKIP")
raise SystemExit
async def task(id, other):
for i in range(3):
try:
print("start", id)
await asyncio.sleep(0)
print("done", id)
except asyncio.CancelledError as er:
print("cancelled", id)
if other is not None:
print(id, "cancels", other)
tasks[other].cancel()
async def main():
global tasks
tasks = [
asyncio.create_task(task(0, 1)),
asyncio.create_task(task(1, 0)),
asyncio.create_task(task(2, None)),
]
await tasks[2]
asyncio.run(main())
|
YifuLiu/AliOS-Things
|
components/py_engine/tests/extmod/uasyncio_cancel_fair.py
|
Python
|
apache-2.0
| 846
|
# Test fairness of cancelling a task
# That tasks which keeps being cancelled by multiple other tasks gets a chance to run
try:
import uasyncio as asyncio
except ImportError:
try:
import asyncio
except ImportError:
print("SKIP")
raise SystemExit
async def task_a():
try:
while True:
print("sleep a")
await asyncio.sleep(0)
except asyncio.CancelledError:
print("cancelled a")
async def task_b(id, other):
while other.cancel():
print("sleep b", id)
await asyncio.sleep(0)
print("done b", id)
async def main():
t = asyncio.create_task(task_a())
for i in range(3):
asyncio.create_task(task_b(i, t))
await t
asyncio.run(main())
|
YifuLiu/AliOS-Things
|
components/py_engine/tests/extmod/uasyncio_cancel_fair2.py
|
Python
|
apache-2.0
| 760
|
# Test a task cancelling itself (currently unsupported)
try:
import uasyncio as asyncio
except ImportError:
try:
import asyncio
except ImportError:
print("SKIP")
raise SystemExit
async def task():
print("task start")
global_task.cancel()
async def main():
global global_task
global_task = asyncio.create_task(task())
try:
await global_task
except asyncio.CancelledError:
print("main cancel")
print("main done")
try:
asyncio.run(main())
except RuntimeError as er:
print(er)
|
YifuLiu/AliOS-Things
|
components/py_engine/tests/extmod/uasyncio_cancel_self.py
|
Python
|
apache-2.0
| 568
|
# Test cancelling a task
try:
import uasyncio as asyncio
except ImportError:
try:
import asyncio
except ImportError:
print("SKIP")
raise SystemExit
async def task(s, allow_cancel):
try:
print("task start")
await asyncio.sleep(s)
print("task done")
except asyncio.CancelledError as er:
print("task cancel")
if allow_cancel:
raise er
async def task2(allow_cancel):
print("task 2")
try:
await asyncio.create_task(task(0.05, allow_cancel))
except asyncio.CancelledError as er:
print("task 2 cancel")
raise er
print("task 2 done")
async def main():
# Cancel task immediately
t = asyncio.create_task(task(2, True))
print(t.cancel())
# Cancel task after it has started
t = asyncio.create_task(task(2, True))
await asyncio.sleep(0.01)
print(t.cancel())
print("main sleep")
await asyncio.sleep(0.01)
# Cancel task multiple times after it has started
t = asyncio.create_task(task(2, True))
await asyncio.sleep(0.01)
for _ in range(4):
print(t.cancel())
print("main sleep")
await asyncio.sleep(0.01)
# Await on a cancelled task
print("main wait")
try:
await t
except asyncio.CancelledError:
print("main got CancelledError")
# Cancel task after it has finished
t = asyncio.create_task(task(0.01, False))
await asyncio.sleep(0.05)
print(t.cancel())
# Nested: task2 waits on task, task2 is cancelled (should cancel task then task2)
print("----")
t = asyncio.create_task(task2(True))
await asyncio.sleep(0.01)
print("main cancel")
t.cancel()
print("main sleep")
await asyncio.sleep(0.1)
# Nested: task2 waits on task, task2 is cancelled but task doesn't allow it (task2 should continue)
print("----")
t = asyncio.create_task(task2(False))
await asyncio.sleep(0.01)
print("main cancel")
t.cancel()
print("main sleep")
await asyncio.sleep(0.1)
asyncio.run(main())
|
YifuLiu/AliOS-Things
|
components/py_engine/tests/extmod/uasyncio_cancel_task.py
|
Python
|
apache-2.0
| 2,078
|
# Test cancelling a task that is waiting on a task that just finishes.
try:
import uasyncio as asyncio
except ImportError:
try:
import asyncio
except ImportError:
print("SKIP")
raise SystemExit
async def sleep_task():
print("sleep_task sleep")
await asyncio.sleep(0)
print("sleep_task wake")
async def wait_task(t):
print("wait_task wait")
await t
print("wait_task wake")
async def main():
waiting_task = asyncio.create_task(wait_task(asyncio.create_task(sleep_task())))
print("main sleep")
await asyncio.sleep(0)
print("main sleep")
await asyncio.sleep(0)
waiting_task.cancel()
print("main wait")
try:
await waiting_task
except asyncio.CancelledError as er:
print(repr(er))
asyncio.run(main())
|
YifuLiu/AliOS-Things
|
components/py_engine/tests/extmod/uasyncio_cancel_wait_on_finished.py
|
Python
|
apache-2.0
| 818
|
# Test current_task() function
try:
import uasyncio as asyncio
except ImportError:
try:
import asyncio
except ImportError:
print("SKIP")
raise SystemExit
async def task(result):
result[0] = asyncio.current_task()
async def main():
result = [None]
t = asyncio.create_task(task(result))
await asyncio.sleep(0)
await asyncio.sleep(0)
print(t is result[0])
asyncio.run(main())
|
YifuLiu/AliOS-Things
|
components/py_engine/tests/extmod/uasyncio_current_task.py
|
Python
|
apache-2.0
| 440
|
# Test Event class
try:
import uasyncio as asyncio
except ImportError:
try:
import asyncio
except ImportError:
print("SKIP")
raise SystemExit
async def task(id, ev):
print("start", id)
print(await ev.wait())
print("end", id)
async def task_delay_set(t, ev):
await asyncio.sleep(t)
print("set event")
ev.set()
async def main():
ev = asyncio.Event()
# Set and clear without anything waiting, and test is_set()
print(ev.is_set())
ev.set()
print(ev.is_set())
ev.clear()
print(ev.is_set())
# Create 2 tasks waiting on the event
print("----")
asyncio.create_task(task(1, ev))
asyncio.create_task(task(2, ev))
print("yield")
await asyncio.sleep(0)
print("set event")
ev.set()
print("yield")
await asyncio.sleep(0)
# Create a task waiting on the already-set event
print("----")
asyncio.create_task(task(3, ev))
print("yield")
await asyncio.sleep(0)
# Clear event, start a task, then set event again
print("----")
print("clear event")
ev.clear()
asyncio.create_task(task(4, ev))
await asyncio.sleep(0)
print("set event")
ev.set()
await asyncio.sleep(0)
# Cancel a task waiting on an event (set event then cancel task)
print("----")
ev = asyncio.Event()
t = asyncio.create_task(task(5, ev))
await asyncio.sleep(0)
ev.set()
t.cancel()
await asyncio.sleep(0.1)
# Cancel a task waiting on an event (cancel task then set event)
print("----")
ev = asyncio.Event()
t = asyncio.create_task(task(6, ev))
await asyncio.sleep(0)
t.cancel()
ev.set()
await asyncio.sleep(0.1)
# Wait for an event that does get set in time
print("----")
ev.clear()
asyncio.create_task(task_delay_set(0.01, ev))
await asyncio.wait_for(ev.wait(), 0.1)
await asyncio.sleep(0)
# Wait for an event that doesn't get set in time
print("----")
ev.clear()
asyncio.create_task(task_delay_set(0.1, ev))
try:
await asyncio.wait_for(ev.wait(), 0.01)
except asyncio.TimeoutError:
print("TimeoutError")
await ev.wait()
asyncio.run(main())
|
YifuLiu/AliOS-Things
|
components/py_engine/tests/extmod/uasyncio_event.py
|
Python
|
apache-2.0
| 2,217
|
# Test fairness of Event.set()
# That tasks which continuously wait on events don't take over the scheduler
try:
import uasyncio as asyncio
except ImportError:
try:
import asyncio
except ImportError:
print("SKIP")
raise SystemExit
async def task1(id):
for i in range(4):
print("sleep", id)
await asyncio.sleep(0)
async def task2(id, ev):
for i in range(4):
ev.set()
ev.clear()
print("wait", id)
await ev.wait()
async def main():
ev = asyncio.Event()
tasks = [
asyncio.create_task(task1(0)),
asyncio.create_task(task2(2, ev)),
asyncio.create_task(task1(1)),
asyncio.create_task(task2(3, ev)),
]
await tasks[1]
ev.set()
asyncio.run(main())
|
YifuLiu/AliOS-Things
|
components/py_engine/tests/extmod/uasyncio_event_fair.py
|
Python
|
apache-2.0
| 791
|
# Test general exception handling
try:
import uasyncio as asyncio
except ImportError:
try:
import asyncio
except ImportError:
print("SKIP")
raise SystemExit
# main task raising an exception
async def main():
print("main start")
raise ValueError(1)
print("main done")
try:
asyncio.run(main())
except ValueError as er:
print("ValueError", er.args[0])
# sub-task raising an exception
async def task():
print("task start")
raise ValueError(2)
print("task done")
async def main():
print("main start")
t = asyncio.create_task(task())
await t
print("main done")
try:
asyncio.run(main())
except ValueError as er:
print("ValueError", er.args[0])
# main task raising an exception with sub-task not yet scheduled
# TODO not currently working, task is never scheduled
async def task():
# print('task run') uncomment this line when it works
pass
async def main():
print("main start")
asyncio.create_task(task())
raise ValueError(3)
print("main done")
try:
asyncio.run(main())
except ValueError as er:
print("ValueError", er.args[0])
|
YifuLiu/AliOS-Things
|
components/py_engine/tests/extmod/uasyncio_exception.py
|
Python
|
apache-2.0
| 1,158
|
# Test fairness of scheduler
try:
import uasyncio as asyncio
except ImportError:
try:
import asyncio
except ImportError:
print("SKIP")
raise SystemExit
async def task(id, t):
print("task start", id)
while True:
if t > 0:
print("task work", id)
await asyncio.sleep(t)
async def main():
t1 = asyncio.create_task(task(1, -0.01))
t2 = asyncio.create_task(task(2, 0.1))
t3 = asyncio.create_task(task(3, 0.18))
t4 = asyncio.create_task(task(4, -100))
await asyncio.sleep(0.5)
t1.cancel()
t2.cancel()
t3.cancel()
t4.cancel()
print("finish")
asyncio.run(main())
|
YifuLiu/AliOS-Things
|
components/py_engine/tests/extmod/uasyncio_fair.py
|
Python
|
apache-2.0
| 673
|
# test uasyncio.gather() function
try:
import uasyncio as asyncio
except ImportError:
try:
import asyncio
except ImportError:
print("SKIP")
raise SystemExit
async def factorial(name, number):
f = 1
for i in range(2, number + 1):
print("Task {}: Compute factorial({})...".format(name, i))
await asyncio.sleep(0.01)
f *= i
print("Task {}: factorial({}) = {}".format(name, number, f))
return f
async def task(id):
print("start", id)
await asyncio.sleep(0.2)
print("end", id)
async def gather_task():
print("gather_task")
await asyncio.gather(task(1), task(2))
print("gather_task2")
async def main():
# Simple gather with return values
print(await asyncio.gather(factorial("A", 2), factorial("B", 3), factorial("C", 4)))
# Cancel a multi gather
# TODO doesn't work, Task should not forward cancellation from gather to sub-task
# but rather CancelledError should cancel the gather directly, which will then cancel
# all sub-tasks explicitly
# t = asyncio.create_task(gather_task())
# await asyncio.sleep(0.1)
# t.cancel()
# await asyncio.sleep(0.01)
asyncio.run(main())
|
YifuLiu/AliOS-Things
|
components/py_engine/tests/extmod/uasyncio_gather.py
|
Python
|
apache-2.0
| 1,217
|
# Test get_event_loop()
try:
import uasyncio as asyncio
except ImportError:
try:
import asyncio
except ImportError:
print("SKIP")
raise SystemExit
async def main():
print("start")
await asyncio.sleep(0.01)
print("end")
loop = asyncio.get_event_loop()
loop.run_until_complete(main())
|
YifuLiu/AliOS-Things
|
components/py_engine/tests/extmod/uasyncio_get_event_loop.py
|
Python
|
apache-2.0
| 336
|
# test that basic scheduling of tasks, and uasyncio.sleep_ms, does not use the heap
import micropython
# strict stackless builds can't call functions without allocating a frame on the heap
try:
f = lambda: 0
micropython.heap_lock()
f()
micropython.heap_unlock()
except RuntimeError:
print("SKIP")
raise SystemExit
try:
import uasyncio as asyncio
except ImportError:
try:
import asyncio
except ImportError:
print("SKIP")
raise SystemExit
async def task(id, n, t):
for i in range(n):
print(id, i)
await asyncio.sleep_ms(t)
async def main():
t1 = asyncio.create_task(task(1, 4, 20))
t2 = asyncio.create_task(task(2, 2, 50))
micropython.heap_lock()
print("start")
await asyncio.sleep_ms(1)
print("sleep")
await asyncio.sleep_ms(70)
print("finish")
micropython.heap_unlock()
asyncio.run(main())
|
YifuLiu/AliOS-Things
|
components/py_engine/tests/extmod/uasyncio_heaplock.py
|
Python
|
apache-2.0
| 918
|
# Test Lock class
try:
import uasyncio as asyncio
except ImportError:
try:
import asyncio
except ImportError:
print("SKIP")
raise SystemExit
async def task_loop(id, lock):
print("task start", id)
for i in range(3):
async with lock:
print("task have", id, i)
print("task end", id)
async def task_sleep(lock):
async with lock:
print("task have", lock.locked())
await asyncio.sleep(0.2)
print("task release", lock.locked())
await lock.acquire()
print("task have again")
lock.release()
async def task_cancel(id, lock, to_cancel=None):
try:
async with lock:
print("task got", id)
await asyncio.sleep(0.1)
print("task release", id)
if to_cancel:
to_cancel[0].cancel()
except asyncio.CancelledError:
print("task cancel", id)
async def main():
lock = asyncio.Lock()
# Basic acquire/release
print(lock.locked())
await lock.acquire()
print(lock.locked())
await asyncio.sleep(0)
lock.release()
print(lock.locked())
await asyncio.sleep(0)
# Use with "async with"
async with lock:
print("have lock")
# 3 tasks wanting the lock
print("----")
asyncio.create_task(task_loop(1, lock))
asyncio.create_task(task_loop(2, lock))
t3 = asyncio.create_task(task_loop(3, lock))
await lock.acquire()
await asyncio.sleep(0)
lock.release()
await t3
# 2 sleeping tasks both wanting the lock
print("----")
asyncio.create_task(task_sleep(lock))
await asyncio.sleep(0.1)
await task_sleep(lock)
# 3 tasks, the first cancelling the second, the third should still run
print("----")
ts = [None]
asyncio.create_task(task_cancel(0, lock, ts))
ts[0] = asyncio.create_task(task_cancel(1, lock))
asyncio.create_task(task_cancel(2, lock))
await asyncio.sleep(0.3)
print(lock.locked())
# 3 tasks, the second and third being cancelled while waiting on the lock
print("----")
t0 = asyncio.create_task(task_cancel(0, lock))
t1 = asyncio.create_task(task_cancel(1, lock))
t2 = asyncio.create_task(task_cancel(2, lock))
await asyncio.sleep(0.05)
t1.cancel()
await asyncio.sleep(0.1)
t2.cancel()
await asyncio.sleep(0.1)
print(lock.locked())
asyncio.run(main())
|
YifuLiu/AliOS-Things
|
components/py_engine/tests/extmod/uasyncio_lock.py
|
Python
|
apache-2.0
| 2,394
|
# Test that locks work when cancelling multiple waiters on the lock
try:
import uasyncio as asyncio
except ImportError:
try:
import asyncio
except ImportError:
print("SKIP")
raise SystemExit
async def task(i, lock, lock_flag):
print("task", i, "start")
try:
await lock.acquire()
except asyncio.CancelledError:
print("task", i, "cancel")
return
print("task", i, "lock_flag", lock_flag[0])
lock_flag[0] = True
await asyncio.sleep(0)
lock.release()
lock_flag[0] = False
print("task", i, "done")
async def main():
# Create a lock and acquire it so the tasks below must wait
lock = asyncio.Lock()
await lock.acquire()
lock_flag = [True]
# Create 4 tasks and let them all run
t0 = asyncio.create_task(task(0, lock, lock_flag))
t1 = asyncio.create_task(task(1, lock, lock_flag))
t2 = asyncio.create_task(task(2, lock, lock_flag))
t3 = asyncio.create_task(task(3, lock, lock_flag))
await asyncio.sleep(0)
# Cancel 2 of the tasks (which are waiting on the lock) and release the lock
t1.cancel()
t2.cancel()
lock.release()
lock_flag[0] = False
# Let the tasks run to completion
for _ in range(4):
await asyncio.sleep(0)
# The locke should be unlocked
print(lock.locked())
asyncio.run(main())
|
YifuLiu/AliOS-Things
|
components/py_engine/tests/extmod/uasyncio_lock_cancel.py
|
Python
|
apache-2.0
| 1,373
|
# Test Loop.stop() to stop the event loop
try:
import uasyncio as asyncio
except ImportError:
try:
import asyncio
except ImportError:
print("SKIP")
raise SystemExit
async def task():
print("task")
async def main():
print("start")
# Stop the loop after next yield
loop.stop()
# Check that calling stop() again doesn't do/break anything
loop.stop()
# This await should stop
print("sleep")
await asyncio.sleep(0)
# Schedule stop, then create a new task, then yield
loop.stop()
asyncio.create_task(task())
await asyncio.sleep(0)
# Final stop
print("end")
loop.stop()
loop = asyncio.get_event_loop()
loop.create_task(main())
for i in range(3):
print("run", i)
loop.run_forever()
|
YifuLiu/AliOS-Things
|
components/py_engine/tests/extmod/uasyncio_loop_stop.py
|
Python
|
apache-2.0
| 795
|
# Test MicroPython extensions on CPython asyncio:
# - sleep_ms
# - wait_for_ms
try:
import utime, uasyncio
except ImportError:
print("SKIP")
raise SystemExit
async def task(id, t):
print("task start", id)
await uasyncio.sleep_ms(t)
print("task end", id)
return id * 2
async def main():
# Simple sleep_ms
t0 = utime.ticks_ms()
await uasyncio.sleep_ms(1)
print(utime.ticks_diff(utime.ticks_ms(), t0) < 100)
# When task finished before the timeout
print(await uasyncio.wait_for_ms(task(1, 5), 50))
# When timeout passes and task is cancelled
try:
print(await uasyncio.wait_for_ms(task(2, 50), 5))
except uasyncio.TimeoutError:
print("timeout")
print("finish")
uasyncio.run(main())
|
YifuLiu/AliOS-Things
|
components/py_engine/tests/extmod/uasyncio_micropython.py
|
Python
|
apache-2.0
| 772
|
# Test Loop.new_event_loop()
try:
import uasyncio as asyncio
except ImportError:
try:
import asyncio
except ImportError:
print("SKIP")
raise SystemExit
async def task():
for i in range(4):
print("task", i)
await asyncio.sleep(0)
await asyncio.sleep(0)
async def main():
print("start")
loop.create_task(task())
await asyncio.sleep(0)
print("stop")
loop.stop()
# Use default event loop to run some tasks
loop = asyncio.get_event_loop()
loop.create_task(main())
loop.run_forever()
# Create new event loop, old one should not keep running
loop = asyncio.new_event_loop()
loop.create_task(main())
loop.run_forever()
|
YifuLiu/AliOS-Things
|
components/py_engine/tests/extmod/uasyncio_new_event_loop.py
|
Python
|
apache-2.0
| 703
|
# Test that tasks return their value correctly to the caller
try:
import uasyncio as asyncio
except ImportError:
try:
import asyncio
except ImportError:
print("SKIP")
raise SystemExit
def custom_handler(loop, context):
print("custom_handler", repr(context["exception"]))
async def task(i):
# Raise with 2 args so exception prints the same in uPy and CPython
raise ValueError(i, i + 1)
async def main():
loop = asyncio.get_event_loop()
# Check default exception handler, should be None
print(loop.get_exception_handler())
# Set exception handler and test it was set
loop.set_exception_handler(custom_handler)
print(loop.get_exception_handler() == custom_handler)
# Create a task that raises and uses the custom exception handler
asyncio.create_task(task(0))
print("sleep")
for _ in range(2):
await asyncio.sleep(0)
# Create 2 tasks to test order of printing exception
asyncio.create_task(task(1))
asyncio.create_task(task(2))
print("sleep")
for _ in range(2):
await asyncio.sleep(0)
# Create a task, let it run, then await it (no exception should be printed)
t = asyncio.create_task(task(3))
await asyncio.sleep(0)
try:
await t
except ValueError as er:
print(repr(er))
print("done")
asyncio.run(main())
|
YifuLiu/AliOS-Things
|
components/py_engine/tests/extmod/uasyncio_set_exception_handler.py
|
Python
|
apache-2.0
| 1,381
|
# Test the Task.done() method
try:
import uasyncio as asyncio
except ImportError:
try:
import asyncio
except ImportError:
print("SKIP")
raise SystemExit
async def task(t, exc=None):
print("task start")
if t >= 0:
await asyncio.sleep(t)
if exc:
raise exc
print("task done")
async def main():
# Task that finishes immediately.
print("=" * 10)
t = asyncio.create_task(task(-1))
print(t.done())
await asyncio.sleep(0)
print(t.done())
await t
print(t.done())
# Task that starts, runs and finishes.
print("=" * 10)
t = asyncio.create_task(task(0.01))
print(t.done())
await asyncio.sleep(0)
print(t.done())
await t
print(t.done())
# Task that raises immediately.
print("=" * 10)
t = asyncio.create_task(task(-1, ValueError))
print(t.done())
await asyncio.sleep(0)
print(t.done())
try:
await t
except ValueError as er:
print(repr(er))
print(t.done())
# Task that raises after a delay.
print("=" * 10)
t = asyncio.create_task(task(0.01, ValueError))
print(t.done())
await asyncio.sleep(0)
print(t.done())
try:
await t
except ValueError as er:
print(repr(er))
print(t.done())
asyncio.run(main())
|
YifuLiu/AliOS-Things
|
components/py_engine/tests/extmod/uasyncio_task_done.py
|
Python
|
apache-2.0
| 1,332
|
# Test Event class
try:
import uasyncio as asyncio
except ImportError:
print("SKIP")
raise SystemExit
import micropython
try:
micropython.schedule
except AttributeError:
print("SKIP")
raise SystemExit
try:
# Unix port can't select/poll on user-defined types.
import uselect as select
poller = select.poll()
poller.register(asyncio.ThreadSafeFlag())
except TypeError:
print("SKIP")
raise SystemExit
async def task(id, flag):
print("task", id)
await flag.wait()
print("task", id, "done")
def set_from_schedule(flag):
print("schedule")
flag.set()
print("schedule done")
async def main():
flag = asyncio.ThreadSafeFlag()
# Set the flag from within the loop.
t = asyncio.create_task(task(1, flag))
print("yield")
await asyncio.sleep(0)
print("set event")
flag.set()
print("yield")
await asyncio.sleep(0)
print("wait task")
await t
# Set the flag from scheduler context.
print("----")
t = asyncio.create_task(task(2, flag))
print("yield")
await asyncio.sleep(0)
print("set event")
micropython.schedule(set_from_schedule, flag)
print("yield")
await asyncio.sleep(0)
print("wait task")
await t
# Flag already set.
print("----")
print("set event")
flag.set()
t = asyncio.create_task(task(3, flag))
print("yield")
await asyncio.sleep(0)
print("wait task")
await t
asyncio.run(main())
|
YifuLiu/AliOS-Things
|
components/py_engine/tests/extmod/uasyncio_threadsafeflag.py
|
Python
|
apache-2.0
| 1,488
|
# Test asyncio.wait_for
try:
import uasyncio as asyncio
except ImportError:
try:
import asyncio
except ImportError:
print("SKIP")
raise SystemExit
async def task(id, t):
print("task start", id)
await asyncio.sleep(t)
print("task end", id)
return id * 2
async def task_catch():
print("task_catch start")
try:
await asyncio.sleep(0.2)
except asyncio.CancelledError:
print("ignore cancel")
print("task_catch done")
async def task_raise():
print("task start")
raise ValueError
async def task_cancel_other(t, other):
print("task_cancel_other start")
await asyncio.sleep(t)
print("task_cancel_other cancel")
other.cancel()
async def task_wait_for_cancel(id, t, t_wait):
print("task_wait_for_cancel start")
try:
await asyncio.wait_for(task(id, t), t_wait)
except asyncio.CancelledError as er:
print("task_wait_for_cancel cancelled")
raise er
async def task_wait_for_cancel_ignore(t_wait):
print("task_wait_for_cancel_ignore start")
try:
await asyncio.wait_for(task_catch(), t_wait)
except asyncio.CancelledError as er:
print("task_wait_for_cancel_ignore cancelled")
raise er
async def main():
sep = "-" * 10
# When task finished before the timeout
print(await asyncio.wait_for(task(1, 0.01), 10))
print(sep)
# When timeout passes and task is cancelled
try:
print(await asyncio.wait_for(task(2, 10), 0.01))
except asyncio.TimeoutError:
print("timeout")
print(sep)
# When timeout passes and task is cancelled, but task ignores the cancellation request
try:
print(await asyncio.wait_for(task_catch(), 0.1))
except asyncio.TimeoutError:
print("TimeoutError")
print(sep)
# When task raises an exception
try:
print(await asyncio.wait_for(task_raise(), 1))
except ValueError:
print("ValueError")
print(sep)
# Timeout of None means wait forever
print(await asyncio.wait_for(task(3, 0.1), None))
print(sep)
# When task is cancelled by another task
t = asyncio.create_task(task(4, 10))
asyncio.create_task(task_cancel_other(0.01, t))
try:
print(await asyncio.wait_for(t, 1))
except asyncio.CancelledError as er:
print(repr(er))
print(sep)
# When wait_for gets cancelled
t = asyncio.create_task(task_wait_for_cancel(4, 1, 2))
await asyncio.sleep(0.01)
t.cancel()
await asyncio.sleep(0.01)
print(sep)
# When wait_for gets cancelled and awaited task ignores the cancellation request
t = asyncio.create_task(task_wait_for_cancel_ignore(2))
await asyncio.sleep(0.01)
t.cancel()
await asyncio.sleep(0.01)
print(sep)
print("finish")
asyncio.run(main())
|
YifuLiu/AliOS-Things
|
components/py_engine/tests/extmod/uasyncio_wait_for.py
|
Python
|
apache-2.0
| 2,851
|
# Test asyncio.wait_for, with forwarding cancellation
try:
import uasyncio as asyncio
except ImportError:
try:
import asyncio
except ImportError:
print("SKIP")
raise SystemExit
async def awaiting(t, return_if_fail):
try:
print("awaiting started")
await asyncio.sleep(t)
except asyncio.CancelledError as er:
# CPython wait_for raises CancelledError inside task but TimeoutError in wait_for
print("awaiting canceled")
if return_if_fail:
return False # return has no effect if Cancelled
else:
raise er
except Exception as er:
print("caught exception", er)
raise er
async def test_cancellation_forwarded(catch, catch_inside):
print("----------")
async def wait():
try:
await asyncio.wait_for(awaiting(2, catch_inside), 1)
except asyncio.TimeoutError as er:
print("Got timeout error")
raise er
except asyncio.CancelledError as er:
print("Got canceled")
if not catch:
raise er
async def cancel(t):
print("cancel started")
await asyncio.sleep(0.01)
print("cancel wait()")
t.cancel()
t = asyncio.create_task(wait())
k = asyncio.create_task(cancel(t))
try:
await t
except asyncio.CancelledError:
print("waiting got cancelled")
asyncio.run(test_cancellation_forwarded(False, False))
asyncio.run(test_cancellation_forwarded(False, True))
asyncio.run(test_cancellation_forwarded(True, True))
asyncio.run(test_cancellation_forwarded(True, False))
|
YifuLiu/AliOS-Things
|
components/py_engine/tests/extmod/uasyncio_wait_for_fwd.py
|
Python
|
apache-2.0
| 1,657
|
# Test waiting on a task
try:
import uasyncio as asyncio
except ImportError:
try:
import asyncio
except ImportError:
print("SKIP")
raise SystemExit
try:
import utime
ticks = utime.ticks_ms
ticks_diff = utime.ticks_diff
except:
import time
ticks = lambda: int(time.time() * 1000)
ticks_diff = lambda t1, t0: t1 - t0
async def task(t):
print("task", t)
async def delay_print(t, s):
await asyncio.sleep(t)
print(s)
async def task_raise():
print("task_raise")
raise ValueError
async def main():
print("start")
# Wait on a task
t = asyncio.create_task(task(1))
await t
# Wait on a task that's already done
t = asyncio.create_task(task(2))
await asyncio.sleep(0.001)
await t
# Wait again on same task
await t
print("----")
# Create 2 tasks
ts1 = asyncio.create_task(delay_print(0.04, "hello"))
ts2 = asyncio.create_task(delay_print(0.08, "world"))
# Time how long the tasks take to finish, they should execute in parallel
print("start")
t0 = ticks()
await ts1
t1 = ticks()
await ts2
t2 = ticks()
print("took {} {}".format(round(ticks_diff(t1, t0), -1), round(ticks_diff(t2, t1), -1)))
# Wait on a task that raises an exception
t = asyncio.create_task(task_raise())
try:
await t
except ValueError:
print("ValueError")
asyncio.run(main())
|
YifuLiu/AliOS-Things
|
components/py_engine/tests/extmod/uasyncio_wait_task.py
|
Python
|
apache-2.0
| 1,453
|
try:
try:
import ubinascii as binascii
except ImportError:
import binascii
except ImportError:
print("SKIP")
raise SystemExit
print(binascii.a2b_base64(b""))
print(binascii.a2b_base64(b"Zg=="))
print(binascii.a2b_base64(b"Zm8="))
print(binascii.a2b_base64(b"Zm9v"))
print(binascii.a2b_base64(b"Zm9vYg=="))
print(binascii.a2b_base64(b"Zm9vYmE="))
print(binascii.a2b_base64(b"Zm9vYmFy"))
print(binascii.a2b_base64(b"AAECAwQFBgc="))
print(binascii.a2b_base64(b"CAkKCwwNDg8="))
print(binascii.a2b_base64(b"f4D/"))
print(binascii.a2b_base64(b"f4D+")) # convert '+'
print(binascii.a2b_base64(b"MTIzNEFCQ0RhYmNk"))
# Ignore invalid characters and pad sequences
print(binascii.a2b_base64(b"Zm9v\n"))
print(binascii.a2b_base64(b"Zm\x009v\n"))
print(binascii.a2b_base64(b"Zm9v=="))
print(binascii.a2b_base64(b"Zm9v==="))
print(binascii.a2b_base64(b"Zm9v===YmFy"))
try:
print(binascii.a2b_base64(b"abc"))
except ValueError:
print("ValueError")
try:
print(binascii.a2b_base64(b"abcde="))
except ValueError:
print("ValueError")
try:
print(binascii.a2b_base64(b"ab*d"))
except ValueError:
print("ValueError")
try:
print(binascii.a2b_base64(b"ab=cdef="))
except ValueError:
print("ValueError")
|
YifuLiu/AliOS-Things
|
components/py_engine/tests/extmod/ubinascii_a2b_base64.py
|
Python
|
apache-2.0
| 1,248
|
try:
try:
import ubinascii as binascii
except ImportError:
import binascii
except ImportError:
print("SKIP")
raise SystemExit
print(binascii.b2a_base64(b""))
print(binascii.b2a_base64(b"f"))
print(binascii.b2a_base64(b"fo"))
print(binascii.b2a_base64(b"foo"))
print(binascii.b2a_base64(b"foob"))
print(binascii.b2a_base64(b"fooba"))
print(binascii.b2a_base64(b"foobar"))
print(binascii.b2a_base64(b"\x00\x01\x02\x03\x04\x05\x06\x07"))
print(binascii.b2a_base64(b"\x08\x09\x0a\x0b\x0c\x0d\x0e\x0f"))
print(binascii.b2a_base64(b"\x7f\x80\xff"))
print(binascii.b2a_base64(b"1234ABCDabcd"))
print(binascii.b2a_base64(b"\x00\x00>")) # convert into '+'
|
YifuLiu/AliOS-Things
|
components/py_engine/tests/extmod/ubinascii_b2a_base64.py
|
Python
|
apache-2.0
| 682
|
try:
try:
import ubinascii as binascii
except ImportError:
import binascii
except ImportError:
print("SKIP")
raise SystemExit
try:
binascii.crc32
except AttributeError:
print("SKIP")
raise SystemExit
print(hex(binascii.crc32(b"The quick brown fox jumps over the lazy dog")))
print(hex(binascii.crc32(b"\x00" * 32)))
print(hex(binascii.crc32(b"\xff" * 32)))
print(hex(binascii.crc32(bytes(range(32)))))
print(hex(binascii.crc32(b" over the lazy dog", binascii.crc32(b"The quick brown fox jumps"))))
print(hex(binascii.crc32(b"\x00" * 16, binascii.crc32(b"\x00" * 16))))
print(hex(binascii.crc32(b"\xff" * 16, binascii.crc32(b"\xff" * 16))))
print(hex(binascii.crc32(bytes(range(16, 32)), binascii.crc32(bytes(range(16))))))
|
YifuLiu/AliOS-Things
|
components/py_engine/tests/extmod/ubinascii_crc32.py
|
Python
|
apache-2.0
| 770
|
try:
try:
import ubinascii as binascii
except ImportError:
import binascii
except ImportError:
print("SKIP")
raise SystemExit
print(binascii.hexlify(b"\x00\x01\x02\x03\x04\x05\x06\x07"))
print(binascii.hexlify(b"\x08\x09\x0a\x0b\x0c\x0d\x0e\x0f"))
print(binascii.hexlify(b"\x7f\x80\xff"))
print(binascii.hexlify(b"1234ABCDabcd"))
|
YifuLiu/AliOS-Things
|
components/py_engine/tests/extmod/ubinascii_hexlify.py
|
Python
|
apache-2.0
| 363
|
try:
try:
import ubinascii as binascii
except ImportError:
import binascii
except ImportError:
print("SKIP")
raise SystemExit
# two arguments supported in uPy but not CPython
a = binascii.hexlify(b"123", ":")
print(a)
# zero length buffer
print(binascii.hexlify(b"", b":"))
|
YifuLiu/AliOS-Things
|
components/py_engine/tests/extmod/ubinascii_micropython.py
|
Python
|
apache-2.0
| 308
|
try:
try:
import ubinascii as binascii
except ImportError:
import binascii
except ImportError:
print("SKIP")
raise SystemExit
print(binascii.unhexlify(b"0001020304050607"))
print(binascii.unhexlify(b"08090a0b0c0d0e0f"))
print(binascii.unhexlify(b"7f80ff"))
print(binascii.unhexlify(b"313233344142434461626364"))
try:
a = binascii.unhexlify(b"0") # odd buffer length
except ValueError:
print("ValueError")
try:
a = binascii.unhexlify(b"gg") # digit not hex
except ValueError:
print("ValueError")
|
YifuLiu/AliOS-Things
|
components/py_engine/tests/extmod/ubinascii_unhexlify.py
|
Python
|
apache-2.0
| 548
|
try:
from Crypto.Cipher import AES
aes = AES.new
except ImportError:
try:
from ucryptolib import aes
except ImportError:
print("SKIP")
raise SystemExit
crypto = aes(b"1234" * 4, 2, b"5678" * 4)
enc = crypto.encrypt(bytes(range(32)))
print(enc)
crypto = aes(b"1234" * 4, 2, b"5678" * 4)
print(crypto.decrypt(enc))
|
YifuLiu/AliOS-Things
|
components/py_engine/tests/extmod/ucryptolib_aes128_cbc.py
|
Python
|
apache-2.0
| 355
|
try:
from ucryptolib import aes
except ImportError:
print("SKIP")
raise SystemExit
def _new(k, ctr_initial):
return aes(k, 6, ctr_initial)
try:
_new(b"x" * 16, b"x" * 16)
except ValueError as e:
# is CTR support disabled?
if e.args[0] == "mode":
print("SKIP")
raise SystemExit
raise e
crypto = _new(b"1234" * 4, b"5678" * 4)
enc = crypto.encrypt(b"a")
print(enc)
enc += crypto.encrypt(b"b" * 1000)
print(enc)
crypto = _new(b"1234" * 4, b"5678" * 4)
print(crypto.decrypt(enc))
|
YifuLiu/AliOS-Things
|
components/py_engine/tests/extmod/ucryptolib_aes128_ctr.py
|
Python
|
apache-2.0
| 530
|
try:
from Crypto.Cipher import AES
aes = AES.new
except ImportError:
try:
from ucryptolib import aes
except ImportError:
print("SKIP")
raise SystemExit
crypto = aes(b"1234" * 4, 1)
enc = crypto.encrypt(bytes(range(32)))
print(enc)
crypto = aes(b"1234" * 4, 1)
print(crypto.decrypt(enc))
|
YifuLiu/AliOS-Things
|
components/py_engine/tests/extmod/ucryptolib_aes128_ecb.py
|
Python
|
apache-2.0
| 329
|
# This tests minimal configuration of ucrypto module, which is
# AES128 encryption (anything else, including AES128 decryption,
# is optional).
try:
from Crypto.Cipher import AES
aes = AES.new
except ImportError:
try:
from ucryptolib import aes
except ImportError:
print("SKIP")
raise SystemExit
crypto = aes(b"1234" * 4, 1)
enc = crypto.encrypt(bytes(range(32)))
print(enc)
|
YifuLiu/AliOS-Things
|
components/py_engine/tests/extmod/ucryptolib_aes128_ecb_enc.py
|
Python
|
apache-2.0
| 417
|
# Inplace operations (input and output buffer is the same)
try:
from ucryptolib import aes
except ImportError:
print("SKIP")
raise SystemExit
crypto = aes(b"1234" * 4, 1)
buf = bytearray(bytes(range(32)))
crypto.encrypt(buf, buf)
print(buf)
crypto = aes(b"1234" * 4, 1)
crypto.decrypt(buf, buf)
print(buf)
|
YifuLiu/AliOS-Things
|
components/py_engine/tests/extmod/ucryptolib_aes128_ecb_inpl.py
|
Python
|
apache-2.0
| 320
|
# Operations with pre-allocated output buffer
try:
from ucryptolib import aes
except ImportError:
print("SKIP")
raise SystemExit
crypto = aes(b"1234" * 4, 1)
enc = bytearray(32)
crypto.encrypt(bytes(range(32)), enc)
print(enc)
crypto = aes(b"1234" * 4, 1)
dec = bytearray(32)
crypto.decrypt(enc, dec)
print(dec)
|
YifuLiu/AliOS-Things
|
components/py_engine/tests/extmod/ucryptolib_aes128_ecb_into.py
|
Python
|
apache-2.0
| 326
|
try:
from Crypto.Cipher import AES
aes = AES.new
except ImportError:
try:
from ucryptolib import aes
except ImportError:
print("SKIP")
raise SystemExit
crypto = aes(b"1234" * 8, 2, b"5678" * 4)
enc = crypto.encrypt(bytes(range(32)))
print(enc)
crypto = aes(b"1234" * 8, 2, b"5678" * 4)
print(crypto.decrypt(enc))
|
YifuLiu/AliOS-Things
|
components/py_engine/tests/extmod/ucryptolib_aes256_cbc.py
|
Python
|
apache-2.0
| 355
|
try:
from Crypto.Cipher import AES
aes = AES.new
except ImportError:
try:
from ucryptolib import aes
except ImportError:
print("SKIP")
raise SystemExit
crypto = aes(b"1234" * 8, 1)
enc = crypto.encrypt(bytes(range(32)))
print(enc)
crypto = aes(b"1234" * 8, 1)
print(crypto.decrypt(enc))
|
YifuLiu/AliOS-Things
|
components/py_engine/tests/extmod/ucryptolib_aes256_ecb.py
|
Python
|
apache-2.0
| 329
|
# This test checks previously known problem values for 32-bit ports.
# It's less useful for 64-bit ports.
try:
import uctypes
except ImportError:
print("SKIP")
raise SystemExit
buf = b"12345678abcd"
struct = uctypes.struct(
uctypes.addressof(buf),
{"f32": uctypes.UINT32 | 0, "f64": uctypes.UINT64 | 4},
uctypes.LITTLE_ENDIAN,
)
struct.f32 = 0x7FFFFFFF
print(buf)
struct.f32 = 0x80000000
print(buf)
struct.f32 = 0xFF010203
print(buf)
struct.f64 = 0x80000000
print(buf)
struct.f64 = 0x80000000 * 2
print(buf)
print("=")
buf = b"12345678abcd"
struct = uctypes.struct(
uctypes.addressof(buf),
{"f32": uctypes.UINT32 | 0, "f64": uctypes.UINT64 | 4},
uctypes.BIG_ENDIAN,
)
struct.f32 = 0x7FFFFFFF
print(buf)
struct.f32 = 0x80000000
print(buf)
struct.f32 = 0xFF010203
print(buf)
struct.f64 = 0x80000000
print(buf)
struct.f64 = 0x80000000 * 2
print(buf)
|
YifuLiu/AliOS-Things
|
components/py_engine/tests/extmod/uctypes_32bit_intbig.py
|
Python
|
apache-2.0
| 896
|
try:
import uctypes
except ImportError:
print("SKIP")
raise SystemExit
desc = {
# arr is array at offset 0, of UINT8 elements, array size is 2
"arr": (uctypes.ARRAY | 0, uctypes.UINT8 | 2),
# arr2 is array at offset 0, size 2, of structures defined recursively
"arr2": (uctypes.ARRAY | 0, 2, {"b": uctypes.UINT8 | 0}),
"arr3": (uctypes.ARRAY | 2, uctypes.UINT16 | 2),
# aligned
"arr5": (uctypes.ARRAY | 0, uctypes.UINT32 | 1),
# unaligned
"arr6": (uctypes.ARRAY | 1, uctypes.UINT32 | 1),
"arr7": (uctypes.ARRAY | 0, 1, {"l": uctypes.UINT32 | 0}),
"arr8": (uctypes.ARRAY | 1, 1, {"l": uctypes.UINT32 | 0}),
}
data = bytearray(5)
S = uctypes.struct(uctypes.addressof(data), desc, uctypes.LITTLE_ENDIAN)
# assign byte
S.arr[0] = 0x11
print(hex(S.arr[0]))
assert hex(S.arr[0]) == "0x11"
# assign word
S.arr3[0] = 0x2233
print(hex(S.arr3[0]))
assert hex(S.arr3[0]) == "0x2233"
# assign word, with index
S.arr3[1] = 0x4455
print(hex(S.arr3[1]))
assert hex(S.arr3[1]) == "0x4455"
# assign long, aligned
S.arr5[0] = 0x66778899
print(hex(S.arr5[0]))
assert hex(S.arr5[0]) == "0x66778899"
print(S.arr5[0] == S.arr7[0].l)
assert S.arr5[0] == S.arr7[0].l
# assign long, unaligned
S.arr6[0] = 0xAABBCCDD
print(hex(S.arr6[0]))
assert hex(S.arr6[0]) == "0xaabbccdd"
print(S.arr6[0] == S.arr8[0].l)
assert S.arr6[0] == S.arr8[0].l
|
YifuLiu/AliOS-Things
|
components/py_engine/tests/extmod/uctypes_array_assign_le.py
|
Python
|
apache-2.0
| 1,382
|
import usys
try:
import uctypes
except ImportError:
print("SKIP")
raise SystemExit
if usys.byteorder != "little":
print("SKIP")
raise SystemExit
desc = {
# arr is array at offset 0, of UINT8 elements, array size is 2
"arr": (uctypes.ARRAY | 0, uctypes.UINT8 | 2),
# arr2 is array at offset 0, size 2, of structures defined recursively
"arr2": (uctypes.ARRAY | 0, 2, {"b": uctypes.UINT8 | 0}),
"arr3": (uctypes.ARRAY | 2, uctypes.UINT16 | 2),
# aligned
"arr5": (uctypes.ARRAY | 0, uctypes.UINT32 | 1),
"arr7": (uctypes.ARRAY | 0, 1, {"l": uctypes.UINT32 | 0}),
"arr8": (uctypes.ARRAY | 0, uctypes.INT8 | 1),
"arr9": (uctypes.ARRAY | 0, uctypes.INT16 | 1),
"arr10": (uctypes.ARRAY | 0, uctypes.INT32 | 1),
"arr11": (uctypes.ARRAY | 0, uctypes.INT64 | 1),
"arr12": (uctypes.ARRAY | 0, uctypes.UINT64 | 1),
"arr13": (uctypes.ARRAY | 1, 1, {"l": {}}),
}
data = bytearray(8)
S = uctypes.struct(uctypes.addressof(data), desc)
# assign byte
S.arr[0] = 0x11
print(hex(S.arr[0]))
assert hex(S.arr[0]) == "0x11"
# assign word
S.arr3[0] = 0x2233
print(hex(S.arr3[0]))
assert hex(S.arr3[0]) == "0x2233"
# assign word, with index
S.arr3[1] = 0x4455
print(hex(S.arr3[1]))
assert hex(S.arr3[1]) == "0x4455"
# assign long, aligned
S.arr5[0] = 0x66778899
print(hex(S.arr5[0]))
assert hex(S.arr5[0]) == "0x66778899"
print(S.arr5[0] == S.arr7[0].l)
assert S.arr5[0] == S.arr7[0].l
# assign int8
S.arr8[0] = 0x11
print(hex(S.arr8[0]))
assert hex(S.arr8[0]) == "0x11"
# assign int16
S.arr9[0] = 0x1122
print(hex(S.arr9[0]))
assert hex(S.arr9[0]) == "0x1122"
# assign int32
S.arr10[0] = 0x11223344
print(hex(S.arr10[0]))
assert hex(S.arr10[0]) == "0x11223344"
# index out of range
try:
print(S.arr8[2])
except IndexError:
print("IndexError")
# syntax error in descriptor
try:
S.arr13[0].l = 0x11
except TypeError:
print("TypeError")
# operation not supported
try:
S.arr13[0] = 0x11
except TypeError:
print("TypeError")
|
YifuLiu/AliOS-Things
|
components/py_engine/tests/extmod/uctypes_array_assign_native_le.py
|
Python
|
apache-2.0
| 2,012
|
import usys
try:
import uctypes
except ImportError:
print("SKIP")
raise SystemExit
if usys.byteorder != "little":
print("SKIP")
raise SystemExit
desc = {
# arr is array at offset 0, of UINT8 elements, array size is 2
"arr": (uctypes.ARRAY | 0, uctypes.UINT8 | 2),
# arr2 is array at offset 0, size 2, of structures defined recursively
"arr2": (uctypes.ARRAY | 0, 2, {"b": uctypes.UINT8 | 0}),
"arr3": (uctypes.ARRAY | 2, uctypes.UINT16 | 2),
# aligned
"arr5": (uctypes.ARRAY | 0, uctypes.UINT32 | 1),
"arr7": (uctypes.ARRAY | 0, 1, {"l": uctypes.UINT32 | 0}),
"arr8": (uctypes.ARRAY | 0, uctypes.INT8 | 1),
"arr9": (uctypes.ARRAY | 0, uctypes.INT16 | 1),
"arr10": (uctypes.ARRAY | 0, uctypes.INT32 | 1),
"arr11": (uctypes.ARRAY | 0, uctypes.INT64 | 1),
"arr12": (uctypes.ARRAY | 0, uctypes.UINT64 | 1),
"arr13": (uctypes.ARRAY | 1, 1, {"l": {}}),
}
data = bytearray(8)
S = uctypes.struct(uctypes.addressof(data), desc)
# assign int64
S.arr11[0] = 0x11223344
print(hex(S.arr11[0]))
assert hex(S.arr11[0]) == "0x11223344"
# assign uint64
S.arr12[0] = 0x11223344
print(hex(S.arr12[0]))
assert hex(S.arr12[0]) == "0x11223344"
|
YifuLiu/AliOS-Things
|
components/py_engine/tests/extmod/uctypes_array_assign_native_le_intbig.py
|
Python
|
apache-2.0
| 1,205
|
# Test uctypes array, load and store, with array size > 1
try:
import uctypes
except ImportError:
print("SKIP")
raise SystemExit
N = 5
for endian in ("NATIVE", "LITTLE_ENDIAN", "BIG_ENDIAN"):
for type_ in ("INT8", "UINT8", "INT16", "UINT16", "INT32", "UINT32", "INT64", "UINT64"):
desc = {"arr": (uctypes.ARRAY | 0, getattr(uctypes, type_) | N)}
sz = uctypes.sizeof(desc)
data = bytearray(sz)
s = uctypes.struct(uctypes.addressof(data), desc, getattr(uctypes, endian))
for i in range(N):
s.arr[i] = i - 2
print(endian, type_, sz, *(s.arr[i] for i in range(N)))
|
YifuLiu/AliOS-Things
|
components/py_engine/tests/extmod/uctypes_array_load_store.py
|
Python
|
apache-2.0
| 640
|
try:
import uctypes
except ImportError:
print("SKIP")
raise SystemExit
desc = {
"arr": (uctypes.ARRAY | 0, uctypes.UINT8 | 2),
"arr2": (uctypes.ARRAY | 2, uctypes.INT8 | 2),
}
data = bytearray(b"01234567")
S = uctypes.struct(uctypes.addressof(data), desc, uctypes.LITTLE_ENDIAN)
# Arrays of UINT8 are accessed as bytearrays
print(S.arr)
# But not INT8, because value range is different
print(type(S.arr2))
# convert to buffer
print(bytearray(S))
|
YifuLiu/AliOS-Things
|
components/py_engine/tests/extmod/uctypes_bytearray.py
|
Python
|
apache-2.0
| 471
|
try:
import uctypes
except ImportError:
print("SKIP")
raise SystemExit
data = bytearray(b"01234567")
print(uctypes.bytes_at(uctypes.addressof(data), 4))
print(uctypes.bytearray_at(uctypes.addressof(data), 4))
|
YifuLiu/AliOS-Things
|
components/py_engine/tests/extmod/uctypes_byteat.py
|
Python
|
apache-2.0
| 223
|
# test general errors with uctypes
try:
import uctypes
except ImportError:
print("SKIP")
raise SystemExit
data = bytearray(b"01234567")
# del subscr not supported
S = uctypes.struct(uctypes.addressof(data), {})
try:
del S[0]
except TypeError:
print("TypeError")
# list is an invalid descriptor
S = uctypes.struct(uctypes.addressof(data), [])
try:
S.x
except TypeError:
print("TypeError")
# can't access attribute with invalid descriptor
S = uctypes.struct(uctypes.addressof(data), {"x": []})
try:
S.x
except TypeError:
print("TypeError")
# can't assign to aggregate
S = uctypes.struct(uctypes.addressof(data), {"x": (uctypes.ARRAY | 0, uctypes.INT8 | 2)})
try:
S.x = 1
except TypeError:
print("TypeError")
# unsupported unary op
try:
hash(S)
except TypeError:
print("TypeError")
|
YifuLiu/AliOS-Things
|
components/py_engine/tests/extmod/uctypes_error.py
|
Python
|
apache-2.0
| 838
|
try:
import uctypes
except ImportError:
print("SKIP")
raise SystemExit
desc = {
"s0": uctypes.UINT16 | 0,
"sub": (0, {"b0": uctypes.UINT8 | 0, "b1": uctypes.UINT8 | 1}),
"arr": (uctypes.ARRAY | 0, uctypes.UINT8 | 2),
"arr2": (uctypes.ARRAY | 0, 2, {"b": uctypes.UINT8 | 0}),
"bitf0": uctypes.BFUINT16 | 0 | 0 << uctypes.BF_POS | 8 << uctypes.BF_LEN,
"bitf1": uctypes.BFUINT16 | 0 | 8 << uctypes.BF_POS | 8 << uctypes.BF_LEN,
"bf0": uctypes.BFUINT16 | 0 | 0 << uctypes.BF_POS | 4 << uctypes.BF_LEN,
"bf1": uctypes.BFUINT16 | 0 | 4 << uctypes.BF_POS | 4 << uctypes.BF_LEN,
"bf2": uctypes.BFUINT16 | 0 | 8 << uctypes.BF_POS | 4 << uctypes.BF_LEN,
"bf3": uctypes.BFUINT16 | 0 | 12 << uctypes.BF_POS | 4 << uctypes.BF_LEN,
"ptr": (uctypes.PTR | 0, uctypes.UINT8),
"ptr2": (uctypes.PTR | 0, {"b": uctypes.UINT8 | 0}),
}
data = bytearray(b"01")
S = uctypes.struct(uctypes.addressof(data), desc, uctypes.LITTLE_ENDIAN)
# print(S)
print(hex(S.s0))
assert hex(S.s0) == "0x3130"
# print(S.sub.b0)
print(S.sub.b0, S.sub.b1)
assert S.sub.b0, S.sub.b1 == (0x30, 0x31)
try:
S[0]
assert False, "Can't index struct"
except TypeError:
print("TypeError")
print("arr:", S.arr[0], S.arr[1])
assert (S.arr[0], S.arr[1]) == (0x30, 0x31)
print("arr of struct:", S.arr2[0].b, S.arr2[1].b)
assert (S.arr2[0].b, S.arr2[1].b) == (0x30, 0x31)
try:
S.arr[2]
assert False, "Out of bounds index"
except IndexError:
print("IndexError")
print("bf:", S.bitf0, S.bitf1)
assert (S.bitf0, S.bitf1) == (0x30, 0x31)
print("bf 4bit:", S.bf3, S.bf2, S.bf1, S.bf0)
assert (S.bf3, S.bf2, S.bf1, S.bf0) == (3, 1, 3, 0)
# Write access
S.sub.b0 = ord("2")
print(data)
assert bytes(data) == b"21"
S.bf3 = 5
print(data)
assert bytes(data) == b"2Q"
desc2 = {
"bf8": uctypes.BFUINT8 | 0 | 0 << uctypes.BF_POS | 4 << uctypes.BF_LEN,
"bf32": uctypes.BFUINT32 | 0 | 20 << uctypes.BF_POS | 4 << uctypes.BF_LEN,
}
data2 = bytearray(b"0123")
S2 = uctypes.struct(uctypes.addressof(data2), desc2, uctypes.LITTLE_ENDIAN)
# bitfield using uint8 as base type
S2.bf8 = 5
print(data2)
assert bytes(data2) == b"5123"
# bitfield using uint32 as base type
S2.bf32 = 5
print(data2)
assert bytes(data2) == b"51R3"
|
YifuLiu/AliOS-Things
|
components/py_engine/tests/extmod/uctypes_le.py
|
Python
|
apache-2.0
| 2,257
|
try:
import uctypes
except ImportError:
print("SKIP")
raise SystemExit
desc = {
"f32": uctypes.FLOAT32 | 0,
"f64": uctypes.FLOAT64 | 0,
"uf64": uctypes.FLOAT64 | 2, # unaligned
}
data = bytearray(10)
S = uctypes.struct(uctypes.addressof(data), desc, uctypes.LITTLE_ENDIAN)
S.f32 = 12.34
print("%.4f" % S.f32)
S.f64 = 12.34
print("%.4f" % S.f64)
S.uf64 = 12.34
print("%.4f" % S.uf64)
# array of float/double
desc = {
"af32": (uctypes.ARRAY | 0, uctypes.FLOAT32 | 2),
"af64": (uctypes.ARRAY | 0, uctypes.FLOAT64 | 2),
}
data = bytearray(16)
S = uctypes.struct(uctypes.addressof(data), desc, uctypes.LITTLE_ENDIAN)
S.af32[0] = 1
S.af32[1] = 2
print("%.4f %.4f" % (S.af32[0], S.af32[1]), data)
S.af64[0] = 1
S.af64[1] = 2
print("%.4f %.4f" % (S.af64[0], S.af64[1]), data)
|
YifuLiu/AliOS-Things
|
components/py_engine/tests/extmod/uctypes_le_float.py
|
Python
|
apache-2.0
| 810
|
try:
import uctypes
except ImportError:
print("SKIP")
raise SystemExit
desc = {
"f32": uctypes.FLOAT32 | 0,
"f64": uctypes.FLOAT64 | 0,
}
data = bytearray(8)
S = uctypes.struct(uctypes.addressof(data), desc, uctypes.NATIVE)
S.f32 = 12.34
print("%.4f" % S.f32)
S.f64 = 12.34
print("%.4f" % S.f64)
|
YifuLiu/AliOS-Things
|
components/py_engine/tests/extmod/uctypes_native_float.py
|
Python
|
apache-2.0
| 321
|