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
# This test is exactly like uctypes_le.py, but uses native structure layout. # Codepaths for packed vs native structures are different. This test only works # on little-endian machine (no matter if 32 or 64 bit). import usys try: import uctypes except ImportError: print("SKIP") raise SystemExit if usys.byteorder != "little": 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.NATIVE) # 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.NATIVE) # 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_native_le.py
Python
apache-2.0
2,540
# test printing of uctypes objects try: import uctypes except ImportError: print("SKIP") raise SystemExit # we use an address of "0" because we just want to print something deterministic # and don't actually need to set/get any values in the struct desc = {"arr": (uctypes.ARRAY | 0, uctypes.UINT8 | 1)} S = uctypes.struct(0, desc) print(S) desc2 = [(uctypes.ARRAY | 0, uctypes.UINT8 | 1)] S2 = uctypes.struct(0, desc2) print(S2) desc3 = (uctypes.ARRAY | 0, uctypes.UINT8 | 1) S3 = uctypes.struct(0, desc3) print(S3) desc4 = (uctypes.PTR | 0, uctypes.UINT8 | 1) S4 = uctypes.struct(0, desc4) print(S4)
YifuLiu/AliOS-Things
components/py_engine/tests/extmod/uctypes_print.py
Python
apache-2.0
619
import usys try: import uctypes except ImportError: print("SKIP") raise SystemExit if usys.byteorder != "little": print("SKIP") raise SystemExit desc = { "ptr": (uctypes.PTR | 0, uctypes.UINT8), "ptr16": (uctypes.PTR | 0, uctypes.UINT16), "ptr2": (uctypes.PTR | 0, {"b": uctypes.UINT8 | 0}), } bytes = b"01" addr = uctypes.addressof(bytes) buf = addr.to_bytes(uctypes.sizeof(desc), "little") S = uctypes.struct(uctypes.addressof(buf), desc, uctypes.LITTLE_ENDIAN) print(addr == int(S.ptr)) print(addr == int(S.ptr2)) print(S.ptr[0]) assert S.ptr[0] == ord("0") print(S.ptr[1]) assert S.ptr[1] == ord("1") print(hex(S.ptr16[0])) assert hex(S.ptr16[0]) == "0x3130" print(S.ptr2[0].b, S.ptr2[1].b) print(S.ptr2[0].b, S.ptr2[1].b) print(hex(S.ptr16[0])) assert (S.ptr2[0].b, S.ptr2[1].b) == (48, 49)
YifuLiu/AliOS-Things
components/py_engine/tests/extmod/uctypes_ptr_le.py
Python
apache-2.0
836
import usys try: import uctypes except ImportError: print("SKIP") raise SystemExit if usys.byteorder != "little": print("SKIP") raise SystemExit desc = { "ptr": (uctypes.PTR | 0, uctypes.UINT8), "ptr16": (uctypes.PTR | 0, uctypes.UINT16), "ptr2": (uctypes.PTR | 0, {"b": uctypes.UINT8 | 0}), } bytes = b"01" addr = uctypes.addressof(bytes) buf = addr.to_bytes(uctypes.sizeof(desc), "little") S = uctypes.struct(uctypes.addressof(buf), desc, uctypes.NATIVE) print(S.ptr[0]) assert S.ptr[0] == ord("0") print(S.ptr[1]) assert S.ptr[1] == ord("1") print(hex(S.ptr16[0])) assert hex(S.ptr16[0]) == "0x3130" print(S.ptr2[0].b, S.ptr2[1].b) print(S.ptr2[0].b, S.ptr2[1].b) print(hex(S.ptr16[0])) assert (S.ptr2[0].b, S.ptr2[1].b) == (48, 49)
YifuLiu/AliOS-Things
components/py_engine/tests/extmod/uctypes_ptr_native_le.py
Python
apache-2.0
776
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), "arr4": (uctypes.ARRAY | 0, 2, {"b": uctypes.UINT8 | 0, "w": uctypes.UINT16 | 1}), "sub": ( 0, { "b1": uctypes.BFUINT8 | 0 | 4 << uctypes.BF_POS | 4 << uctypes.BF_LEN, "b2": uctypes.BFUINT8 | 0 | 0 << uctypes.BF_POS | 4 << uctypes.BF_LEN, }, ), } data = bytearray(b"01234567") S = uctypes.struct(uctypes.addressof(data), desc, uctypes.LITTLE_ENDIAN) print(uctypes.sizeof(S.arr)) assert uctypes.sizeof(S.arr) == 2 print(uctypes.sizeof(S.arr2)) assert uctypes.sizeof(S.arr2) == 2 print(uctypes.sizeof(S.arr3)) try: print(uctypes.sizeof(S.arr3[0])) except TypeError: print("TypeError") print(uctypes.sizeof(S.arr4)) assert uctypes.sizeof(S.arr4) == 6 print(uctypes.sizeof(S.sub)) assert uctypes.sizeof(S.sub) == 1 # invalid descriptor try: print(uctypes.sizeof([])) except TypeError: print("TypeError")
YifuLiu/AliOS-Things
components/py_engine/tests/extmod/uctypes_sizeof.py
Python
apache-2.0
1,286
try: import uctypes except ImportError: print("SKIP") raise SystemExit print(uctypes.sizeof({"f": uctypes.FLOAT32})) print(uctypes.sizeof({"f": uctypes.FLOAT64})) print(uctypes.sizeof({"f": (uctypes.ARRAY | 0, uctypes.FLOAT32 | 2)})) print(uctypes.sizeof({"f": (uctypes.ARRAY | 0, uctypes.FLOAT64 | 2)}))
YifuLiu/AliOS-Things
components/py_engine/tests/extmod/uctypes_sizeof_float.py
Python
apache-2.0
318
try: import uctypes except ImportError: print("SKIP") raise SystemExit desc = { "f1": 0 | uctypes.UINT32, "f2": 4 | uctypes.UINT8, } # uctypes.NATIVE is default print(uctypes.sizeof(desc) == uctypes.sizeof(desc, uctypes.NATIVE)) # Here we assume that that we run on a platform with convential ABI # (which rounds up structure size based on max alignment). For platforms # where that doesn't hold, this tests should be just disabled in the runner. print(uctypes.sizeof(desc, uctypes.NATIVE) > uctypes.sizeof(desc, uctypes.LITTLE_ENDIAN)) # When taking sizeof of instantiated structure, layout type param # is prohibited (because structure already has its layout type). s = uctypes.struct(0, desc, uctypes.LITTLE_ENDIAN) try: uctypes.sizeof(s, uctypes.LITTLE_ENDIAN) except TypeError: print("TypeError")
YifuLiu/AliOS-Things
components/py_engine/tests/extmod/uctypes_sizeof_layout.py
Python
apache-2.0
835
try: import uctypes except ImportError: print("SKIP") raise SystemExit S1 = {} assert uctypes.sizeof(S1) == 0 S2 = {"a": uctypes.UINT8 | 0} assert uctypes.sizeof(S2) == 1 S3 = { "a": uctypes.UINT8 | 0, "b": uctypes.UINT8 | 1, } assert uctypes.sizeof(S3) == 2 S4 = { "a": uctypes.UINT8 | 0, "b": uctypes.UINT32 | 4, "c": uctypes.UINT8 | 8, } assert uctypes.sizeof(S4) == 12 S5 = { "a": uctypes.UINT8 | 0, "b": uctypes.UINT32 | 4, "c": uctypes.UINT8 | 8, "d": uctypes.UINT32 | 0, "sub": (4, {"b0": uctypes.UINT8 | 0, "b1": uctypes.UINT8 | 1}), } assert uctypes.sizeof(S5) == 12 s5 = uctypes.struct(0, S5) assert uctypes.sizeof(s5) == 12 assert uctypes.sizeof(s5.sub) == 2 S6 = { "ptr": (uctypes.PTR | 0, uctypes.UINT8), } # As if there're no other arch bitnesses assert uctypes.sizeof(S6) in (4, 8) S7 = { "arr": (uctypes.ARRAY | 0, uctypes.UINT8 | 5), } assert uctypes.sizeof(S7) == 5 S8 = { "arr": (uctypes.ARRAY | 0, 3, {"a": uctypes.UINT32 | 0, "b": uctypes.UINT8 | 4}), } assert uctypes.sizeof(S8) == 24
YifuLiu/AliOS-Things
components/py_engine/tests/extmod/uctypes_sizeof_native.py
Python
apache-2.0
1,081
try: from ucollections import OrderedDict import uctypes except ImportError: print("SKIP") raise SystemExit desc = OrderedDict( { # 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), "arr4": (uctypes.ARRAY | 0, 2, {"b": uctypes.UINT8 | 0, "w": uctypes.UINT16 | 1}), "sub": ( 0, { "b1": uctypes.BFUINT8 | 0 | 4 << uctypes.BF_POS | 4 << uctypes.BF_LEN, "b2": uctypes.BFUINT8 | 0 | 0 << uctypes.BF_POS | 4 << uctypes.BF_LEN, }, ), } ) data = bytearray(b"01234567") S = uctypes.struct(uctypes.addressof(data), desc, uctypes.LITTLE_ENDIAN) print(uctypes.sizeof(S.arr)) assert uctypes.sizeof(S.arr) == 2 print(uctypes.sizeof(S.arr2)) assert uctypes.sizeof(S.arr2) == 2 print(uctypes.sizeof(S.arr3)) try: print(uctypes.sizeof(S.arr3[0])) except TypeError: print("TypeError") print(uctypes.sizeof(S.arr4)) assert uctypes.sizeof(S.arr4) == 6 print(uctypes.sizeof(S.sub)) assert uctypes.sizeof(S.sub) == 1 # invalid descriptor try: print(uctypes.sizeof([])) except TypeError: print("TypeError")
YifuLiu/AliOS-Things
components/py_engine/tests/extmod/uctypes_sizeof_od.py
Python
apache-2.0
1,402
try: import uhashlib except ImportError: print("SKIP") raise SystemExit for algo_name in ("md5", "sha1", "sha256"): algo = getattr(uhashlib, algo_name, None) if not algo: continue # Running .digest() several times in row is not supported. h = algo(b"123") h.digest() try: h.digest() print("fail") except ValueError: # Expected path, don't print anything so test output is the # same even if the algorithm is not implemented on the port. pass # Partial digests are not supported. h = algo(b"123") h.digest() try: h.update(b"456") print("fail") except ValueError: # Expected path, don't print anything so test output is the # same even if the algorithm is not implemented on the port. pass print("done")
YifuLiu/AliOS-Things
components/py_engine/tests/extmod/uhashlib_final.py
Python
apache-2.0
855
try: import uhashlib as hashlib except ImportError: try: import hashlib except ImportError: # This is neither uPy, nor cPy, so must be uPy with # uhashlib module disabled. print("SKIP") raise SystemExit try: hashlib.md5 except AttributeError: # MD5 is only available on some ports print("SKIP") raise SystemExit md5 = hashlib.md5(b"hello") md5.update(b"world") print(md5.digest())
YifuLiu/AliOS-Things
components/py_engine/tests/extmod/uhashlib_md5.py
Python
apache-2.0
451
try: import uhashlib as hashlib except ImportError: try: import hashlib except ImportError: # This is neither uPy, nor cPy, so must be uPy with # uhashlib module disabled. print("SKIP") raise SystemExit try: hashlib.sha1 except AttributeError: # SHA1 is only available on some ports print("SKIP") raise SystemExit sha1 = hashlib.sha1(b"hello") sha1.update(b"world") print(sha1.digest())
YifuLiu/AliOS-Things
components/py_engine/tests/extmod/uhashlib_sha1.py
Python
apache-2.0
457
try: import uhashlib as hashlib except ImportError: try: import hashlib except ImportError: # This is neither uPy, nor cPy, so must be uPy with # uhashlib module disabled. print("SKIP") raise SystemExit h = hashlib.sha256() print(h.digest()) h = hashlib.sha256() h.update(b"123") print(h.digest()) h = hashlib.sha256() h.update(b"abcd" * 1000) print(h.digest()) print(hashlib.sha256(b"\xff" * 64).digest()) # 56 bytes is a boundary case in the algorithm print(hashlib.sha256(b"\xff" * 56).digest()) # TODO: running .digest() several times in row is not supported() # h = hashlib.sha256(b'123') # print(h.digest()) # print(h.digest()) # TODO: partial digests are not supported # h = hashlib.sha256(b'123') # print(h.digest()) # h.update(b'456') # print(h.digest())
YifuLiu/AliOS-Things
components/py_engine/tests/extmod/uhashlib_sha256.py
Python
apache-2.0
824
try: import uheapq as heapq except: try: import heapq except ImportError: print("SKIP") raise SystemExit try: heapq.heappop([]) except IndexError: print("IndexError") try: heapq.heappush((), 1) except TypeError: print("TypeError") def pop_and_print(h): l = [] while h: l.append(str(heapq.heappop(h))) print(" ".join(l)) h = [] heapq.heappush(h, 3) heapq.heappush(h, 1) heapq.heappush(h, 2) print(h) pop_and_print(h) h = [4, 3, 8, 9, 10, 2, 7, 11, 5] heapq.heapify(h) print(h) heapq.heappush(h, 1) heapq.heappush(h, 6) heapq.heappush(h, 12) print(h) pop_and_print(h)
YifuLiu/AliOS-Things
components/py_engine/tests/extmod/uheapq1.py
Python
apache-2.0
645
try: from uio import StringIO import ujson as json except: try: from io import StringIO import json except ImportError: print("SKIP") raise SystemExit s = StringIO() json.dump(False, s) print(s.getvalue()) s = StringIO() json.dump({"a": (2, [3, None])}, s) print(s.getvalue()) # dump to a small-int not allowed try: json.dump(123, 1) except (AttributeError, OSError): # CPython and uPy have different errors print("Exception") # dump to an object not allowed try: json.dump(123, {}) except (AttributeError, OSError): # CPython and uPy have different errors print("Exception")
YifuLiu/AliOS-Things
components/py_engine/tests/extmod/ujson_dump.py
Python
apache-2.0
646
# test ujson.dump in combination with uio.IOBase try: import uio as io import ujson as json except ImportError: try: import io, json except ImportError: print("SKIP") raise SystemExit if not hasattr(io, "IOBase"): print("SKIP") raise SystemExit # a user stream that only has the write method class S(io.IOBase): def __init__(self): self.buf = "" def write(self, buf): if type(buf) == bytearray: # uPy passes a bytearray, CPython passes a str buf = str(buf, "ascii") self.buf += buf return len(buf) # dump to the user stream s = S() json.dump([123, {}], s) print(s.buf)
YifuLiu/AliOS-Things
components/py_engine/tests/extmod/ujson_dump_iobase.py
Python
apache-2.0
688
try: from uio import StringIO import ujson as json except: try: from io import StringIO import json except ImportError: print("SKIP") raise SystemExit for sep in [ None, (", ", ": "), (",", ": "), (",", ":"), [", ", ": "], [",", ": "], [",", ":"], ]: s = StringIO() json.dump(False, s, separators=sep) print(s.getvalue()) s = StringIO() json.dump({"a": (2, [3, None])}, s, separators=sep) print(s.getvalue()) # dump to a small-int not allowed try: json.dump(123, 1, separators=sep) except (AttributeError, OSError): # CPython and uPy have different errors print("Exception") # dump to an object not allowed try: json.dump(123, {}, separators=sep) except (AttributeError, OSError): # CPython and uPy have different errors print("Exception") try: s = StringIO() json.dump(False, s, separators={"a": 1}) except (TypeError, ValueError): # CPython and uPy have different errors print("Exception") # invalid separator types for sep in [1, object()]: try: s = StringIO() json.dump(False, s, separators=sep) except TypeError: print("Exception") # too many/ not enough separators for sep in [(), (",", ":", "?"), (",",), []]: try: s = StringIO() json.dump(False, s, separators=sep) except ValueError: print("Exception")
YifuLiu/AliOS-Things
components/py_engine/tests/extmod/ujson_dump_separators.py
Python
apache-2.0
1,454
try: import ujson as json except ImportError: try: import json except ImportError: print("SKIP") raise SystemExit print(json.dumps(False)) print(json.dumps(True)) print(json.dumps(None)) print(json.dumps(1)) print(json.dumps("abc")) print(json.dumps("\x00\x01\x7e")) print(json.dumps([])) print(json.dumps([1])) print(json.dumps([1, 2])) print(json.dumps([1, True])) print(json.dumps(())) print(json.dumps((1,))) print(json.dumps((1, 2))) print(json.dumps((1, (2, 3)))) print(json.dumps({})) print(json.dumps({"a": 1})) print(json.dumps({"a": (2, [3, None])})) print(json.dumps('"quoted"')) print(json.dumps("space\n\r\tspace")) print(json.dumps({None: -1})) print(json.dumps({False: 0})) print(json.dumps({True: 1})) print(json.dumps({1: 2}))
YifuLiu/AliOS-Things
components/py_engine/tests/extmod/ujson_dumps.py
Python
apache-2.0
781
# test uPy ujson behaviour that's not valid in CPy try: import ujson except ImportError: print("SKIP") raise SystemExit print(ujson.dumps(b"1234"))
YifuLiu/AliOS-Things
components/py_engine/tests/extmod/ujson_dumps_extra.py
Python
apache-2.0
162
try: import ujson as json except ImportError: try: import json except ImportError: print("SKIP") raise SystemExit print(json.dumps(1.2)) print(json.dumps({1.5: "hi"}))
YifuLiu/AliOS-Things
components/py_engine/tests/extmod/ujson_dumps_float.py
Python
apache-2.0
205
try: import ujson as json from ucollections import OrderedDict except ImportError: try: import json from collections import OrderedDict except ImportError: print("SKIP") raise SystemExit print(json.dumps(OrderedDict(((1, 2), (3, 4)))))
YifuLiu/AliOS-Things
components/py_engine/tests/extmod/ujson_dumps_ordereddict.py
Python
apache-2.0
285
try: import ujson as json except ImportError: try: import json except ImportError: print("SKIP") raise SystemExit for sep in [ None, (", ", ": "), (",", ": "), (",", ":"), [", ", ": "], [",", ": "], [",", ":"], ]: print(json.dumps(False, separators=sep)) print(json.dumps(True, separators=sep)) print(json.dumps(None, separators=sep)) print(json.dumps(1, separators=sep)) print(json.dumps("abc", separators=sep)) print(json.dumps("\x00\x01\x7e", separators=sep)) print(json.dumps([], separators=sep)) print(json.dumps([1], separators=sep)) print(json.dumps([1, 2], separators=sep)) print(json.dumps([1, True], separators=sep)) print(json.dumps((), separators=sep)) print(json.dumps((1,), separators=sep)) print(json.dumps((1, 2), separators=sep)) print(json.dumps((1, (2, 3)), separators=sep)) print(json.dumps({}, separators=sep)) print(json.dumps({"a": 1}, separators=sep)) print(json.dumps({"a": (2, [3, None])}, separators=sep)) print(json.dumps('"quoted"', separators=sep)) print(json.dumps("space\n\r\tspace", separators=sep)) print(json.dumps({None: -1}, separators=sep)) print(json.dumps({False: 0}, separators=sep)) print(json.dumps({True: 1}, separators=sep)) print(json.dumps({1: 2}, separators=sep)) try: json.dumps(False, separators={"a": 1}) except (TypeError, ValueError): # CPython and uPy have different errors print("Exception") # invalid separator types for sep in [1, object()]: try: json.dumps(False, separators=sep) except TypeError: print("Exception") # too many/ not enough separators for sep in [(), (",", ":", "?"), (",",), []]: try: json.dumps(False, separators=sep) except ValueError: print("Exception")
YifuLiu/AliOS-Things
components/py_engine/tests/extmod/ujson_dumps_separators.py
Python
apache-2.0
1,849
try: from uio import StringIO import ujson as json except: try: from io import StringIO import json except ImportError: print("SKIP") raise SystemExit print(json.load(StringIO("null"))) print(json.load(StringIO('"abc\\u0064e"'))) print(json.load(StringIO("[false, true, 1, -2]"))) print(json.load(StringIO('{"a":true}')))
YifuLiu/AliOS-Things
components/py_engine/tests/extmod/ujson_load.py
Python
apache-2.0
371
try: import ujson as json except ImportError: try: import json except ImportError: print("SKIP") raise SystemExit def my_print(o): if isinstance(o, dict): print("sorted dict", sorted(o.items())) else: print(o) my_print(json.loads("null")) my_print(json.loads("false")) my_print(json.loads("true")) my_print(json.loads("1")) my_print(json.loads("-2")) my_print(json.loads('"abc\\u0064e"')) my_print(json.loads("[]")) my_print(json.loads("[null]")) my_print(json.loads("[null,false,true]")) my_print(json.loads(" [ null , false , true ] ")) my_print(json.loads("{}")) my_print(json.loads('{"a":true}')) my_print(json.loads('{"a":null, "b":false, "c":true}')) my_print(json.loads('{"a":[], "b":[1], "c":{"3":4}}')) my_print(json.loads('"abc\\bdef"')) my_print(json.loads('"abc\\fdef"')) my_print(json.loads('"abc\\ndef"')) my_print(json.loads('"abc\\rdef"')) my_print(json.loads('"abc\\tdef"')) my_print(json.loads('"abc\\uabcd"')) # whitespace handling my_print(json.loads('{\n\t"a":[]\r\n, "b":[1], "c":{"3":4} \n\r\t\r\r\r\n}')) # loading nothing should raise exception try: json.loads("") except ValueError: print("ValueError") # string which is not closed try: my_print(json.loads('"abc')) except ValueError: print("ValueError") # unaccompanied closing brace try: my_print(json.loads("]")) except ValueError: print("ValueError") # unspecified object type try: my_print(json.loads("a")) except ValueError: print("ValueError") # bad property name try: my_print(json.loads('{{}:"abc"}')) except ValueError: print("ValueError") # unexpected characters after white space try: my_print(json.loads("[null] a")) except ValueError: print("ValueError")
YifuLiu/AliOS-Things
components/py_engine/tests/extmod/ujson_loads.py
Python
apache-2.0
1,770
# test loading from bytes and bytearray (introduced in Python 3.6) try: import ujson as json except ImportError: try: import json except ImportError: print("SKIP") raise SystemExit print(json.loads(b"[1,2]")) print(json.loads(bytearray(b"[null]")))
YifuLiu/AliOS-Things
components/py_engine/tests/extmod/ujson_loads_bytes.py
Python
apache-2.0
287
try: import ujson as json except ImportError: try: import json except ImportError: print("SKIP") raise SystemExit def my_print(o): print("%.3f" % o) my_print(json.loads("1.2")) my_print(json.loads("1e2")) my_print(json.loads("-2.3")) my_print(json.loads("-2e3")) my_print(json.loads("-2e+3")) my_print(json.loads("-2e-3"))
YifuLiu/AliOS-Things
components/py_engine/tests/extmod/ujson_loads_float.py
Python
apache-2.0
367
try: import urandom as random except ImportError: try: import random except ImportError: print("SKIP") raise SystemExit # check getrandbits returns a value within the bit range for b in (1, 2, 3, 4, 16, 32): for i in range(50): assert random.getrandbits(b) < (1 << b) # check that seed(0) gives a non-zero value random.seed(0) print(random.getrandbits(16) != 0) # check that PRNG is repeatable random.seed(1) r = random.getrandbits(16) random.seed(1) print(random.getrandbits(16) == r) # check that zero bits works print(random.getrandbits(0)) # check that it throws an error for negative bits try: random.getrandbits(-1) except ValueError: print("ValueError")
YifuLiu/AliOS-Things
components/py_engine/tests/extmod/urandom_basic.py
Python
apache-2.0
722
try: import urandom as random except ImportError: try: import random except ImportError: print("SKIP") raise SystemExit try: random.randint except AttributeError: print("SKIP") raise SystemExit print("randrange") for i in range(50): assert 0 <= random.randrange(4) < 4 assert 2 <= random.randrange(2, 6) < 6 assert -2 <= random.randrange(-2, 2) < 2 assert random.randrange(1, 9, 2) in (1, 3, 5, 7) assert random.randrange(2, 1, -1) in (1, 2) # empty range try: random.randrange(0) except ValueError: print("ValueError") # empty range try: random.randrange(2, 1) except ValueError: print("ValueError") # zero step try: random.randrange(2, 1, 0) except ValueError: print("ValueError") # empty range try: random.randrange(2, 1, 1) except ValueError: print("ValueError") print("randint") for i in range(50): assert 0 <= random.randint(0, 4) <= 4 assert 2 <= random.randint(2, 6) <= 6 assert -2 <= random.randint(-2, 2) <= 2 # empty range try: random.randint(2, 1) except ValueError: print("ValueError") print("choice") lst = [1, 2, 5, 6] for i in range(50): assert random.choice(lst) in lst # empty sequence try: random.choice([]) except IndexError: print("IndexError")
YifuLiu/AliOS-Things
components/py_engine/tests/extmod/urandom_extra.py
Python
apache-2.0
1,308
try: import urandom as random except ImportError: try: import random except ImportError: print("SKIP") raise SystemExit try: random.randint except AttributeError: print("SKIP") raise SystemExit print("random") for i in range(50): assert 0 <= random.random() < 1 print("uniform") for i in range(50): assert 0 <= random.uniform(0, 4) <= 4 assert 2 <= random.uniform(2, 6) <= 6 assert -2 <= random.uniform(-2, 2) <= 2
YifuLiu/AliOS-Things
components/py_engine/tests/extmod/urandom_extra_float.py
Python
apache-2.0
482
# test urandom.seed() without any arguments try: import urandom as random except ImportError: try: import random except ImportError: print("SKIP") raise SystemExit try: random.seed() except ValueError: # no default seed on this platform print("SKIP") raise SystemExit def rng_seq(): return [random.getrandbits(16) for _ in range(10)] # seed with default and check that doesn't produce the same RNG sequence random.seed() seq = rng_seq() random.seed() print(seq == rng_seq()) random.seed(None) print(seq == rng_seq())
YifuLiu/AliOS-Things
components/py_engine/tests/extmod/urandom_seed_default.py
Python
apache-2.0
579
try: import ure as re except ImportError: try: import re except ImportError: print("SKIP") raise SystemExit r = re.compile(".+") m = r.match("abc") print(m.group(0)) try: m.group(1) except IndexError: print("IndexError") # conversion of re and match to string str(r) str(m) r = re.compile("(.+)1") m = r.match("xyz781") print(m.group(0)) print(m.group(1)) try: m.group(2) except IndexError: print("IndexError") r = re.compile("[a-cu-z]") m = r.match("a") print(m.group(0)) m = r.match("z") print(m.group(0)) m = r.match("d") print(m) m = r.match("A") print(m) print("===") r = re.compile("[^a-cu-z]") m = r.match("a") print(m) m = r.match("z") print(m) m = r.match("d") print(m.group(0)) m = r.match("A") print(m.group(0)) print("===") # '-' character within character class block print(re.match("[-a]+", "-a]d").group(0)) print(re.match("[a-]+", "-a]d").group(0)) print("===") r = re.compile("o+") m = r.search("foobar") print(m.group(0)) try: m.group(1) except IndexError: print("IndexError") m = re.match(".*", "foo") print(m.group(0)) m = re.search("w.r", "hello world") print(m.group(0)) m = re.match("a+?", "ab") print(m.group(0)) m = re.match("a*?", "ab") print(m.group(0)) m = re.match("^ab$", "ab") print(m.group(0)) m = re.match("a|b", "b") print(m.group(0)) m = re.match("a|b|c", "c") print(m.group(0)) # Case where anchors fail to match r = re.compile("^b|b$") m = r.search("abc") print(m) try: re.compile("*") except: print("Caught invalid regex") # bytes objects m = re.match(rb"a+?", b"ab") print(m.group(0)) print("===") # escaping m = re.match(r"a\.c", "a.c") print(m.group(0) if m else "") m = re.match(r"a\.b", "abc") print(m is None) m = re.match(r"a\.b", "a\\bc") print(m is None) m = re.match(r"[a\-z]", "abc") print(m.group(0)) m = re.match(r"[.\]]*", ".].]a") print(m.group(0)) m = re.match(r"[.\]+]*", ".]+.]a") print(m.group(0)) m = re.match(r"[a-f0-9x\-yz]*", "abxcd1-23") print(m.group(0)) m = re.match(r"[a\\b]*", "a\\aa\\bb\\bbab") print(m.group(0)) m = re.search(r"[a\-z]", "-") print(m.group(0)) m = re.search(r"[a\-z]", "f") print(m is None) m = re.search(r"[a\]z]", "a") print(m.group(0)) print(re.compile(r"[-a]").split("foo-bar")) print(re.compile(r"[a-]").split("foo-bar")) print(re.compile(r"[ax\-]").split("foo-bar")) print(re.compile(r"[a\-x]").split("foo-bar")) print(re.compile(r"[\-ax]").split("foo-bar")) print("===") # Module functions take str/bytes/re. for f in (re.match, re.search): print(f(".", "foo").group(0)) print(f(b".", b"foo").group(0)) print(f(re.compile("."), "foo").group(0)) try: f(123, "a") except TypeError: print("TypeError") print("===")
YifuLiu/AliOS-Things
components/py_engine/tests/extmod/ure1.py
Python
apache-2.0
2,723
# test printing debugging info when compiling try: import ure ure.DEBUG except (ImportError, AttributeError): print("SKIP") raise SystemExit ure.compile("^a|b[0-9]\w$", ure.DEBUG)
YifuLiu/AliOS-Things
components/py_engine/tests/extmod/ure_debug.py
Python
apache-2.0
198
# test errors in regex try: import ure as re except ImportError: try: import re except ImportError: print("SKIP") raise SystemExit def test_re(r): try: re.compile(r) print("OK") except: # uPy and CPy use different errors, so just ignore the type print("Error") test_re(r"?") test_re(r"*") test_re(r"+") test_re(r")") test_re(r"[") test_re(r"([") test_re(r"([)") test_re(r"[a\]")
YifuLiu/AliOS-Things
components/py_engine/tests/extmod/ure_error.py
Python
apache-2.0
453
# test groups, and nested groups try: import ure as re except ImportError: try: import re except ImportError: print("SKIP") raise SystemExit def print_groups(match): print("----") try: i = 0 while True: print(match.group(i)) i += 1 except IndexError: pass m = re.match(r"(([0-9]*)([a-z]*)[0-9]*)", "1234hello567") print_groups(m) m = re.match(r"([0-9]*)(([a-z]*)([0-9]*))", "1234hello567") print_groups(m) # optional group that matches print_groups(re.match(r"(a)?b(c)", "abc")) # optional group that doesn't match print_groups(re.match(r"(a)?b(c)", "bc"))
YifuLiu/AliOS-Things
components/py_engine/tests/extmod/ure_group.py
Python
apache-2.0
661
# test match.groups() try: import ure as re except ImportError: try: import re except ImportError: print("SKIP") raise SystemExit try: m = re.match(".", "a") m.groups except AttributeError: print("SKIP") raise SystemExit m = re.match(r"(([0-9]*)([a-z]*)[0-9]*)", "1234hello567") print(m.groups()) m = re.match(r"([0-9]*)(([a-z]*)([0-9]*))", "1234hello567") print(m.groups()) # optional group that matches print(re.match(r"(a)?b(c)", "abc").groups()) # optional group that doesn't match print(re.match(r"(a)?b(c)", "bc").groups()) # only a single match print(re.match(r"abc", "abc").groups())
YifuLiu/AliOS-Things
components/py_engine/tests/extmod/ure_groups.py
Python
apache-2.0
652
# Test overflow in ure.compile output code. try: import ure as re except ImportError: print("SKIP") raise SystemExit def test_re(r): try: re.compile(r) except: print("Error") # too many chars in [] test_re("[" + "a" * 256 + "]") # too many groups test_re("(a)" * 256) # jump too big for ? test_re("(" + "a" * 62 + ")?") # jump too big for * test_re("(" + "a" * 60 + ".)*") test_re("(" + "a" * 60 + "..)*") # jump too big for + test_re("(" + "a" * 62 + ")+") # jump too big for | test_re("b" * 63 + "|a")
YifuLiu/AliOS-Things
components/py_engine/tests/extmod/ure_limit.py
Python
apache-2.0
550
# test named char classes try: import ure as re except ImportError: try: import re except ImportError: print("SKIP") raise SystemExit def print_groups(match): print("----") try: i = 0 while True: print(m.group(i)) i += 1 except IndexError: pass m = re.match(r"\w+", "1234hello567 abc") print_groups(m) m = re.match(r"(\w+)\s+(\w+)", "ABC \t1234hello567 abc") print_groups(m) m = re.match(r"(\S+)\s+(\D+)", "ABC \thello abc567 abc") print_groups(m) m = re.match(r"(([0-9]*)([a-z]*)\d*)", "1234hello567") print_groups(m)
YifuLiu/AliOS-Things
components/py_engine/tests/extmod/ure_namedclass.py
Python
apache-2.0
623
# test match.span(), and nested spans try: import ure as re except ImportError: try: import re except ImportError: print("SKIP") raise SystemExit try: m = re.match(".", "a") m.span except AttributeError: print("SKIP") raise SystemExit def print_spans(match): print("----") try: i = 0 while True: print(match.span(i), match.start(i), match.end(i)) i += 1 except IndexError: pass m = re.match(r"(([0-9]*)([a-z]*)[0-9]*)", "1234hello567") print_spans(m) m = re.match(r"([0-9]*)(([a-z]*)([0-9]*))", "1234hello567") print_spans(m) # optional span that matches print_spans(re.match(r"(a)?b(c)", "abc")) # optional span that doesn't match print_spans(re.match(r"(a)?b(c)", "bc"))
YifuLiu/AliOS-Things
components/py_engine/tests/extmod/ure_span.py
Python
apache-2.0
794
try: import ure as re except ImportError: try: import re except ImportError: print("SKIP") raise SystemExit r = re.compile(" ") s = r.split("a b c foobar") print(s) r = re.compile(" +") s = r.split("a b c foobar") print(s) r = re.compile(" +") s = r.split("a b c foobar", 1) print(s) r = re.compile(" +") s = r.split("a b c foobar", 2) print(s) r = re.compile("[a-f]+") s = r.split("0a3b9") print(s) # bytes objects r = re.compile(b"x") s = r.split(b"fooxbar") print(s)
YifuLiu/AliOS-Things
components/py_engine/tests/extmod/ure_split.py
Python
apache-2.0
527
# test splitting with pattern matches that can be empty # # CPython 3.5 issues a FutureWarning for these tests because their # behaviour will change in a future version. MicroPython just stops # splitting as soon as an empty match is found. try: import ure as re except ImportError: print("SKIP") raise SystemExit r = re.compile(" *") s = r.split("a b c foobar") print(s) r = re.compile("x*") s = r.split("foo") print(s) r = re.compile("x*") s = r.split("axbc") print(s)
YifuLiu/AliOS-Things
components/py_engine/tests/extmod/ure_split_empty.py
Python
apache-2.0
493
try: import ure as re except ImportError: print("SKIP") raise SystemExit r = re.compile("( )") try: s = r.split("a b c foobar") except NotImplementedError: print("NotImplementedError")
YifuLiu/AliOS-Things
components/py_engine/tests/extmod/ure_split_notimpl.py
Python
apache-2.0
206
try: import ure as re except ImportError: try: import re except ImportError: print("SKIP") raise SystemExit try: re.match("(a*)*", "aaa") except RuntimeError: print("RuntimeError")
YifuLiu/AliOS-Things
components/py_engine/tests/extmod/ure_stack_overflow.py
Python
apache-2.0
226
try: import ure as re except ImportError: try: import re except ImportError: print("SKIP") raise SystemExit try: re.sub except AttributeError: print("SKIP") raise SystemExit def multiply(m): return str(int(m.group(0)) * 2) print(re.sub("\d+", multiply, "10 20 30 40 50")) print(re.sub("\d+", lambda m: str(int(m.group(0)) // 2), "10 20 30 40 50")) def A(): return "A" print(re.sub("a", A(), "aBCBABCDabcda.")) print( re.sub( r"def\s+([a-zA-Z_][a-zA-Z_0-9]*)\s*\(\s*\):", "static PyObject*\npy_\\1(void){\n return;\n}\n", "\n\ndef myfunc():\n\ndef myfunc1():\n\ndef myfunc2():", ) ) print( re.compile("(calzino) (blu|bianco|verde) e (scarpa) (blu|bianco|verde)").sub( r"\g<1> colore \2 con \g<3> colore \4? ...", "calzino blu e scarpa verde" ) ) # \g immediately followed by another \g print(re.sub("(abc)", r"\g<1>\g<1>", "abc")) # no matches at all print(re.sub("a", "b", "c")) # with maximum substitution count specified print(re.sub("a", "b", "1a2a3a", 2)) # invalid group try: re.sub("(a)", "b\\2", "a") except: print("invalid group") # invalid group with very large number (to test overflow in uPy) try: re.sub("(a)", "b\\199999999999999999999999999999999999999", "a") except: print("invalid group") # Module function takes str/bytes/re. print(re.sub("a", "a", "a")) print(re.sub(b".", b"a", b"a")) print(re.sub(re.compile("a"), "a", "a")) try: re.sub(123, "a", "a") except TypeError: print("TypeError") # Include \ in the sub replacement print(re.sub("b", "\\\\b", "abc"))
YifuLiu/AliOS-Things
components/py_engine/tests/extmod/ure_sub.py
Python
apache-2.0
1,627
# test re.sub with unmatched groups, behaviour changed in CPython 3.5 try: import ure as re except ImportError: try: import re except ImportError: print("SKIP") raise SystemExit try: re.sub except AttributeError: print("SKIP") raise SystemExit # first group matches, second optional group doesn't so is replaced with a blank print(re.sub(r"(a)(b)?", r"\2-\1", "1a2"))
YifuLiu/AliOS-Things
components/py_engine/tests/extmod/ure_sub_unmatched.py
Python
apache-2.0
419
try: import usocket as socket, uselect as select, uerrno as errno except ImportError: try: import socket, select, errno select.poll # Raises AttributeError for CPython implementations without poll() except (ImportError, AttributeError): print("SKIP") raise SystemExit poller = select.poll() s = socket.socket() poller.register(s) # https://docs.python.org/3/library/select.html#select.poll.register # "Registering a file descriptor that’s already registered is not an error, # and has the same effect as registering the descriptor exactly once." poller.register(s) # 2 args are mandatory unlike register() try: poller.modify(s) except TypeError: print("modify:TypeError") poller.modify(s, select.POLLIN) poller.unregister(s) try: poller.modify(s, select.POLLIN) except OSError as e: assert e.errno == errno.ENOENT # poll after closing the socket, should return POLLNVAL poller.register(s) s.close() p = poller.poll(0) print(len(p), p[0][-1])
YifuLiu/AliOS-Things
components/py_engine/tests/extmod/uselect_poll_basic.py
Python
apache-2.0
1,015
# test select.poll on UDP sockets try: import usocket as socket, uselect as select except ImportError: try: import socket, select except ImportError: print("SKIP") raise SystemExit s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) s.bind(socket.getaddrinfo("127.0.0.1", 8000)[0][-1]) poll = select.poll() # UDP socket should not be readable poll.register(s, select.POLLIN) print(len(poll.poll(0))) # UDP socket should be writable poll.modify(s, select.POLLOUT) print(poll.poll(0)[0][1] == select.POLLOUT) # same test for select.select, but just skip it if the function isn't available if hasattr(select, "select"): r, w, e = select.select([s], [], [], 0) assert not r and not w and not e
YifuLiu/AliOS-Things
components/py_engine/tests/extmod/uselect_poll_udp.py
Python
apache-2.0
741
# Test basic, stand-alone TCP socket functionality try: import usocket as socket, uerrno as errno except ImportError: try: import socket, errno except ImportError: print("SKIP") raise SystemExit # recv() on a fresh socket should raise ENOTCONN s = socket.socket() try: s.recv(1) except OSError as er: print("ENOTCONN:", er.errno == errno.ENOTCONN)
YifuLiu/AliOS-Things
components/py_engine/tests/extmod/usocket_tcp_basic.py
Python
apache-2.0
394
# test non-blocking UDP sockets try: import usocket as socket, uerrno as errno except ImportError: try: import socket, errno except ImportError: print("SKIP") raise SystemExit s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) s.bind(socket.getaddrinfo("127.0.0.1", 8000)[0][-1]) s.settimeout(0) try: s.recv(1) except OSError as er: print("EAGAIN:", er.errno == errno.EAGAIN)
YifuLiu/AliOS-Things
components/py_engine/tests/extmod/usocket_udp_nonblock.py
Python
apache-2.0
426
# very basic test of ssl module, just to test the methods exist try: import uio as io import ussl as ssl except ImportError: print("SKIP") raise SystemExit # create in client mode try: ss = ssl.wrap_socket(io.BytesIO(), server_hostname="test.example.com") except OSError as er: print("wrap_socket:", repr(er)) # create in server mode (can use this object for further tests) socket = io.BytesIO() ss = ssl.wrap_socket(socket, server_side=1) # print print(repr(ss)[:12]) # setblocking() propagates call to the underlying stream object, and # io.BytesIO doesn't have setblocking() (in CPython too). # try: # ss.setblocking(False) # except NotImplementedError: # print('setblocking: NotImplementedError') # ss.setblocking(True) # write print(ss.write(b"aaaa")) # read (underlying socket has no data) print(ss.read(8)) # read (underlying socket has data, but it's bad data) socket.write(b"aaaaaaaaaaaaaaaa") socket.seek(0) try: ss.read(8) except OSError as er: print("read:", repr(er)) # close ss.close() # close 2nd time ss.close() # read on closed socket try: ss.read(10) except OSError as er: print("read:", repr(er)) # write on closed socket try: ss.write(b"aaaa") except OSError as er: print("write:", repr(er))
YifuLiu/AliOS-Things
components/py_engine/tests/extmod/ussl_basic.py
Python
apache-2.0
1,277
# Test ussl with key/cert passed in try: import uio as io import ussl as ssl except ImportError: print("SKIP") raise SystemExit key = b"0\x82\x019\x02\x01\x00\x02A\x00\xf9\xe0}\xbd\xd7\x9cI\x18\x06\xc3\xcb\xb5\xec@r\xfbD\x18\x80\xaaWoZ{\xcc\xa3\xeb!\"\x0fY\x9e]-\xee\xe4\t!BY\x9f{7\xf3\xf2\x8f}}\r|.\xa8<\ta\xb2\xd7W\xb3\xc9\x19A\xc39\x02\x03\x01\x00\x01\x02@\x07:\x9fh\xa6\x9c6\xe1#\x10\xf7\x0b\xc4Q\xf9\x01\x9b\xee\xb9\x8a4\r\\\xa8\xc8:\xd5\xca\x97\x99\xaa\x16\x04)\xa8\xf9\x13\xdeq\x0ev`\xa7\x83\xc5\x8b`\xdb\xef \x9d\x93\xe8g\x84\x96\xfaV\\\xf4R\xda\xd0\xa1\x02!\x00\xfeR\xbf\n\x91Su\x87L\x98{\xeb%\xed\xfb\x06u)@\xfe\x1b\xde\xa0\xc6@\xab\xc5\xedg\x8e\x10[\x02!\x00\xfb\x86=\x85\xa4'\xde\x85\xb5L\xe0)\x99\xfaL\x8c3A\x02\xa8<\xdew\xad\x00\xe3\x1d\x05\xd8\xb4N\xfb\x02 \x08\xb0M\x04\x90hx\x88q\xcew\xd5U\xcbf\x9b\x16\xdf\x9c\xef\xd1\x85\xee\x9a7Ug\x02\xb0Z\x03'\x02 9\xa0D\xe2$|\xf9\xefz]5\x92rs\xb5+\xfd\xe6,\x1c\xadmn\xcf\xd5?3|\x0em)\x17\x02 5Z\xcc/\xa5?\n\x04%\x9b{N\x9dX\xddI\xbe\xd2\xb0\xa0\x03BQ\x02\x82\xc2\xe0u)\xbd\xb8\xaf" # Invalid key try: ssl.wrap_socket(io.BytesIO(), key=b"!") except ValueError as er: print(repr(er)) # Valid key, no cert try: ssl.wrap_socket(io.BytesIO(), key=key) except TypeError as er: print(repr(er)) # Valid key, invalid cert try: ssl.wrap_socket(io.BytesIO(), key=key, cert=b"!") except ValueError as er: print(repr(er))
YifuLiu/AliOS-Things
components/py_engine/tests/extmod/ussl_keycert.py
Python
apache-2.0
1,409
# test utime resolutions try: import utime except ImportError: print("SKIP") raise SystemExit def gmtime_time(): return utime.gmtime(utime.time()) def localtime_time(): return utime.localtime(utime.time()) def test(): TEST_TIME = 2500 EXPECTED_MAP = ( # (function name, min. number of results in 2.5 sec) ("time", 3), ("gmtime", 3), ("localtime", 3), ("gmtime_time", 3), ("localtime_time", 3), ("ticks_ms", 15), ("ticks_us", 15), ("ticks_ns", 15), ("ticks_cpu", 15), ) # call time functions results_map = {} end_time = utime.ticks_ms() + TEST_TIME while utime.ticks_diff(end_time, utime.ticks_ms()) > 0: utime.sleep_ms(100) for func_name, _ in EXPECTED_MAP: try: time_func = getattr(utime, func_name, None) or globals()[func_name] now = time_func() # may raise AttributeError except (KeyError, AttributeError): continue try: results_map[func_name].add(now) except KeyError: results_map[func_name] = {now} # check results for func_name, min_len in EXPECTED_MAP: print("Testing %s" % func_name) results = results_map.get(func_name) if results is None: pass elif func_name == "ticks_cpu" and results == {0}: # ticks_cpu() returns 0 on some ports (e.g. unix) pass elif len(results) < min_len: print( "%s() returns %s result%s in %s ms, expecting >= %s" % (func_name, len(results), "s"[: len(results) != 1], TEST_TIME, min_len) ) test()
YifuLiu/AliOS-Things
components/py_engine/tests/extmod/utime_res.py
Python
apache-2.0
1,756
# test utime.time_ns() try: import utime utime.sleep_us utime.time_ns except (ImportError, AttributeError): print("SKIP") raise SystemExit t0 = utime.time_ns() utime.sleep_us(5000) t1 = utime.time_ns() # Check that time_ns increases. print(t0 < t1) # Check that time_ns counts correctly, but be very lenient with the bounds (2ms to 50ms). if 2000000 < t1 - t0 < 50000000: print(True) else: print(t0, t1, t1 - t0)
YifuLiu/AliOS-Things
components/py_engine/tests/extmod/utime_time_ns.py
Python
apache-2.0
447
# Test for utimeq module which implements task queue with support for # wraparound time (utime.ticks_ms() style). try: from utime import ticks_add, ticks_diff from utimeq import utimeq except ImportError: print("SKIP") raise SystemExit DEBUG = 0 MAX = ticks_add(0, -1) MODULO_HALF = MAX // 2 + 1 if DEBUG: def dprint(*v): print(*v) else: def dprint(*v): pass # Try not to crash on invalid data h = utimeq(10) try: h.push(1) assert False except TypeError: pass try: h.pop(1) assert False except IndexError: pass # unsupported unary op try: ~h assert False except TypeError: pass # pushing on full queue h = utimeq(1) h.push(1, 0, 0) try: h.push(2, 0, 0) assert False except IndexError: pass # popping into invalid type try: h.pop([]) assert False except TypeError: pass # length assert len(h) == 1 # peektime assert h.peektime() == 1 # peektime with empty queue try: utimeq(1).peektime() assert False except IndexError: pass def pop_all(h): l = [] while h: item = [0, 0, 0] h.pop(item) # print("!", item) l.append(tuple(item)) dprint(l) return l def add(h, v): h.push(v, 0, 0) dprint("-----") # h.dump() dprint("-----") h = utimeq(10) add(h, 0) add(h, MAX) add(h, MAX - 1) add(h, 101) add(h, 100) add(h, MAX - 2) dprint(h) l = pop_all(h) for i in range(len(l) - 1): diff = ticks_diff(l[i + 1][0], l[i][0]) assert diff > 0 def edge_case(edge, offset): h = utimeq(10) add(h, ticks_add(0, offset)) add(h, ticks_add(edge, offset)) dprint(h) l = pop_all(h) diff = ticks_diff(l[1][0], l[0][0]) dprint(diff, diff > 0) return diff dprint("===") diff = edge_case(MODULO_HALF - 1, 0) assert diff == MODULO_HALF - 1 assert edge_case(MODULO_HALF - 1, 100) == diff assert edge_case(MODULO_HALF - 1, -100) == diff # We expect diff to be always positive, per the definition of heappop() which should return # the smallest value. # This is the edge case where this invariant breaks, due to assymetry of two's-complement # range - there's one more negative integer than positive, so heappushing values like below # will then make ticks_diff() return the minimum negative value. We could make heappop # return them in a different order, but ticks_diff() result would be the same. Conclusion: # never add to a heap values where (a - b) == MODULO_HALF (and which are >= MODULO_HALF # ticks apart in real time of course). dprint("===") diff = edge_case(MODULO_HALF, 0) assert diff == -MODULO_HALF assert edge_case(MODULO_HALF, 100) == diff assert edge_case(MODULO_HALF, -100) == diff dprint("===") diff = edge_case(MODULO_HALF + 1, 0) assert diff == MODULO_HALF - 1 assert edge_case(MODULO_HALF + 1, 100) == diff assert edge_case(MODULO_HALF + 1, -100) == diff print("OK")
YifuLiu/AliOS-Things
components/py_engine/tests/extmod/utimeq1.py
Python
apache-2.0
2,896
try: from utimeq import utimeq except ImportError: print("SKIP") raise SystemExit h = utimeq(10) # Check that for 2 same-key items, the queue is stable (pops items # in the same order they were pushed). Unfortunately, this no longer # holds for more same-key values, as the underlying heap structure # is not stable itself. h.push(100, 20, 0) h.push(100, 10, 0) res = [0, 0, 0] h.pop(res) assert res == [100, 20, 0] h.pop(res) assert res == [100, 10, 0] print("OK")
YifuLiu/AliOS-Things
components/py_engine/tests/extmod/utimeq_stable.py
Python
apache-2.0
482
try: import uzlib as zlib import uio as io except ImportError: print("SKIP") raise SystemExit # Raw DEFLATE bitstream buf = io.BytesIO(b"\xcbH\xcd\xc9\xc9\x07\x00") inp = zlib.DecompIO(buf, -8) print(buf.seek(0, 1)) print(inp.read(1)) print(buf.seek(0, 1)) print(inp.read(2)) print(inp.read()) print(buf.seek(0, 1)) print(inp.read(1)) print(inp.read()) print(buf.seek(0, 1)) # zlib bitstream inp = zlib.DecompIO(io.BytesIO(b"x\x9c30\xa0=\x00\x00\xb3q\x12\xc1")) print(inp.read(10)) print(inp.read()) # zlib bitstream, wrong checksum inp = zlib.DecompIO(io.BytesIO(b"x\x9c30\xa0=\x00\x00\xb3q\x12\xc0")) try: print(inp.read()) except OSError as e: print(repr(e))
YifuLiu/AliOS-Things
components/py_engine/tests/extmod/uzlib_decompio.py
Python
apache-2.0
691
try: import uzlib as zlib import uio as io except ImportError: print("SKIP") raise SystemExit # gzip bitstream buf = io.BytesIO( b"\x1f\x8b\x08\x08\x99\x0c\xe5W\x00\x03hello\x00\xcbH\xcd\xc9\xc9\x07\x00\x86\xa6\x106\x05\x00\x00\x00" ) inp = zlib.DecompIO(buf, 16 + 8) print(buf.seek(0, 1)) print(inp.read(1)) print(buf.seek(0, 1)) print(inp.read(2)) print(inp.read()) print(buf.seek(0, 1)) print(inp.read(1)) print(inp.read()) print(buf.seek(0, 1)) # Check FHCRC field buf = io.BytesIO( b"\x1f\x8b\x08\x02\x99\x0c\xe5W\x00\x03\x00\x00\xcbH\xcd\xc9\xc9\x07\x00\x86\xa6\x106\x05\x00\x00\x00" ) inp = zlib.DecompIO(buf, 16 + 8) print(inp.read()) # Check FEXTRA field buf = io.BytesIO( b"\x1f\x8b\x08\x04\x99\x0c\xe5W\x00\x03\x01\x00X\xcbH\xcd\xc9\xc9\x07\x00\x86\xa6\x106\x05\x00\x00\x00" ) inp = zlib.DecompIO(buf, 16 + 8) print(inp.read()) # broken header buf = io.BytesIO( b"\x1f\x8c\x08\x08\x99\x0c\xe5W\x00\x03hello\x00\xcbH\xcd\xc9\xc9\x07\x00\x86\xa6\x106\x05\x00\x00\x00" ) try: inp = zlib.DecompIO(buf, 16 + 8) except ValueError: print("ValueError") # broken crc32 buf = io.BytesIO( b"\x1f\x8b\x08\x08\x99\x0c\xe5W\x00\x03hello\x00\xcbH\xcd\xc9\xc9\x07\x00\x86\xa7\x106\x05\x00\x00\x00" ) inp = zlib.DecompIO(buf, 16 + 8) try: inp.read(6) except OSError as e: print(repr(e)) # broken uncompressed size - not checked so far # buf = io.BytesIO(b'\x1f\x8b\x08\x08\x99\x0c\xe5W\x00\x03hello\x00\xcbH\xcd\xc9\xc9\x07\x00\x86\xa6\x106\x06\x00\x00\x00') # inp = zlib.DecompIO(buf, 16 + 8) # inp.read(6)
YifuLiu/AliOS-Things
components/py_engine/tests/extmod/uzlib_decompio_gz.py
Python
apache-2.0
1,561
try: import zlib except ImportError: try: import uzlib as zlib except ImportError: print("SKIP") raise SystemExit PATTERNS = [ # Packed results produced by CPy's zlib.compress() (b"0", b"x\x9c3\x00\x00\x001\x001"), (b"a", b"x\x9cK\x04\x00\x00b\x00b"), (b"0" * 100, b"x\x9c30\xa0=\x00\x00\xb3q\x12\xc1"), ( bytes(range(64)), b"x\x9cc`dbfaec\xe7\xe0\xe4\xe2\xe6\xe1\xe5\xe3\x17\x10\x14\x12\x16\x11\x15\x13\x97\x90\x94\x92\x96\x91\x95\x93WPTRVQUS\xd7\xd0\xd4\xd2\xd6\xd1\xd5\xd370426153\xb7\xb0\xb4\xb2\xb6\xb1\xb5\xb3\x07\x00\xaa\xe0\x07\xe1", ), (b"hello", b"x\x01\x01\x05\x00\xfa\xffhello\x06,\x02\x15"), # compression level 0 # adaptive/dynamic huffman tree ( b"13371813150|13764518736|12345678901", b"x\x9c\x05\xc1\x81\x01\x000\x04\x04\xb1\x95\\\x1f\xcfn\x86o\x82d\x06Qq\xc8\x9d\xc5X}<e\xb5g\x83\x0f\x89X\x07\xab", ), # dynamic Huffman tree with "case 17" (repeat code for 3-10 times) ( b">I}\x00\x951D>I}\x00\x951D>I}\x00\x951D>I}\x00\x951D", b"x\x9c\x05\xc11\x01\x00\x00\x00\x010\x95\x14py\x84\x12C_\x9bR\x8cV\x8a\xd1J1Z)F\x1fw`\x089", ), ] for unpacked, packed in PATTERNS: assert zlib.decompress(packed) == unpacked print(unpacked) # Raw DEFLATE bitstream v = b"\xcbH\xcd\xc9\xc9\x07\x00" exp = b"hello" out = zlib.decompress(v, -15) assert out == exp print(exp) # Even when you ask CPython zlib.compress to produce Raw DEFLATE stream, # it returns it with adler2 and oriignal size appended, as if it was a # zlib stream. Make sure there're no random issues decompressing such. v = b"\xcbH\xcd\xc9\xc9\x07\x00\x86\xa6\x106\x05\x00\x00\x00" out = zlib.decompress(v, -15) assert out == exp # this should error try: zlib.decompress(b"abc") except Exception: print("Exception") # invalid block type try: zlib.decompress(b"\x07", -15) # final-block, block-type=3 (invalid) except Exception as er: print("Exception")
YifuLiu/AliOS-Things
components/py_engine/tests/extmod/uzlib_decompress.py
Python
apache-2.0
1,985
# test VFS functionality without any particular filesystem type try: import uos uos.mount except (ImportError, AttributeError): print("SKIP") raise SystemExit class Filesystem: def __init__(self, id, fail=0): self.id = id self.fail = fail def mount(self, readonly, mkfs): print(self.id, "mount", readonly, mkfs) def umount(self): print(self.id, "umount") def ilistdir(self, dir): print(self.id, "ilistdir", dir) return iter([("a%d" % self.id, 0, 0)]) def chdir(self, dir): print(self.id, "chdir", dir) if self.fail: raise OSError(self.fail) def getcwd(self): print(self.id, "getcwd") return "dir%d" % self.id def mkdir(self, path): print(self.id, "mkdir", path) def remove(self, path): print(self.id, "remove", path) def rename(self, old_path, new_path): print(self.id, "rename", old_path, new_path) def rmdir(self, path): print(self.id, "rmdir", path) def stat(self, path): print(self.id, "stat", path) return (self.id,) def statvfs(self, path): print(self.id, "statvfs", path) return (self.id,) def open(self, file, mode): print(self.id, "open", file, mode) # first we umount any existing mount points the target may have try: uos.umount("/") except OSError: pass for path in uos.listdir("/"): uos.umount("/" + path) # stat root dir print(uos.stat("/")) # statvfs root dir; verify that f_namemax has a sensible size print(uos.statvfs("/")[9] >= 32) # getcwd when in root dir print(uos.getcwd()) # test operations on the root directory with nothing mounted, they should all fail for func in ("chdir", "listdir", "mkdir", "remove", "rmdir", "stat"): for arg in ("x", "/x"): try: getattr(uos, func)(arg) except OSError: print(func, arg, "OSError") # basic mounting and listdir uos.mount(Filesystem(1), "/test_mnt") print(uos.listdir()) # ilistdir i = uos.ilistdir() print(next(i)) try: next(i) except StopIteration: print("StopIteration") try: next(i) except StopIteration: print("StopIteration") # referencing the mount point in different ways print(uos.listdir("test_mnt")) print(uos.listdir("/test_mnt")) # mounting another filesystem uos.mount(Filesystem(2), "/test_mnt2", readonly=True) print(uos.listdir()) print(uos.listdir("/test_mnt2")) # mounting over an existing mount point try: uos.mount(Filesystem(3), "/test_mnt2") except OSError: print("OSError") # mkdir of a mount point try: uos.mkdir("/test_mnt") except OSError: print("OSError") # rename across a filesystem try: uos.rename("/test_mnt/a", "/test_mnt2/b") except OSError: print("OSError") # delegating to mounted filesystem uos.chdir("test_mnt") print(uos.listdir()) print(uos.getcwd()) uos.mkdir("test_dir") uos.remove("test_file") uos.rename("test_file", "test_file2") uos.rmdir("test_dir") print(uos.stat("test_file")) print(uos.statvfs("/test_mnt")) open("test_file") open("test_file", "wb") # umount uos.umount("/test_mnt") uos.umount("/test_mnt2") # umount a non-existent mount point try: uos.umount("/test_mnt") except OSError: print("OSError") # root dir uos.mount(Filesystem(3), "/") print(uos.stat("/")) print(uos.statvfs("/")) print(uos.listdir()) open("test") uos.mount(Filesystem(4), "/mnt") print(uos.listdir()) print(uos.listdir("/mnt")) uos.chdir("/mnt") print(uos.listdir()) # chdir to a subdir within root-mounted vfs, and then listdir uos.chdir("/subdir") print(uos.listdir()) uos.chdir("/") uos.umount("/") print(uos.listdir("/")) uos.umount("/mnt") # chdir to a non-existent mount point (current directory should remain unchanged) try: uos.chdir("/foo") except OSError: print("OSError") print(uos.getcwd()) # chdir to a non-existent subdirectory in a mounted filesystem uos.mount(Filesystem(5, 1), "/mnt") try: uos.chdir("/mnt/subdir") except OSError: print("OSError") print(uos.getcwd())
YifuLiu/AliOS-Things
components/py_engine/tests/extmod/vfs_basic.py
Python
apache-2.0
4,068
# Test for behaviour of combined standard and extended block device try: import uos uos.VfsFat uos.VfsLfs2 except (ImportError, AttributeError): print("SKIP") raise SystemExit class RAMBlockDevice: ERASE_BLOCK_SIZE = 512 def __init__(self, blocks): self.data = bytearray(blocks * self.ERASE_BLOCK_SIZE) def readblocks(self, block, buf, off=0): addr = block * self.ERASE_BLOCK_SIZE + off for i in range(len(buf)): buf[i] = self.data[addr + i] def writeblocks(self, block, buf, off=None): if off is None: # erase, then write off = 0 addr = block * self.ERASE_BLOCK_SIZE + off for i in range(len(buf)): self.data[addr + i] = buf[i] def ioctl(self, op, arg): if op == 4: # block count return len(self.data) // self.ERASE_BLOCK_SIZE if op == 5: # block size return self.ERASE_BLOCK_SIZE if op == 6: # erase block return 0 def test(bdev, vfs_class): print("test", vfs_class) # mkfs vfs_class.mkfs(bdev) # construction vfs = vfs_class(bdev) # statvfs print(vfs.statvfs("/")) # open, write close f = vfs.open("test", "w") for i in range(10): f.write("some data") f.close() # ilistdir print(list(vfs.ilistdir())) # read with vfs.open("test", "r") as f: print(f.read()) try: bdev = RAMBlockDevice(50) except MemoryError: print("SKIP") raise SystemExit test(bdev, uos.VfsFat) test(bdev, uos.VfsLfs2)
YifuLiu/AliOS-Things
components/py_engine/tests/extmod/vfs_blockdev.py
Python
apache-2.0
1,595
try: import uerrno import uos except ImportError: print("SKIP") raise SystemExit try: uos.VfsFat except AttributeError: print("SKIP") raise SystemExit class RAMFS: SEC_SIZE = 512 def __init__(self, blocks): self.data = bytearray(blocks * self.SEC_SIZE) def readblocks(self, n, buf): # print("readblocks(%s, %x(%d))" % (n, id(buf), len(buf))) for i in range(len(buf)): buf[i] = self.data[n * self.SEC_SIZE + i] def writeblocks(self, n, buf): # print("writeblocks(%s, %x)" % (n, id(buf))) for i in range(len(buf)): self.data[n * self.SEC_SIZE + i] = buf[i] def ioctl(self, op, arg): # print("ioctl(%d, %r)" % (op, arg)) if op == 4: # MP_BLOCKDEV_IOCTL_BLOCK_COUNT return len(self.data) // self.SEC_SIZE if op == 5: # MP_BLOCKDEV_IOCTL_BLOCK_SIZE return self.SEC_SIZE try: bdev = RAMFS(50) except MemoryError: print("SKIP") raise SystemExit uos.VfsFat.mkfs(bdev) vfs = uos.VfsFat(bdev) uos.mount(vfs, "/ramdisk") uos.chdir("/ramdisk") # file IO f = open("foo_file.txt", "w") print(str(f)[:17], str(f)[-1:]) f.write("hello!") f.flush() f.close() f.close() # allowed try: f.write("world!") except OSError as e: print(e.errno == uerrno.EINVAL) try: f.read() except OSError as e: print(e.errno == uerrno.EINVAL) try: f.flush() except OSError as e: print(e.errno == uerrno.EINVAL) try: open("foo_file.txt", "x") except OSError as e: print(e.errno == uerrno.EEXIST) with open("foo_file.txt", "a") as f: f.write("world!") with open("foo_file.txt") as f2: print(f2.read()) print(f2.tell()) f2.seek(0, 0) # SEEK_SET print(f2.read(1)) f2.seek(0, 1) # SEEK_CUR print(f2.read(1)) f2.seek(2, 1) # SEEK_CUR print(f2.read(1)) f2.seek(-2, 2) # SEEK_END print(f2.read(1)) # using constructor of FileIO type to open a file # no longer working with new VFS sub-system # FileIO = type(f) # with FileIO("/ramdisk/foo_file.txt") as f: # print(f.read()) # dirs vfs.mkdir("foo_dir") try: vfs.rmdir("foo_file.txt") except OSError as e: print(e.errno == 20) # uerrno.ENOTDIR vfs.remove("foo_file.txt") print(list(vfs.ilistdir()))
YifuLiu/AliOS-Things
components/py_engine/tests/extmod/vfs_fat_fileio1.py
Python
apache-2.0
2,292
try: import uerrno import uos except ImportError: print("SKIP") raise SystemExit try: uos.VfsFat except AttributeError: print("SKIP") raise SystemExit class RAMFS: SEC_SIZE = 512 def __init__(self, blocks): self.data = bytearray(blocks * self.SEC_SIZE) def readblocks(self, n, buf): # print("readblocks(%s, %x(%d))" % (n, id(buf), len(buf))) for i in range(len(buf)): buf[i] = self.data[n * self.SEC_SIZE + i] def writeblocks(self, n, buf): # print("writeblocks(%s, %x)" % (n, id(buf))) for i in range(len(buf)): self.data[n * self.SEC_SIZE + i] = buf[i] def ioctl(self, op, arg): # print("ioctl(%d, %r)" % (op, arg)) if op == 4: # MP_BLOCKDEV_IOCTL_BLOCK_COUNT return len(self.data) // self.SEC_SIZE if op == 5: # MP_BLOCKDEV_IOCTL_BLOCK_SIZE return self.SEC_SIZE try: bdev = RAMFS(50) except MemoryError: print("SKIP") raise SystemExit uos.VfsFat.mkfs(bdev) vfs = uos.VfsFat(bdev) uos.mount(vfs, "/ramdisk") uos.chdir("/ramdisk") try: vfs.mkdir("foo_dir") except OSError as e: print(e.errno == uerrno.EEXIST) try: vfs.remove("foo_dir") except OSError as e: print(e.errno == uerrno.EISDIR) try: vfs.remove("no_file.txt") except OSError as e: print(e.errno == uerrno.ENOENT) try: vfs.rename("foo_dir", "/null/file") except OSError as e: print(e.errno == uerrno.ENOENT) # file in dir with open("foo_dir/file-in-dir.txt", "w+t") as f: f.write("data in file") with open("foo_dir/file-in-dir.txt", "r+b") as f: print(f.read()) with open("foo_dir/sub_file.txt", "w") as f: f.write("subdir file") # directory not empty try: vfs.rmdir("foo_dir") except OSError as e: print(e.errno == uerrno.EACCES) # trim full path vfs.rename("foo_dir/file-in-dir.txt", "foo_dir/file.txt") print(list(vfs.ilistdir("foo_dir"))) vfs.rename("foo_dir/file.txt", "moved-to-root.txt") print(list(vfs.ilistdir())) # check that renaming to existing file will overwrite it with open("temp", "w") as f: f.write("new text") vfs.rename("temp", "moved-to-root.txt") print(list(vfs.ilistdir())) with open("moved-to-root.txt") as f: print(f.read()) # valid removes vfs.remove("foo_dir/sub_file.txt") vfs.rmdir("foo_dir") print(list(vfs.ilistdir())) # disk full try: bsize = vfs.statvfs("/ramdisk")[0] free = vfs.statvfs("/ramdisk")[2] + 1 f = open("large_file.txt", "wb") f.write(bytearray(bsize * free)) except OSError as e: print("ENOSPC:", e.errno == 28) # uerrno.ENOSPC f.close()
YifuLiu/AliOS-Things
components/py_engine/tests/extmod/vfs_fat_fileio2.py
Python
apache-2.0
2,625
# Test VfsFat class and its finaliser try: import uerrno, uos uos.VfsFat except (ImportError, AttributeError): print("SKIP") raise SystemExit class RAMBlockDevice: def __init__(self, blocks, sec_size=512): self.sec_size = sec_size self.data = bytearray(blocks * self.sec_size) def readblocks(self, n, buf): for i in range(len(buf)): buf[i] = self.data[n * self.sec_size + i] def writeblocks(self, n, buf): for i in range(len(buf)): self.data[n * self.sec_size + i] = buf[i] def ioctl(self, op, arg): if op == 4: # MP_BLOCKDEV_IOCTL_BLOCK_COUNT return len(self.data) // self.sec_size if op == 5: # MP_BLOCKDEV_IOCTL_BLOCK_SIZE return self.sec_size # Create block device, and skip test if not enough RAM try: bdev = RAMBlockDevice(50) except MemoryError: print("SKIP") raise SystemExit # Format block device and create VFS object uos.VfsFat.mkfs(bdev) vfs = uos.VfsFat(bdev) # Here we test that opening a file with the heap locked fails correctly. This # is a special case because file objects use a finaliser and allocating with a # finaliser is a different path to normal allocation. It would be better to # test this in the core tests but there are no core objects that use finaliser. import micropython micropython.heap_lock() try: vfs.open("x", "r") except MemoryError: print("MemoryError") micropython.heap_unlock() # Here we test that the finaliser is actually called during a garbage collection. import gc # Do a large number of single-block allocations to move the GC head forwards, # ensuring that the files are allocated from never-before-used blocks and # therefore couldn't possibly have any references to them left behind on # the stack. for i in range(1024): [] N = 4 for i in range(N): n = "x%d" % i f = vfs.open(n, "w") f.write(n) f = None # release f without closing [0, 1, 2, 3] # use up Python stack so f is really gone gc.collect() # should finalise all N files by closing them for i in range(N): with vfs.open("x%d" % i, "r") as f: print(f.read())
YifuLiu/AliOS-Things
components/py_engine/tests/extmod/vfs_fat_finaliser.py
Python
apache-2.0
2,174
try: import uos except ImportError: print("SKIP") raise SystemExit try: uos.VfsFat except AttributeError: print("SKIP") raise SystemExit class RAMFS: SEC_SIZE = 512 def __init__(self, blocks): self.data = bytearray(blocks * self.SEC_SIZE) def readblocks(self, n, buf): # print("readblocks(%s, %x(%d))" % (n, id(buf), len(buf))) for i in range(len(buf)): buf[i] = self.data[n * self.SEC_SIZE + i] def writeblocks(self, n, buf): # print("writeblocks(%s, %x)" % (n, id(buf))) for i in range(len(buf)): self.data[n * self.SEC_SIZE + i] = buf[i] def ioctl(self, op, arg): # print("ioctl(%d, %r)" % (op, arg)) if op == 4: # MP_BLOCKDEV_IOCTL_BLOCK_COUNT return len(self.data) // self.SEC_SIZE if op == 5: # MP_BLOCKDEV_IOCTL_BLOCK_SIZE return self.SEC_SIZE try: bdev = RAMFS(50) bdev2 = RAMFS(50) except MemoryError: print("SKIP") raise SystemExit # first we umount any existing mount points the target may have try: uos.umount("/") except OSError: pass for path in uos.listdir("/"): uos.umount("/" + path) uos.VfsFat.mkfs(bdev) uos.mount(bdev, "/") print(uos.getcwd()) f = open("test.txt", "w") f.write("hello") f.close() print(uos.listdir()) print(uos.listdir("/")) print(uos.stat("")[:-3]) print(uos.stat("/")[:-3]) print(uos.stat("test.txt")[:-3]) print(uos.stat("/test.txt")[:-3]) f = open("/test.txt") print(f.read()) f.close() uos.rename("test.txt", "test2.txt") print(uos.listdir()) uos.rename("test2.txt", "/test3.txt") print(uos.listdir()) uos.rename("/test3.txt", "test4.txt") print(uos.listdir()) uos.rename("/test4.txt", "/test5.txt") print(uos.listdir()) uos.mkdir("dir") print(uos.listdir()) uos.mkdir("/dir2") print(uos.listdir()) uos.mkdir("dir/subdir") print(uos.listdir("dir")) for exist in ("", "/", "dir", "/dir", "dir/subdir"): try: uos.mkdir(exist) except OSError as er: print("mkdir OSError", er.errno == 17) # EEXIST uos.chdir("/") print(uos.stat("test5.txt")[:-3]) uos.VfsFat.mkfs(bdev2) uos.mount(bdev2, "/sys") print(uos.listdir()) print(uos.listdir("sys")) print(uos.listdir("/sys")) uos.rmdir("dir2") uos.remove("test5.txt") print(uos.listdir()) uos.umount("/") print(uos.getcwd()) print(uos.listdir()) print(uos.listdir("sys")) # test importing a file from a mounted FS import usys usys.path.clear() usys.path.append("/sys") with open("sys/test_module.py", "w") as f: f.write('print("test_module!")') import test_module
YifuLiu/AliOS-Things
components/py_engine/tests/extmod/vfs_fat_more.py
Python
apache-2.0
2,584
# Test for VfsFat using a RAM device, mtime feature try: import utime, uos utime.time utime.sleep uos.VfsFat except (ImportError, AttributeError): print("SKIP") raise SystemExit class RAMBlockDevice: ERASE_BLOCK_SIZE = 512 def __init__(self, blocks): self.data = bytearray(blocks * self.ERASE_BLOCK_SIZE) def readblocks(self, block, buf): addr = block * self.ERASE_BLOCK_SIZE for i in range(len(buf)): buf[i] = self.data[addr + i] def writeblocks(self, block, buf): addr = block * self.ERASE_BLOCK_SIZE for i in range(len(buf)): self.data[addr + i] = buf[i] def ioctl(self, op, arg): if op == 4: # block count return len(self.data) // self.ERASE_BLOCK_SIZE if op == 5: # block size return self.ERASE_BLOCK_SIZE def test(bdev, vfs_class): print("test", vfs_class) # Initial format of block device. vfs_class.mkfs(bdev) # construction vfs = vfs_class(bdev) # Create an empty file, should have a timestamp. current_time = int(utime.time()) vfs.open("test1", "wt").close() # Wait 2 seconds so mtime will increase (FAT has 2 second resolution). utime.sleep(2) # Create another empty file, should have a timestamp. vfs.open("test2", "wt").close() # Stat the files and check mtime is non-zero. stat1 = vfs.stat("test1") stat2 = vfs.stat("test2") print(stat1[8] != 0, stat2[8] != 0) # Check that test1 has mtime which matches time.time() at point of creation. # TODO this currently fails on the unix port because FAT stores timestamps # in localtime and stat() is UTC based. # print(current_time - 1 <= stat1[8] <= current_time + 1) # Check that test1 is older than test2. print(stat1[8] < stat2[8]) # Unmount. vfs.umount() bdev = RAMBlockDevice(50) test(bdev, uos.VfsFat)
YifuLiu/AliOS-Things
components/py_engine/tests/extmod/vfs_fat_mtime.py
Python
apache-2.0
1,932
try: import uerrno import uos except ImportError: print("SKIP") raise SystemExit try: uos.VfsFat except AttributeError: print("SKIP") raise SystemExit class RAMFS_OLD: SEC_SIZE = 512 def __init__(self, blocks): self.data = bytearray(blocks * self.SEC_SIZE) def readblocks(self, n, buf): # print("readblocks(%s, %x(%d))" % (n, id(buf), len(buf))) for i in range(len(buf)): buf[i] = self.data[n * self.SEC_SIZE + i] def writeblocks(self, n, buf): # print("writeblocks(%s, %x)" % (n, id(buf))) for i in range(len(buf)): self.data[n * self.SEC_SIZE + i] = buf[i] def sync(self): pass def count(self): return len(self.data) // self.SEC_SIZE try: bdev = RAMFS_OLD(50) except MemoryError: print("SKIP") raise SystemExit uos.VfsFat.mkfs(bdev) vfs = uos.VfsFat(bdev) uos.mount(vfs, "/ramdisk") # file io with vfs.open("file.txt", "w") as f: f.write("hello!") print(list(vfs.ilistdir())) with vfs.open("file.txt", "r") as f: print(f.read()) vfs.remove("file.txt") print(list(vfs.ilistdir()))
YifuLiu/AliOS-Things
components/py_engine/tests/extmod/vfs_fat_oldproto.py
Python
apache-2.0
1,150
try: import uerrno import uos except ImportError: print("SKIP") raise SystemExit try: uos.VfsFat except AttributeError: print("SKIP") raise SystemExit class RAMFS: SEC_SIZE = 512 def __init__(self, blocks): self.data = bytearray(blocks * self.SEC_SIZE) def readblocks(self, n, buf): # print("readblocks(%s, %x(%d))" % (n, id(buf), len(buf))) for i in range(len(buf)): buf[i] = self.data[n * self.SEC_SIZE + i] def writeblocks(self, n, buf): # print("writeblocks(%s, %x)" % (n, id(buf))) for i in range(len(buf)): self.data[n * self.SEC_SIZE + i] = buf[i] def ioctl(self, op, arg): # print("ioctl(%d, %r)" % (op, arg)) if op == 4: # MP_BLOCKDEV_IOCTL_BLOCK_COUNT return len(self.data) // self.SEC_SIZE if op == 5: # MP_BLOCKDEV_IOCTL_BLOCK_SIZE return self.SEC_SIZE try: bdev = RAMFS(50) except MemoryError: print("SKIP") raise SystemExit uos.VfsFat.mkfs(bdev) print(b"FOO_FILETXT" not in bdev.data) print(b"hello!" not in bdev.data) vfs = uos.VfsFat(bdev) uos.mount(vfs, "/ramdisk") print("statvfs:", vfs.statvfs("/ramdisk")) print("getcwd:", vfs.getcwd()) try: vfs.stat("no_file.txt") except OSError as e: print(e.errno == uerrno.ENOENT) with vfs.open("foo_file.txt", "w") as f: f.write("hello!") print(list(vfs.ilistdir())) print("stat root:", vfs.stat("/")[:-3]) # timestamps differ across runs print("stat file:", vfs.stat("foo_file.txt")[:-3]) # timestamps differ across runs print(b"FOO_FILETXT" in bdev.data) print(b"hello!" in bdev.data) vfs.mkdir("foo_dir") vfs.chdir("foo_dir") print("getcwd:", vfs.getcwd()) print(list(vfs.ilistdir())) with vfs.open("sub_file.txt", "w") as f: f.write("subdir file") try: vfs.chdir("sub_file.txt") except OSError as e: print(e.errno == uerrno.ENOENT) vfs.chdir("..") print("getcwd:", vfs.getcwd()) uos.umount(vfs) vfs = uos.VfsFat(bdev) print(list(vfs.ilistdir(b""))) # list a non-existent directory try: vfs.ilistdir(b"no_exist") except OSError as e: print("ENOENT:", e.errno == uerrno.ENOENT)
YifuLiu/AliOS-Things
components/py_engine/tests/extmod/vfs_fat_ramdisk.py
Python
apache-2.0
2,172
# test making a FAT filesystem on a very large block device try: import uos except ImportError: print("SKIP") raise SystemExit try: uos.VfsFat except AttributeError: print("SKIP") raise SystemExit class RAMBDevSparse: SEC_SIZE = 512 def __init__(self, blocks): self.blocks = blocks self.data = {} def readblocks(self, n, buf): # print("readblocks(%s, %x(%d))" % (n, id(buf), len(buf))) assert len(buf) == self.SEC_SIZE if n not in self.data: self.data[n] = bytearray(self.SEC_SIZE) buf[:] = self.data[n] def writeblocks(self, n, buf): # print("writeblocks(%s, %x)" % (n, id(buf))) mv = memoryview(buf) for off in range(0, len(buf), self.SEC_SIZE): s = n + off // self.SEC_SIZE if s not in self.data: self.data[s] = bytearray(self.SEC_SIZE) self.data[s][:] = mv[off : off + self.SEC_SIZE] def ioctl(self, op, arg): # print("ioctl(%d, %r)" % (op, arg)) if op == 4: # MP_BLOCKDEV_IOCTL_BLOCK_COUNT return self.blocks if op == 5: # MP_BLOCKDEV_IOCTL_BLOCK_SIZE return self.SEC_SIZE try: bdev = RAMBDevSparse(4 * 1024 * 1024 * 1024 // RAMBDevSparse.SEC_SIZE) uos.VfsFat.mkfs(bdev) except MemoryError: print("SKIP") raise SystemExit vfs = uos.VfsFat(bdev) uos.mount(vfs, "/ramdisk") print("statvfs:", vfs.statvfs("/ramdisk")) f = open("/ramdisk/test.txt", "w") f.write("test file") f.close() print("statvfs:", vfs.statvfs("/ramdisk")) f = open("/ramdisk/test.txt") print(f.read()) f.close() uos.umount(vfs)
YifuLiu/AliOS-Things
components/py_engine/tests/extmod/vfs_fat_ramdisklarge.py
Python
apache-2.0
1,664
# Test for VfsLittle using a RAM device try: import uos uos.VfsLfs1 uos.VfsLfs2 except (ImportError, AttributeError): print("SKIP") raise SystemExit class RAMBlockDevice: ERASE_BLOCK_SIZE = 1024 def __init__(self, blocks): self.data = bytearray(blocks * self.ERASE_BLOCK_SIZE) def readblocks(self, block, buf, off): addr = block * self.ERASE_BLOCK_SIZE + off for i in range(len(buf)): buf[i] = self.data[addr + i] def writeblocks(self, block, buf, off): addr = block * self.ERASE_BLOCK_SIZE + off for i in range(len(buf)): self.data[addr + i] = buf[i] def ioctl(self, op, arg): if op == 4: # block count return len(self.data) // self.ERASE_BLOCK_SIZE if op == 5: # block size return self.ERASE_BLOCK_SIZE if op == 6: # erase block return 0 def print_stat(st, print_size=True): # don't print times (just check that they have the correct type) print(st[:6], st[6] if print_size else -1, type(st[7]), type(st[8]), type(st[9])) def test(bdev, vfs_class): print("test", vfs_class) # mkfs vfs_class.mkfs(bdev) # construction vfs = vfs_class(bdev) # statvfs print(vfs.statvfs("/")) # open, write close f = vfs.open("test", "w") f.write("littlefs") f.close() # statvfs after creating a file print(vfs.statvfs("/")) # ilistdir print(list(vfs.ilistdir())) print(list(vfs.ilistdir("/"))) print(list(vfs.ilistdir(b"/"))) # mkdir, rmdir vfs.mkdir("testdir") print(list(vfs.ilistdir())) print(sorted(list(vfs.ilistdir("testdir")))) vfs.rmdir("testdir") print(list(vfs.ilistdir())) vfs.mkdir("testdir") # stat a file print_stat(vfs.stat("test")) # stat a dir (size seems to vary on LFS2 so don't print that) print_stat(vfs.stat("testdir"), False) # read with vfs.open("test", "r") as f: print(f.read()) # create large file with vfs.open("testbig", "w") as f: data = "large012" * 32 * 16 print("data length:", len(data)) for i in range(4): print("write", i) f.write(data) # stat after creating large file print(vfs.statvfs("/")) # rename vfs.rename("testbig", "testbig2") print(sorted(list(vfs.ilistdir()))) vfs.chdir("testdir") vfs.rename("/testbig2", "testbig2") print(sorted(list(vfs.ilistdir()))) vfs.rename("testbig2", "/testbig2") vfs.chdir("/") print(sorted(list(vfs.ilistdir()))) # remove vfs.remove("testbig2") print(sorted(list(vfs.ilistdir()))) # getcwd, chdir vfs.mkdir("/testdir2") vfs.mkdir("/testdir/subdir") print(vfs.getcwd()) vfs.chdir("/testdir") print(vfs.getcwd()) # create file in directory to make sure paths are relative vfs.open("test2", "w").close() print_stat(vfs.stat("test2")) print_stat(vfs.stat("/testdir/test2")) vfs.remove("test2") # chdir back to root and remove testdir vfs.chdir("/") print(vfs.getcwd()) vfs.chdir("testdir") print(vfs.getcwd()) vfs.chdir("..") print(vfs.getcwd()) vfs.chdir("testdir/subdir") print(vfs.getcwd()) vfs.chdir("../..") print(vfs.getcwd()) vfs.chdir("/./testdir2") print(vfs.getcwd()) vfs.chdir("../testdir") print(vfs.getcwd()) vfs.chdir("../..") print(vfs.getcwd()) vfs.chdir(".//testdir") print(vfs.getcwd()) vfs.chdir("subdir/./") print(vfs.getcwd()) vfs.chdir("/") print(vfs.getcwd()) vfs.rmdir("testdir/subdir") vfs.rmdir("testdir") vfs.rmdir("testdir2") bdev = RAMBlockDevice(30) test(bdev, uos.VfsLfs1) test(bdev, uos.VfsLfs2)
YifuLiu/AliOS-Things
components/py_engine/tests/extmod/vfs_lfs.py
Python
apache-2.0
3,777
# Test for VfsLittle using a RAM device, testing error handling from corrupt block device try: import uos uos.VfsLfs1 uos.VfsLfs2 except (ImportError, AttributeError): print("SKIP") raise SystemExit class RAMBlockDevice: ERASE_BLOCK_SIZE = 1024 def __init__(self, blocks): self.data = bytearray(blocks * self.ERASE_BLOCK_SIZE) self.ret = 0 def readblocks(self, block, buf, off): addr = block * self.ERASE_BLOCK_SIZE + off for i in range(len(buf)): buf[i] = self.data[addr + i] return self.ret def writeblocks(self, block, buf, off): addr = block * self.ERASE_BLOCK_SIZE + off for i in range(len(buf)): self.data[addr + i] = buf[i] return self.ret def ioctl(self, op, arg): if op == 4: # block count return len(self.data) // self.ERASE_BLOCK_SIZE if op == 5: # block size return self.ERASE_BLOCK_SIZE if op == 6: # erase block return 0 def corrupt(bdev, block): addr = block * bdev.ERASE_BLOCK_SIZE for i in range(bdev.ERASE_BLOCK_SIZE): bdev.data[addr + i] = i & 0xFF def create_vfs(bdev, vfs_class): bdev.ret = 0 vfs_class.mkfs(bdev) vfs = vfs_class(bdev) with vfs.open("f", "w") as f: for i in range(100): f.write("test") return vfs def test(bdev, vfs_class): print("test", vfs_class) # statvfs vfs = create_vfs(bdev, vfs_class) corrupt(bdev, 0) corrupt(bdev, 1) try: print(vfs.statvfs("")) except OSError: print("statvfs OSError") # error during read vfs = create_vfs(bdev, vfs_class) f = vfs.open("f", "r") bdev.ret = -5 # EIO try: f.read(10) except OSError: print("read OSError") # error during write vfs = create_vfs(bdev, vfs_class) f = vfs.open("f", "a") bdev.ret = -5 # EIO try: f.write("test") except OSError: print("write OSError") # error during close vfs = create_vfs(bdev, vfs_class) f = vfs.open("f", "w") f.write("test") bdev.ret = -5 # EIO try: f.close() except OSError: print("close OSError") # error during flush vfs = create_vfs(bdev, vfs_class) f = vfs.open("f", "w") f.write("test") bdev.ret = -5 # EIO try: f.flush() except OSError: print("flush OSError") bdev.ret = 0 f.close() bdev = RAMBlockDevice(30) test(bdev, uos.VfsLfs1) test(bdev, uos.VfsLfs2)
YifuLiu/AliOS-Things
components/py_engine/tests/extmod/vfs_lfs_corrupt.py
Python
apache-2.0
2,568
# Test for VfsLittle using a RAM device, testing error handling try: import uos uos.VfsLfs1 uos.VfsLfs2 except (ImportError, AttributeError): print("SKIP") raise SystemExit class RAMBlockDevice: ERASE_BLOCK_SIZE = 1024 def __init__(self, blocks): self.data = bytearray(blocks * self.ERASE_BLOCK_SIZE) def readblocks(self, block, buf, off): addr = block * self.ERASE_BLOCK_SIZE + off for i in range(len(buf)): buf[i] = self.data[addr + i] def writeblocks(self, block, buf, off): addr = block * self.ERASE_BLOCK_SIZE + off for i in range(len(buf)): self.data[addr + i] = buf[i] def ioctl(self, op, arg): if op == 4: # block count return len(self.data) // self.ERASE_BLOCK_SIZE if op == 5: # block size return self.ERASE_BLOCK_SIZE if op == 6: # erase block return 0 def test(bdev, vfs_class): print("test", vfs_class) # mkfs with too-small block device try: vfs_class.mkfs(RAMBlockDevice(1)) except OSError: print("mkfs OSError") # mount with invalid filesystem try: vfs_class(bdev) except OSError: print("mount OSError") # set up for following tests vfs_class.mkfs(bdev) vfs = vfs_class(bdev) with vfs.open("testfile", "w") as f: f.write("test") vfs.mkdir("testdir") # ilistdir try: vfs.ilistdir("noexist") except OSError: print("ilistdir OSError") # remove try: vfs.remove("noexist") except OSError: print("remove OSError") # rmdir try: vfs.rmdir("noexist") except OSError: print("rmdir OSError") # rename try: vfs.rename("noexist", "somethingelse") except OSError: print("rename OSError") # mkdir try: vfs.mkdir("testdir") except OSError: print("mkdir OSError") # chdir to nonexistent try: vfs.chdir("noexist") except OSError: print("chdir OSError") print(vfs.getcwd()) # check still at root # chdir to file try: vfs.chdir("testfile") except OSError: print("chdir OSError") print(vfs.getcwd()) # check still at root # stat try: vfs.stat("noexist") except OSError: print("stat OSError") # error during seek with vfs.open("testfile", "r") as f: f.seek(1 << 30) # SEEK_SET try: f.seek(1 << 30, 1) # SEEK_CUR except OSError: print("seek OSError") bdev = RAMBlockDevice(30) test(bdev, uos.VfsLfs1) test(bdev, uos.VfsLfs2)
YifuLiu/AliOS-Things
components/py_engine/tests/extmod/vfs_lfs_error.py
Python
apache-2.0
2,689
# Test for VfsLittle using a RAM device, file IO try: import uos uos.VfsLfs1 uos.VfsLfs2 except (ImportError, AttributeError): print("SKIP") raise SystemExit class RAMBlockDevice: ERASE_BLOCK_SIZE = 1024 def __init__(self, blocks): self.data = bytearray(blocks * self.ERASE_BLOCK_SIZE) def readblocks(self, block, buf, off): addr = block * self.ERASE_BLOCK_SIZE + off for i in range(len(buf)): buf[i] = self.data[addr + i] def writeblocks(self, block, buf, off): addr = block * self.ERASE_BLOCK_SIZE + off for i in range(len(buf)): self.data[addr + i] = buf[i] def ioctl(self, op, arg): if op == 4: # block count return len(self.data) // self.ERASE_BLOCK_SIZE if op == 5: # block size return self.ERASE_BLOCK_SIZE if op == 6: # erase block return 0 def test(bdev, vfs_class): print("test", vfs_class) # mkfs vfs_class.mkfs(bdev) # construction vfs = vfs_class(bdev) # create text, print, write, close f = vfs.open("test.txt", "wt") print(f) f.write("littlefs") f.close() # close already-closed file f.close() # create binary, print, write, flush, close f = vfs.open("test.bin", "wb") print(f) f.write("littlefs") f.flush() f.close() # create for append f = vfs.open("test.bin", "ab") f.write("more") f.close() # create exclusive f = vfs.open("test2.bin", "xb") f.close() # create exclusive with error try: vfs.open("test2.bin", "x") except OSError: print("open OSError") # read default with vfs.open("test.txt", "") as f: print(f.read()) # read text with vfs.open("test.txt", "rt") as f: print(f.read()) # read binary with vfs.open("test.bin", "rb") as f: print(f.read()) # create read and write with vfs.open("test.bin", "r+b") as f: print(f.read(8)) f.write("MORE") with vfs.open("test.bin", "rb") as f: print(f.read()) # seek and tell f = vfs.open("test.txt", "r") print(f.tell()) f.seek(3, 0) print(f.tell()) f.close() # open nonexistent try: vfs.open("noexist", "r") except OSError: print("open OSError") # open multiple files at the same time f1 = vfs.open("test.txt", "") f2 = vfs.open("test.bin", "b") print(f1.read()) print(f2.read()) f1.close() f2.close() bdev = RAMBlockDevice(30) test(bdev, uos.VfsLfs1) test(bdev, uos.VfsLfs2)
YifuLiu/AliOS-Things
components/py_engine/tests/extmod/vfs_lfs_file.py
Python
apache-2.0
2,626
# Test for VfsLittle using a RAM device, with mount/umount try: import uos uos.VfsLfs1 uos.VfsLfs2 except (ImportError, AttributeError): print("SKIP") raise SystemExit class RAMBlockDevice: ERASE_BLOCK_SIZE = 1024 def __init__(self, blocks): self.data = bytearray(blocks * self.ERASE_BLOCK_SIZE) def readblocks(self, block, buf, off=0): addr = block * self.ERASE_BLOCK_SIZE + off for i in range(len(buf)): buf[i] = self.data[addr + i] def writeblocks(self, block, buf, off=0): addr = block * self.ERASE_BLOCK_SIZE + off for i in range(len(buf)): self.data[addr + i] = buf[i] def ioctl(self, op, arg): if op == 4: # block count return len(self.data) // self.ERASE_BLOCK_SIZE if op == 5: # block size return self.ERASE_BLOCK_SIZE if op == 6: # erase block return 0 def test(vfs_class): print("test", vfs_class) bdev = RAMBlockDevice(30) # mount bdev unformatted try: uos.mount(bdev, "/lfs") except Exception as er: print(repr(er)) # mkfs vfs_class.mkfs(bdev) # construction vfs = vfs_class(bdev) # mount uos.mount(vfs, "/lfs") # import with open("/lfs/lfsmod.py", "w") as f: f.write('print("hello from lfs")\n') import lfsmod # import package uos.mkdir("/lfs/lfspkg") with open("/lfs/lfspkg/__init__.py", "w") as f: f.write('print("package")\n') import lfspkg # chdir and import module from current directory (needs "" in sys.path) uos.mkdir("/lfs/subdir") uos.chdir("/lfs/subdir") uos.rename("/lfs/lfsmod.py", "/lfs/subdir/lfsmod2.py") import lfsmod2 # umount uos.umount("/lfs") # mount read-only vfs = vfs_class(bdev) uos.mount(vfs, "/lfs", readonly=True) # test reading works with open("/lfs/subdir/lfsmod2.py") as f: print("lfsmod2.py:", f.read()) # test writing fails try: open("/lfs/test_write", "w") except OSError as er: print(repr(er)) # umount uos.umount("/lfs") # mount bdev again uos.mount(bdev, "/lfs") # umount uos.umount("/lfs") # clear imported modules usys.modules.clear() # initialise path import usys usys.path.clear() usys.path.append("/lfs") usys.path.append("") # run tests test(uos.VfsLfs1) test(uos.VfsLfs2)
YifuLiu/AliOS-Things
components/py_engine/tests/extmod/vfs_lfs_mount.py
Python
apache-2.0
2,447
# Test for VfsLfs using a RAM device, mtime feature try: import utime, uos utime.time utime.sleep uos.VfsLfs2 except (ImportError, AttributeError): print("SKIP") raise SystemExit class RAMBlockDevice: ERASE_BLOCK_SIZE = 1024 def __init__(self, blocks): self.data = bytearray(blocks * self.ERASE_BLOCK_SIZE) def readblocks(self, block, buf, off): addr = block * self.ERASE_BLOCK_SIZE + off for i in range(len(buf)): buf[i] = self.data[addr + i] def writeblocks(self, block, buf, off): addr = block * self.ERASE_BLOCK_SIZE + off for i in range(len(buf)): self.data[addr + i] = buf[i] def ioctl(self, op, arg): if op == 4: # block count return len(self.data) // self.ERASE_BLOCK_SIZE if op == 5: # block size return self.ERASE_BLOCK_SIZE if op == 6: # erase block return 0 def test(bdev, vfs_class): print("test", vfs_class) # Initial format of block device. vfs_class.mkfs(bdev) # construction print("mtime=True") vfs = vfs_class(bdev, mtime=True) # Create an empty file, should have a timestamp. current_time = int(utime.time()) vfs.open("test1", "wt").close() # Wait 1 second so mtime will increase by at least 1. utime.sleep(1) # Create another empty file, should have a timestamp. vfs.open("test2", "wt").close() # Stat the files and check mtime is non-zero. stat1 = vfs.stat("test1") stat2 = vfs.stat("test2") print(stat1[8] != 0, stat2[8] != 0) # Check that test1 has mtime which matches time.time() at point of creation. print(current_time <= stat1[8] <= current_time + 1) # Check that test1 is older than test2. print(stat1[8] < stat2[8]) # Wait 1 second so mtime will increase by at least 1. utime.sleep(1) # Open test1 for reading and ensure mtime did not change. vfs.open("test1", "rt").close() print(vfs.stat("test1") == stat1) # Open test1 for writing and ensure mtime increased from the previous value. vfs.open("test1", "wt").close() stat1_old = stat1 stat1 = vfs.stat("test1") print(stat1_old[8] < stat1[8]) # Unmount. vfs.umount() # Check that remounting with mtime=False can read the timestamps. print("mtime=False") vfs = vfs_class(bdev, mtime=False) print(vfs.stat("test1") == stat1) print(vfs.stat("test2") == stat2) f = vfs.open("test1", "wt") f.close() print(vfs.stat("test1") == stat1) vfs.umount() # Check that remounting with mtime=True still has the timestamps. print("mtime=True") vfs = vfs_class(bdev, mtime=True) print(vfs.stat("test1") == stat1) print(vfs.stat("test2") == stat2) vfs.umount() bdev = RAMBlockDevice(30) test(bdev, uos.VfsLfs2)
YifuLiu/AliOS-Things
components/py_engine/tests/extmod/vfs_lfs_mtime.py
Python
apache-2.0
2,861
# Test for VfsLfs using a RAM device, when the first superblock does not exist try: import uos uos.VfsLfs2 except (ImportError, AttributeError): print("SKIP") raise SystemExit class RAMBlockDevice: def __init__(self, block_size, data): self.block_size = block_size self.data = data def readblocks(self, block, buf, off): addr = block * self.block_size + off for i in range(len(buf)): buf[i] = self.data[addr + i] def ioctl(self, op, arg): if op == 4: # block count return len(self.data) // self.block_size if op == 5: # block size return self.block_size if op == 6: # erase block return 0 # This is a valid littlefs2 filesystem with a block size of 64 bytes. # The first block (where the first superblock is stored) is fully erased. lfs2_data = b"\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\x02\x00\x00\x00\xf0\x0f\xff\xf7littlefs/\xe0\x00\x10\x00\x00\x02\x00@\x00\x00\x00\x04\x00\x00\x00\xff\x00\x00\x00\xff\xff\xff\x7f\xfe\x03\x00\x00p\x1f\xfc\x08\x1b\xb4\x14\xa7\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\x01\x00\x00\x00\xff\xef\xff\xf7test.txt \x00\x00\x08p\x1f\xfc\x08\x83\xf1u\xba\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00" # Create the block device from the static data (it will be read-only). bdev = RAMBlockDevice(64, lfs2_data) # Create the VFS explicitly, no auto-detection is needed for this. vfs = uos.VfsLfs2(bdev) print(list(vfs.ilistdir())) # Mount the block device directly; this relies on auto-detection. uos.mount(bdev, "/userfs") print(uos.listdir("/userfs")) # Clean up. uos.umount("/userfs")
YifuLiu/AliOS-Things
components/py_engine/tests/extmod/vfs_lfs_superblock.py
Python
apache-2.0
2,238
# Test for VfsPosix try: import uos uos.VfsPosix except (ImportError, AttributeError): print("SKIP") raise SystemExit # We need a directory for testing that doesn't already exist. # Skip the test if it does exist. temp_dir = "micropy_test_dir" try: uos.stat(temp_dir) print("SKIP") raise SystemExit except OSError: pass # getcwd and chdir curdir = uos.getcwd() uos.chdir("/") print(uos.getcwd()) uos.chdir(curdir) print(uos.getcwd() == curdir) # stat print(type(uos.stat("/"))) # listdir and ilistdir print(type(uos.listdir("/"))) # mkdir uos.mkdir(temp_dir) # file create f = open(temp_dir + "/test", "w") f.write("hello") f.close() # close on a closed file should succeed f.close() # construct a file object using the type constructor, with a raw fileno f = type(f)(2) print(f) # file read f = open(temp_dir + "/test", "r") print(f.read()) f.close() # rename uos.rename(temp_dir + "/test", temp_dir + "/test2") print(uos.listdir(temp_dir)) # construct new VfsPosix with path argument vfs = uos.VfsPosix(temp_dir) print(list(i[0] for i in vfs.ilistdir("."))) # stat, statvfs print(type(vfs.stat("."))) print(type(vfs.statvfs("."))) # check types of ilistdir with str/bytes arguments print(type(list(vfs.ilistdir("."))[0][0])) print(type(list(vfs.ilistdir(b"."))[0][0])) # remove uos.remove(temp_dir + "/test2") print(uos.listdir(temp_dir)) # remove with error try: uos.remove(temp_dir + "/test2") except OSError: print("remove OSError") # rmdir uos.rmdir(temp_dir) print(temp_dir in uos.listdir()) # rmdir with error try: uos.rmdir(temp_dir) except OSError: print("rmdir OSError")
YifuLiu/AliOS-Things
components/py_engine/tests/extmod/vfs_posix.py
Python
apache-2.0
1,649
# test VFS functionality with a user-defined filesystem # also tests parts of uio.IOBase implementation import usys try: import uio uio.IOBase import uos uos.mount except (ImportError, AttributeError): print("SKIP") raise SystemExit class UserFile(uio.IOBase): def __init__(self, mode, data): assert isinstance(data, bytes) self.is_text = mode.find("b") == -1 self.data = data self.pos = 0 def read(self): if self.is_text: return str(self.data, "utf8") else: return self.data def readinto(self, buf): assert not self.is_text n = 0 while n < len(buf) and self.pos < len(self.data): buf[n] = self.data[self.pos] n += 1 self.pos += 1 return n def ioctl(self, req, arg): print("ioctl", req, arg) return 0 class UserFS: def __init__(self, files): self.files = files def mount(self, readonly, mksfs): pass def umount(self): pass def stat(self, path): print("stat", path) if path in self.files: return (32768, 0, 0, 0, 0, 0, 0, 0, 0, 0) raise OSError def open(self, path, mode): print("open", path, mode) return UserFile(mode, self.files[path]) # create and mount a user filesystem user_files = { "/data.txt": b"some data in a text file", "/usermod1.py": b"print('in usermod1')\nimport usermod2", "/usermod2.py": b"print('in usermod2')", } uos.mount(UserFS(user_files), "/userfs") # open and read a file f = open("/userfs/data.txt") print(f.read()) # import files from the user filesystem usys.path.append("/userfs") import usermod1 # unmount and undo path addition uos.umount("/userfs") usys.path.pop()
YifuLiu/AliOS-Things
components/py_engine/tests/extmod/vfs_userfs.py
Python
apache-2.0
1,821
try: import uio import uerrno import uwebsocket except ImportError: print("SKIP") raise SystemExit # put raw data in the stream and do a websocket read def ws_read(msg, sz): ws = uwebsocket.websocket(uio.BytesIO(msg)) return ws.read(sz) # do a websocket write and then return the raw data from the stream def ws_write(msg, sz): s = uio.BytesIO() ws = uwebsocket.websocket(s) ws.write(msg) s.seek(0) return s.read(sz) # basic frame print(ws_read(b"\x81\x04ping", 4)) print(ws_read(b"\x80\x04ping", 4)) # FRAME_CONT print(ws_write(b"pong", 6)) # split frames are not supported # print(ws_read(b"\x01\x04ping", 4)) # extended payloads print(ws_read(b"\x81~\x00\x80" + b"ping" * 32, 128)) print(ws_write(b"pong" * 32, 132)) # mask (returned data will be 'mask' ^ 'mask') print(ws_read(b"\x81\x84maskmask", 4)) # close control frame s = uio.BytesIO(b"\x88\x00") # FRAME_CLOSE ws = uwebsocket.websocket(s) print(ws.read(1)) s.seek(2) print(s.read(4)) # misc control frames print(ws_read(b"\x89\x00\x81\x04ping", 4)) # FRAME_PING print(ws_read(b"\x8a\x00\x81\x04pong", 4)) # FRAME_PONG # close method ws = uwebsocket.websocket(uio.BytesIO()) ws.close() # ioctl ws = uwebsocket.websocket(uio.BytesIO()) print(ws.ioctl(8)) # GET_DATA_OPTS print(ws.ioctl(9, 2)) # SET_DATA_OPTS print(ws.ioctl(9)) try: ws.ioctl(-1) except OSError as e: print("ioctl: EINVAL:", e.errno == uerrno.EINVAL)
YifuLiu/AliOS-Things
components/py_engine/tests/extmod/websocket_basic.py
Python
apache-2.0
1,450
# check if async/await keywords are supported async def foo(): await 1 print("async")
YifuLiu/AliOS-Things
components/py_engine/tests/feature_check/async_check.py
Python
apache-2.0
92
try: bytearray print("bytearray") except NameError: print("no")
YifuLiu/AliOS-Things
components/py_engine/tests/feature_check/bytearray.py
Python
apache-2.0
76
try: import usys as sys except ImportError: import sys print(sys.byteorder)
YifuLiu/AliOS-Things
components/py_engine/tests/feature_check/byteorder.py
Python
apache-2.0
85
try: complex print("complex") except NameError: print("no")
YifuLiu/AliOS-Things
components/py_engine/tests/feature_check/complex.py
Python
apache-2.0
72
x = const(1) print(x)
YifuLiu/AliOS-Things
components/py_engine/tests/feature_check/const.py
Python
apache-2.0
22
try: extra_coverage print("coverage") except NameError: print("no")
YifuLiu/AliOS-Things
components/py_engine/tests/feature_check/coverage.py
Python
apache-2.0
80
# detect how many bits of precision the floating point implementation has try: float except NameError: print(0) else: if float("1.0000001") == float("1.0"): print(30) elif float("1e300") == float("inf"): print(32) else: print(64)
YifuLiu/AliOS-Things
components/py_engine/tests/feature_check/float.py
Python
apache-2.0
275
# check whether f-strings (PEP-498) are supported a = 1 print(f"a={a}")
YifuLiu/AliOS-Things
components/py_engine/tests/feature_check/fstring.py
Python
apache-2.0
72
# Check whether arbitrary-precision integers (MPZ) are supported print(1000000000000000000000000000000000000000000000)
YifuLiu/AliOS-Things
components/py_engine/tests/feature_check/int_big.py
Python
apache-2.0
119
# this test for the availability of native emitter @micropython.native def f(): pass f() print("native")
YifuLiu/AliOS-Things
components/py_engine/tests/feature_check/native_check.py
Python
apache-2.0
111
# Check for emacs keys in REPL t = +11 t == 2
YifuLiu/AliOS-Things
components/py_engine/tests/feature_check/repl_emacs_check.py
Python
apache-2.0
48
# just check if ctrl+w is supported, because it makes sure that # both MICROPY_REPL_EMACS_WORDS_MOVE and MICROPY_REPL_EXTRA_WORDS_MOVE are enabled. t = 1231 t == 1
YifuLiu/AliOS-Things
components/py_engine/tests/feature_check/repl_words_move_check.py
Python
apache-2.0
165
class Foo: def __radd__(self, other): pass try: 5 + Foo() except TypeError: print("TypeError")
YifuLiu/AliOS-Things
components/py_engine/tests/feature_check/reverse_ops.py
Python
apache-2.0
117
# check if set literal syntax is supported print({1})
YifuLiu/AliOS-Things
components/py_engine/tests/feature_check/set_check.py
Python
apache-2.0
54
try: slice print("slice") except NameError: print("no")
YifuLiu/AliOS-Things
components/py_engine/tests/feature_check/slice.py
Python
apache-2.0
68
try: import uio print("uio") except ImportError: print("no")
YifuLiu/AliOS-Things
components/py_engine/tests/feature_check/uio_module.py
Python
apache-2.0
74
# test construction of array from array with float type try: from uarray import array except ImportError: try: from array import array except ImportError: print("SKIP") raise SystemExit print(array("f", array("h", [1, 2]))) print(array("d", array("f", [1, 2])))
YifuLiu/AliOS-Things
components/py_engine/tests/float/array_construct.py
Python
apache-2.0
300
# test builtin abs function with float args for val in ( "1.0", "-1.0", "0.0", "-0.0", "nan", "-nan", "inf", "-inf", ): print(val, abs(float(val)))
YifuLiu/AliOS-Things
components/py_engine/tests/float/builtin_float_abs.py
Python
apache-2.0
185
# test builtin hash function with float args # these should hash to an integer with a specific value for val in ( "0.0", "-0.0", "1.0", "2.0", "-12.0", "12345.0", ): print(val, hash(float(val))) # just check that these values are hashable for val in ( "0.1", "-0.1", "10.3", "0.4e3", "1e16", "inf", "-inf", "nan", ): print(val, type(hash(float(val))))
YifuLiu/AliOS-Things
components/py_engine/tests/float/builtin_float_hash.py
Python
apache-2.0
418
# test builtin min and max functions with float args try: min max except: print("SKIP") raise SystemExit print(min(0, 1.0)) print(min(1.0, 0)) print(min(0, -1.0)) print(min(-1.0, 0)) print(max(0, 1.0)) print(max(1.0, 0)) print(max(0, -1.0)) print(max(-1.0, 0)) print(min(1.5, -1.5)) print(min(-1.5, 1.5)) print(max(1.5, -1.5)) print(max(-1.5, 1.5)) print(min([1, 2.9, 4, 0, -1, 2])) print(max([1, 2.9, 4, 0, -1, 2])) print(min([1, 2.9, 4, 6.5, -1, 2])) print(max([1, 2.9, 4, 6.5, -1, 2])) print(min([1, 2.9, 4, -6.5, -1, 2])) print(max([1, 2.9, 4, -6.5, -1, 2]))
YifuLiu/AliOS-Things
components/py_engine/tests/float/builtin_float_minmax.py
Python
apache-2.0
585
# test builtin pow function with float args print(pow(0.0, 0.0)) print(pow(0, 1.0)) print(pow(1.0, 1)) print(pow(2.0, 3.0)) print(pow(2.0, -4.0)) print(pow(0.0, float("inf"))) print(pow(0.0, float("-inf"))) print(pow(0.0, float("nan")))
YifuLiu/AliOS-Things
components/py_engine/tests/float/builtin_float_pow.py
Python
apache-2.0
239
# test round() with floats # check basic cases tests = [ [0.0], [1.0], [0.1], [-0.1], [123.4], [123.6], [-123.4], [-123.6], [1.234567, 5], [1.23456, 1], [1.23456, 0], [1234.56, -2], ] for t in tests: print(round(*t)) # check .5 cases for i in range(11): print(round((i - 5) / 2)) # test second arg for i in range(-1, 3): print(round(1.47, i)) # test inf and nan for val in (float("inf"), float("nan")): try: round(val) except (ValueError, OverflowError) as e: print(type(e))
YifuLiu/AliOS-Things
components/py_engine/tests/float/builtin_float_round.py
Python
apache-2.0
563
# test round() with floats that return large integers for x in (-1e25, 1e25): print("%.3g" % round(x))
YifuLiu/AliOS-Things
components/py_engine/tests/float/builtin_float_round_intbig.py
Python
apache-2.0
108