diff --git a/tests/cmdline/cmd_parsetree.py b/tests/cmdline/cmd_parsetree.py index da36c80703..50da369543 100644 --- a/tests/cmdline/cmd_parsetree.py +++ b/tests/cmdline/cmd_parsetree.py @@ -4,9 +4,9 @@ for i in (): pass a = None -b = 'str' -c = 'a very long str that will not be interned' -d = b'bytes' -e = b'a very long bytes that will not be interned' +b = "str" +c = "a very long str that will not be interned" +d = b"bytes" +e = b"a very long bytes that will not be interned" f = 123456789012345678901234567890 g = 123 diff --git a/tests/cmdline/cmd_showbc.py b/tests/cmdline/cmd_showbc.py index f30b39ee10..a960c15c4a 100644 --- a/tests/cmdline/cmd_showbc.py +++ b/tests/cmdline/cmd_showbc.py @@ -1,5 +1,6 @@ # cmdline: -v -v # test printing of all bytecodes +# fmt: off def f(): # constants diff --git a/tests/cmdline/cmd_showbc.py.exp b/tests/cmdline/cmd_showbc.py.exp index 4d90ae22ca..325efc7dba 100644 --- a/tests/cmdline/cmd_showbc.py.exp +++ b/tests/cmdline/cmd_showbc.py.exp @@ -7,7 +7,7 @@ arg names: (N_EXC_STACK 0) bc=0 line=1 ######## - bc=\\d\+ line=159 + bc=\\d\+ line=160 00 MAKE_FUNCTION \.\+ \\d\+ STORE_NAME f \\d\+ MAKE_FUNCTION \.\+ @@ -45,7 +45,7 @@ Raw bytecode (code_info_size=\\d\+, bytecode_size=\\d\+): (INIT_CELL 16) bc=0 line=1 ######## - bc=\\d\+ line=126 + bc=\\d\+ line=127 00 LOAD_CONST_NONE 01 LOAD_CONST_FALSE 02 BINARY_OP 27 __add__ @@ -320,7 +320,7 @@ Raw bytecode (code_info_size=\\d\+, bytecode_size=\\d\+): (N_EXC_STACK 0) bc=0 line=1 ######## - bc=\\d\+ line=132 + bc=\\d\+ line=133 00 LOAD_CONST_SMALL_INT 1 01 DUP_TOP 02 STORE_FAST 0 @@ -376,7 +376,7 @@ arg names: a (N_EXC_STACK 0) (INIT_CELL 0) ######## - bc=\\d\+ line=138 + bc=\\d\+ line=139 00 LOAD_CONST_SMALL_INT 2 01 BUILD_TUPLE 1 03 LOAD_NULL @@ -393,9 +393,9 @@ arg names: (N_STATE 2) (N_EXC_STACK 0) bc=0 line=1 - bc=0 line=143 - bc=3 line=144 - bc=6 line=145 + bc=0 line=144 + bc=3 line=145 + bc=6 line=146 00 LOAD_CONST_NONE 01 YIELD_VALUE 02 POP_TOP @@ -418,7 +418,7 @@ arg names: (N_EXC_STACK 0) bc=0 line=1 ######## - bc=13 line=149 + bc=13 line=150 00 LOAD_NAME __name__ (cache=0) 04 STORE_NAME __module__ 07 LOAD_CONST_STRING 'Class' @@ -433,7 +433,7 @@ arg names: self (N_STATE 4) (N_EXC_STACK 0) bc=0 line=1 - bc=0 line=156 + bc=0 line=157 00 LOAD_GLOBAL super (cache=0) \\d\+ LOAD_GLOBAL __class__ (cache=0) \\d\+ LOAD_FAST 0 @@ -450,7 +450,7 @@ arg names: * * * (N_STATE 9) (N_EXC_STACK 0) bc=0 line=1 - bc=0 line=59 + bc=0 line=60 ######## 00 LOAD_NULL 01 LOAD_FAST 2 @@ -474,7 +474,7 @@ arg names: * * * (N_STATE 10) (N_EXC_STACK 0) bc=0 line=1 - bc=0 line=60 + bc=0 line=61 ######## 00 BUILD_LIST 0 02 LOAD_FAST 2 @@ -517,7 +517,7 @@ arg names: * (N_EXC_STACK 0) bc=0 line=1 ######## - bc=\\d\+ line=113 + bc=\\d\+ line=114 00 LOAD_DEREF 0 02 LOAD_CONST_SMALL_INT 1 03 BINARY_OP 27 __add__ @@ -536,7 +536,7 @@ arg names: * b (N_EXC_STACK 0) bc=0 line=1 ######## - bc=\\d\+ line=139 + bc=\\d\+ line=140 00 LOAD_FAST 1 01 LOAD_DEREF 0 03 BINARY_OP 27 __add__ diff --git a/tests/cpydiff/core_class_delnotimpl.py b/tests/cpydiff/core_class_delnotimpl.py index c51c3d536f..18c176e9bb 100644 --- a/tests/cpydiff/core_class_delnotimpl.py +++ b/tests/cpydiff/core_class_delnotimpl.py @@ -6,9 +6,11 @@ workaround: Unknown """ import gc -class Foo(): + +class Foo: def __del__(self): - print('__del__') + print("__del__") + f = Foo() del f diff --git a/tests/cpydiff/core_class_mro.py b/tests/cpydiff/core_class_mro.py index 99713e790c..bdd6dd5df6 100644 --- a/tests/cpydiff/core_class_mro.py +++ b/tests/cpydiff/core_class_mro.py @@ -4,12 +4,16 @@ description: Method Resolution Order (MRO) is not compliant with CPython cause: Depth first non-exhaustive method resolution order workaround: Avoid complex class hierarchies with multiple inheritance and complex method overrides. Keep in mind that many languages don't support multiple inheritance at all. """ + + class Foo: def __str__(self): return "Foo" + class C(tuple, Foo): pass + t = C((1, 2, 3)) print(t) diff --git a/tests/cpydiff/core_class_supermultiple.py b/tests/cpydiff/core_class_supermultiple.py index f0823ee11d..9a87b85a87 100644 --- a/tests/cpydiff/core_class_supermultiple.py +++ b/tests/cpydiff/core_class_supermultiple.py @@ -4,24 +4,29 @@ description: When inheriting from multiple classes super() only calls one class cause: See :ref:`cpydiff_core_class_mro` workaround: See :ref:`cpydiff_core_class_mro` """ + + class A: def __init__(self): print("A.__init__") + class B(A): def __init__(self): print("B.__init__") super().__init__() + class C(A): def __init__(self): print("C.__init__") super().__init__() -class D(B,C): +class D(B, C): def __init__(self): print("D.__init__") super().__init__() + D() diff --git a/tests/cpydiff/core_class_superproperty.py b/tests/cpydiff/core_class_superproperty.py index 1ec210550e..2d7775a902 100644 --- a/tests/cpydiff/core_class_superproperty.py +++ b/tests/cpydiff/core_class_superproperty.py @@ -4,15 +4,19 @@ description: Calling super() getter property in subclass will return a property cause: Unknown workaround: Unknown """ + + class A: @property def p(self): - return {"a":10} + return {"a": 10} + class AA(A): @property def p(self): return super().p + a = AA() print(a.p) diff --git a/tests/cpydiff/core_function_userattr.py b/tests/cpydiff/core_function_userattr.py index 2972939084..a8380c690a 100644 --- a/tests/cpydiff/core_function_userattr.py +++ b/tests/cpydiff/core_function_userattr.py @@ -4,8 +4,11 @@ description: User-defined attributes for functions are not supported cause: MicroPython is highly optimized for memory usage. workaround: Use external dictionary, e.g. ``FUNC_X[f] = 0``. """ + + def f(): pass + f.x = 0 print(f.x) diff --git a/tests/cpydiff/core_generator_noexit.py b/tests/cpydiff/core_generator_noexit.py index c25fbe75a2..149e9a0a90 100644 --- a/tests/cpydiff/core_generator_noexit.py +++ b/tests/cpydiff/core_generator_noexit.py @@ -4,11 +4,15 @@ description: Context manager __exit__() not called in a generator which does not cause: Unknown workaround: Unknown """ + + class foo(object): def __enter__(self): - print('Enter') + print("Enter") + def __exit__(self, *args): - print('Exit') + print("Exit") + def bar(x): with foo(): @@ -16,9 +20,11 @@ def bar(x): x += 1 yield x + def func(): g = bar(0) for _ in range(3): print(next(g)) + func() diff --git a/tests/cpydiff/core_import_prereg.py b/tests/cpydiff/core_import_prereg.py index 4a71217821..3ce2340c68 100644 --- a/tests/cpydiff/core_import_prereg.py +++ b/tests/cpydiff/core_import_prereg.py @@ -12,6 +12,7 @@ except NameError as e: print(e) try: from modules import foo - print('Should not get here') + + print("Should not get here") except NameError as e: print(e) diff --git a/tests/cpydiff/core_import_split_ns_pkgs.py b/tests/cpydiff/core_import_split_ns_pkgs.py index 700620c470..62bf337a22 100644 --- a/tests/cpydiff/core_import_split_ns_pkgs.py +++ b/tests/cpydiff/core_import_split_ns_pkgs.py @@ -5,6 +5,7 @@ cause: MicroPython's import system is highly optimized for simplicity, minimal m workaround: Don't install modules belonging to the same namespace package in different directories. For MicroPython, it's recommended to have at most 3-component module search paths: for your current application, per-user (writable), system-wide (non-writable). """ import sys + sys.path.append(sys.path[1] + "/modules") sys.path.append(sys.path[1] + "/modules2") diff --git a/tests/cpydiff/core_locals.py b/tests/cpydiff/core_locals.py index 0240e5a1a9..af3280c6d7 100644 --- a/tests/cpydiff/core_locals.py +++ b/tests/cpydiff/core_locals.py @@ -4,8 +4,11 @@ description: Local variables aren't included in locals() result cause: MicroPython doesn't maintain symbolic local environment, it is optimized to an array of slots. Thus, local variables can't be accessed by a name. workaround: Unknown """ + + def test(): val = 2 print(locals()) + test() diff --git a/tests/cpydiff/core_locals_eval.py b/tests/cpydiff/core_locals_eval.py index 8416e3b069..025d226372 100644 --- a/tests/cpydiff/core_locals_eval.py +++ b/tests/cpydiff/core_locals_eval.py @@ -6,9 +6,11 @@ workaround: Unknown """ val = 1 + def test(): val = 2 print(val) eval("print(val)") + test() diff --git a/tests/cpydiff/modules/foo.py b/tests/cpydiff/modules/foo.py index e6e33a7b46..51cd4b2490 100644 --- a/tests/cpydiff/modules/foo.py +++ b/tests/cpydiff/modules/foo.py @@ -1,2 +1,2 @@ -print('foo') +print("foo") xxx diff --git a/tests/cpydiff/modules_array_containment.py b/tests/cpydiff/modules_array_containment.py index 190a3c2760..8f25b0d491 100644 --- a/tests/cpydiff/modules_array_containment.py +++ b/tests/cpydiff/modules_array_containment.py @@ -5,4 +5,5 @@ cause: Unknown workaround: Unknown """ import array -print(1 in array.array('B', b'12')) + +print(1 in array.array("B", b"12")) diff --git a/tests/cpydiff/modules_array_deletion.py b/tests/cpydiff/modules_array_deletion.py index 97f988da23..3376527373 100644 --- a/tests/cpydiff/modules_array_deletion.py +++ b/tests/cpydiff/modules_array_deletion.py @@ -5,6 +5,7 @@ cause: Unknown workaround: Unknown """ import array -a = array.array('b', (1, 2, 3)) + +a = array.array("b", (1, 2, 3)) del a[1] print(a) diff --git a/tests/cpydiff/modules_array_subscrstep.py b/tests/cpydiff/modules_array_subscrstep.py index 1103f18269..24308bd904 100644 --- a/tests/cpydiff/modules_array_subscrstep.py +++ b/tests/cpydiff/modules_array_subscrstep.py @@ -5,5 +5,6 @@ cause: Unknown workaround: Unknown """ import array -a = array.array('b', (1, 2, 3)) + +a = array.array("b", (1, 2, 3)) print(a[3:2:2]) diff --git a/tests/cpydiff/modules_deque.py b/tests/cpydiff/modules_deque.py index a503ea4f55..4d2746d1f8 100644 --- a/tests/cpydiff/modules_deque.py +++ b/tests/cpydiff/modules_deque.py @@ -5,5 +5,6 @@ cause: Unknown workaround: Use regular lists. micropython-lib has implementation of collections.deque. """ import collections + D = collections.deque() print(D) diff --git a/tests/cpydiff/modules_json_nonserializable.py b/tests/cpydiff/modules_json_nonserializable.py index 913b734e8b..ffe523786f 100644 --- a/tests/cpydiff/modules_json_nonserializable.py +++ b/tests/cpydiff/modules_json_nonserializable.py @@ -5,10 +5,11 @@ cause: Unknown workaround: Unknown """ import json + a = bytes(x for x in range(256)) try: z = json.dumps(a) x = json.loads(z) - print('Should not get here') + print("Should not get here") except TypeError: - print('TypeError') + print("TypeError") diff --git a/tests/cpydiff/modules_os_environ.py b/tests/cpydiff/modules_os_environ.py index db471a159e..491d8a3101 100644 --- a/tests/cpydiff/modules_os_environ.py +++ b/tests/cpydiff/modules_os_environ.py @@ -5,12 +5,13 @@ cause: Unknown workaround: Use ``getenv``, ``putenv`` and ``unsetenv`` """ import os + try: - print(os.environ.get('NEW_VARIABLE')) - os.environ['NEW_VARIABLE'] = 'VALUE' - print(os.environ['NEW_VARIABLE']) + print(os.environ.get("NEW_VARIABLE")) + os.environ["NEW_VARIABLE"] = "VALUE" + print(os.environ["NEW_VARIABLE"]) except AttributeError: - print('should not get here') - print(os.getenv('NEW_VARIABLE')) - os.putenv('NEW_VARIABLE', 'VALUE') - print(os.getenv('NEW_VARIABLE')) + print("should not get here") + print(os.getenv("NEW_VARIABLE")) + os.putenv("NEW_VARIABLE", "VALUE") + print(os.getenv("NEW_VARIABLE")) diff --git a/tests/cpydiff/modules_os_getenv.py b/tests/cpydiff/modules_os_getenv.py index 1313755564..d1e828438e 100644 --- a/tests/cpydiff/modules_os_getenv.py +++ b/tests/cpydiff/modules_os_getenv.py @@ -5,6 +5,7 @@ cause: The ``environ`` attribute is not implemented workaround: Unknown """ import os -print(os.getenv('NEW_VARIABLE')) -os.putenv('NEW_VARIABLE', 'VALUE') -print(os.getenv('NEW_VARIABLE')) + +print(os.getenv("NEW_VARIABLE")) +os.putenv("NEW_VARIABLE", "VALUE") +print(os.getenv("NEW_VARIABLE")) diff --git a/tests/cpydiff/modules_os_getenv_argcount.py b/tests/cpydiff/modules_os_getenv_argcount.py index 375cf614b2..d7838a92cc 100644 --- a/tests/cpydiff/modules_os_getenv_argcount.py +++ b/tests/cpydiff/modules_os_getenv_argcount.py @@ -5,9 +5,10 @@ cause: Unknown workaround: Test that the return value is ``None`` """ import os + try: - print(os.getenv('NEW_VARIABLE', 'DEFAULT')) + print(os.getenv("NEW_VARIABLE", "DEFAULT")) except TypeError: - print('should not get here') + print("should not get here") # this assumes NEW_VARIABLE is never an empty variable - print(os.getenv('NEW_VARIABLE') or 'DEFAULT') + print(os.getenv("NEW_VARIABLE") or "DEFAULT") diff --git a/tests/cpydiff/modules_struct_fewargs.py b/tests/cpydiff/modules_struct_fewargs.py index 08d32ca672..cb6b0fd874 100644 --- a/tests/cpydiff/modules_struct_fewargs.py +++ b/tests/cpydiff/modules_struct_fewargs.py @@ -5,8 +5,9 @@ cause: Unknown workaround: Unknown """ import struct + try: - print(struct.pack('bb', 1)) - print('Should not get here') + print(struct.pack("bb", 1)) + print("Should not get here") except: - print('struct.error') + print("struct.error") diff --git a/tests/cpydiff/modules_struct_manyargs.py b/tests/cpydiff/modules_struct_manyargs.py index cdbb5c672c..03395baad3 100644 --- a/tests/cpydiff/modules_struct_manyargs.py +++ b/tests/cpydiff/modules_struct_manyargs.py @@ -5,8 +5,9 @@ cause: Unknown workaround: Unknown """ import struct + try: - print(struct.pack('bb', 1, 2, 3)) - print('Should not get here') + print(struct.pack("bb", 1, 2, 3)) + print("Should not get here") except: - print('struct.error') + print("struct.error") diff --git a/tests/cpydiff/modules_sys_stdassign.py b/tests/cpydiff/modules_sys_stdassign.py index 1bf2a598a0..7d086078a9 100644 --- a/tests/cpydiff/modules_sys_stdassign.py +++ b/tests/cpydiff/modules_sys_stdassign.py @@ -5,5 +5,6 @@ cause: They are stored in read-only memory. workaround: Unknown """ import sys + sys.stdin = None print(sys.stdin) diff --git a/tests/cpydiff/syntax_spaces.py b/tests/cpydiff/syntax_spaces.py index 8578a51e28..c308240a78 100644 --- a/tests/cpydiff/syntax_spaces.py +++ b/tests/cpydiff/syntax_spaces.py @@ -5,14 +5,14 @@ cause: Unknown workaround: Unknown """ try: - print(eval('1and 0')) + print(eval("1and 0")) except SyntaxError: - print('Should have worked') + print("Should have worked") try: - print(eval('1or 0')) + print(eval("1or 0")) except SyntaxError: - print('Should have worked') + print("Should have worked") try: - print(eval('1if 1else 0')) + print(eval("1if 1else 0")) except SyntaxError: - print('Should have worked') + print("Should have worked") diff --git a/tests/cpydiff/types_bytes_format.py b/tests/cpydiff/types_bytes_format.py index 697ee52698..ad04987711 100644 --- a/tests/cpydiff/types_bytes_format.py +++ b/tests/cpydiff/types_bytes_format.py @@ -4,4 +4,4 @@ description: bytes objects support .format() method cause: MicroPython strives to be a more regular implementation, so if both `str` and `bytes` support ``__mod__()`` (the % operator), it makes sense to support ``format()`` for both too. Support for ``__mod__`` can also be compiled out, which leaves only ``format()`` for bytes formatting. workaround: If you are interested in CPython compatibility, don't use ``.format()`` on bytes objects. """ -print(b'{}'.format(1)) +print(b"{}".format(1)) diff --git a/tests/cpydiff/types_bytes_keywords.py b/tests/cpydiff/types_bytes_keywords.py index bdba966f7f..ade83d0a70 100644 --- a/tests/cpydiff/types_bytes_keywords.py +++ b/tests/cpydiff/types_bytes_keywords.py @@ -4,4 +4,4 @@ description: bytes() with keywords not implemented cause: Unknown workaround: Pass the encoding as a positional parameter, e.g. ``print(bytes('abc', 'utf-8'))`` """ -print(bytes('abc', encoding='utf8')) +print(bytes("abc", encoding="utf8")) diff --git a/tests/cpydiff/types_bytes_subscrstep.py b/tests/cpydiff/types_bytes_subscrstep.py index 2871bda6c1..51b94cb710 100644 --- a/tests/cpydiff/types_bytes_subscrstep.py +++ b/tests/cpydiff/types_bytes_subscrstep.py @@ -4,4 +4,4 @@ description: Bytes subscription with step != 1 not implemented cause: MicroPython is highly optimized for memory usage. workaround: Use explicit loop for this very rare operation. """ -print(b'123'[0:3:2]) +print(b"123"[0:3:2]) diff --git a/tests/cpydiff/types_dict_keys_set.py b/tests/cpydiff/types_dict_keys_set.py index 1a9af9d389..3a0849a355 100644 --- a/tests/cpydiff/types_dict_keys_set.py +++ b/tests/cpydiff/types_dict_keys_set.py @@ -4,4 +4,4 @@ description: Dictionary keys view does not behave as a set. cause: Not implemented. workaround: Explicitly convert keys to a set before using set operations. """ -print({1:2, 3:4}.keys() & {1}) +print({1: 2, 3: 4}.keys() & {1}) diff --git a/tests/cpydiff/types_exception_subclassinit.py b/tests/cpydiff/types_exception_subclassinit.py index 39cdaf45b8..ade9ebc7ab 100644 --- a/tests/cpydiff/types_exception_subclassinit.py +++ b/tests/cpydiff/types_exception_subclassinit.py @@ -8,8 +8,11 @@ workaround: Call using ``super()`` instead:: def __init__(self): super().__init__() """ + + class A(Exception): def __init__(self): Exception.__init__(self) + a = A() diff --git a/tests/cpydiff/types_float_rounding.py b/tests/cpydiff/types_float_rounding.py index c8d3cfbe88..a5b591966b 100644 --- a/tests/cpydiff/types_float_rounding.py +++ b/tests/cpydiff/types_float_rounding.py @@ -4,4 +4,4 @@ description: uPy and CPython outputs formats may differ cause: Unknown workaround: Unknown """ -print('%.1g' % -9.9) +print("%.1g" % -9.9) diff --git a/tests/cpydiff/types_int_subclassconv.py b/tests/cpydiff/types_int_subclassconv.py index 260b060ed6..5d337412c7 100644 --- a/tests/cpydiff/types_int_subclassconv.py +++ b/tests/cpydiff/types_int_subclassconv.py @@ -4,8 +4,11 @@ description: No int conversion for int-derived types available cause: Unknown workaround: Avoid subclassing builtin types unless really needed. Prefer https://en.wikipedia.org/wiki/Composition_over_inheritance . """ + + class A(int): __add__ = lambda self, other: A(int(self) + other) + a = A(42) -print(a+a) +print(a + a) diff --git a/tests/cpydiff/types_str_endswith.py b/tests/cpydiff/types_str_endswith.py index ac2600bd25..f222ac1cd3 100644 --- a/tests/cpydiff/types_str_endswith.py +++ b/tests/cpydiff/types_str_endswith.py @@ -4,4 +4,4 @@ description: Start/end indices such as str.endswith(s, start) not implemented cause: Unknown workaround: Unknown """ -print('abc'.endswith('c', 1)) +print("abc".endswith("c", 1)) diff --git a/tests/cpydiff/types_str_formatsubscr.py b/tests/cpydiff/types_str_formatsubscr.py index dd1d8d33d7..1b83cfff6c 100644 --- a/tests/cpydiff/types_str_formatsubscr.py +++ b/tests/cpydiff/types_str_formatsubscr.py @@ -4,4 +4,4 @@ description: Attributes/subscr not implemented cause: Unknown workaround: Unknown """ -print('{a[0]}'.format(a=[1, 2])) +print("{a[0]}".format(a=[1, 2])) diff --git a/tests/cpydiff/types_str_keywords.py b/tests/cpydiff/types_str_keywords.py index b336b1a73e..77a4eac1c1 100644 --- a/tests/cpydiff/types_str_keywords.py +++ b/tests/cpydiff/types_str_keywords.py @@ -4,4 +4,4 @@ description: str(...) with keywords not implemented cause: Unknown workaround: Input the encoding format directly. eg ``print(bytes('abc', 'utf-8'))`` """ -print(str(b'abc', encoding='utf8')) +print(str(b"abc", encoding="utf8")) diff --git a/tests/cpydiff/types_str_ljust_rjust.py b/tests/cpydiff/types_str_ljust_rjust.py index fa3f594c1f..72e5105e02 100644 --- a/tests/cpydiff/types_str_ljust_rjust.py +++ b/tests/cpydiff/types_str_ljust_rjust.py @@ -4,4 +4,4 @@ description: str.ljust() and str.rjust() not implemented cause: MicroPython is highly optimized for memory usage. Easy workarounds available. workaround: Instead of ``s.ljust(10)`` use ``"%-10s" % s``, instead of ``s.rjust(10)`` use ``"% 10s" % s``. Alternatively, ``"{:<10}".format(s)`` or ``"{:>10}".format(s)``. """ -print('abc'.ljust(10)) +print("abc".ljust(10)) diff --git a/tests/cpydiff/types_str_rsplitnone.py b/tests/cpydiff/types_str_rsplitnone.py index cadf869877..5d334fea2f 100644 --- a/tests/cpydiff/types_str_rsplitnone.py +++ b/tests/cpydiff/types_str_rsplitnone.py @@ -4,4 +4,4 @@ description: None as first argument for rsplit such as str.rsplit(None, n) not i cause: Unknown workaround: Unknown """ -print('a a a'.rsplit(None, 1)) +print("a a a".rsplit(None, 1)) diff --git a/tests/cpydiff/types_str_subscrstep.py b/tests/cpydiff/types_str_subscrstep.py index 0c2fce1b11..2d3245e558 100644 --- a/tests/cpydiff/types_str_subscrstep.py +++ b/tests/cpydiff/types_str_subscrstep.py @@ -4,4 +4,4 @@ description: Subscript with step != 1 is not yet implemented cause: Unknown workaround: Unknown """ -print('abcdefghi'[0:9:2]) +print("abcdefghi"[0:9:2]) diff --git a/tests/extmod/btree1.py b/tests/extmod/btree1.py index 59638ef0a4..4890d92b42 100644 --- a/tests/extmod/btree1.py +++ b/tests/extmod/btree1.py @@ -6,7 +6,7 @@ except ImportError: print("SKIP") raise SystemExit -#f = open("_test.db", "w+b") +# f = open("_test.db", "w+b") f = uio.BytesIO() db = btree.open(f, pagesize=512) diff --git a/tests/extmod/framebuf1.py b/tests/extmod/framebuf1.py index 2c13665228..c8e0132265 100644 --- a/tests/extmod/framebuf1.py +++ b/tests/extmod/framebuf1.py @@ -8,9 +8,11 @@ w = 5 h = 16 size = w * h // 8 buf = bytearray(size) -maps = {framebuf.MONO_VLSB : 'MONO_VLSB', - framebuf.MONO_HLSB : 'MONO_HLSB', - framebuf.MONO_HMSB : 'MONO_HMSB'} +maps = { + framebuf.MONO_VLSB: "MONO_VLSB", + framebuf.MONO_HLSB: "MONO_HLSB", + framebuf.MONO_HMSB: "MONO_HMSB", +} for mapping in maps.keys(): for x in range(size): @@ -43,33 +45,33 @@ for mapping in maps.keys(): # hline fbuf.fill(0) fbuf.hline(0, 1, w, 1) - print('hline', buf) + print("hline", buf) # vline fbuf.fill(0) fbuf.vline(1, 0, h, 1) - print('vline', buf) + print("vline", buf) # rect fbuf.fill(0) fbuf.rect(1, 1, 3, 3, 1) - print('rect', buf) + print("rect", buf) - #fill rect + # fill rect fbuf.fill(0) - fbuf.fill_rect(0, 0, 0, 3, 1) # zero width, no-operation + fbuf.fill_rect(0, 0, 0, 3, 1) # zero width, no-operation fbuf.fill_rect(1, 1, 3, 3, 1) - print('fill_rect', buf) + print("fill_rect", buf) # line fbuf.fill(0) fbuf.line(1, 1, 3, 3, 1) - print('line', buf) + print("line", buf) # line steep negative gradient fbuf.fill(0) fbuf.line(3, 3, 2, 1, 1) - print('line', buf) + print("line", buf) # scroll fbuf.fill(0) @@ -89,7 +91,7 @@ for mapping in maps.keys(): fbuf.fill(0) fbuf.text("hello", 0, 0, 1) print(buf) - fbuf.text("hello", 0, 0, 0) # clear + fbuf.text("hello", 0, 0, 0) # clear print(buf) # char out of font range set to chr(127) diff --git a/tests/extmod/framebuf16.py b/tests/extmod/framebuf16.py index fe81f7f93f..e658f1345a 100644 --- a/tests/extmod/framebuf16.py +++ b/tests/extmod/framebuf16.py @@ -4,28 +4,30 @@ except ImportError: print("SKIP") raise SystemExit + def printbuf(): print("--8<--") for y in range(h): - print(buf[y * w * 2:(y + 1) * w * 2]) + print(buf[y * w * 2 : (y + 1) * w * 2]) print("-->8--") + w = 4 h = 5 buf = bytearray(w * h * 2) fbuf = framebuf.FrameBuffer(buf, w, h, framebuf.RGB565) # fill -fbuf.fill(0xffff) +fbuf.fill(0xFFFF) printbuf() fbuf.fill(0x0000) printbuf() # put pixel -fbuf.pixel(0, 0, 0xeeee) -fbuf.pixel(3, 0, 0xee00) -fbuf.pixel(0, 4, 0x00ee) -fbuf.pixel(3, 4, 0x0ee0) +fbuf.pixel(0, 0, 0xEEEE) +fbuf.pixel(3, 0, 0xEE00) +fbuf.pixel(0, 4, 0x00EE) +fbuf.pixel(3, 4, 0x0EE0) printbuf() # get pixel @@ -33,7 +35,7 @@ print(fbuf.pixel(0, 4), fbuf.pixel(1, 1)) # scroll fbuf.fill(0x0000) -fbuf.pixel(2, 2, 0xffff) +fbuf.pixel(2, 2, 0xFFFF) printbuf() fbuf.scroll(0, 1) printbuf() @@ -48,11 +50,11 @@ buf2 = bytearray(w2 * h2 * 2) fbuf2 = framebuf.FrameBuffer(buf2, w2, h2, framebuf.RGB565) fbuf2.fill(0x0000) -fbuf2.pixel(0, 0, 0x0ee0) -fbuf2.pixel(0, 2, 0xee00) -fbuf2.pixel(1, 0, 0x00ee) -fbuf2.pixel(1, 2, 0xe00e) -fbuf.fill(0xffff) +fbuf2.pixel(0, 0, 0x0EE0) +fbuf2.pixel(0, 2, 0xEE00) +fbuf2.pixel(1, 0, 0x00EE) +fbuf2.pixel(1, 2, 0xE00E) +fbuf.fill(0xFFFF) fbuf.blit(fbuf2, 3, 3, 0x0000) fbuf.blit(fbuf2, -1, -1, 0x0000) fbuf.blit(fbuf2, 16, 16, 0x0000) diff --git a/tests/extmod/framebuf2.py b/tests/extmod/framebuf2.py index a313170eb5..097057fe96 100644 --- a/tests/extmod/framebuf2.py +++ b/tests/extmod/framebuf2.py @@ -4,14 +4,16 @@ except ImportError: print("SKIP") raise SystemExit + def printbuf(): print("--8<--") for y in range(h): for x in range(w): - print('%u' % ((buf[(x + y * w) // 4] >> ((x & 3) << 1)) & 3), end='') + print("%u" % ((buf[(x + y * w) // 4] >> ((x & 3) << 1)) & 3), end="") print() print("-->8--") + w = 8 h = 5 buf = bytearray(w * h // 4) diff --git a/tests/extmod/framebuf4.py b/tests/extmod/framebuf4.py index 8358fa55b9..56593ee155 100644 --- a/tests/extmod/framebuf4.py +++ b/tests/extmod/framebuf4.py @@ -4,50 +4,52 @@ except ImportError: print("SKIP") raise SystemExit + def printbuf(): print("--8<--") for y in range(h): - print(buf[y * w // 2:(y + 1) * w // 2]) + print(buf[y * w // 2 : (y + 1) * w // 2]) print("-->8--") + w = 16 h = 8 buf = bytearray(w * h // 2) fbuf = framebuf.FrameBuffer(buf, w, h, framebuf.GS4_HMSB) # fill -fbuf.fill(0x0f) +fbuf.fill(0x0F) printbuf() -fbuf.fill(0xa0) +fbuf.fill(0xA0) printbuf() # put pixel fbuf.pixel(0, 0, 0x01) printbuf() -fbuf.pixel(w-1, 0, 0x02) +fbuf.pixel(w - 1, 0, 0x02) printbuf() -fbuf.pixel(w-1, h-1, 0x03) +fbuf.pixel(w - 1, h - 1, 0x03) printbuf() -fbuf.pixel(0, h-1, 0x04) +fbuf.pixel(0, h - 1, 0x04) printbuf() # get pixel -print(fbuf.pixel(0, 0), fbuf.pixel(w-1, 0), fbuf.pixel(w-1, h-1), fbuf.pixel(0, h-1)) -print(fbuf.pixel(1, 0), fbuf.pixel(w-2, 0), fbuf.pixel(w-2, h-1), fbuf.pixel(1, h-1)) +print(fbuf.pixel(0, 0), fbuf.pixel(w - 1, 0), fbuf.pixel(w - 1, h - 1), fbuf.pixel(0, h - 1)) +print(fbuf.pixel(1, 0), fbuf.pixel(w - 2, 0), fbuf.pixel(w - 2, h - 1), fbuf.pixel(1, h - 1)) # fill rect -fbuf.fill_rect(0, 0, w, h, 0x0f) +fbuf.fill_rect(0, 0, w, h, 0x0F) printbuf() -fbuf.fill_rect(0, 0, w, h, 0xf0) -fbuf.fill_rect(1, 0, w//2+1, 1, 0xf1) +fbuf.fill_rect(0, 0, w, h, 0xF0) +fbuf.fill_rect(1, 0, w // 2 + 1, 1, 0xF1) printbuf() -fbuf.fill_rect(1, 0, w//2+1, 1, 0x10) -fbuf.fill_rect(1, 0, w//2, 1, 0xf1) +fbuf.fill_rect(1, 0, w // 2 + 1, 1, 0x10) +fbuf.fill_rect(1, 0, w // 2, 1, 0xF1) printbuf() -fbuf.fill_rect(1, 0, w//2, 1, 0x10) -fbuf.fill_rect(0, h-4, w//2+1, 4, 0xaf) +fbuf.fill_rect(1, 0, w // 2, 1, 0x10) +fbuf.fill_rect(0, h - 4, w // 2 + 1, 4, 0xAF) printbuf() -fbuf.fill_rect(0, h-4, w//2+1, 4, 0xb0) -fbuf.fill_rect(0, h-4, w//2, 4, 0xaf) +fbuf.fill_rect(0, h - 4, w // 2 + 1, 4, 0xB0) +fbuf.fill_rect(0, h - 4, w // 2, 4, 0xAF) printbuf() -fbuf.fill_rect(0, h-4, w//2, 4, 0xb0) +fbuf.fill_rect(0, h - 4, w // 2, 4, 0xB0) diff --git a/tests/extmod/framebuf8.py b/tests/extmod/framebuf8.py index b6899aae91..a3ca6fcd4f 100644 --- a/tests/extmod/framebuf8.py +++ b/tests/extmod/framebuf8.py @@ -4,14 +4,16 @@ except ImportError: print("SKIP") raise SystemExit + def printbuf(): print("--8<--") for y in range(h): for x in range(w): - print('%02x' % buf[(x + y * w)], end='') + print("%02x" % buf[(x + y * w)], end="") print() print("-->8--") + w = 8 h = 5 buf = bytearray(w * h) @@ -25,7 +27,7 @@ printbuf() fbuf.pixel(0, 0, 0x11) fbuf.pixel(w - 1, 0, 0x22) fbuf.pixel(0, h - 1, 0x33) -fbuf.pixel(w - 1, h - 1, 0xff) +fbuf.pixel(w - 1, h - 1, 0xFF) printbuf() # get pixel diff --git a/tests/extmod/framebuf_subclass.py b/tests/extmod/framebuf_subclass.py index f44a306a35..aad5d2a1e9 100644 --- a/tests/extmod/framebuf_subclass.py +++ b/tests/extmod/framebuf_subclass.py @@ -3,9 +3,10 @@ try: import framebuf except ImportError: - print('SKIP') + print("SKIP") raise SystemExit + class FB(framebuf.FrameBuffer): def __init__(self, n): self.n = n @@ -14,6 +15,7 @@ class FB(framebuf.FrameBuffer): def foo(self): self.hline(0, 2, self.n, 0x0304) + fb = FB(n=3) fb.pixel(0, 0, 0x0102) fb.foo() @@ -31,12 +33,13 @@ print(bytes(fb2)) class NotAFrameBuf: pass + try: fb.blit(NotAFrameBuf(), 0, 0) except TypeError: - print('TypeError') + print("TypeError") try: fb.blit(None, 0, 0) except TypeError: - print('TypeError') + print("TypeError") diff --git a/tests/extmod/machine_pinbase.py b/tests/extmod/machine_pinbase.py index 45aa4d8b5b..8bddd4bb70 100644 --- a/tests/extmod/machine_pinbase.py +++ b/tests/extmod/machine_pinbase.py @@ -10,7 +10,6 @@ except: class MyPin(machine.PinBase): - def __init__(self): print("__init__") self.v = False @@ -21,6 +20,7 @@ class MyPin(machine.PinBase): self.v = not self.v return int(self.v) + p = MyPin() print(p.value()) diff --git a/tests/extmod/machine_pulse.py b/tests/extmod/machine_pulse.py index 458fe09a11..65d15fb351 100644 --- a/tests/extmod/machine_pulse.py +++ b/tests/extmod/machine_pulse.py @@ -11,7 +11,6 @@ except: class ConstPin(machine.PinBase): - def __init__(self, value): self.v = value @@ -23,7 +22,6 @@ class ConstPin(machine.PinBase): class TogglePin(machine.PinBase): - def __init__(self): self.v = 0 diff --git a/tests/extmod/machine_signal.py b/tests/extmod/machine_signal.py index dcc0de1a5d..1ffdb56436 100644 --- a/tests/extmod/machine_signal.py +++ b/tests/extmod/machine_signal.py @@ -11,6 +11,7 @@ except: print("SKIP") raise SystemExit + class Pin(machine.PinBase): def __init__(self): self.v = 0 diff --git a/tests/extmod/machine_timer.py b/tests/extmod/machine_timer.py index b7e6a280f9..c9a47c4025 100644 --- a/tests/extmod/machine_timer.py +++ b/tests/extmod/machine_timer.py @@ -2,6 +2,7 @@ try: import utime, umachine as machine + machine.Timer except: print("SKIP") @@ -27,11 +28,11 @@ t2.deinit() t.deinit() # create one-shot timer with callback and wait for it to print (should be just once) -t = machine.Timer(period=1, mode=machine.Timer.ONE_SHOT, callback=lambda t:print('one-shot')) +t = machine.Timer(period=1, mode=machine.Timer.ONE_SHOT, callback=lambda t: print("one-shot")) utime.sleep_ms(5) t.deinit() # create periodic timer with callback and wait for it to print -t = machine.Timer(period=4, mode=machine.Timer.PERIODIC, callback=lambda t:print('periodic')) +t = machine.Timer(period=4, mode=machine.Timer.PERIODIC, callback=lambda t: print("periodic")) utime.sleep_ms(14) t.deinit() diff --git a/tests/extmod/time_ms_us.py b/tests/extmod/time_ms_us.py index 7c915d067a..ac2ed8be27 100644 --- a/tests/extmod/time_ms_us.py +++ b/tests/extmod/time_ms_us.py @@ -1,5 +1,6 @@ try: import utime + utime.sleep_ms, utime.sleep_us, utime.ticks_diff, utime.ticks_ms, utime.ticks_us, utime.ticks_cpu except (ImportError, AttributeError): print("SKIP") diff --git a/tests/extmod/ubinascii_a2b_base64.py b/tests/extmod/ubinascii_a2b_base64.py index 05a3169f3a..2630965e6a 100644 --- a/tests/extmod/ubinascii_a2b_base64.py +++ b/tests/extmod/ubinascii_a2b_base64.py @@ -7,40 +7,40 @@ except ImportError: print("SKIP") raise SystemExit -print(binascii.a2b_base64(b'')) -print(binascii.a2b_base64(b'Zg==')) -print(binascii.a2b_base64(b'Zm8=')) -print(binascii.a2b_base64(b'Zm9v')) -print(binascii.a2b_base64(b'Zm9vYg==')) -print(binascii.a2b_base64(b'Zm9vYmE=')) -print(binascii.a2b_base64(b'Zm9vYmFy')) +print(binascii.a2b_base64(b"")) +print(binascii.a2b_base64(b"Zg==")) +print(binascii.a2b_base64(b"Zm8=")) +print(binascii.a2b_base64(b"Zm9v")) +print(binascii.a2b_base64(b"Zm9vYg==")) +print(binascii.a2b_base64(b"Zm9vYmE=")) +print(binascii.a2b_base64(b"Zm9vYmFy")) -print(binascii.a2b_base64(b'AAECAwQFBgc=')) -print(binascii.a2b_base64(b'CAkKCwwNDg8=')) -print(binascii.a2b_base64(b'f4D/')) -print(binascii.a2b_base64(b'f4D+')) # convert '+' -print(binascii.a2b_base64(b'MTIzNEFCQ0RhYmNk')) +print(binascii.a2b_base64(b"AAECAwQFBgc=")) +print(binascii.a2b_base64(b"CAkKCwwNDg8=")) +print(binascii.a2b_base64(b"f4D/")) +print(binascii.a2b_base64(b"f4D+")) # convert '+' +print(binascii.a2b_base64(b"MTIzNEFCQ0RhYmNk")) # Ignore invalid characters and pad sequences -print(binascii.a2b_base64(b'Zm9v\n')) -print(binascii.a2b_base64(b'Zm\x009v\n')) -print(binascii.a2b_base64(b'Zm9v==')) -print(binascii.a2b_base64(b'Zm9v===')) -print(binascii.a2b_base64(b'Zm9v===YmFy')) +print(binascii.a2b_base64(b"Zm9v\n")) +print(binascii.a2b_base64(b"Zm\x009v\n")) +print(binascii.a2b_base64(b"Zm9v==")) +print(binascii.a2b_base64(b"Zm9v===")) +print(binascii.a2b_base64(b"Zm9v===YmFy")) try: - print(binascii.a2b_base64(b'abc')) + print(binascii.a2b_base64(b"abc")) except ValueError: print("ValueError") try: - print(binascii.a2b_base64(b'abcde=')) + print(binascii.a2b_base64(b"abcde=")) except ValueError: print("ValueError") try: - print(binascii.a2b_base64(b'ab*d')) + print(binascii.a2b_base64(b"ab*d")) except ValueError: print("ValueError") try: - print(binascii.a2b_base64(b'ab=cdef=')) + print(binascii.a2b_base64(b"ab=cdef=")) except ValueError: print("ValueError") diff --git a/tests/extmod/ubinascii_b2a_base64.py b/tests/extmod/ubinascii_b2a_base64.py index f4bb69fe0c..9c100f972b 100644 --- a/tests/extmod/ubinascii_b2a_base64.py +++ b/tests/extmod/ubinascii_b2a_base64.py @@ -7,16 +7,16 @@ except ImportError: print("SKIP") raise SystemExit -print(binascii.b2a_base64(b'')) -print(binascii.b2a_base64(b'f')) -print(binascii.b2a_base64(b'fo')) -print(binascii.b2a_base64(b'foo')) -print(binascii.b2a_base64(b'foob')) -print(binascii.b2a_base64(b'fooba')) -print(binascii.b2a_base64(b'foobar')) +print(binascii.b2a_base64(b"")) +print(binascii.b2a_base64(b"f")) +print(binascii.b2a_base64(b"fo")) +print(binascii.b2a_base64(b"foo")) +print(binascii.b2a_base64(b"foob")) +print(binascii.b2a_base64(b"fooba")) +print(binascii.b2a_base64(b"foobar")) -print(binascii.b2a_base64(b'\x00\x01\x02\x03\x04\x05\x06\x07')) -print(binascii.b2a_base64(b'\x08\x09\x0a\x0b\x0c\x0d\x0e\x0f')) -print(binascii.b2a_base64(b'\x7f\x80\xff')) -print(binascii.b2a_base64(b'1234ABCDabcd')) -print(binascii.b2a_base64(b'\x00\x00>')) # convert into '+' +print(binascii.b2a_base64(b"\x00\x01\x02\x03\x04\x05\x06\x07")) +print(binascii.b2a_base64(b"\x08\x09\x0a\x0b\x0c\x0d\x0e\x0f")) +print(binascii.b2a_base64(b"\x7f\x80\xff")) +print(binascii.b2a_base64(b"1234ABCDabcd")) +print(binascii.b2a_base64(b"\x00\x00>")) # convert into '+' diff --git a/tests/extmod/ubinascii_crc32.py b/tests/extmod/ubinascii_crc32.py index 89664a9b36..8f5f4d9ba5 100644 --- a/tests/extmod/ubinascii_crc32.py +++ b/tests/extmod/ubinascii_crc32.py @@ -13,12 +13,12 @@ except AttributeError: print("SKIP") raise SystemExit -print(hex(binascii.crc32(b'The quick brown fox jumps over the lazy dog'))) -print(hex(binascii.crc32(b'\x00' * 32))) -print(hex(binascii.crc32(b'\xff' * 32))) +print(hex(binascii.crc32(b"The quick brown fox jumps over the lazy dog"))) +print(hex(binascii.crc32(b"\x00" * 32))) +print(hex(binascii.crc32(b"\xff" * 32))) print(hex(binascii.crc32(bytes(range(32))))) -print(hex(binascii.crc32(b' over the lazy dog', binascii.crc32(b'The quick brown fox jumps')))) -print(hex(binascii.crc32(b'\x00' * 16, binascii.crc32(b'\x00' * 16)))) -print(hex(binascii.crc32(b'\xff' * 16, binascii.crc32(b'\xff' * 16)))) +print(hex(binascii.crc32(b" over the lazy dog", binascii.crc32(b"The quick brown fox jumps")))) +print(hex(binascii.crc32(b"\x00" * 16, binascii.crc32(b"\x00" * 16)))) +print(hex(binascii.crc32(b"\xff" * 16, binascii.crc32(b"\xff" * 16)))) print(hex(binascii.crc32(bytes(range(16, 32)), binascii.crc32(bytes(range(16)))))) diff --git a/tests/extmod/ubinascii_hexlify.py b/tests/extmod/ubinascii_hexlify.py index bc99287476..2329f53edd 100644 --- a/tests/extmod/ubinascii_hexlify.py +++ b/tests/extmod/ubinascii_hexlify.py @@ -7,7 +7,7 @@ except ImportError: print("SKIP") raise SystemExit -print(binascii.hexlify(b'\x00\x01\x02\x03\x04\x05\x06\x07')) -print(binascii.hexlify(b'\x08\x09\x0a\x0b\x0c\x0d\x0e\x0f')) -print(binascii.hexlify(b'\x7f\x80\xff')) -print(binascii.hexlify(b'1234ABCDabcd')) +print(binascii.hexlify(b"\x00\x01\x02\x03\x04\x05\x06\x07")) +print(binascii.hexlify(b"\x08\x09\x0a\x0b\x0c\x0d\x0e\x0f")) +print(binascii.hexlify(b"\x7f\x80\xff")) +print(binascii.hexlify(b"1234ABCDabcd")) diff --git a/tests/extmod/ubinascii_micropython.py b/tests/extmod/ubinascii_micropython.py index 77084ec9ee..94e8daa557 100644 --- a/tests/extmod/ubinascii_micropython.py +++ b/tests/extmod/ubinascii_micropython.py @@ -8,8 +8,8 @@ except ImportError: raise SystemExit # two arguments supported in uPy but not CPython -a = binascii.hexlify(b'123', ':') +a = binascii.hexlify(b"123", ":") print(a) # zero length buffer -print(binascii.hexlify(b'', b':')) +print(binascii.hexlify(b"", b":")) diff --git a/tests/extmod/ubinascii_unhexlify.py b/tests/extmod/ubinascii_unhexlify.py index 865abfe3a8..413eaf1b6f 100644 --- a/tests/extmod/ubinascii_unhexlify.py +++ b/tests/extmod/ubinascii_unhexlify.py @@ -7,17 +7,17 @@ except ImportError: print("SKIP") raise SystemExit -print(binascii.unhexlify(b'0001020304050607')) -print(binascii.unhexlify(b'08090a0b0c0d0e0f')) -print(binascii.unhexlify(b'7f80ff')) -print(binascii.unhexlify(b'313233344142434461626364')) +print(binascii.unhexlify(b"0001020304050607")) +print(binascii.unhexlify(b"08090a0b0c0d0e0f")) +print(binascii.unhexlify(b"7f80ff")) +print(binascii.unhexlify(b"313233344142434461626364")) try: - a = binascii.unhexlify(b'0') # odd buffer length + a = binascii.unhexlify(b"0") # odd buffer length except ValueError: - print('ValueError') + print("ValueError") try: - a = binascii.unhexlify(b'gg') # digit not hex + a = binascii.unhexlify(b"gg") # digit not hex except ValueError: - print('ValueError') + print("ValueError") diff --git a/tests/extmod/ucryptolib_aes128_cbc.py b/tests/extmod/ucryptolib_aes128_cbc.py index 4c5ea6acb2..d861d2c6bf 100644 --- a/tests/extmod/ucryptolib_aes128_cbc.py +++ b/tests/extmod/ucryptolib_aes128_cbc.py @@ -1,5 +1,6 @@ try: from Crypto.Cipher import AES + aes = AES.new except ImportError: try: diff --git a/tests/extmod/ucryptolib_aes128_ctr.py b/tests/extmod/ucryptolib_aes128_ctr.py index 5a16b45297..538d9606e9 100644 --- a/tests/extmod/ucryptolib_aes128_ctr.py +++ b/tests/extmod/ucryptolib_aes128_ctr.py @@ -10,7 +10,7 @@ def _new(k, ctr_initial): try: - _new(b'x' * 16, b'x' * 16) + _new(b"x" * 16, b"x" * 16) except ValueError as e: # is CTR support disabled? if e.args[0] == "mode": @@ -19,9 +19,9 @@ except ValueError as e: raise e crypto = _new(b"1234" * 4, b"5678" * 4) -enc = crypto.encrypt(b'a') +enc = crypto.encrypt(b"a") print(enc) -enc += crypto.encrypt(b'b' * 1000) +enc += crypto.encrypt(b"b" * 1000) print(enc) crypto = _new(b"1234" * 4, b"5678" * 4) diff --git a/tests/extmod/ucryptolib_aes128_ecb.py b/tests/extmod/ucryptolib_aes128_ecb.py index 89451b282c..5c0e179986 100644 --- a/tests/extmod/ucryptolib_aes128_ecb.py +++ b/tests/extmod/ucryptolib_aes128_ecb.py @@ -1,5 +1,6 @@ try: from Crypto.Cipher import AES + aes = AES.new except ImportError: try: diff --git a/tests/extmod/ucryptolib_aes128_ecb_enc.py b/tests/extmod/ucryptolib_aes128_ecb_enc.py index 55b676d361..1d4484b0bc 100644 --- a/tests/extmod/ucryptolib_aes128_ecb_enc.py +++ b/tests/extmod/ucryptolib_aes128_ecb_enc.py @@ -3,6 +3,7 @@ # is optional). try: from Crypto.Cipher import AES + aes = AES.new except ImportError: try: diff --git a/tests/extmod/ucryptolib_aes256_cbc.py b/tests/extmod/ucryptolib_aes256_cbc.py index a907f26e26..c01846f199 100644 --- a/tests/extmod/ucryptolib_aes256_cbc.py +++ b/tests/extmod/ucryptolib_aes256_cbc.py @@ -1,5 +1,6 @@ try: from Crypto.Cipher import AES + aes = AES.new except ImportError: try: diff --git a/tests/extmod/ucryptolib_aes256_ecb.py b/tests/extmod/ucryptolib_aes256_ecb.py index 326383a454..0760063c14 100644 --- a/tests/extmod/ucryptolib_aes256_ecb.py +++ b/tests/extmod/ucryptolib_aes256_ecb.py @@ -1,5 +1,6 @@ try: from Crypto.Cipher import AES + aes = AES.new except ImportError: try: diff --git a/tests/extmod/uctypes_32bit_intbig.py b/tests/extmod/uctypes_32bit_intbig.py index 6b4d3d76cd..eed36e8774 100644 --- a/tests/extmod/uctypes_32bit_intbig.py +++ b/tests/extmod/uctypes_32bit_intbig.py @@ -10,16 +10,16 @@ buf = b"12345678abcd" struct = uctypes.struct( uctypes.addressof(buf), {"f32": uctypes.UINT32 | 0, "f64": uctypes.UINT64 | 4}, - uctypes.LITTLE_ENDIAN + uctypes.LITTLE_ENDIAN, ) -struct.f32 = 0x7fffffff +struct.f32 = 0x7FFFFFFF print(buf) struct.f32 = 0x80000000 print(buf) -struct.f32 = 0xff010203 +struct.f32 = 0xFF010203 print(buf) struct.f64 = 0x80000000 @@ -34,16 +34,16 @@ buf = b"12345678abcd" struct = uctypes.struct( uctypes.addressof(buf), {"f32": uctypes.UINT32 | 0, "f64": uctypes.UINT64 | 4}, - uctypes.BIG_ENDIAN + uctypes.BIG_ENDIAN, ) -struct.f32 = 0x7fffffff +struct.f32 = 0x7FFFFFFF print(buf) struct.f32 = 0x80000000 print(buf) -struct.f32 = 0xff010203 +struct.f32 = 0xFF010203 print(buf) struct.f64 = 0x80000000 diff --git a/tests/extmod/uctypes_array_assign_le.py b/tests/extmod/uctypes_array_assign_le.py index 6afa7e0a24..d822faf7e8 100644 --- a/tests/extmod/uctypes_array_assign_le.py +++ b/tests/extmod/uctypes_array_assign_le.py @@ -10,19 +10,17 @@ desc = { # arr2 is array at offset 0, size 2, of structures defined recursively "arr2": (uctypes.ARRAY | 0, 2, {"b": uctypes.UINT8 | 0}), "arr3": (uctypes.ARRAY | 2, uctypes.UINT16 | 2), - # aligned "arr5": (uctypes.ARRAY | 0, uctypes.UINT32 | 1), # unaligned "arr6": (uctypes.ARRAY | 1, uctypes.UINT32 | 1), - "arr7": (uctypes.ARRAY | 0, 1, {"l": uctypes.UINT32 | 0}), - "arr8": (uctypes.ARRAY | 1, 1, {"l": uctypes.UINT32 | 0}) + "arr8": (uctypes.ARRAY | 1, 1, {"l": uctypes.UINT32 | 0}), } data = bytearray(5) -S = uctypes.struct(uctypes.addressof(data), desc, uctypes.LITTLE_ENDIAN) +S = uctypes.struct(uctypes.addressof(data), desc, uctypes.LITTLE_ENDIAN) # assign byte S.arr[0] = 0x11 @@ -55,4 +53,3 @@ assert hex(S.arr6[0]) == "0xaabbccdd" print(S.arr6[0] == S.arr8[0].l) assert S.arr6[0] == S.arr8[0].l - diff --git a/tests/extmod/uctypes_array_assign_native_le.py b/tests/extmod/uctypes_array_assign_native_le.py index a538bf9add..d4c27fc4b3 100644 --- a/tests/extmod/uctypes_array_assign_native_le.py +++ b/tests/extmod/uctypes_array_assign_native_le.py @@ -1,4 +1,5 @@ import sys + try: import uctypes except ImportError: @@ -15,16 +16,14 @@ desc = { # arr2 is array at offset 0, size 2, of structures defined recursively "arr2": (uctypes.ARRAY | 0, 2, {"b": uctypes.UINT8 | 0}), "arr3": (uctypes.ARRAY | 2, uctypes.UINT16 | 2), - # aligned "arr5": (uctypes.ARRAY | 0, uctypes.UINT32 | 1), "arr7": (uctypes.ARRAY | 0, 1, {"l": uctypes.UINT32 | 0}), - "arr8": (uctypes.ARRAY | 0, uctypes.INT8 | 1), "arr9": (uctypes.ARRAY | 0, uctypes.INT16 | 1), "arr10": (uctypes.ARRAY | 0, uctypes.INT32 | 1), "arr11": (uctypes.ARRAY | 0, uctypes.INT64 | 1), - "arr12": (uctypes.ARRAY | 0, uctypes.UINT64| 1), + "arr12": (uctypes.ARRAY | 0, uctypes.UINT64 | 1), "arr13": (uctypes.ARRAY | 1, 1, {"l": {}}), } diff --git a/tests/extmod/uctypes_array_assign_native_le_intbig.py b/tests/extmod/uctypes_array_assign_native_le_intbig.py index 84dfba0e29..f33c63b4ef 100644 --- a/tests/extmod/uctypes_array_assign_native_le_intbig.py +++ b/tests/extmod/uctypes_array_assign_native_le_intbig.py @@ -1,4 +1,5 @@ import sys + try: import uctypes except ImportError: @@ -15,16 +16,14 @@ desc = { # arr2 is array at offset 0, size 2, of structures defined recursively "arr2": (uctypes.ARRAY | 0, 2, {"b": uctypes.UINT8 | 0}), "arr3": (uctypes.ARRAY | 2, uctypes.UINT16 | 2), - # aligned "arr5": (uctypes.ARRAY | 0, uctypes.UINT32 | 1), "arr7": (uctypes.ARRAY | 0, 1, {"l": uctypes.UINT32 | 0}), - "arr8": (uctypes.ARRAY | 0, uctypes.INT8 | 1), "arr9": (uctypes.ARRAY | 0, uctypes.INT16 | 1), "arr10": (uctypes.ARRAY | 0, uctypes.INT32 | 1), "arr11": (uctypes.ARRAY | 0, uctypes.INT64 | 1), - "arr12": (uctypes.ARRAY | 0, uctypes.UINT64| 1), + "arr12": (uctypes.ARRAY | 0, uctypes.UINT64 | 1), "arr13": (uctypes.ARRAY | 1, 1, {"l": {}}), } diff --git a/tests/extmod/uctypes_byteat.py b/tests/extmod/uctypes_byteat.py index ab2535db8f..0619d31dc9 100644 --- a/tests/extmod/uctypes_byteat.py +++ b/tests/extmod/uctypes_byteat.py @@ -4,7 +4,7 @@ except ImportError: print("SKIP") raise SystemExit -data = bytearray(b'01234567') +data = bytearray(b"01234567") -print(uctypes.bytes_at(uctypes.addressof(data), 4)) -print(uctypes.bytearray_at(uctypes.addressof(data), 4)) +print(uctypes.bytes_at(uctypes.addressof(data), 4)) +print(uctypes.bytearray_at(uctypes.addressof(data), 4)) diff --git a/tests/extmod/uctypes_error.py b/tests/extmod/uctypes_error.py index 68106ac782..d429562615 100644 --- a/tests/extmod/uctypes_error.py +++ b/tests/extmod/uctypes_error.py @@ -9,35 +9,35 @@ except ImportError: data = bytearray(b"01234567") # del subscr not supported -S = uctypes.struct(uctypes.addressof(data), {}) +S = uctypes.struct(uctypes.addressof(data), {}) try: del S[0] except TypeError: - print('TypeError') + print("TypeError") # list is an invalid descriptor -S = uctypes.struct(uctypes.addressof(data), []) +S = uctypes.struct(uctypes.addressof(data), []) try: - S.x + S.x except TypeError: - print('TypeError') + print("TypeError") # can't access attribute with invalid descriptor -S = uctypes.struct(uctypes.addressof(data), {'x':[]}) +S = uctypes.struct(uctypes.addressof(data), {"x": []}) try: - S.x + S.x except TypeError: - print('TypeError') + print("TypeError") # can't assign to aggregate -S = uctypes.struct(uctypes.addressof(data), {'x':(uctypes.ARRAY | 0, uctypes.INT8 | 2)}) +S = uctypes.struct(uctypes.addressof(data), {"x": (uctypes.ARRAY | 0, uctypes.INT8 | 2)}) try: - S.x = 1 + S.x = 1 except TypeError: - print('TypeError') + print("TypeError") # unsupported unary op try: hash(S) except TypeError: - print('TypeError') + print("TypeError") diff --git a/tests/extmod/uctypes_le.py b/tests/extmod/uctypes_le.py index 7df5ac0909..23f2af982a 100644 --- a/tests/extmod/uctypes_le.py +++ b/tests/extmod/uctypes_le.py @@ -6,20 +6,15 @@ except ImportError: desc = { "s0": uctypes.UINT16 | 0, - "sub": (0, { - "b0": uctypes.UINT8 | 0, - "b1": uctypes.UINT8 | 1, - }), + "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, + "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}), } @@ -28,10 +23,10 @@ data = bytearray(b"01") S = uctypes.struct(uctypes.addressof(data), desc, uctypes.LITTLE_ENDIAN) -#print(S) +# print(S) print(hex(S.s0)) assert hex(S.s0) == "0x3130" -#print(S.sub.b0) +# print(S.sub.b0) print(S.sub.b0, S.sub.b1) assert S.sub.b0, S.sub.b1 == (0x30, 0x31) @@ -73,7 +68,7 @@ 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 + "bf32": uctypes.BFUINT32 | 0 | 20 << uctypes.BF_POS | 4 << uctypes.BF_LEN, } data2 = bytearray(b"0123") diff --git a/tests/extmod/uctypes_le_float.py b/tests/extmod/uctypes_le_float.py index 84ff2b84cf..89e9a9e0ab 100644 --- a/tests/extmod/uctypes_le_float.py +++ b/tests/extmod/uctypes_le_float.py @@ -7,7 +7,7 @@ except ImportError: desc = { "f32": uctypes.FLOAT32 | 0, "f64": uctypes.FLOAT64 | 0, - "uf64": uctypes.FLOAT64 | 2, # unaligned + "uf64": uctypes.FLOAT64 | 2, # unaligned } data = bytearray(10) @@ -15,10 +15,10 @@ data = bytearray(10) S = uctypes.struct(uctypes.addressof(data), desc, uctypes.LITTLE_ENDIAN) S.f32 = 12.34 -print('%.4f' % S.f32) +print("%.4f" % S.f32) S.f64 = 12.34 -print('%.4f' % S.f64) +print("%.4f" % S.f64) S.uf64 = 12.34 -print('%.4f' % S.uf64) +print("%.4f" % S.uf64) diff --git a/tests/extmod/uctypes_native_float.py b/tests/extmod/uctypes_native_float.py index acef47036d..e7d3ddabd9 100644 --- a/tests/extmod/uctypes_native_float.py +++ b/tests/extmod/uctypes_native_float.py @@ -14,7 +14,7 @@ data = bytearray(8) S = uctypes.struct(uctypes.addressof(data), desc, uctypes.NATIVE) S.f32 = 12.34 -print('%.4f' % S.f32) +print("%.4f" % S.f32) S.f64 = 12.34 -print('%.4f' % S.f64) +print("%.4f" % S.f64) diff --git a/tests/extmod/uctypes_native_le.py b/tests/extmod/uctypes_native_le.py index 8bba03b38c..c161539c62 100644 --- a/tests/extmod/uctypes_native_le.py +++ b/tests/extmod/uctypes_native_le.py @@ -2,6 +2,7 @@ # Codepaths for packed vs native structures are different. This test only works # on little-endian machine (no matter if 32 or 64 bit). import sys + try: import uctypes except ImportError: @@ -15,20 +16,15 @@ if sys.byteorder != "little": desc = { "s0": uctypes.UINT16 | 0, - "sub": (0, { - "b0": uctypes.UINT8 | 0, - "b1": uctypes.UINT8 | 1, - }), + "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, + "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}), } @@ -37,10 +33,10 @@ data = bytearray(b"01") S = uctypes.struct(uctypes.addressof(data), desc, uctypes.NATIVE) -#print(S) +# print(S) print(hex(S.s0)) assert hex(S.s0) == "0x3130" -#print(S.sub.b0) +# print(S.sub.b0) print(S.sub.b0, S.sub.b1) assert S.sub.b0, S.sub.b1 == (0x30, 0x31) @@ -81,7 +77,7 @@ 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 + "bf32": uctypes.BFUINT32 | 0 | 20 << uctypes.BF_POS | 4 << uctypes.BF_LEN, } data2 = bytearray(b"0123") diff --git a/tests/extmod/uctypes_print.py b/tests/extmod/uctypes_print.py index c310238e54..6e0018abc7 100644 --- a/tests/extmod/uctypes_print.py +++ b/tests/extmod/uctypes_print.py @@ -16,10 +16,10 @@ desc2 = [(uctypes.ARRAY | 0, uctypes.UINT8 | 1)] S2 = uctypes.struct(0, desc2) print(S2) -desc3 = ((uctypes.ARRAY | 0, uctypes.UINT8 | 1)) +desc3 = (uctypes.ARRAY | 0, uctypes.UINT8 | 1) S3 = uctypes.struct(0, desc3) print(S3) -desc4 = ((uctypes.PTR | 0, uctypes.UINT8 | 1)) +desc4 = (uctypes.PTR | 0, uctypes.UINT8 | 1) S4 = uctypes.struct(0, desc4) print(S4) diff --git a/tests/extmod/uctypes_ptr_le.py b/tests/extmod/uctypes_ptr_le.py index fc625f4227..5d8094ee48 100644 --- a/tests/extmod/uctypes_ptr_le.py +++ b/tests/extmod/uctypes_ptr_le.py @@ -1,4 +1,5 @@ import sys + try: import uctypes except ImportError: @@ -32,6 +33,6 @@ 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(S.ptr2[0].b, S.ptr2[1].b) print(hex(S.ptr16[0])) assert (S.ptr2[0].b, S.ptr2[1].b) == (48, 49) diff --git a/tests/extmod/uctypes_ptr_native_le.py b/tests/extmod/uctypes_ptr_native_le.py index 24508b1cb4..8ca4d2c55c 100644 --- a/tests/extmod/uctypes_ptr_native_le.py +++ b/tests/extmod/uctypes_ptr_native_le.py @@ -1,4 +1,5 @@ import sys + try: import uctypes except ImportError: @@ -30,6 +31,6 @@ 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(S.ptr2[0].b, S.ptr2[1].b) print(hex(S.ptr16[0])) assert (S.ptr2[0].b, S.ptr2[1].b) == (48, 49) diff --git a/tests/extmod/uctypes_sizeof.py b/tests/extmod/uctypes_sizeof.py index e42e06c924..6e52232e39 100644 --- a/tests/extmod/uctypes_sizeof.py +++ b/tests/extmod/uctypes_sizeof.py @@ -11,10 +11,13 @@ desc = { "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, - }), + "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") diff --git a/tests/extmod/uctypes_sizeof_float.py b/tests/extmod/uctypes_sizeof_float.py index 1ba8871bdc..351632d76b 100644 --- a/tests/extmod/uctypes_sizeof_float.py +++ b/tests/extmod/uctypes_sizeof_float.py @@ -4,5 +4,5 @@ except ImportError: print("SKIP") raise SystemExit -print(uctypes.sizeof({'f':uctypes.FLOAT32})) -print(uctypes.sizeof({'f':uctypes.FLOAT64})) +print(uctypes.sizeof({"f": uctypes.FLOAT32})) +print(uctypes.sizeof({"f": uctypes.FLOAT64})) diff --git a/tests/extmod/uctypes_sizeof_native.py b/tests/extmod/uctypes_sizeof_native.py index 32c740e773..352c191e0d 100644 --- a/tests/extmod/uctypes_sizeof_native.py +++ b/tests/extmod/uctypes_sizeof_native.py @@ -28,10 +28,7 @@ S5 = { "b": uctypes.UINT32 | 4, "c": uctypes.UINT8 | 8, "d": uctypes.UINT32 | 0, - "sub": (4, { - "b0": uctypes.UINT8 | 0, - "b1": uctypes.UINT8 | 1, - }), + "sub": (4, {"b0": uctypes.UINT8 | 0, "b1": uctypes.UINT8 | 1,}), } assert uctypes.sizeof(S5) == 12 diff --git a/tests/extmod/uctypes_sizeof_od.py b/tests/extmod/uctypes_sizeof_od.py index 192ee91528..2f070095b5 100644 --- a/tests/extmod/uctypes_sizeof_od.py +++ b/tests/extmod/uctypes_sizeof_od.py @@ -5,18 +5,23 @@ 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, - }), -}) +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") diff --git a/tests/extmod/uhashlib_md5.py b/tests/extmod/uhashlib_md5.py index 10b6d054e7..07d5f31692 100644 --- a/tests/extmod/uhashlib_md5.py +++ b/tests/extmod/uhashlib_md5.py @@ -16,6 +16,6 @@ except AttributeError: print("SKIP") raise SystemExit -md5 = hashlib.md5(b'hello') -md5.update(b'world') +md5 = hashlib.md5(b"hello") +md5.update(b"world") print(md5.digest()) diff --git a/tests/extmod/uhashlib_sha1.py b/tests/extmod/uhashlib_sha1.py index 4f7066899a..a573121316 100644 --- a/tests/extmod/uhashlib_sha1.py +++ b/tests/extmod/uhashlib_sha1.py @@ -16,6 +16,6 @@ except AttributeError: print("SKIP") raise SystemExit -sha1 = hashlib.sha1(b'hello') -sha1.update(b'world') +sha1 = hashlib.sha1(b"hello") +sha1.update(b"world") print(sha1.digest()) diff --git a/tests/extmod/uhashlib_sha256.py b/tests/extmod/uhashlib_sha256.py index 676d479794..2e6df7df13 100644 --- a/tests/extmod/uhashlib_sha256.py +++ b/tests/extmod/uhashlib_sha256.py @@ -27,12 +27,12 @@ print(hashlib.sha256(b"\xff" * 64).digest()) 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()) +# 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()) +# h = hashlib.sha256(b'123') +# print(h.digest()) +# h.update(b'456') +# print(h.digest()) diff --git a/tests/extmod/uheapq1.py b/tests/extmod/uheapq1.py index 7c1fe4e1ec..a470bb6f71 100644 --- a/tests/extmod/uheapq1.py +++ b/tests/extmod/uheapq1.py @@ -17,11 +17,13 @@ try: except TypeError: print("TypeError") + def pop_and_print(h): l = [] while h: l.append(str(heapq.heappop(h))) - print(' '.join(l)) + print(" ".join(l)) + h = [] heapq.heappush(h, 3) diff --git a/tests/extmod/ujson_dump.py b/tests/extmod/ujson_dump.py index b1cb4a9cbc..feda8a47dd 100644 --- a/tests/extmod/ujson_dump.py +++ b/tests/extmod/ujson_dump.py @@ -20,11 +20,11 @@ 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') +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') +except (AttributeError, OSError): # CPython and uPy have different errors + print("Exception") diff --git a/tests/extmod/ujson_dump_iobase.py b/tests/extmod/ujson_dump_iobase.py index 51d507cd1a..7ecf23afb6 100644 --- a/tests/extmod/ujson_dump_iobase.py +++ b/tests/extmod/ujson_dump_iobase.py @@ -7,27 +7,28 @@ except ImportError: try: import io, json except ImportError: - print('SKIP') + print("SKIP") raise SystemExit -if not hasattr(io, 'IOBase'): - print('SKIP') +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 = '' + self.buf = "" + def write(self, buf): if type(buf) == bytearray: # uPy passes a bytearray, CPython passes a str - buf = str(buf, 'ascii') + buf = str(buf, "ascii") self.buf += buf return len(buf) # dump to the user stream s = S() -json.dump([123, {}], s) +json.dump([123, {}], s) print(s.buf) diff --git a/tests/extmod/ujson_dumps.py b/tests/extmod/ujson_dumps.py index c33126cec6..251b268755 100644 --- a/tests/extmod/ujson_dumps.py +++ b/tests/extmod/ujson_dumps.py @@ -11,8 +11,8 @@ 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("abc")) +print(json.dumps("\x00\x01\x7e")) print(json.dumps([])) print(json.dumps([1])) print(json.dumps([1, 2])) @@ -22,10 +22,10 @@ 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({"a": 1})) +print(json.dumps({"a": (2, [3, None])})) print(json.dumps('"quoted"')) -print(json.dumps('space\n\r\tspace')) +print(json.dumps("space\n\r\tspace")) print(json.dumps({None: -1})) print(json.dumps({False: 0})) print(json.dumps({True: 1})) diff --git a/tests/extmod/ujson_dumps_extra.py b/tests/extmod/ujson_dumps_extra.py index 21a388c32d..f2aa7f249f 100644 --- a/tests/extmod/ujson_dumps_extra.py +++ b/tests/extmod/ujson_dumps_extra.py @@ -6,4 +6,4 @@ except ImportError: print("SKIP") raise SystemExit -print(ujson.dumps(b'1234')) +print(ujson.dumps(b"1234")) diff --git a/tests/extmod/ujson_dumps_float.py b/tests/extmod/ujson_dumps_float.py index 40adb1e267..25681d0c23 100644 --- a/tests/extmod/ujson_dumps_float.py +++ b/tests/extmod/ujson_dumps_float.py @@ -8,4 +8,4 @@ except ImportError: raise SystemExit print(json.dumps(1.2)) -print(json.dumps({1.5: 'hi'})) +print(json.dumps({1.5: "hi"})) diff --git a/tests/extmod/ujson_load.py b/tests/extmod/ujson_load.py index 9725ab2ddc..7cec9246b8 100644 --- a/tests/extmod/ujson_load.py +++ b/tests/extmod/ujson_load.py @@ -9,7 +9,7 @@ except: print("SKIP") raise SystemExit -print(json.load(StringIO('null'))) +print(json.load(StringIO("null"))) print(json.load(StringIO('"abc\\u0064e"'))) -print(json.load(StringIO('[false, true, 1, -2]'))) +print(json.load(StringIO("[false, true, 1, -2]"))) print(json.load(StringIO('{"a":true}'))) diff --git a/tests/extmod/ujson_loads.py b/tests/extmod/ujson_loads.py index adba3c068d..2de9cdcbc1 100644 --- a/tests/extmod/ujson_loads.py +++ b/tests/extmod/ujson_loads.py @@ -7,23 +7,25 @@ except ImportError: print("SKIP") raise SystemExit + def my_print(o): if isinstance(o, dict): - print('sorted dict', sorted(o.items())) + 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("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("[]")) +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}}')) @@ -39,36 +41,36 @@ 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('') + json.loads("") except ValueError: - print('ValueError') + print("ValueError") # string which is not closed try: my_print(json.loads('"abc')) except ValueError: - print('ValueError') + print("ValueError") # unaccompanied closing brace try: - my_print(json.loads(']')) + my_print(json.loads("]")) except ValueError: - print('ValueError') + print("ValueError") # unspecified object type try: - my_print(json.loads('a')) + my_print(json.loads("a")) except ValueError: - print('ValueError') + print("ValueError") # bad property name try: my_print(json.loads('{{}:"abc"}')) except ValueError: - print('ValueError') + print("ValueError") # unexpected characters after white space try: - my_print(json.loads('[null] a')) + my_print(json.loads("[null] a")) except ValueError: - print('ValueError') + print("ValueError") diff --git a/tests/extmod/ujson_loads_bytes.py b/tests/extmod/ujson_loads_bytes.py index 507e4ca885..3ee87bbcd5 100644 --- a/tests/extmod/ujson_loads_bytes.py +++ b/tests/extmod/ujson_loads_bytes.py @@ -9,5 +9,5 @@ except ImportError: print("SKIP") raise SystemExit -print(json.loads(b'[1,2]')) -print(json.loads(bytearray(b'[null]'))) +print(json.loads(b"[1,2]")) +print(json.loads(bytearray(b"[null]"))) diff --git a/tests/extmod/ujson_loads_float.py b/tests/extmod/ujson_loads_float.py index 086853a2d4..842718f37d 100644 --- a/tests/extmod/ujson_loads_float.py +++ b/tests/extmod/ujson_loads_float.py @@ -7,12 +7,14 @@ 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')) +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")) diff --git a/tests/extmod/urandom_basic.py b/tests/extmod/urandom_basic.py index 57e6b26cba..180197398f 100644 --- a/tests/extmod/urandom_basic.py +++ b/tests/extmod/urandom_basic.py @@ -26,4 +26,4 @@ print(random.getrandbits(16) == r) try: random.getrandbits(0) except ValueError: - print('ValueError') + print("ValueError") diff --git a/tests/extmod/urandom_extra.py b/tests/extmod/urandom_extra.py index 0cfd9280b5..78e17379dc 100644 --- a/tests/extmod/urandom_extra.py +++ b/tests/extmod/urandom_extra.py @@ -10,10 +10,10 @@ except ImportError: try: random.randint except AttributeError: - print('SKIP') + print("SKIP") raise SystemExit -print('randrange') +print("randrange") for i in range(50): assert 0 <= random.randrange(4) < 4 assert 2 <= random.randrange(2, 6) < 6 @@ -25,27 +25,27 @@ for i in range(50): try: random.randrange(0) except ValueError: - print('ValueError') + print("ValueError") # empty range try: random.randrange(2, 1) except ValueError: - print('ValueError') + print("ValueError") # zero step try: random.randrange(2, 1, 0) except ValueError: - print('ValueError') + print("ValueError") # empty range try: random.randrange(2, 1, 1) except ValueError: - print('ValueError') + print("ValueError") -print('randint') +print("randint") for i in range(50): assert 0 <= random.randint(0, 4) <= 4 assert 2 <= random.randint(2, 6) <= 6 @@ -55,9 +55,9 @@ for i in range(50): try: random.randint(2, 1) except ValueError: - print('ValueError') + print("ValueError") -print('choice') +print("choice") lst = [1, 2, 5, 6] for i in range(50): assert random.choice(lst) in lst @@ -66,4 +66,4 @@ for i in range(50): try: random.choice([]) except IndexError: - print('IndexError') + print("IndexError") diff --git a/tests/extmod/urandom_extra_float.py b/tests/extmod/urandom_extra_float.py index f665fd18ad..65918da136 100644 --- a/tests/extmod/urandom_extra_float.py +++ b/tests/extmod/urandom_extra_float.py @@ -10,14 +10,14 @@ except ImportError: try: random.randint except AttributeError: - print('SKIP') + print("SKIP") raise SystemExit -print('random') +print("random") for i in range(50): assert 0 <= random.random() < 1 -print('uniform') +print("uniform") for i in range(50): assert 0 <= random.uniform(0, 4) <= 4 assert 2 <= random.uniform(2, 6) <= 6 diff --git a/tests/extmod/ure1.py b/tests/extmod/ure1.py index ae9ff34703..9e1be5fc79 100644 --- a/tests/extmod/ure1.py +++ b/tests/extmod/ure1.py @@ -70,11 +70,16 @@ 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)) +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$") @@ -87,24 +92,36 @@ except: print("Caught invalid regex") # bytes objects -m = re.match(rb'a+?', b'ab'); print(m.group(0)) +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')) +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("===") diff --git a/tests/extmod/ure_debug.py b/tests/extmod/ure_debug.py index 621fc8d50e..7a07ede2d4 100644 --- a/tests/extmod/ure_debug.py +++ b/tests/extmod/ure_debug.py @@ -1,9 +1,10 @@ # 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) +ure.compile("^a|b[0-9]\w$", ure.DEBUG) diff --git a/tests/extmod/ure_error.py b/tests/extmod/ure_error.py index 02d48d2a83..52a96b7c03 100644 --- a/tests/extmod/ure_error.py +++ b/tests/extmod/ure_error.py @@ -9,18 +9,20 @@ 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 + 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\]') + +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\]") diff --git a/tests/extmod/ure_group.py b/tests/extmod/ure_group.py index 4e39468c5b..41425dd623 100644 --- a/tests/extmod/ure_group.py +++ b/tests/extmod/ure_group.py @@ -9,8 +9,9 @@ except ImportError: print("SKIP") raise SystemExit + def print_groups(match): - print('----') + print("----") try: i = 0 while True: @@ -19,14 +20,15 @@ def print_groups(match): except IndexError: pass -m = re.match(r'(([0-9]*)([a-z]*)[0-9]*)','1234hello567') + +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') +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')) +print_groups(re.match(r"(a)?b(c)", "abc")) # optional group that doesn't match -print_groups(re.match(r'(a)?b(c)', 'bc')) +print_groups(re.match(r"(a)?b(c)", "bc")) diff --git a/tests/extmod/ure_groups.py b/tests/extmod/ure_groups.py index 4fac896d7f..7da072a920 100644 --- a/tests/extmod/ure_groups.py +++ b/tests/extmod/ure_groups.py @@ -13,21 +13,21 @@ try: m = re.match(".", "a") m.groups except AttributeError: - print('SKIP') + print("SKIP") raise SystemExit -m = re.match(r'(([0-9]*)([a-z]*)[0-9]*)','1234hello567') +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') +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()) +print(re.match(r"(a)?b(c)", "abc").groups()) # optional group that doesn't match -print(re.match(r'(a)?b(c)', 'bc').groups()) +print(re.match(r"(a)?b(c)", "bc").groups()) # only a single match -print(re.match(r'abc', 'abc').groups()) +print(re.match(r"abc", "abc").groups()) diff --git a/tests/extmod/ure_namedclass.py b/tests/extmod/ure_namedclass.py index 215d09613f..00d58ad98a 100644 --- a/tests/extmod/ure_namedclass.py +++ b/tests/extmod/ure_namedclass.py @@ -9,8 +9,9 @@ except ImportError: print("SKIP") raise SystemExit + def print_groups(match): - print('----') + print("----") try: i = 0 while True: @@ -19,14 +20,15 @@ def print_groups(match): except IndexError: pass -m = re.match(r'\w+','1234hello567 abc') + +m = re.match(r"\w+", "1234hello567 abc") print_groups(m) -m = re.match(r'(\w+)\s+(\w+)','ABC \t1234hello567 abc') +m = re.match(r"(\w+)\s+(\w+)", "ABC \t1234hello567 abc") print_groups(m) -m = re.match(r'(\S+)\s+(\D+)','ABC \thello abc567 abc') +m = re.match(r"(\S+)\s+(\D+)", "ABC \thello abc567 abc") print_groups(m) -m = re.match(r'(([0-9]*)([a-z]*)\d*)','1234hello567') +m = re.match(r"(([0-9]*)([a-z]*)\d*)", "1234hello567") print_groups(m) diff --git a/tests/extmod/ure_span.py b/tests/extmod/ure_span.py index 50f44399ce..03a3fef9f3 100644 --- a/tests/extmod/ure_span.py +++ b/tests/extmod/ure_span.py @@ -13,12 +13,12 @@ try: m = re.match(".", "a") m.span except AttributeError: - print('SKIP') + print("SKIP") raise SystemExit def print_spans(match): - print('----') + print("----") try: i = 0 while True: @@ -27,14 +27,15 @@ def print_spans(match): except IndexError: pass -m = re.match(r'(([0-9]*)([a-z]*)[0-9]*)','1234hello567') + +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') +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')) +print_spans(re.match(r"(a)?b(c)", "abc")) # optional span that doesn't match -print_spans(re.match(r'(a)?b(c)', 'bc')) +print_spans(re.match(r"(a)?b(c)", "bc")) diff --git a/tests/extmod/ure_split_notimpl.py b/tests/extmod/ure_split_notimpl.py index da6e9652d0..51bad791ef 100644 --- a/tests/extmod/ure_split_notimpl.py +++ b/tests/extmod/ure_split_notimpl.py @@ -4,8 +4,8 @@ except ImportError: print("SKIP") raise SystemExit -r = re.compile('( )') +r = re.compile("( )") try: s = r.split("a b c foobar") except NotImplementedError: - print('NotImplementedError') + print("NotImplementedError") diff --git a/tests/extmod/ure_sub.py b/tests/extmod/ure_sub.py index 4aeb8650a1..6bb332077d 100644 --- a/tests/extmod/ure_sub.py +++ b/tests/extmod/ure_sub.py @@ -4,58 +4,59 @@ except ImportError: try: import re except ImportError: - print('SKIP') + print("SKIP") raise SystemExit try: re.sub except AttributeError: - print('SKIP') + 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("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():' + 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' + 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" ) ) # no matches at all -print(re.sub('a', 'b', 'c')) +print(re.sub("a", "b", "c")) # with maximum substitution count specified -print(re.sub('a', 'b', '1a2a3a', 2)) +print(re.sub("a", "b", "1a2a3a", 2)) # invalid group try: - re.sub('(a)', 'b\\2', 'a') + re.sub("(a)", "b\\2", "a") except: - print('invalid group') + print("invalid group") # invalid group with very large number (to test overflow in uPy) try: - re.sub('(a)', 'b\\199999999999999999999999999999999999999', 'a') + re.sub("(a)", "b\\199999999999999999999999999999999999999", "a") except: - print('invalid group') + print("invalid group") diff --git a/tests/extmod/ure_sub_unmatched.py b/tests/extmod/ure_sub_unmatched.py index 4795b3196f..d6312bfc2c 100644 --- a/tests/extmod/ure_sub_unmatched.py +++ b/tests/extmod/ure_sub_unmatched.py @@ -6,14 +6,14 @@ except ImportError: try: import re except ImportError: - print('SKIP') + print("SKIP") raise SystemExit try: re.sub except AttributeError: - print('SKIP') + 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')) +print(re.sub(r"(a)(b)?", r"\2-\1", "1a2")) diff --git a/tests/extmod/uselect_poll_basic.py b/tests/extmod/uselect_poll_basic.py index 82a7195c03..07328365b3 100644 --- a/tests/extmod/uselect_poll_basic.py +++ b/tests/extmod/uselect_poll_basic.py @@ -3,6 +3,7 @@ try: except ImportError: try: import socket, select, errno + select.poll # Raises AttributeError for CPython implementations without poll() except (ImportError, AttributeError): print("SKIP") diff --git a/tests/extmod/uselect_poll_udp.py b/tests/extmod/uselect_poll_udp.py index e7d7dfe341..f6be262ee0 100644 --- a/tests/extmod/uselect_poll_udp.py +++ b/tests/extmod/uselect_poll_udp.py @@ -8,10 +8,10 @@ except ImportError: 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.bind(socket.getaddrinfo("127.0.0.1", 8000)[0][-1]) poll = select.poll() # UDP socket should not be readable diff --git a/tests/extmod/usocket_udp_nonblock.py b/tests/extmod/usocket_udp_nonblock.py index 63197584da..7dc0e562a3 100644 --- a/tests/extmod/usocket_udp_nonblock.py +++ b/tests/extmod/usocket_udp_nonblock.py @@ -11,10 +11,10 @@ except ImportError: s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) -s.bind(socket.getaddrinfo('127.0.0.1', 8000)[0][-1]) +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.args[0] == errno.EAGAIN) + print("EAGAIN:", er.args[0] == errno.EAGAIN) diff --git a/tests/extmod/ussl_basic.py b/tests/extmod/ussl_basic.py index a040fc20ca..b4e21c7dce 100644 --- a/tests/extmod/ussl_basic.py +++ b/tests/extmod/ussl_basic.py @@ -11,7 +11,7 @@ except ImportError: try: ss = ssl.wrap_socket(io.BytesIO()) except OSError as er: - print('wrap_socket:', repr(er)) + print("wrap_socket:", repr(er)) # create in server mode (can use this object for further tests) socket = io.BytesIO() @@ -22,25 +22,25 @@ print(repr(ss)[:12]) # setblocking() propagates call to the underlying stream object, and # io.BytesIO doesn't have setblocking() (in CPython too). -#try: +# try: # ss.setblocking(False) -#except NotImplementedError: +# except NotImplementedError: # print('setblocking: NotImplementedError') -#ss.setblocking(True) +# ss.setblocking(True) # write -print(ss.write(b'aaaa')) +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.write(b"aaaaaaaaaaaaaaaa") socket.seek(0) try: ss.read(8) except OSError as er: - print('read:', repr(er)) + print("read:", repr(er)) # close ss.close() @@ -51,10 +51,10 @@ ss.close() try: ss.read(10) except OSError as er: - print('read:', repr(er)) + print("read:", repr(er)) # write on closed socket try: - ss.write(b'aaaa') + ss.write(b"aaaa") except OSError as er: - print('write:', repr(er)) + print("write:", repr(er)) diff --git a/tests/extmod/ussl_keycert.py b/tests/extmod/ussl_keycert.py index 9b3eae6027..87a40a1e55 100644 --- a/tests/extmod/ussl_keycert.py +++ b/tests/extmod/ussl_keycert.py @@ -7,11 +7,11 @@ 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' +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'!') + ssl.wrap_socket(io.BytesIO(), key=b"!") except ValueError as er: print(repr(er)) @@ -23,6 +23,6 @@ except TypeError as er: # Valid key, invalid cert try: - ssl.wrap_socket(io.BytesIO(), key=key, cert=b'!') + ssl.wrap_socket(io.BytesIO(), key=key, cert=b"!") except ValueError as er: print(repr(er)) diff --git a/tests/extmod/utimeq1.py b/tests/extmod/utimeq1.py index dc7f3b6600..234d7a31dd 100644 --- a/tests/extmod/utimeq1.py +++ b/tests/extmod/utimeq1.py @@ -13,12 +13,17 @@ 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: @@ -69,22 +74,25 @@ try: except IndexError: pass + def pop_all(h): l = [] while h: item = [0, 0, 0] h.pop(item) - #print("!", item) + # print("!", item) l.append(tuple(item)) dprint(l) return l + def add(h, v): h.push(v, 0, 0) dprint("-----") - #h.dump() + # h.dump() dprint("-----") + h = utimeq(10) add(h, 0) add(h, MAX) @@ -98,6 +106,7 @@ 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)) @@ -108,6 +117,7 @@ def edge_case(edge, offset): dprint(diff, diff > 0) return diff + dprint("===") diff = edge_case(MODULO_HALF - 1, 0) assert diff == MODULO_HALF - 1 diff --git a/tests/extmod/uzlib_decompio.py b/tests/extmod/uzlib_decompio.py index 112a825976..6a0aae8bcd 100644 --- a/tests/extmod/uzlib_decompio.py +++ b/tests/extmod/uzlib_decompio.py @@ -7,7 +7,7 @@ except ImportError: # Raw DEFLATE bitstream -buf = io.BytesIO(b'\xcbH\xcd\xc9\xc9\x07\x00') +buf = io.BytesIO(b"\xcbH\xcd\xc9\xc9\x07\x00") inp = zlib.DecompIO(buf, -8) print(buf.seek(0, 1)) print(inp.read(1)) @@ -21,12 +21,12 @@ print(buf.seek(0, 1)) # zlib bitstream -inp = zlib.DecompIO(io.BytesIO(b'x\x9c30\xa0=\x00\x00\xb3q\x12\xc1')) +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')) +inp = zlib.DecompIO(io.BytesIO(b"x\x9c30\xa0=\x00\x00\xb3q\x12\xc0")) try: print(inp.read()) except OSError as e: diff --git a/tests/extmod/uzlib_decompio_gz.py b/tests/extmod/uzlib_decompio_gz.py index 02087f7639..1bc8ba885b 100644 --- a/tests/extmod/uzlib_decompio_gz.py +++ b/tests/extmod/uzlib_decompio_gz.py @@ -7,7 +7,9 @@ except ImportError: # 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') +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)) @@ -20,24 +22,32 @@ 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') +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') +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') +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') +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) @@ -45,6 +55,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) +# 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) diff --git a/tests/extmod/uzlib_decompress.py b/tests/extmod/uzlib_decompress.py index dd6e4876fa..8d4a9640b4 100644 --- a/tests/extmod/uzlib_decompress.py +++ b/tests/extmod/uzlib_decompress.py @@ -9,15 +9,24 @@ except ImportError: 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 + (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}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'), + ( + 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: @@ -26,26 +35,26 @@ for unpacked, packed in PATTERNS: # Raw DEFLATE bitstream -v = b'\xcbH\xcd\xc9\xc9\x07\x00' +v = b"\xcbH\xcd\xc9\xc9\x07\x00" exp = b"hello" out = zlib.decompress(v, -15) -assert(out == exp) +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' +v = b"\xcbH\xcd\xc9\xc9\x07\x00\x86\xa6\x106\x05\x00\x00\x00" out = zlib.decompress(v, -15) -assert(out == exp) +assert out == exp # this should error try: - zlib.decompress(b'abc') + zlib.decompress(b"abc") except Exception: print("Exception") # invalid block type try: - zlib.decompress(b'\x07', -15) # final-block, block-type=3 (invalid) + zlib.decompress(b"\x07", -15) # final-block, block-type=3 (invalid) except Exception as er: - print('Exception') + print("Exception") diff --git a/tests/extmod/vfs_basic.py b/tests/extmod/vfs_basic.py index fbcc92bade..c8e203b3df 100644 --- a/tests/extmod/vfs_basic.py +++ b/tests/extmod/vfs_basic.py @@ -2,6 +2,7 @@ try: import uos + uos.mount except (ImportError, AttributeError): print("SKIP") @@ -11,55 +12,67 @@ except (ImportError, AttributeError): class Filesystem: def __init__(self, id): self.id = id + def mount(self, readonly, mkfs): - print(self.id, 'mount', readonly, mkfs) + print(self.id, "mount", readonly, mkfs) + def umount(self): - print(self.id, 'umount') + print(self.id, "umount") + def ilistdir(self, dir): - print(self.id, 'ilistdir', dir) - return iter([('a%d' % self.id, 0, 0)]) + print(self.id, "ilistdir", dir) + return iter([("a%d" % self.id, 0, 0)]) + def chdir(self, dir): - print(self.id, 'chdir', dir) + print(self.id, "chdir", dir) + def getcwd(self): - print(self.id, 'getcwd') - return 'dir%d' % self.id + print(self.id, "getcwd") + return "dir%d" % self.id + def mkdir(self, path): - print(self.id, 'mkdir', path) + print(self.id, "mkdir", path) + def remove(self, path): - print(self.id, 'remove', path) + print(self.id, "remove", path) + def rename(self, old_path, new_path): - print(self.id, 'rename', old_path, new_path) + print(self.id, "rename", old_path, new_path) + def rmdir(self, path): - print(self.id, 'rmdir', path) + print(self.id, "rmdir", path) + def stat(self, path): - print(self.id, 'stat', path) + print(self.id, "stat", path) return (self.id,) + def statvfs(self, path): - print(self.id, 'statvfs', path) + print(self.id, "statvfs", path) return (self.id,) + def open(self, file, mode): - print(self.id, 'open', file, mode) + print(self.id, "open", file, mode) # first we umount any existing mount points the target may have try: - uos.umount('/') + uos.umount("/") except OSError: pass -for path in uos.listdir('/'): - uos.umount('/' + path) +for path in uos.listdir("/"): + uos.umount("/" + path) # stat root dir -print(uos.stat('/')) +print(uos.stat("/")) # statvfs root dir; verify that f_namemax has a sensible size -print(uos.statvfs('/')[9] >= 32) +print(uos.statvfs("/")[9] >= 32) # getcwd when in root dir print(uos.getcwd()) # basic mounting and listdir -uos.mount(Filesystem(1), '/test_mnt') +uos.mount(Filesystem(1), "/test_mnt") print(uos.listdir()) # ilistdir @@ -68,80 +81,80 @@ print(next(i)) try: next(i) except StopIteration: - print('StopIteration') + print("StopIteration") try: next(i) except StopIteration: - print('StopIteration') + print("StopIteration") # referencing the mount point in different ways -print(uos.listdir('test_mnt')) -print(uos.listdir('/test_mnt')) +print(uos.listdir("test_mnt")) +print(uos.listdir("/test_mnt")) # mounting another filesystem -uos.mount(Filesystem(2), '/test_mnt2', readonly=True) +uos.mount(Filesystem(2), "/test_mnt2", readonly=True) print(uos.listdir()) -print(uos.listdir('/test_mnt2')) +print(uos.listdir("/test_mnt2")) # mounting over an existing mount point try: - uos.mount(Filesystem(3), '/test_mnt2') + uos.mount(Filesystem(3), "/test_mnt2") except OSError: - print('OSError') + print("OSError") # mkdir of a mount point try: - uos.mkdir('/test_mnt') + uos.mkdir("/test_mnt") except OSError: - print('OSError') + print("OSError") # rename across a filesystem try: - uos.rename('/test_mnt/a', '/test_mnt2/b') + uos.rename("/test_mnt/a", "/test_mnt2/b") except OSError: - print('OSError') + print("OSError") # delegating to mounted filesystem -uos.chdir('test_mnt') +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') +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') +uos.umount("/test_mnt") +uos.umount("/test_mnt2") # umount a non-existent mount point try: - uos.umount('/test_mnt') + uos.umount("/test_mnt") except OSError: - print('OSError') + print("OSError") # root dir -uos.mount(Filesystem(3), '/') -print(uos.stat('/')) -print(uos.statvfs('/')) +uos.mount(Filesystem(3), "/") +print(uos.stat("/")) +print(uos.statvfs("/")) print(uos.listdir()) -open('test') +open("test") -uos.mount(Filesystem(4), '/mnt') +uos.mount(Filesystem(4), "/mnt") print(uos.listdir()) -print(uos.listdir('/mnt')) -uos.chdir('/mnt') +print(uos.listdir("/mnt")) +uos.chdir("/mnt") print(uos.listdir()) # chdir to a subdir within root-mounted vfs, and then listdir -uos.chdir('/subdir') +uos.chdir("/subdir") print(uos.listdir()) -uos.chdir('/') +uos.chdir("/") -uos.umount('/') -print(uos.listdir('/')) -uos.umount('/mnt') +uos.umount("/") +print(uos.listdir("/")) +uos.umount("/mnt") diff --git a/tests/extmod/vfs_blockdev.py b/tests/extmod/vfs_blockdev.py index d82b10610f..e24169ba93 100644 --- a/tests/extmod/vfs_blockdev.py +++ b/tests/extmod/vfs_blockdev.py @@ -2,12 +2,14 @@ try: import uos + uos.VfsFat uos.VfsLfs2 except (ImportError, AttributeError): print("SKIP") raise SystemExit + class RAMBlockDevice: ERASE_BLOCK_SIZE = 512 @@ -28,15 +30,16 @@ class RAMBlockDevice: self.data[addr + i] = buf[i] def ioctl(self, op, arg): - if op == 4: # block count + if op == 4: # block count return len(self.data) // self.ERASE_BLOCK_SIZE - if op == 5: # block size + if op == 5: # block size return self.ERASE_BLOCK_SIZE - if op == 6: # erase block + if op == 6: # erase block return 0 + def test(bdev, vfs_class): - print('test', vfs_class) + print("test", vfs_class) # mkfs vfs_class.mkfs(bdev) @@ -45,21 +48,22 @@ def test(bdev, vfs_class): vfs = vfs_class(bdev) # statvfs - print(vfs.statvfs('/')) + print(vfs.statvfs("/")) # open, write close - f = vfs.open('test', 'w') + f = vfs.open("test", "w") for i in range(10): - f.write('some data') + f.write("some data") f.close() # ilistdir print(list(vfs.ilistdir())) # read - with vfs.open('test', 'r') as f: + with vfs.open("test", "r") as f: print(f.read()) + try: bdev = RAMBlockDevice(50) except MemoryError: diff --git a/tests/extmod/vfs_fat_fileio1.py b/tests/extmod/vfs_fat_fileio1.py index 7fe040d539..e42911093f 100644 --- a/tests/extmod/vfs_fat_fileio1.py +++ b/tests/extmod/vfs_fat_fileio1.py @@ -20,17 +20,17 @@ class RAMFS: self.data = bytearray(blocks * self.SEC_SIZE) def readblocks(self, n, buf): - #print("readblocks(%s, %x(%d))" % (n, id(buf), len(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))) + # 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)) + # 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 @@ -45,8 +45,8 @@ except MemoryError: uos.VfsFat.mkfs(bdev) vfs = uos.VfsFat(bdev) -uos.mount(vfs, '/ramdisk') -uos.chdir('/ramdisk') +uos.mount(vfs, "/ramdisk") +uos.chdir("/ramdisk") # file IO f = open("foo_file.txt", "w") @@ -54,7 +54,7 @@ print(str(f)[:17], str(f)[-1:]) f.write("hello!") f.flush() f.close() -f.close() # allowed +f.close() # allowed try: f.write("world!") except OSError as e: @@ -82,21 +82,21 @@ with open("foo_file.txt") as f2: print(f2.read()) print(f2.tell()) - f2.seek(0, 0) # SEEK_SET + f2.seek(0, 0) # SEEK_SET print(f2.read(1)) - f2.seek(0, 1) # SEEK_CUR + f2.seek(0, 1) # SEEK_CUR print(f2.read(1)) - f2.seek(2, 1) # SEEK_CUR + f2.seek(2, 1) # SEEK_CUR print(f2.read(1)) - f2.seek(-2, 2) # SEEK_END + 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: +# FileIO = type(f) +# with FileIO("/ramdisk/foo_file.txt") as f: # print(f.read()) # dirs @@ -105,7 +105,7 @@ vfs.mkdir("foo_dir") try: vfs.rmdir("foo_file.txt") except OSError as e: - print(e.args[0] == 20) # uerrno.ENOTDIR + print(e.args[0] == 20) # uerrno.ENOTDIR vfs.remove("foo_file.txt") print(list(vfs.ilistdir())) diff --git a/tests/extmod/vfs_fat_fileio2.py b/tests/extmod/vfs_fat_fileio2.py index 6721f9b934..a9cea2bed8 100644 --- a/tests/extmod/vfs_fat_fileio2.py +++ b/tests/extmod/vfs_fat_fileio2.py @@ -20,17 +20,17 @@ class RAMFS: self.data = bytearray(blocks * self.SEC_SIZE) def readblocks(self, n, buf): - #print("readblocks(%s, %x(%d))" % (n, id(buf), len(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))) + # 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)) + # 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 @@ -45,8 +45,8 @@ except MemoryError: uos.VfsFat.mkfs(bdev) vfs = uos.VfsFat(bdev) -uos.mount(vfs, '/ramdisk') -uos.chdir('/ramdisk') +uos.mount(vfs, "/ramdisk") +uos.chdir("/ramdisk") try: vfs.mkdir("foo_dir") @@ -111,4 +111,4 @@ try: f = open("large_file.txt", "wb") f.write(bytearray(bsize * free)) except OSError as e: - print("ENOSPC:", e.args[0] == 28) # uerrno.ENOSPC + print("ENOSPC:", e.args[0] == 28) # uerrno.ENOSPC diff --git a/tests/extmod/vfs_fat_finaliser.py b/tests/extmod/vfs_fat_finaliser.py index c7254c5f05..e30f42f847 100644 --- a/tests/extmod/vfs_fat_finaliser.py +++ b/tests/extmod/vfs_fat_finaliser.py @@ -2,6 +2,7 @@ try: import uerrno, uos + uos.VfsFat except (ImportError, AttributeError): print("SKIP") @@ -22,9 +23,9 @@ class RAMBlockDevice: self.data[n * self.sec_size + i] = buf[i] def ioctl(self, op, arg): - if op == 4: # MP_BLOCKDEV_IOCTL_BLOCK_COUNT + if op == 4: # MP_BLOCKDEV_IOCTL_BLOCK_COUNT return len(self.data) // self.sec_size - if op == 5: # MP_BLOCKDEV_IOCTL_BLOCK_SIZE + if op == 5: # MP_BLOCKDEV_IOCTL_BLOCK_SIZE return self.sec_size @@ -44,23 +45,25 @@ vfs = uos.VfsFat(bdev) # 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') + vfs.open("x", "r") except MemoryError: - print('MemoryError') + print("MemoryError") micropython.heap_unlock() # Here we test that the finaliser is actually called during a garbage collection. import gc + N = 4 for i in range(N): - n = 'x%d' % i - f = vfs.open(n, 'w') + 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 + 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: + with vfs.open("x%d" % i, "r") as f: print(f.read()) diff --git a/tests/extmod/vfs_fat_more.py b/tests/extmod/vfs_fat_more.py index 9505fd3282..d8449829de 100644 --- a/tests/extmod/vfs_fat_more.py +++ b/tests/extmod/vfs_fat_more.py @@ -19,17 +19,17 @@ class RAMFS: self.data = bytearray(blocks * self.SEC_SIZE) def readblocks(self, n, buf): - #print("readblocks(%s, %x(%d))" % (n, id(buf), len(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))) + # 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)) + # 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 @@ -45,75 +45,76 @@ except MemoryError: # first we umount any existing mount points the target may have try: - uos.umount('/') + uos.umount("/") except OSError: pass -for path in uos.listdir('/'): - uos.umount('/' + path) +for path in uos.listdir("/"): + uos.umount("/" + path) uos.VfsFat.mkfs(bdev) -uos.mount(bdev, '/') +uos.mount(bdev, "/") print(uos.getcwd()) -f = open('test.txt', 'w') -f.write('hello') +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]) +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') +f = open("/test.txt") print(f.read()) f.close() -uos.rename('test.txt', 'test2.txt') +uos.rename("test.txt", "test2.txt") print(uos.listdir()) -uos.rename('test2.txt', '/test3.txt') +uos.rename("test2.txt", "/test3.txt") print(uos.listdir()) -uos.rename('/test3.txt', 'test4.txt') +uos.rename("/test3.txt", "test4.txt") print(uos.listdir()) -uos.rename('/test4.txt', '/test5.txt') +uos.rename("/test4.txt", "/test5.txt") print(uos.listdir()) -uos.mkdir('dir') +uos.mkdir("dir") print(uos.listdir()) -uos.mkdir('/dir2') +uos.mkdir("/dir2") print(uos.listdir()) -uos.mkdir('dir/subdir') -print(uos.listdir('dir')) -for exist in ('', '/', 'dir', '/dir', 'dir/subdir'): +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.args[0] == 17) # EEXIST + print("mkdir OSError", er.args[0] == 17) # EEXIST -uos.chdir('/') -print(uos.stat('test5.txt')[:-3]) +uos.chdir("/") +print(uos.stat("test5.txt")[:-3]) uos.VfsFat.mkfs(bdev2) -uos.mount(bdev2, '/sys') +uos.mount(bdev2, "/sys") print(uos.listdir()) -print(uos.listdir('sys')) -print(uos.listdir('/sys')) +print(uos.listdir("sys")) +print(uos.listdir("/sys")) -uos.rmdir('dir2') -uos.remove('test5.txt') +uos.rmdir("dir2") +uos.remove("test5.txt") print(uos.listdir()) -uos.umount('/') +uos.umount("/") print(uos.getcwd()) print(uos.listdir()) -print(uos.listdir('sys')) +print(uos.listdir("sys")) # test importing a file from a mounted FS import sys + sys.path.clear() -sys.path.append('/sys') -with open('sys/test_module.py', 'w') as f: +sys.path.append("/sys") +with open("sys/test_module.py", "w") as f: f.write('print("test_module!")') import test_module diff --git a/tests/extmod/vfs_fat_oldproto.py b/tests/extmod/vfs_fat_oldproto.py index 3caaa368db..93d00f9ce4 100644 --- a/tests/extmod/vfs_fat_oldproto.py +++ b/tests/extmod/vfs_fat_oldproto.py @@ -11,6 +11,7 @@ except AttributeError: print("SKIP") raise SystemExit + class RAMFS_OLD: SEC_SIZE = 512 @@ -19,12 +20,12 @@ class RAMFS_OLD: self.data = bytearray(blocks * self.SEC_SIZE) def readblocks(self, n, buf): - #print("readblocks(%s, %x(%d))" % (n, id(buf), len(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))) + # print("writeblocks(%s, %x)" % (n, id(buf))) for i in range(len(buf)): self.data[n * self.SEC_SIZE + i] = buf[i] diff --git a/tests/extmod/vfs_fat_ramdisk.py b/tests/extmod/vfs_fat_ramdisk.py index 11b2df7f42..5f758bf89c 100644 --- a/tests/extmod/vfs_fat_ramdisk.py +++ b/tests/extmod/vfs_fat_ramdisk.py @@ -20,17 +20,17 @@ class RAMFS: self.data = bytearray(blocks * self.SEC_SIZE) def readblocks(self, n, buf): - #print("readblocks(%s, %x(%d))" % (n, id(buf), len(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))) + # 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)) + # 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 @@ -64,7 +64,7 @@ with vfs.open("foo_file.txt", "w") as f: print(list(vfs.ilistdir())) print("stat root:", vfs.stat("/")) -print("stat file:", vfs.stat("foo_file.txt")[:-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) @@ -94,4 +94,4 @@ print(list(vfs.ilistdir(b""))) try: vfs.ilistdir(b"no_exist") except OSError as e: - print('ENOENT:', e.args[0] == uerrno.ENOENT) + print("ENOENT:", e.args[0] == uerrno.ENOENT) diff --git a/tests/extmod/vfs_fat_ramdisklarge.py b/tests/extmod/vfs_fat_ramdisklarge.py index 4ac52b257f..69d4a8cbbd 100644 --- a/tests/extmod/vfs_fat_ramdisklarge.py +++ b/tests/extmod/vfs_fat_ramdisklarge.py @@ -22,23 +22,23 @@ class RAMBDevSparse: self.data = {} def readblocks(self, n, buf): - #print("readblocks(%s, %x(%d))" % (n, id(buf), len(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))) + # 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] + self.data[s][:] = mv[off : off + self.SEC_SIZE] def ioctl(self, op, arg): - #print("ioctl(%d, %r)" % (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 @@ -57,13 +57,13 @@ uos.mount(vfs, "/ramdisk") print("statvfs:", vfs.statvfs("/ramdisk")) -f = open('/ramdisk/test.txt', 'w') -f.write('test file') +f = open("/ramdisk/test.txt", "w") +f.write("test file") f.close() print("statvfs:", vfs.statvfs("/ramdisk")) -f = open('/ramdisk/test.txt') +f = open("/ramdisk/test.txt") print(f.read()) f.close() diff --git a/tests/extmod/vfs_lfs.py b/tests/extmod/vfs_lfs.py index 46c770b437..c3656fe687 100644 --- a/tests/extmod/vfs_lfs.py +++ b/tests/extmod/vfs_lfs.py @@ -2,12 +2,14 @@ try: import uos + uos.VfsLfs1 uos.VfsLfs2 except (ImportError, AttributeError): print("SKIP") raise SystemExit + class RAMBlockDevice: ERASE_BLOCK_SIZE = 1024 @@ -25,15 +27,16 @@ class RAMBlockDevice: self.data[addr + i] = buf[i] def ioctl(self, op, arg): - if op == 4: # block count + if op == 4: # block count return len(self.data) // self.ERASE_BLOCK_SIZE - if op == 5: # block size + if op == 5: # block size return self.ERASE_BLOCK_SIZE - if op == 6: # erase block + if op == 6: # erase block return 0 + def test(bdev, vfs_class): - print('test', vfs_class) + print("test", vfs_class) # mkfs vfs_class.mkfs(bdev) @@ -42,65 +45,66 @@ def test(bdev, vfs_class): vfs = vfs_class(bdev) # statvfs - print(vfs.statvfs('/')) + print(vfs.statvfs("/")) # open, write close - f = vfs.open('test', 'w') - f.write('littlefs') + f = vfs.open("test", "w") + f.write("littlefs") f.close() # statvfs after creating a file - print(vfs.statvfs('/')) + print(vfs.statvfs("/")) # ilistdir print(list(vfs.ilistdir())) - print(list(vfs.ilistdir('/'))) - print(list(vfs.ilistdir(b'/'))) + print(list(vfs.ilistdir("/"))) + print(list(vfs.ilistdir(b"/"))) # mkdir, rmdir - vfs.mkdir('testdir') + vfs.mkdir("testdir") print(list(vfs.ilistdir())) - print(list(vfs.ilistdir('testdir'))) - vfs.rmdir('testdir') + print(list(vfs.ilistdir("testdir"))) + vfs.rmdir("testdir") print(list(vfs.ilistdir())) - vfs.mkdir('testdir') + vfs.mkdir("testdir") # stat a file - print(vfs.stat('test')) + print(vfs.stat("test")) # stat a dir (size seems to vary on LFS2 so don't print that) - print(vfs.stat('testdir')[:6]) + print(vfs.stat("testdir")[:6]) # read - with vfs.open('test', 'r') as f: + 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)) + with vfs.open("testbig", "w") as f: + data = "large012" * 32 * 16 + print("data length:", len(data)) for i in range(4): - print('write', i) + print("write", i) f.write(data) # stat after creating large file - print(vfs.statvfs('/')) + print(vfs.statvfs("/")) # rename - vfs.rename('testbig', 'testbig2') + vfs.rename("testbig", "testbig2") print(list(vfs.ilistdir())) # remove - vfs.remove('testbig2') + vfs.remove("testbig2") print(list(vfs.ilistdir())) # getcwd, chdir print(vfs.getcwd()) - vfs.chdir('/testdir') + vfs.chdir("/testdir") print(vfs.getcwd()) - vfs.chdir('/') + vfs.chdir("/") print(vfs.getcwd()) - vfs.rmdir('testdir') + vfs.rmdir("testdir") + bdev = RAMBlockDevice(30) test(bdev, uos.VfsLfs1) diff --git a/tests/extmod/vfs_lfs_corrupt.py b/tests/extmod/vfs_lfs_corrupt.py index 90c3e82163..330458709a 100644 --- a/tests/extmod/vfs_lfs_corrupt.py +++ b/tests/extmod/vfs_lfs_corrupt.py @@ -2,12 +2,14 @@ try: import uos + uos.VfsLfs1 uos.VfsLfs2 except (ImportError, AttributeError): print("SKIP") raise SystemExit + class RAMBlockDevice: ERASE_BLOCK_SIZE = 1024 @@ -28,79 +30,83 @@ class RAMBlockDevice: return self.ret def ioctl(self, op, arg): - if op == 4: # block count + if op == 4: # block count return len(self.data) // self.ERASE_BLOCK_SIZE - if op == 5: # block size + if op == 5: # block size return self.ERASE_BLOCK_SIZE - if op == 6: # erase block + 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 + 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: + with vfs.open("f", "w") as f: for i in range(100): - f.write('test') + f.write("test") return vfs + def test(bdev, vfs_class): - print('test', vfs_class) + print("test", vfs_class) # statvfs vfs = create_vfs(bdev, vfs_class) corrupt(bdev, 0) corrupt(bdev, 1) try: - print(vfs.statvfs('')) + print(vfs.statvfs("")) except OSError: - print('statvfs OSError') + print("statvfs OSError") # error during read vfs = create_vfs(bdev, vfs_class) - f = vfs.open('f', 'r') - bdev.ret = -5 # EIO + f = vfs.open("f", "r") + bdev.ret = -5 # EIO try: f.read(10) except OSError: - print('read OSError') + print("read OSError") # error during write vfs = create_vfs(bdev, vfs_class) - f = vfs.open('f', 'a') - bdev.ret = -5 # EIO + f = vfs.open("f", "a") + bdev.ret = -5 # EIO try: - f.write('test') + f.write("test") except OSError: - print('write 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 + f = vfs.open("f", "w") + f.write("test") + bdev.ret = -5 # EIO try: f.close() except OSError: - print('close 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 + f = vfs.open("f", "w") + f.write("test") + bdev.ret = -5 # EIO try: f.flush() except OSError: - print('flush OSError') + print("flush OSError") bdev.ret = 0 f.close() + bdev = RAMBlockDevice(30) test(bdev, uos.VfsLfs1) test(bdev, uos.VfsLfs2) diff --git a/tests/extmod/vfs_lfs_error.py b/tests/extmod/vfs_lfs_error.py index 793fae59e2..717284ea01 100644 --- a/tests/extmod/vfs_lfs_error.py +++ b/tests/extmod/vfs_lfs_error.py @@ -2,12 +2,14 @@ try: import uos + uos.VfsLfs1 uos.VfsLfs2 except (ImportError, AttributeError): print("SKIP") raise SystemExit + class RAMBlockDevice: ERASE_BLOCK_SIZE = 1024 @@ -25,92 +27,94 @@ class RAMBlockDevice: self.data[addr + i] = buf[i] def ioctl(self, op, arg): - if op == 4: # block count + if op == 4: # block count return len(self.data) // self.ERASE_BLOCK_SIZE - if op == 5: # block size + if op == 5: # block size return self.ERASE_BLOCK_SIZE - if op == 6: # erase block + if op == 6: # erase block return 0 + def test(bdev, vfs_class): - print('test', vfs_class) + print("test", vfs_class) # mkfs with too-small block device try: vfs_class.mkfs(RAMBlockDevice(1)) except OSError: - print('mkfs OSError') + print("mkfs OSError") # mount with invalid filesystem try: vfs_class(bdev) except OSError: - print('mount 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') + with vfs.open("testfile", "w") as f: + f.write("test") + vfs.mkdir("testdir") # ilistdir try: - vfs.ilistdir('noexist') + vfs.ilistdir("noexist") except OSError: - print('ilistdir OSError') + print("ilistdir OSError") # remove try: - vfs.remove('noexist') + vfs.remove("noexist") except OSError: - print('remove OSError') + print("remove OSError") # rmdir try: - vfs.rmdir('noexist') + vfs.rmdir("noexist") except OSError: - print('rmdir OSError') + print("rmdir OSError") # rename try: - vfs.rename('noexist', 'somethingelse') + vfs.rename("noexist", "somethingelse") except OSError: - print('rename OSError') + print("rename OSError") # mkdir try: - vfs.mkdir('testdir') + vfs.mkdir("testdir") except OSError: - print('mkdir OSError') + print("mkdir OSError") # chdir to nonexistent try: - vfs.chdir('noexist') + vfs.chdir("noexist") except OSError: - print('chdir OSError') - print(vfs.getcwd()) # check still at root + print("chdir OSError") + print(vfs.getcwd()) # check still at root # chdir to file try: - vfs.chdir('testfile') + vfs.chdir("testfile") except OSError: - print('chdir OSError') - print(vfs.getcwd()) # check still at root + print("chdir OSError") + print(vfs.getcwd()) # check still at root # stat try: - vfs.stat('noexist') + vfs.stat("noexist") except OSError: - print('stat OSError') + print("stat OSError") # error during seek - with vfs.open('testfile', 'r') as f: - f.seek(1 << 30) # SEEK_SET + with vfs.open("testfile", "r") as f: + f.seek(1 << 30) # SEEK_SET try: - f.seek(1 << 30, 1) # SEEK_CUR + f.seek(1 << 30, 1) # SEEK_CUR except OSError: - print('seek OSError') + print("seek OSError") + bdev = RAMBlockDevice(30) test(bdev, uos.VfsLfs1) diff --git a/tests/extmod/vfs_lfs_file.py b/tests/extmod/vfs_lfs_file.py index 477a62e2ff..774cca2964 100644 --- a/tests/extmod/vfs_lfs_file.py +++ b/tests/extmod/vfs_lfs_file.py @@ -2,12 +2,14 @@ try: import uos + uos.VfsLfs1 uos.VfsLfs2 except (ImportError, AttributeError): print("SKIP") raise SystemExit + class RAMBlockDevice: ERASE_BLOCK_SIZE = 1024 @@ -25,15 +27,16 @@ class RAMBlockDevice: self.data[addr + i] = buf[i] def ioctl(self, op, arg): - if op == 4: # block count + if op == 4: # block count return len(self.data) // self.ERASE_BLOCK_SIZE - if op == 5: # block size + if op == 5: # block size return self.ERASE_BLOCK_SIZE - if op == 6: # erase block + if op == 6: # erase block return 0 + def test(bdev, vfs_class): - print('test', vfs_class) + print("test", vfs_class) # mkfs vfs_class.mkfs(bdev) @@ -42,57 +45,57 @@ def test(bdev, vfs_class): vfs = vfs_class(bdev) # create text, print, write, close - f = vfs.open('test.txt', 'wt') + f = vfs.open("test.txt", "wt") print(f) - f.write('littlefs') + f.write("littlefs") f.close() # close already-closed file f.close() # create binary, print, write, flush, close - f = vfs.open('test.bin', 'wb') + f = vfs.open("test.bin", "wb") print(f) - f.write('littlefs') + f.write("littlefs") f.flush() f.close() # create for append - f = vfs.open('test.bin', 'ab') - f.write('more') + f = vfs.open("test.bin", "ab") + f.write("more") f.close() # create exclusive - f = vfs.open('test2.bin', 'xb') + f = vfs.open("test2.bin", "xb") f.close() # create exclusive with error try: - vfs.open('test2.bin', 'x') + vfs.open("test2.bin", "x") except OSError: - print('open OSError') + print("open OSError") # read default - with vfs.open('test.txt', '') as f: + with vfs.open("test.txt", "") as f: print(f.read()) # read text - with vfs.open('test.txt', 'rt') as f: + with vfs.open("test.txt", "rt") as f: print(f.read()) # read binary - with vfs.open('test.bin', 'rb') as f: + with vfs.open("test.bin", "rb") as f: print(f.read()) # create read and write - with vfs.open('test.bin', 'r+b') as f: + with vfs.open("test.bin", "r+b") as f: print(f.read(8)) - f.write('MORE') - with vfs.open('test.bin', 'rb') as f: + f.write("MORE") + with vfs.open("test.bin", "rb") as f: print(f.read()) # seek and tell - f = vfs.open('test.txt', 'r') + f = vfs.open("test.txt", "r") print(f.tell()) f.seek(3, 0) print(f.tell()) @@ -100,18 +103,19 @@ def test(bdev, vfs_class): # open nonexistent try: - vfs.open('noexist', 'r') + vfs.open("noexist", "r") except OSError: - print('open OSError') + print("open OSError") # open multiple files at the same time - f1 = vfs.open('test.txt', '') - f2 = vfs.open('test.bin', 'b') + 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) diff --git a/tests/extmod/vfs_lfs_mount.py b/tests/extmod/vfs_lfs_mount.py index 76263f4978..7ac19184b9 100644 --- a/tests/extmod/vfs_lfs_mount.py +++ b/tests/extmod/vfs_lfs_mount.py @@ -2,12 +2,14 @@ try: import uos + uos.VfsLfs1 uos.VfsLfs2 except (ImportError, AttributeError): print("SKIP") raise SystemExit + class RAMBlockDevice: ERASE_BLOCK_SIZE = 1024 @@ -25,15 +27,16 @@ class RAMBlockDevice: self.data[addr + i] = buf[i] def ioctl(self, op, arg): - if op == 4: # block count + if op == 4: # block count return len(self.data) // self.ERASE_BLOCK_SIZE - if op == 5: # block size + if op == 5: # block size return self.ERASE_BLOCK_SIZE - if op == 6: # erase block + if op == 6: # erase block return 0 + def test(bdev, vfs_class): - print('test', vfs_class) + print("test", vfs_class) # mkfs vfs_class.mkfs(bdev) @@ -42,31 +45,33 @@ def test(bdev, vfs_class): vfs = vfs_class(bdev) # mount - uos.mount(vfs, '/lfs') + uos.mount(vfs, "/lfs") # import - with open('/lfs/lfsmod.py', 'w') as f: + 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: + uos.mkdir("/lfs/lfspkg") + with open("/lfs/lfspkg/__init__.py", "w") as f: f.write('print("package")\n') import lfspkg # umount - uos.umount('/lfs') + uos.umount("/lfs") # clear imported modules sys.modules.clear() + bdev = RAMBlockDevice(30) # initialise path import sys + sys.path.clear() -sys.path.append('/lfs') +sys.path.append("/lfs") # run tests test(bdev, uos.VfsLfs1) diff --git a/tests/extmod/vfs_userfs.py b/tests/extmod/vfs_userfs.py index 7f6e48cb1e..06e546b081 100644 --- a/tests/extmod/vfs_userfs.py +++ b/tests/extmod/vfs_userfs.py @@ -5,8 +5,10 @@ import sys try: import uio + uio.IOBase import uos + uos.mount except (ImportError, AttributeError): print("SKIP") @@ -17,8 +19,10 @@ class UserFile(uio.IOBase): def __init__(self, data): self.data = data self.pos = 0 + def read(self): return self.data + def readinto(self, buf): n = 0 while n < len(buf) and self.pos < len(self.data): @@ -26,44 +30,49 @@ class UserFile(uio.IOBase): n += 1 self.pos += 1 return n + def ioctl(self, req, arg): - print('ioctl', 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) + 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) + print("open", path, mode) return UserFile(self.files[path]) # create and mount a user filesystem user_files = { - '/data.txt': b"some data in a text file\n", - '/usermod1.py': b"print('in usermod1')\nimport usermod2", - '/usermod2.py': b"print('in usermod2')", + "/data.txt": b"some data in a text file\n", + "/usermod1.py": b"print('in usermod1')\nimport usermod2", + "/usermod2.py": b"print('in usermod2')", } -uos.mount(UserFS(user_files), '/userfs') +uos.mount(UserFS(user_files), "/userfs") # open and read a file -f = open('/userfs/data.txt') +f = open("/userfs/data.txt") print(f.read()) # import files from the user filesystem -sys.path.append('/userfs') +sys.path.append("/userfs") import usermod1 # unmount and undo path addition -uos.umount('/userfs') +uos.umount("/userfs") sys.path.pop() diff --git a/tests/extmod/websocket_basic.py b/tests/extmod/websocket_basic.py index 6cc6f0fd15..10396e914d 100644 --- a/tests/extmod/websocket_basic.py +++ b/tests/extmod/websocket_basic.py @@ -11,6 +11,7 @@ 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() @@ -19,31 +20,32 @@ def ws_write(msg, sz): 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_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_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 +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 +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()) @@ -51,8 +53,8 @@ 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(8)) # GET_DATA_OPTS +print(ws.ioctl(9, 2)) # SET_DATA_OPTS print(ws.ioctl(9)) try: ws.ioctl(-1) diff --git a/tests/feature_check/byteorder.py b/tests/feature_check/byteorder.py index d60f939568..c82a41a24b 100644 --- a/tests/feature_check/byteorder.py +++ b/tests/feature_check/byteorder.py @@ -1,2 +1,3 @@ import sys + print(sys.byteorder) diff --git a/tests/feature_check/complex.py b/tests/feature_check/complex.py index a22eb52ce3..7576dcb953 100644 --- a/tests/feature_check/complex.py +++ b/tests/feature_check/complex.py @@ -3,4 +3,3 @@ try: print("complex") except NameError: print("no") - diff --git a/tests/feature_check/coverage.py b/tests/feature_check/coverage.py index dcda53eae2..82647ee314 100644 --- a/tests/feature_check/coverage.py +++ b/tests/feature_check/coverage.py @@ -1,5 +1,5 @@ try: extra_coverage - print('coverage') + print("coverage") except NameError: - print('no') + print("no") diff --git a/tests/feature_check/float.py b/tests/feature_check/float.py index af93f59763..d6d2a99d24 100644 --- a/tests/feature_check/float.py +++ b/tests/feature_check/float.py @@ -5,9 +5,9 @@ try: except NameError: print(0) else: - if float('1.0000001') == float('1.0'): + if float("1.0000001") == float("1.0"): print(30) - elif float('1e300') == float('inf'): + elif float("1e300") == float("inf"): print(32) else: print(64) diff --git a/tests/feature_check/reverse_ops.py b/tests/feature_check/reverse_ops.py index 668748bc57..68eb91b44e 100644 --- a/tests/feature_check/reverse_ops.py +++ b/tests/feature_check/reverse_ops.py @@ -1,8 +1,8 @@ class Foo: - def __radd__(self, other): pass + try: 5 + Foo() except TypeError: diff --git a/tests/feature_check/uio_module.py b/tests/feature_check/uio_module.py index 1031cba909..bad8d7c95b 100644 --- a/tests/feature_check/uio_module.py +++ b/tests/feature_check/uio_module.py @@ -1,5 +1,6 @@ try: import uio + print("uio") except ImportError: print("no") diff --git a/tests/float/array_construct.py b/tests/float/array_construct.py index eb735c67c3..f6a3a9dc9d 100644 --- a/tests/float/array_construct.py +++ b/tests/float/array_construct.py @@ -9,5 +9,5 @@ except ImportError: print("SKIP") raise SystemExit -print(array('f', array('h', [1, 2]))) -print(array('d', array('f', [1, 2]))) +print(array("f", array("h", [1, 2]))) +print(array("d", array("f", [1, 2]))) diff --git a/tests/float/builtin_float_abs.py b/tests/float/builtin_float_abs.py index c0935c6eec..f7ce9e156f 100644 --- a/tests/float/builtin_float_abs.py +++ b/tests/float/builtin_float_abs.py @@ -1,13 +1,13 @@ # test builtin abs function with float args for val in ( - '1.0', - '-1.0', - '0.0', - '-0.0', - 'nan', - '-nan', - 'inf', - '-inf', - ): + "1.0", + "-1.0", + "0.0", + "-0.0", + "nan", + "-nan", + "inf", + "-inf", +): print(val, abs(float(val))) diff --git a/tests/float/builtin_float_hash.py b/tests/float/builtin_float_hash.py index 7a7e374010..1388bb0e83 100644 --- a/tests/float/builtin_float_hash.py +++ b/tests/float/builtin_float_hash.py @@ -2,24 +2,24 @@ # 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', - ): + "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', - ): + "0.1", + "-0.1", + "10.3", + "0.4e3", + "1e16", + "inf", + "-inf", + "nan", +): print(val, type(hash(float(val)))) diff --git a/tests/float/builtin_float_minmax.py b/tests/float/builtin_float_minmax.py index 266ed133d5..8a53746e5d 100644 --- a/tests/float/builtin_float_minmax.py +++ b/tests/float/builtin_float_minmax.py @@ -29,4 +29,3 @@ 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])) - diff --git a/tests/float/builtin_float_pow.py b/tests/float/builtin_float_pow.py index 2de1b48176..98998bdc7c 100644 --- a/tests/float/builtin_float_pow.py +++ b/tests/float/builtin_float_pow.py @@ -6,6 +6,6 @@ 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'))) +print(pow(0.0, float("inf"))) +print(pow(0.0, float("-inf"))) +print(pow(0.0, float("nan"))) diff --git a/tests/float/builtin_float_round.py b/tests/float/builtin_float_round.py index 63cb39aa35..1153b8a2bf 100644 --- a/tests/float/builtin_float_round.py +++ b/tests/float/builtin_float_round.py @@ -2,8 +2,18 @@ # 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] + [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)) @@ -17,7 +27,7 @@ for i in range(-1, 3): print(round(1.47, i)) # test inf and nan -for val in (float('inf'), float('nan')): +for val in (float("inf"), float("nan")): try: round(val) except (ValueError, OverflowError) as e: diff --git a/tests/float/builtin_float_round_intbig.py b/tests/float/builtin_float_round_intbig.py index 2083e3ea3a..c8a338eefd 100644 --- a/tests/float/builtin_float_round_intbig.py +++ b/tests/float/builtin_float_round_intbig.py @@ -1,4 +1,4 @@ # test round() with floats that return large integers for x in (-1e25, 1e25): - print('%.3g' % round(x)) + print("%.3g" % round(x)) diff --git a/tests/float/bytearray_construct.py b/tests/float/bytearray_construct.py index 4e7631b2b9..257d37d1be 100644 --- a/tests/float/bytearray_construct.py +++ b/tests/float/bytearray_construct.py @@ -9,4 +9,4 @@ except ImportError: print("SKIP") raise SystemExit -print(bytearray(array('f', [1, 2.3]))) +print(bytearray(array("f", [1, 2.3]))) diff --git a/tests/float/bytes_construct.py b/tests/float/bytes_construct.py index 96294659bf..0806087b0e 100644 --- a/tests/float/bytes_construct.py +++ b/tests/float/bytes_construct.py @@ -9,4 +9,4 @@ except ImportError: print("SKIP") raise SystemExit -print(bytes(array('f', [1, 2.3]))) +print(bytes(array("f", [1, 2.3]))) diff --git a/tests/float/cmath_fun.py b/tests/float/cmath_fun.py index d3df25e111..7b5e692452 100644 --- a/tests/float/cmath_fun.py +++ b/tests/float/cmath_fun.py @@ -11,29 +11,33 @@ print("%.5g" % e) print("%.5g" % pi) test_values_non_zero = [] -base_values = (0.0, 0.5, 1.2345, 10.) +base_values = (0.0, 0.5, 1.2345, 10.0) for r in base_values: for i in base_values: - if r != 0. or i != 0.: + if r != 0.0 or i != 0.0: test_values_non_zero.append(complex(r, i)) - if r != 0.: + if r != 0.0: test_values_non_zero.append(complex(-r, i)) - if i != 0.: + if i != 0.0: test_values_non_zero.append(complex(r, -i)) - if r != 0. and i != 0.: + if r != 0.0 and i != 0.0: test_values_non_zero.append(complex(-r, -i)) -test_values = [complex(0., 0.),] + test_values_non_zero +test_values = [complex(0.0, 0.0),] + test_values_non_zero print(test_values) functions = [ - ('phase', phase, test_values), - ('polar', polar, test_values), - ('rect', rect, ((0, 0), (0, 1), (0, -1), (1, 0), (-1, 0), (1, 1), (-1, 1), (1, -1), (123., -456.))), - ('exp', exp, test_values), - ('log', log, test_values_non_zero), - ('sqrt', sqrt, test_values), - ('cos', cos, test_values), - ('sin', sin, test_values), + ("phase", phase, test_values), + ("polar", polar, test_values), + ( + "rect", + rect, + ((0, 0), (0, 1), (0, -1), (1, 0), (-1, 0), (1, 1), (-1, 1), (1, -1), (123.0, -456.0)), + ), + ("exp", exp, test_values), + ("log", log, test_values_non_zero), + ("sqrt", sqrt, test_values), + ("cos", cos, test_values), + ("sin", sin, test_values), ] for f_name, f, test_vals in functions: @@ -51,5 +55,5 @@ for f_name, f, test_vals in functions: # some test (eg cmath.sqrt(-0.5)) disagree with CPython with tiny real part real = ret.real if abs(real) < 1e-6: - real = 0. + real = 0.0 print("complex(%.5g, %.5g)" % (real, ret.imag)) diff --git a/tests/float/cmath_fun_special.py b/tests/float/cmath_fun_special.py index 471fda8c0d..33b94d04db 100644 --- a/tests/float/cmath_fun_special.py +++ b/tests/float/cmath_fun_special.py @@ -2,26 +2,27 @@ try: from cmath import * + log10 except (ImportError, NameError): print("SKIP") raise SystemExit test_values_non_zero = [] -base_values = (0.0, 0.5, 1.2345, 10.) +base_values = (0.0, 0.5, 1.2345, 10.0) for r in base_values: for i in base_values: - if r != 0. or i != 0.: + if r != 0.0 or i != 0.0: test_values_non_zero.append(complex(r, i)) - if r != 0.: + if r != 0.0: test_values_non_zero.append(complex(-r, i)) - if i != 0.: + if i != 0.0: test_values_non_zero.append(complex(r, -i)) - if r != 0. and i != 0.: + if r != 0.0 and i != 0.0: test_values_non_zero.append(complex(-r, -i)) functions = [ - ('log10', log10, test_values_non_zero), + ("log10", log10, test_values_non_zero), ] for f_name, f, test_vals in functions: diff --git a/tests/float/complex1.py b/tests/float/complex1.py index c1fa61ba3c..a510ffc830 100644 --- a/tests/float/complex1.py +++ b/tests/float/complex1.py @@ -27,11 +27,16 @@ print(1j * 2j) print(1j / 2) print((1j / 2j).real) print(1j / (1 + 2j)) -ans = 0j ** 0; print("%.5g %.5g" % (ans.real, ans.imag)) -ans = 0j ** 1; print("%.5g %.5g" % (ans.real, ans.imag)) -ans = 0j ** 0j; print("%.5g %.5g" % (ans.real, ans.imag)) -ans = 1j ** 2.5; print("%.5g %.5g" % (ans.real, ans.imag)) -ans = 1j ** 2.5j; print("%.5g %.5g" % (ans.real, ans.imag)) +ans = 0j ** 0 +print("%.5g %.5g" % (ans.real, ans.imag)) +ans = 0j ** 1 +print("%.5g %.5g" % (ans.real, ans.imag)) +ans = 0j ** 0j +print("%.5g %.5g" % (ans.real, ans.imag)) +ans = 1j ** 2.5 +print("%.5g %.5g" % (ans.real, ans.imag)) +ans = 1j ** 2.5j +print("%.5g %.5g" % (ans.real, ans.imag)) # comparison print(1j == 1) @@ -40,7 +45,7 @@ print(0 + 0j == False, 1 + 0j == True) print(False == 0 + 0j, True == 1 + 0j) # comparison of nan is special -nan = float('nan') * 1j +nan = float("nan") * 1j print(nan == 1j) print(nan == nan) @@ -56,20 +61,22 @@ print(type(hash(1j))) print(1.2 + 3j) # negative base and fractional power should create a complex -ans = (-1) ** 2.3; print("%.5g %.5g" % (ans.real, ans.imag)) -ans = (-1.2) ** -3.4; print("%.5g %.5g" % (ans.real, ans.imag)) +ans = (-1) ** 2.3 +print("%.5g %.5g" % (ans.real, ans.imag)) +ans = (-1.2) ** -3.4 +print("%.5g %.5g" % (ans.real, ans.imag)) # check printing of inf/nan -print(float('nan') * 1j) -print(float('-nan') * 1j) -print(float('inf') * (1 + 1j)) -print(float('-inf') * (1 + 1j)) +print(float("nan") * 1j) +print(float("-nan") * 1j) +print(float("inf") * (1 + 1j)) +print(float("-inf") * (1 + 1j)) # can't assign to attributes try: (1j).imag = 0 except AttributeError: - print('AttributeError') + print("AttributeError") # can't convert rhs to complex try: @@ -95,11 +102,11 @@ try: except TypeError: print("TypeError") -#small int on LHS, complex on RHS, unsupported op +# small int on LHS, complex on RHS, unsupported op try: print(1 | 1j) except TypeError: - print('TypeError') + print("TypeError") # zero division try: diff --git a/tests/float/complex1_intbig.py b/tests/float/complex1_intbig.py index ed2390bbaf..864036b991 100644 --- a/tests/float/complex1_intbig.py +++ b/tests/float/complex1_intbig.py @@ -1,4 +1,5 @@ # test basic complex number functionality # convert bignum to complex on rhs -ans = 1j + (1 << 70); print("%.5g %.5g" % (ans.real, ans.imag)) +ans = 1j + (1 << 70) +print("%.5g %.5g" % (ans.real, ans.imag)) diff --git a/tests/float/float1.py b/tests/float/float1.py index f6d69e3904..efde5146be 100644 --- a/tests/float/float1.py +++ b/tests/float/float1.py @@ -1,11 +1,11 @@ # test basic float capabilities # literals -print(.12) -print(1.) +print(0.12) +print(1.0) print(1.2) print(0e0) -print(0e+0) +print(0e0) print(0e-0) # float construction @@ -68,7 +68,7 @@ print(0.0 == False, 1.0 == True) print(False == 0.0, True == 1.0) # comparison of nan is special -nan = float('nan') +nan = float("nan") print(nan == 1.2) print(nan == nan) @@ -108,7 +108,7 @@ except TypeError: try: print(1 | 1.0) except TypeError: - print('TypeError') + print("TypeError") # can't convert list to float try: diff --git a/tests/float/float2int_doubleprec_intbig.py b/tests/float/float2int_doubleprec_intbig.py index de2137d66c..24d30fe691 100644 --- a/tests/float/float2int_doubleprec_intbig.py +++ b/tests/float/float2int_doubleprec_intbig.py @@ -6,6 +6,7 @@ except: import struct import sys + maxsize_bits = 0 maxsize = sys.maxsize while maxsize: @@ -31,32 +32,33 @@ if ll_type is None: # This case occurs with time.time() values if ll_type != 0: - print(int(1418774543.)) - print("%d" % 1418774543.) + print(int(1418774543.0)) + print("%d" % 1418774543.0) if ll_type == 3: - print(int(2.**100)) - print("%d" % 2.**100) + print(int(2.0 ** 100)) + print("%d" % 2.0 ** 100) else: - print(int(1073741823.)) - print("%d" % 1073741823.) + print(int(1073741823.0)) + print("%d" % 1073741823.0) testpass = True -p2_rng = ((30,63,1024),(62,63,1024))[is_64bit][ll_type] -for i in range(0,p2_rng): - bitcnt = len(bin(int(2.**i))) - 3; +p2_rng = ((30, 63, 1024), (62, 63, 1024))[is_64bit][ll_type] +for i in range(0, p2_rng): + bitcnt = len(bin(int(2.0 ** i))) - 3 if i != bitcnt: - print('fail: 2**%u was %u bits long' % (i, bitcnt)); + print("fail: 2**%u was %u bits long" % (i, bitcnt)) testpass = False -print("power of 2 test: %s" % (testpass and 'passed' or 'failed')) +print("power of 2 test: %s" % (testpass and "passed" or "failed")) testpass = True -p10_rng = ((9,18,23),(18,18,23))[is_64bit][ll_type] -for i in range(0,p10_rng): - digcnt = len(str(int(10.**i))) - 1; +p10_rng = ((9, 18, 23), (18, 18, 23))[is_64bit][ll_type] +for i in range(0, p10_rng): + digcnt = len(str(int(10.0 ** i))) - 1 if i != digcnt: - print('fail: 10**%u was %u digits long' % (i, digcnt)); + print("fail: 10**%u was %u digits long" % (i, digcnt)) testpass = False -print("power of 10 test: %s" % (testpass and 'passed' or 'failed')) +print("power of 10 test: %s" % (testpass and "passed" or "failed")) + def fp2int_test(num, name, should_fail): try: @@ -64,37 +66,38 @@ def fp2int_test(num, name, should_fail): passed = ~should_fail except: passed = should_fail - print('%s: %s' % (name, passed and 'passed' or 'failed')) + print("%s: %s" % (name, passed and "passed" or "failed")) + if ll_type != 2: if ll_type == 0: if is_64bit: - neg_bad_fp = -1.00000005*2.**62. - pos_bad_fp = 2.**62. - neg_good_fp = -2.**62. - pos_good_fp = 0.99999993*2.**62. + neg_bad_fp = -1.00000005 * 2.0 ** 62.0 + pos_bad_fp = 2.0 ** 62.0 + neg_good_fp = -(2.0 ** 62.0) + pos_good_fp = 0.99999993 * 2.0 ** 62.0 else: - neg_bad_fp = -1.00000005*2.**30. - pos_bad_fp = 2.**30. - neg_good_fp = -2.**30. - pos_good_fp = 0.9999999499*2.**30. + neg_bad_fp = -1.00000005 * 2.0 ** 30.0 + pos_bad_fp = 2.0 ** 30.0 + neg_good_fp = -(2.0 ** 30.0) + pos_good_fp = 0.9999999499 * 2.0 ** 30.0 else: - neg_bad_fp = -0.51*2.**64. - pos_bad_fp = 2.**63. - neg_good_fp = -2.**63. - pos_good_fp = 1.9999998*2.**62. + neg_bad_fp = -0.51 * 2.0 ** 64.0 + pos_bad_fp = 2.0 ** 63.0 + neg_good_fp = -(2.0 ** 63.0) + pos_good_fp = 1.9999998 * 2.0 ** 62.0 - fp2int_test(neg_bad_fp, 'neg bad', True) - fp2int_test(pos_bad_fp, 'pos bad', True) - fp2int_test(neg_good_fp, 'neg good', False) - fp2int_test(pos_good_fp, 'pos good', False) + fp2int_test(neg_bad_fp, "neg bad", True) + fp2int_test(pos_bad_fp, "pos bad", True) + fp2int_test(neg_good_fp, "neg good", False) + fp2int_test(pos_good_fp, "pos good", False) else: - fp2int_test(-1.9999999999999981*2.**1023., 'large neg', False) - fp2int_test(1.9999999999999981*2.**1023., 'large pos', False) + fp2int_test(-1.9999999999999981 * 2.0 ** 1023.0, "large neg", False) + fp2int_test(1.9999999999999981 * 2.0 ** 1023.0, "large pos", False) -fp2int_test(float('inf'), 'inf test', True) -fp2int_test(float('nan'), 'NaN test', True) +fp2int_test(float("inf"), "inf test", True) +fp2int_test(float("nan"), "NaN test", True) # test numbers < 1 (this used to fail; see issue #1044) -fp2int_test(0.0001, 'small num', False) -struct.pack('I', int(1/2)) +fp2int_test(0.0001, "small num", False) +struct.pack("I", int(1 / 2)) diff --git a/tests/float/float2int_fp30_intbig.py b/tests/float/float2int_fp30_intbig.py index fbb94a4ccc..da39800401 100644 --- a/tests/float/float2int_fp30_intbig.py +++ b/tests/float/float2int_fp30_intbig.py @@ -6,6 +6,7 @@ except: import struct import sys + maxsize_bits = 0 maxsize = sys.maxsize while maxsize: @@ -30,30 +31,31 @@ if ll_type is None: ll_type = 2 # basic conversion -print(int(14187744.)) -print("%d" % 14187744.) +print(int(14187744.0)) +print("%d" % 14187744.0) if ll_type == 2: - print(int(2.**100)) - print("%d" % 2.**100) + print(int(2.0 ** 100)) + print("%d" % 2.0 ** 100) testpass = True -p2_rng = ((30,63,127),(62,63,127))[is_64bit][ll_type] -for i in range(0,p2_rng): - bitcnt = len(bin(int(2.**i))) - 3; +p2_rng = ((30, 63, 127), (62, 63, 127))[is_64bit][ll_type] +for i in range(0, p2_rng): + bitcnt = len(bin(int(2.0 ** i))) - 3 if i != bitcnt: - print('fail: 2.**%u was %u bits long' % (i, bitcnt)); + print("fail: 2.**%u was %u bits long" % (i, bitcnt)) testpass = False -print("power of 2 test: %s" % (testpass and 'passed' or 'failed')) +print("power of 2 test: %s" % (testpass and "passed" or "failed")) # TODO why does 10**12 fail this test for single precision float? testpass = True p10_rng = 9 -for i in range(0,p10_rng): - digcnt = len(str(int(10.**i))) - 1; +for i in range(0, p10_rng): + digcnt = len(str(int(10.0 ** i))) - 1 if i != digcnt: - print('fail: 10.**%u was %u digits long' % (i, digcnt)); + print("fail: 10.**%u was %u digits long" % (i, digcnt)) testpass = False -print("power of 10 test: %s" % (testpass and 'passed' or 'failed')) +print("power of 10 test: %s" % (testpass and "passed" or "failed")) + def fp2int_test(num, name, should_fail): try: @@ -61,37 +63,38 @@ def fp2int_test(num, name, should_fail): passed = ~should_fail except: passed = should_fail - print('%s: %s' % (name, passed and 'passed' or 'failed')) + print("%s: %s" % (name, passed and "passed" or "failed")) + if ll_type != 2: if ll_type == 0: if is_64bit: - neg_bad_fp = -1.00000005*2.**62. - pos_bad_fp = 2.**62. - neg_good_fp = -2.**62. - pos_good_fp = 0.99999993*2.**62. + neg_bad_fp = -1.00000005 * 2.0 ** 62.0 + pos_bad_fp = 2.0 ** 62.0 + neg_good_fp = -(2.0 ** 62.0) + pos_good_fp = 0.99999993 * 2.0 ** 62.0 else: - neg_bad_fp = -1.00000005*2.**30. - pos_bad_fp = 2.**30. - neg_good_fp = -2.**30. - pos_good_fp = 0.9999999499*2.**30. + neg_bad_fp = -1.00000005 * 2.0 ** 30.0 + pos_bad_fp = 2.0 ** 30.0 + neg_good_fp = -(2.0 ** 30.0) + pos_good_fp = 0.9999999499 * 2.0 ** 30.0 else: - neg_bad_fp = -0.51*2.**64. - pos_bad_fp = 2.**63. - neg_good_fp = -2.**63. - pos_good_fp = 1.9999998*2.**62. + neg_bad_fp = -0.51 * 2.0 ** 64.0 + pos_bad_fp = 2.0 ** 63.0 + neg_good_fp = -(2.0 ** 63.0) + pos_good_fp = 1.9999998 * 2.0 ** 62.0 - fp2int_test(neg_bad_fp, 'neg bad', True) - fp2int_test(pos_bad_fp, 'pos bad', True) - fp2int_test(neg_good_fp, 'neg good', False) - fp2int_test(pos_good_fp, 'pos good', False) + fp2int_test(neg_bad_fp, "neg bad", True) + fp2int_test(pos_bad_fp, "pos bad", True) + fp2int_test(neg_good_fp, "neg good", False) + fp2int_test(pos_good_fp, "pos good", False) else: - fp2int_test(-1.999999879*2.**126., 'large neg', False) - fp2int_test(1.999999879*2.**126., 'large pos', False) + fp2int_test(-1.999999879 * 2.0 ** 126.0, "large neg", False) + fp2int_test(1.999999879 * 2.0 ** 126.0, "large pos", False) -fp2int_test(float('inf'), 'inf test', True) -fp2int_test(float('nan'), 'NaN test', True) +fp2int_test(float("inf"), "inf test", True) +fp2int_test(float("nan"), "NaN test", True) # test numbers < 1 (this used to fail; see issue #1044) -fp2int_test(0.0001, 'small num', False) -struct.pack('I', int(1/2)) +fp2int_test(0.0001, "small num", False) +struct.pack("I", int(1 / 2)) diff --git a/tests/float/float2int_intbig.py b/tests/float/float2int_intbig.py index 3596d2f73d..62aca39634 100644 --- a/tests/float/float2int_intbig.py +++ b/tests/float/float2int_intbig.py @@ -32,30 +32,33 @@ if ll_type is None: # basic conversion +# fmt: off print(int(14187745.)) print("%d" % 14187745.) +# fmt: on if ll_type == 2: - print(int(2.**100)) - print("%d" % 2.**100) + print(int(2.0 ** 100)) + print("%d" % 2.0 ** 100) testpass = True -p2_rng = ((30,63,127),(62,63,127))[is_64bit][ll_type] -for i in range(0,p2_rng): - bitcnt = len(bin(int(2.**i))) - 3; +p2_rng = ((30, 63, 127), (62, 63, 127))[is_64bit][ll_type] +for i in range(0, p2_rng): + bitcnt = len(bin(int(2.0 ** i))) - 3 if i != bitcnt: - print('fail: 2.**%u was %u bits long' % (i, bitcnt)); + print("fail: 2.**%u was %u bits long" % (i, bitcnt)) testpass = False -print("power of 2 test: %s" % (testpass and 'passed' or 'failed')) +print("power of 2 test: %s" % (testpass and "passed" or "failed")) # TODO why does 10**12 fail this test for single precision float? testpass = True p10_rng = 9 if (ll_type == 0 and ~is_64bit) else 11 -for i in range(0,p10_rng): - digcnt = len(str(int(10.**i))) - 1; +for i in range(0, p10_rng): + digcnt = len(str(int(10.0 ** i))) - 1 if i != digcnt: - print('fail: 10.**%u was %u digits long' % (i, digcnt)); + print("fail: 10.**%u was %u digits long" % (i, digcnt)) testpass = False -print("power of 10 test: %s" % (testpass and 'passed' or 'failed')) +print("power of 10 test: %s" % (testpass and "passed" or "failed")) + def fp2int_test(num, name, should_fail): try: @@ -63,37 +66,38 @@ def fp2int_test(num, name, should_fail): passed = ~should_fail except: passed = should_fail - print('%s: %s' % (name, passed and 'passed' or 'failed')) + print("%s: %s" % (name, passed and "passed" or "failed")) + if ll_type != 2: if ll_type == 0: if is_64bit: - neg_bad_fp = -1.00000005*2.**62. - pos_bad_fp = 2.**62. - neg_good_fp = -2.**62. - pos_good_fp = 0.99999993*2.**62. + neg_bad_fp = -1.00000005 * 2.0 ** 62.0 + pos_bad_fp = 2.0 ** 62.0 + neg_good_fp = -(2.0 ** 62.0) + pos_good_fp = 0.99999993 * 2.0 ** 62.0 else: - neg_bad_fp = -1.00000005*2.**30. - pos_bad_fp = 2.**30. - neg_good_fp = -2.**30. - pos_good_fp = 0.9999999499*2.**30. + neg_bad_fp = -1.00000005 * 2.0 ** 30.0 + pos_bad_fp = 2.0 ** 30.0 + neg_good_fp = -(2.0 ** 30.0) + pos_good_fp = 0.9999999499 * 2.0 ** 30.0 else: - neg_bad_fp = -0.51*2.**64. - pos_bad_fp = 2.**63. - neg_good_fp = -2.**63. - pos_good_fp = 1.9999998*2.**62. + neg_bad_fp = -0.51 * 2.0 ** 64.0 + pos_bad_fp = 2.0 ** 63.0 + neg_good_fp = -(2.0 ** 63.0) + pos_good_fp = 1.9999998 * 2.0 ** 62.0 - fp2int_test(neg_bad_fp, 'neg bad', True) - fp2int_test(pos_bad_fp, 'pos bad', True) - fp2int_test(neg_good_fp, 'neg good', False) - fp2int_test(pos_good_fp, 'pos good', False) + fp2int_test(neg_bad_fp, "neg bad", True) + fp2int_test(pos_bad_fp, "pos bad", True) + fp2int_test(neg_good_fp, "neg good", False) + fp2int_test(pos_good_fp, "pos good", False) else: - fp2int_test(-1.999999879*2.**127., 'large neg', False) - fp2int_test(1.999999879*2.**127., 'large pos', False) + fp2int_test(-1.999999879 * 2.0 ** 127.0, "large neg", False) + fp2int_test(1.999999879 * 2.0 ** 127.0, "large pos", False) -fp2int_test(float('inf'), 'inf test', True) -fp2int_test(float('nan'), 'NaN test', True) +fp2int_test(float("inf"), "inf test", True) +fp2int_test(float("nan"), "NaN test", True) # test numbers < 1 (this used to fail; see issue #1044) -fp2int_test(0.0001, 'small num', False) -struct.pack('I', int(1/2)) +fp2int_test(0.0001, "small num", False) +struct.pack("I", int(1 / 2)) diff --git a/tests/float/float_array.py b/tests/float/float_array.py index 0c7f1b3ade..3c2189869b 100644 --- a/tests/float/float_array.py +++ b/tests/float/float_array.py @@ -7,17 +7,19 @@ except ImportError: print("SKIP") raise SystemExit + def test(a): print(a) a.append(1.2) - print(len(a), '%.3f' % a[0]) + print(len(a), "%.3f" % a[0]) a.append(1) a.append(False) - print(len(a), '%.3f %.3f' % (a[1], a[2])) + print(len(a), "%.3f %.3f" % (a[1], a[2])) a[-1] = 3.45 - print('%.3f' % a[-1]) + print("%.3f" % a[-1]) -test(array('f')) -test(array('d')) -print('{:.4f}'.format(array('f', b'\xcc\xcc\xcc=')[0])) +test(array("f")) +test(array("d")) + +print("{:.4f}".format(array("f", b"\xcc\xcc\xcc=")[0])) diff --git a/tests/float/float_compare.py b/tests/float/float_compare.py index 105923ac73..c177aa7e81 100644 --- a/tests/float/float_compare.py +++ b/tests/float/float_compare.py @@ -1,8 +1,10 @@ # Extended float comparisons + class Foo: pass + foo = Foo() print(foo == 1.0) diff --git a/tests/float/float_divmod.py b/tests/float/float_divmod.py index 8e7cd435a5..ec83ce2d19 100644 --- a/tests/float/float_divmod.py +++ b/tests/float/float_divmod.py @@ -1,11 +1,13 @@ # test floating point floor divide and modulus # it has some tricky corner cases + def test(x, y): div, mod = divmod(x, y) - print('%.8f %.8f %.8f %.8f' % (x // y, x % y, div, mod)) + print("%.8f %.8f %.8f %.8f" % (x // y, x % y, div, mod)) print(div == x // y, mod == x % y, abs(div * y + mod - x) < 1e-15) + test(1.23456, 0.7) test(-1.23456, 0.7) test(1.23456, -0.7) diff --git a/tests/float/float_divmod_relaxed.py b/tests/float/float_divmod_relaxed.py index a9450fa2c4..ef5a6ad2e8 100644 --- a/tests/float/float_divmod_relaxed.py +++ b/tests/float/float_divmod_relaxed.py @@ -4,10 +4,12 @@ # pyboard has 32-bit floating point and gives different (but still # correct) answers for certain combinations of divmod arguments. + def test(x, y): div, mod = divmod(x, y) print(div == x // y, mod == x % y, abs(div * y + mod - x) < 1e-6) + test(1.23456, 0.7) test(-1.23456, 0.7) test(1.23456, -0.7) @@ -30,4 +32,4 @@ for i in range(25): try: divmod(1.0, 0) except ZeroDivisionError: - print('ZeroDivisionError') + print("ZeroDivisionError") diff --git a/tests/float/float_format.py b/tests/float/float_format.py index d43535cf2f..4c8a217567 100644 --- a/tests/float/float_format.py +++ b/tests/float/float_format.py @@ -2,18 +2,18 @@ # general rounding for val in (116, 1111, 1234, 5010, 11111): - print('%.0f' % val) - print('%.1f' % val) - print('%.3f' % val) + print("%.0f" % val) + print("%.1f" % val) + print("%.3f" % val) # make sure rounding is done at the correct precision for prec in range(8): - print(('%%.%df' % prec) % 6e-5) + print(("%%.%df" % prec) % 6e-5) # check certain cases that had a digit value of 10 render as a ":" character -print('%.2e' % float('9' * 51 + 'e-39')) -print('%.2e' % float('9' * 40 + 'e-21')) +print("%.2e" % float("9" * 51 + "e-39")) +print("%.2e" % float("9" * 40 + "e-21")) # check a case that would render negative digit values, eg ")" characters # the string is converted back to a float to check for no illegal characters -float('%.23e' % 1e-80) +float("%.23e" % 1e-80) diff --git a/tests/float/float_parse.py b/tests/float/float_parse.py index 4b5fc613d3..de27c33e7b 100644 --- a/tests/float/float_parse.py +++ b/tests/float/float_parse.py @@ -1,36 +1,36 @@ # test parsing of floats -inf = float('inf') +inf = float("inf") # it shouldn't matter where the decimal point is if the exponent balances the value -print(float('1234') - float('0.1234e4')) -print(float('1.015625') - float('1015625e-6')) +print(float("1234") - float("0.1234e4")) +print(float("1.015625") - float("1015625e-6")) # very large integer part with a very negative exponent should cancel out -print('%.4e' % float('9' * 60 + 'e-60')) -print('%.4e' % float('9' * 60 + 'e-40')) +print("%.4e" % float("9" * 60 + "e-60")) +print("%.4e" % float("9" * 60 + "e-40")) # many fractional digits -print(float('.' + '9' * 70)) -print(float('.' + '9' * 70 + 'e20')) -print(float('.' + '9' * 70 + 'e-50') == float('1e-50')) +print(float("." + "9" * 70)) +print(float("." + "9" * 70 + "e20")) +print(float("." + "9" * 70 + "e-50") == float("1e-50")) # tiny fraction with large exponent -print(float('.' + '0' * 60 + '1e10') == float('1e-51')) -print(float('.' + '0' * 60 + '9e25') == float('9e-36')) -print(float('.' + '0' * 60 + '9e40') == float('9e-21')) +print(float("." + "0" * 60 + "1e10") == float("1e-51")) +print(float("." + "0" * 60 + "9e25") == float("9e-36")) +print(float("." + "0" * 60 + "9e40") == float("9e-21")) # ensure that accuracy is retained when value is close to a subnormal -print(float('1.00000000000000000000e-37')) -print(float('10.0000000000000000000e-38')) -print(float('100.000000000000000000e-39')) +print(float("1.00000000000000000000e-37")) +print(float("10.0000000000000000000e-38")) +print(float("100.000000000000000000e-39")) # very large exponent literal -print(float('1e4294967301')) -print(float('1e-4294967301')) -print(float('1e18446744073709551621')) -print(float('1e-18446744073709551621')) +print(float("1e4294967301")) +print(float("1e-4294967301")) +print(float("1e18446744073709551621")) +print(float("1e-18446744073709551621")) # check small decimals are as close to their true value as possible for n in range(1, 10): - print(float('0.%u' % n) == n / 10) + print(float("0.%u" % n) == n / 10) diff --git a/tests/float/float_parse_doubleprec.py b/tests/float/float_parse_doubleprec.py index dcc0dd5921..81fcadcee8 100644 --- a/tests/float/float_parse_doubleprec.py +++ b/tests/float/float_parse_doubleprec.py @@ -1,21 +1,21 @@ # test parsing of floats, requiring double-precision # very large integer part with a very negative exponent should cancel out -print(float('9' * 400 + 'e-100')) -print(float('9' * 400 + 'e-200')) -print(float('9' * 400 + 'e-400')) +print(float("9" * 400 + "e-100")) +print(float("9" * 400 + "e-200")) +print(float("9" * 400 + "e-400")) # many fractional digits -print(float('.' + '9' * 400)) -print(float('.' + '9' * 400 + 'e100')) -print(float('.' + '9' * 400 + 'e-100')) +print(float("." + "9" * 400)) +print(float("." + "9" * 400 + "e100")) +print(float("." + "9" * 400 + "e-100")) # tiny fraction with large exponent -print('%.14e' % float('.' + '0' * 400 + '9e100')) -print('%.14e' % float('.' + '0' * 400 + '9e200')) -print('%.14e' % float('.' + '0' * 400 + '9e400')) +print("%.14e" % float("." + "0" * 400 + "9e100")) +print("%.14e" % float("." + "0" * 400 + "9e200")) +print("%.14e" % float("." + "0" * 400 + "9e400")) # ensure that accuracy is retained when value is close to a subnormal -print(float('1.00000000000000000000e-307')) -print(float('10.0000000000000000000e-308')) -print(float('100.000000000000000000e-309')) +print(float("1.00000000000000000000e-307")) +print(float("10.0000000000000000000e-308")) +print(float("100.000000000000000000e-309")) diff --git a/tests/float/float_struct.py b/tests/float/float_struct.py index c4c186b89e..18893af0e0 100644 --- a/tests/float/float_struct.py +++ b/tests/float/float_struct.py @@ -8,11 +8,10 @@ except ImportError: print("SKIP") raise SystemExit -i = 1. + 1/2 +i = 1.0 + 1 / 2 # TODO: it looks like '=' format modifier is not yet supported # for fmt in ('f', 'd', '>f', '>d', 'f', '>d', 'f", ">d", "' + fmt.format(*args) + '<') + print("{:8s}".format(fmt) + ">" + fmt.format(*args) + "<") + test("{:10.4}", 123.456) test("{:10.4e}", 123.456) @@ -24,21 +25,21 @@ test("{:06e}", float("inf")) test("{:06e}", float("-inf")) test("{:06e}", float("nan")) -test('{:f}', False) -test('{:f}', True) +test("{:f}", False) +test("{:f}", True) # The following fails right now -#test("{:10.1}", 0.0) +# test("{:10.1}", 0.0) print("%.0f" % (1.750000 % 0.08333333333)) # Below isn't compatible with single-precision float -#print("%.1f" % (1.750000 % 0.08333333333)) -#print("%.2f" % (1.750000 % 0.08333333333)) -#print("%.12f" % (1.750000 % 0.08333333333)) +# print("%.1f" % (1.750000 % 0.08333333333)) +# print("%.2f" % (1.750000 % 0.08333333333)) +# print("%.12f" % (1.750000 % 0.08333333333)) # tests for errors in format string try: - '{:10.1b}'.format(0.0) + "{:10.1b}".format(0.0) except ValueError: - print('ValueError') + print("ValueError") diff --git a/tests/float/string_format2.py b/tests/float/string_format2.py index 269023e7ff..7a36f4d2f9 100644 --- a/tests/float/string_format2.py +++ b/tests/float/string_format2.py @@ -3,15 +3,17 @@ full_tests = False + def test(fmt, *args): - print('{:8s}'.format(fmt) + '>' + fmt.format(*args) + '<') + print("{:8s}".format(fmt) + ">" + fmt.format(*args) + "<") + def test_fmt(conv, fill, alignment, sign, prefix, width, precision, type, arg): - fmt = '{' + fmt = "{" if conv: - fmt += '!' + fmt += "!" fmt += conv - fmt += ':' + fmt += ":" if alignment: fmt += fill fmt += alignment @@ -19,88 +21,162 @@ def test_fmt(conv, fill, alignment, sign, prefix, width, precision, type, arg): fmt += prefix fmt += width if precision: - fmt += '.' + fmt += "." fmt += precision fmt += type - fmt += '}' - test(fmt, arg) - if fill == '0' and alignment == '=': - fmt = '{:' + fmt += "}" + test(fmt, arg) + if fill == "0" and alignment == "=": + fmt = "{:" fmt += sign fmt += prefix fmt += width if precision: - fmt += '.' + fmt += "." fmt += precision fmt += type - fmt += '}' + fmt += "}" test(fmt, arg) -eg_nums = (0.0, -0.0, 0.1, 1.234, 12.3459, 1.23456789, 123456789.0, -0.0, - -0.1, -1.234, -12.3459, 1e4, 1e-4, 1e5, 1e-5, 1e6, 1e-6, 1e10, - 1e37, -1e37, 1e-37, -1e-37, - 1.23456e8, 1.23456e7, 1.23456e6, 1.23456e5, 1.23456e4, 1.23456e3, 1.23456e2, 1.23456e1, 1.23456e0, - 1.23456e-1, 1.23456e-2, 1.23456e-3, 1.23456e-4, 1.23456e-5, 1.23456e-6, 1.23456e-7, 1.23456e-8, - -1.23456e8, -1.23456e7, -1.23456e6, -1.23456e5, -1.23456e4, -1.23456e3, -1.23456e2, -1.23456e1, -1.23456e0, - -1.23456e-1, -1.23456e-2, -1.23456e-3, -1.23456e-4, -1.23456e-5, -1.23456e-6, -1.23456e-7, -1.23456e-8) + +eg_nums = ( + 0.0, + -0.0, + 0.1, + 1.234, + 12.3459, + 1.23456789, + 123456789.0, + -0.0, + -0.1, + -1.234, + -12.3459, + 1e4, + 1e-4, + 1e5, + 1e-5, + 1e6, + 1e-6, + 1e10, + 1e37, + -1e37, + 1e-37, + -1e-37, + 1.23456e8, + 1.23456e7, + 1.23456e6, + 1.23456e5, + 1.23456e4, + 1.23456e3, + 1.23456e2, + 1.23456e1, + 1.23456e0, + 1.23456e-1, + 1.23456e-2, + 1.23456e-3, + 1.23456e-4, + 1.23456e-5, + 1.23456e-6, + 1.23456e-7, + 1.23456e-8, + -1.23456e8, + -1.23456e7, + -1.23456e6, + -1.23456e5, + -1.23456e4, + -1.23456e3, + -1.23456e2, + -1.23456e1, + -1.23456e0, + -1.23456e-1, + -1.23456e-2, + -1.23456e-3, + -1.23456e-4, + -1.23456e-5, + -1.23456e-6, + -1.23456e-7, + -1.23456e-8, +) if full_tests: - for type in ('e', 'E', 'g', 'G', 'n'): - for width in ('', '4', '6', '8', '10'): - for alignment in ('', '<', '>', '=', '^'): - for fill in ('', '@', '0', ' '): - for sign in ('', '+', '-', ' '): - for prec in ('', '1', '3', '6'): + for type in ("e", "E", "g", "G", "n"): + for width in ("", "4", "6", "8", "10"): + for alignment in ("", "<", ">", "=", "^"): + for fill in ("", "@", "0", " "): + for sign in ("", "+", "-", " "): + for prec in ("", "1", "3", "6"): for num in eg_nums: - test_fmt('', fill, alignment, sign, '', width, prec, type, num) + test_fmt("", fill, alignment, sign, "", width, prec, type, num) # Note: We use 1.23459 rather than 1.2345 because '{:3f}'.format(1.2345) # rounds differently than print("%.3f", 1.2345); -f_nums = (0.0, -0.0, 0.0001, 0.001, 0.01, 0.1, 1.0, 10.0, - 0.0012, 0.0123, 0.1234, 1.23459, 12.3456, - -0.0001, -0.001, -0.01, -0.1, -1.0, -10.0, - -0.0012, -0.0123, -0.1234, -1.23459, -12.3456) +f_nums = ( + 0.0, + -0.0, + 0.0001, + 0.001, + 0.01, + 0.1, + 1.0, + 10.0, + 0.0012, + 0.0123, + 0.1234, + 1.23459, + 12.3456, + -0.0001, + -0.001, + -0.01, + -0.1, + -1.0, + -10.0, + -0.0012, + -0.0123, + -0.1234, + -1.23459, + -12.3456, +) if full_tests: - for type in ('f', 'F'): - for width in ('', '4', '6', '8', '10'): - for alignment in ('', '<', '>', '=', '^'): - for fill in ('', ' ', '0', '@'): - for sign in ('', '+', '-', ' '): + for type in ("f", "F"): + for width in ("", "4", "6", "8", "10"): + for alignment in ("", "<", ">", "=", "^"): + for fill in ("", " ", "0", "@"): + for sign in ("", "+", "-", " "): # An empty precision defaults to 6, but when uPy is # configured to use a float, we can only use a # precision of 6 with numbers less than 10 and still # get results that compare to CPython (which uses # long doubles). - for prec in ('1', '2', '3'): + for prec in ("1", "2", "3"): for num in f_nums: - test_fmt('', fill, alignment, sign, '', width, prec, type, num) + test_fmt("", fill, alignment, sign, "", width, prec, type, num) for num in int_nums2: - test_fmt('', fill, alignment, sign, '', width, '', type, num) + test_fmt("", fill, alignment, sign, "", width, "", type, num) pct_nums1 = (0.1, 0.58, 0.99, -0.1, -0.58, -0.99) pct_nums2 = (True, False, 1, 0, -1) if full_tests: - type = '%' - for width in ('', '4', '6', '8', '10'): - for alignment in ('', '<', '>', '=', '^'): - for fill in ('', ' ', '0', '@'): - for sign in ('', '+', '-', ' '): + type = "%" + for width in ("", "4", "6", "8", "10"): + for alignment in ("", "<", ">", "=", "^"): + for fill in ("", " ", "0", "@"): + for sign in ("", "+", "-", " "): # An empty precision defaults to 6, but when uPy is # configured to use a float, we can only use a # precision of 6 with numbers less than 10 and still # get results that compare to CPython (which uses # long doubles). - for prec in ('1', '2', '3'): + for prec in ("1", "2", "3"): for num in pct_nums1: - test_fmt('', fill, alignment, sign, '', width, prec, type, num) + test_fmt("", fill, alignment, sign, "", width, prec, type, num) for num in pct_nums2: - test_fmt('', fill, alignment, sign, '', width, '', type, num) + test_fmt("", fill, alignment, sign, "", width, "", type, num) else: for num in pct_nums1: - test_fmt('', '', '', '', '', '', '1', '%', num) + test_fmt("", "", "", "", "", "", "1", "%", num) # We don't currently test a type of '' with floats (see the detailed comment # in objstr.c) diff --git a/tests/float/string_format_fp30.py b/tests/float/string_format_fp30.py index 77b2a52885..5f0b213daa 100644 --- a/tests/float/string_format_fp30.py +++ b/tests/float/string_format_fp30.py @@ -1,11 +1,12 @@ def test(fmt, *args): - print('{:8s}'.format(fmt) + '>' + fmt.format(*args) + '<') + print("{:8s}".format(fmt) + ">" + fmt.format(*args) + "<") + test("{:10.4}", 123.456) test("{:10.4e}", 123.456) test("{:10.4e}", -123.456) -#test("{:10.4f}", 123.456) -#test("{:10.4f}", -123.456) +# test("{:10.4f}", 123.456) +# test("{:10.4f}", -123.456) test("{:10.4g}", 123.456) test("{:10.4g}", -123.456) test("{:10.4n}", 123.456) @@ -15,8 +16,8 @@ test("{:g}", 300) test("{:10.4E}", 123.456) test("{:10.4E}", -123.456) -#test("{:10.4F}", 123.456) -#test("{:10.4F}", -123.456) +# test("{:10.4F}", 123.456) +# test("{:10.4F}", -123.456) test("{:10.4G}", 123.456) test("{:10.4G}", -123.456) @@ -25,17 +26,17 @@ test("{:06e}", float("-inf")) test("{:06e}", float("nan")) # The following fails right now -#test("{:10.1}", 0.0) +# test("{:10.1}", 0.0) print("%.0f" % (1.750000 % 0.08333333333)) # Below isn't compatible with single-precision float -#print("%.1f" % (1.750000 % 0.08333333333)) -#print("%.2f" % (1.750000 % 0.08333333333)) -#print("%.12f" % (1.750000 % 0.08333333333)) +# print("%.1f" % (1.750000 % 0.08333333333)) +# print("%.2f" % (1.750000 % 0.08333333333)) +# print("%.12f" % (1.750000 % 0.08333333333)) # tests for errors in format string try: - '{:10.1b}'.format(0.0) + "{:10.1b}".format(0.0) except ValueError: - print('ValueError') + print("ValueError") diff --git a/tests/float/string_format_modulo.py b/tests/float/string_format_modulo.py index aea534247c..0944615381 100644 --- a/tests/float/string_format_modulo.py +++ b/tests/float/string_format_modulo.py @@ -7,9 +7,9 @@ print("%u" % 1.0) # these 3 have different behaviour in Python 3.x versions # uPy raises a TypeError, following Python 3.5 (earlier versions don't) -#print("%x" % 18.0) -#print("%o" % 18.0) -#print("%X" % 18.0) +# print("%x" % 18.0) +# print("%o" % 18.0) +# print("%X" % 18.0) print("%e" % 1.23456) print("%E" % 1.23456) @@ -22,28 +22,28 @@ print("%06e" % float("inf")) print("%06e" % float("-inf")) print("%06e" % float("nan")) -print("%02.3d" % 123) # prec > width -print("%+f %+f" % (1.23, -1.23)) # float sign -print("% f % f" % (1.23, -1.23)) # float space sign -print("%0f" % -1.23) # negative number with 0 padding +print("%02.3d" % 123) # prec > width +print("%+f %+f" % (1.23, -1.23)) # float sign +print("% f % f" % (1.23, -1.23)) # float space sign +print("%0f" % -1.23) # negative number with 0 padding # numbers with large negative exponents -print('%f' % 1e-10) -print('%f' % 1e-20) -print('%f' % 1e-50) -print('%f' % 1e-100) -print('%f' % 1e-300) +print("%f" % 1e-10) +print("%f" % 1e-20) +print("%f" % 1e-50) +print("%f" % 1e-100) +print("%f" % 1e-300) # large decimal precision should be truncated and not overflow buffer # the output depends on the FP calculation so only first 2 digits are printed # (the 'g' with small e are printed using 'f' style, so need to be checked) -print(('%.40f' % 1e-300)[:2]) -print(('%.40g' % 1e-1)[:2]) -print(('%.40g' % 1e-2)[:2]) -print(('%.40g' % 1e-3)[:2]) -print(('%.40g' % 1e-4)[:2]) +print(("%.40f" % 1e-300)[:2]) +print(("%.40g" % 1e-1)[:2]) +print(("%.40g" % 1e-2)[:2]) +print(("%.40g" % 1e-3)[:2]) +print(("%.40g" % 1e-4)[:2]) -print("%.0g" % 1) # 0 precision 'g' +print("%.0g" % 1) # 0 precision 'g' -print('%.1e' % 9.99) # round up with positive exponent -print('%.1e' % 0.999) # round up with negative exponent +print("%.1e" % 9.99) # round up with positive exponent +print("%.1e" % 0.999) # round up with negative exponent diff --git a/tests/float/string_format_modulo2.py b/tests/float/string_format_modulo2.py index f6b1ae537d..b22021c5d0 100644 --- a/tests/float/string_format_modulo2.py +++ b/tests/float/string_format_modulo2.py @@ -1,24 +1,26 @@ # test formatting floats with large precision, that it doesn't overflow the buffer + def test(num, num_str): - if num == float('inf') or num == 0.0 and num_str != '0.0': + if num == float("inf") or num == 0.0 and num_str != "0.0": # skip numbers that overflow or underflow the FP precision return - for kind in ('e', 'f', 'g'): + for kind in ("e", "f", "g"): # check precision either side of the size of the buffer (32 bytes) for prec in range(23, 36, 2): - fmt = '%.' + '%d' % prec + kind + fmt = "%." + "%d" % prec + kind s = fmt % num check = abs(float(s) - num) if num > 1: check /= num if check > 1e-6: - print('FAIL', num_str, fmt, s, len(s), check) + print("FAIL", num_str, fmt, s, len(s), check) + # check pure zero -test(0.0, '0.0') +test(0.0, "0.0") # check some powers of 10, making sure to include exponents with 3 digits for e in range(-8, 8): num = pow(10, e) - test(num, '1e%d' % e) + test(num, "1e%d" % e) diff --git a/tests/float/string_format_modulo2_intbig.py b/tests/float/string_format_modulo2_intbig.py index 9992ba65d9..8110bc7f62 100644 --- a/tests/float/string_format_modulo2_intbig.py +++ b/tests/float/string_format_modulo2_intbig.py @@ -1,21 +1,23 @@ # test formatting floats with large precision, that it doesn't overflow the buffer + def test(num, num_str): - if num == float('inf') or num == 0.0 and num_str != '0.0': + if num == float("inf") or num == 0.0 and num_str != "0.0": # skip numbers that overflow or underflow the FP precision return - for kind in ('e', 'f', 'g'): + for kind in ("e", "f", "g"): # check precision either side of the size of the buffer (32 bytes) for prec in range(23, 36, 2): - fmt = '%.' + '%d' % prec + kind + fmt = "%." + "%d" % prec + kind s = fmt % num check = abs(float(s) - num) if num > 1: check /= num if check > 1e-6: - print('FAIL', num_str, fmt, s, len(s), check) + print("FAIL", num_str, fmt, s, len(s), check) + # check most powers of 10, making sure to include exponents with 3 digits for e in range(-101, 102): num = pow(10, e) - test(num, '1e%d' % e) + test(num, "1e%d" % e) diff --git a/tests/float/string_format_modulo3.py b/tests/float/string_format_modulo3.py index 5d26f25751..f9d9c43cdf 100644 --- a/tests/float/string_format_modulo3.py +++ b/tests/float/string_format_modulo3.py @@ -1,3 +1,3 @@ # uPy and CPython outputs differ for the following -print("%.1g" % -9.9) # round up 'g' with '-' sign -print("%.2g" % 99.9) # round up +print("%.1g" % -9.9) # round up 'g' with '-' sign +print("%.2g" % 99.9) # round up diff --git a/tests/float/true_value.py b/tests/float/true_value.py index df415f0031..4c8d2e5c82 100644 --- a/tests/float/true_value.py +++ b/tests/float/true_value.py @@ -3,5 +3,5 @@ if not 0.0: print("float 0") -if not 0+0j: +if not 0 + 0j: print("complex 0") diff --git a/tests/import/builtin_import.py b/tests/import/builtin_import.py index 157da98398..734498d1be 100644 --- a/tests/import/builtin_import.py +++ b/tests/import/builtin_import.py @@ -1,22 +1,22 @@ # test calling builtin import function # basic test -__import__('builtins') +__import__("builtins") # first arg should be a string try: __import__(1) except TypeError: - print('TypeError') + print("TypeError") # module name should not be empty try: __import__("") except ValueError: - print('ValueError') + print("ValueError") # level argument should be non-negative try: - __import__('xyz', None, None, None, -1) + __import__("xyz", None, None, None, -1) except ValueError: - print('ValueError') + print("ValueError") diff --git a/tests/import/gen_context.py b/tests/import/gen_context.py index 02f1531467..b7567cf02d 100644 --- a/tests/import/gen_context.py +++ b/tests/import/gen_context.py @@ -2,8 +2,10 @@ import gen_context2 GLOBAL = "GLOBAL" + def gen(): print(GLOBAL) yield 1 + gen_context2.call(gen()) diff --git a/tests/import/import1a.py b/tests/import/import1a.py index 16b2d4d30f..9d7d72ff77 100644 --- a/tests/import/import1a.py +++ b/tests/import/import1a.py @@ -1,2 +1,3 @@ import import1b + print(import1b.var) diff --git a/tests/import/import1b.py b/tests/import/import1b.py index be74eca094..8c9d15a71f 100644 --- a/tests/import/import1b.py +++ b/tests/import/import1b.py @@ -1,4 +1,5 @@ var = 123 + def throw(): raise ValueError diff --git a/tests/import/import2a.py b/tests/import/import2a.py index def6aeb6aa..8fb4905250 100644 --- a/tests/import/import2a.py +++ b/tests/import/import2a.py @@ -1,5 +1,7 @@ from import1b import var + print(var) from import1b import var as var2 + print(var2) diff --git a/tests/import/import3a.py b/tests/import/import3a.py index 2e9d41f71d..2fadd8a52b 100644 --- a/tests/import/import3a.py +++ b/tests/import/import3a.py @@ -1,2 +1,3 @@ from import1b import * + print(var) diff --git a/tests/import/import_file.py b/tests/import/import_file.py index cb9a88a706..90ec4e41e7 100644 --- a/tests/import/import_file.py +++ b/tests/import/import_file.py @@ -1,2 +1,3 @@ import import1b + print(import1b.__file__) diff --git a/tests/import/import_override.py b/tests/import/import_override.py index 6fe99009ee..029ebe54c1 100644 --- a/tests/import/import_override.py +++ b/tests/import/import_override.py @@ -1,11 +1,15 @@ # test overriding __import__ combined with importing from the filesystem + def custom_import(name, globals, locals, fromlist, level): - print('import', name, fromlist, level) + print("import", name, fromlist, level) + class M: var = 456 + return M + orig_import = __import__ try: __import__("builtins").__import__ = custom_import @@ -14,4 +18,4 @@ except AttributeError: raise SystemExit # import1a will be done via normal import which will import1b via our custom import -orig_import('import1a') +orig_import("import1a") diff --git a/tests/import/import_pkg1.py b/tests/import/import_pkg1.py index fe6e4473e3..5c1b2ef4c7 100644 --- a/tests/import/import_pkg1.py +++ b/tests/import/import_pkg1.py @@ -12,5 +12,6 @@ print(pkg_.mod is pkg.mod) # import using "as" import pkg.mod as mm + print(mm is pkg.mod) print(mm.foo()) diff --git a/tests/import/import_pkg3.py b/tests/import/import_pkg3.py index 0ee885b220..ec46979062 100644 --- a/tests/import/import_pkg3.py +++ b/tests/import/import_pkg3.py @@ -3,4 +3,5 @@ from pkg import mod print(mod.foo()) import pkg.mod + print(mod is pkg.mod) diff --git a/tests/import/import_star_error.py b/tests/import/import_star_error.py index 17e237b8c1..9e1757b6ef 100644 --- a/tests/import/import_star_error.py +++ b/tests/import/import_star_error.py @@ -2,12 +2,12 @@ # 'import *' is not allowed in function scope try: - exec('def foo(): from x import *') + exec("def foo(): from x import *") except SyntaxError as er: - print('function', 'SyntaxError') + print("function", "SyntaxError") # 'import *' is not allowed in class scope try: - exec('class C: from x import *') + exec("class C: from x import *") except SyntaxError as er: - print('class', 'SyntaxError') + print("class", "SyntaxError") diff --git a/tests/import/module_getattr.py b/tests/import/module_getattr.py index 4a18f414dd..df7a621815 100644 --- a/tests/import/module_getattr.py +++ b/tests/import/module_getattr.py @@ -10,13 +10,14 @@ except AttributeError: # define __getattr__ def __getattr__(attr): - if attr == 'does_not_exist': + if attr == "does_not_exist": return False raise AttributeError + # do feature test (will also test functionality if the feature exists) -if not hasattr(this, 'does_not_exist'): - print('SKIP') +if not hasattr(this, "does_not_exist"): + print("SKIP") raise SystemExit # check that __getattr__ works as expected diff --git a/tests/import/mpy_invalid.py b/tests/import/mpy_invalid.py index 6e9cbc9db9..d6d01e7f1f 100644 --- a/tests/import/mpy_invalid.py +++ b/tests/import/mpy_invalid.py @@ -5,6 +5,7 @@ import sys, uio try: uio.IOBase import uos + uos.mount except (ImportError, AttributeError): print("SKIP") @@ -15,8 +16,10 @@ class UserFile(uio.IOBase): def __init__(self, data): self.data = data self.pos = 0 + def read(self): return self.data + def readinto(self, buf): n = 0 while n < len(buf) and self.pos < len(self.data): @@ -24,6 +27,7 @@ class UserFile(uio.IOBase): n += 1 self.pos += 1 return n + def ioctl(self, req, arg): return 0 @@ -31,38 +35,42 @@ class UserFile(uio.IOBase): class UserFS: def __init__(self, files): self.files = files + def mount(self, readonly, mksfs): pass + def umount(self): pass + def stat(self, path): if path in self.files: return (32768, 0, 0, 0, 0, 0, 0, 0, 0, 0) raise OSError + def open(self, path, mode): return UserFile(self.files[path]) # these are the test .mpy files user_files = { - '/mod0.mpy': b'', # empty file - '/mod1.mpy': b'M', # too short header - '/mod2.mpy': b'M\x00\x00\x00', # bad version - '/mod3.mpy': b'M\x00\x00\x00\x7f', # qstr window too large + "/mod0.mpy": b"", # empty file + "/mod1.mpy": b"M", # too short header + "/mod2.mpy": b"M\x00\x00\x00", # bad version + "/mod3.mpy": b"M\x00\x00\x00\x7f", # qstr window too large } # create and mount a user filesystem -uos.mount(UserFS(user_files), '/userfs') -sys.path.append('/userfs') +uos.mount(UserFS(user_files), "/userfs") +sys.path.append("/userfs") # import .mpy files from the user filesystem for i in range(len(user_files)): - mod = 'mod%u' % i + mod = "mod%u" % i try: __import__(mod) except ValueError as er: - print(mod, 'ValueError', er) + print(mod, "ValueError", er) # unmount and undo path addition -uos.umount('/userfs') +uos.umount("/userfs") sys.path.pop() diff --git a/tests/import/mpy_native.py b/tests/import/mpy_native.py index 4ee537f4af..5d7bdab4a2 100644 --- a/tests/import/mpy_native.py +++ b/tests/import/mpy_native.py @@ -5,12 +5,13 @@ import sys, uio try: uio.IOBase import uos + uos.mount except (ImportError, AttributeError): print("SKIP") raise SystemExit -if not (sys.platform == 'linux' and sys.maxsize > 2 ** 32): +if not (sys.platform == "linux" and sys.maxsize > 2 ** 32): print("SKIP") raise SystemExit @@ -19,8 +20,10 @@ class UserFile(uio.IOBase): def __init__(self, data): self.data = data self.pos = 0 + def read(self): return self.data + def readinto(self, buf): n = 0 while n < len(buf) and self.pos < len(self.data): @@ -28,6 +31,7 @@ class UserFile(uio.IOBase): n += 1 self.pos += 1 return n + def ioctl(self, req, arg): return 0 @@ -35,19 +39,24 @@ class UserFile(uio.IOBase): class UserFS: def __init__(self, files): self.files = files + def mount(self, readonly, mksfs): pass + def umount(self): pass + def stat(self, path): if path in self.files: return (32768, 0, 0, 0, 0, 0, 0, 0, 0, 0) raise OSError + def open(self, path, mode): return UserFile(self.files[path]) # these are the test .mpy files +# fmt: off user_files = { # bad architecture '/mod0.mpy': b'M\x05\xff\x00\x10', @@ -95,20 +104,21 @@ user_files = { b'\x03\x01\x00' # dummy relocation of rodata ), } +# fmt: on # create and mount a user filesystem -uos.mount(UserFS(user_files), '/userfs') -sys.path.append('/userfs') +uos.mount(UserFS(user_files), "/userfs") +sys.path.append("/userfs") # import .mpy files from the user filesystem for i in range(len(user_files)): - mod = 'mod%u' % i + mod = "mod%u" % i try: __import__(mod) - print(mod, 'OK') + print(mod, "OK") except ValueError as er: - print(mod, 'ValueError', er) + print(mod, "ValueError", er) # unmount and undo path addition -uos.umount('/userfs') +uos.umount("/userfs") sys.path.pop() diff --git a/tests/import/pkg3/mod2.py b/tests/import/pkg3/mod2.py index 67f43bad52..37721faaf3 100644 --- a/tests/import/pkg3/mod2.py +++ b/tests/import/pkg3/mod2.py @@ -1,5 +1,6 @@ print("mod2 __name__:", __name__) print("in mod2") + def foo(): print("mod2.foo()") diff --git a/tests/import/pkg6/__init__.py b/tests/import/pkg6/__init__.py index 923531c1b9..5215da2ec4 100644 --- a/tests/import/pkg6/__init__.py +++ b/tests/import/pkg6/__init__.py @@ -1,2 +1,3 @@ from .x import * -print('init') + +print("init") diff --git a/tests/import/pkg6/x/__init__.py b/tests/import/pkg6/x/__init__.py index 6b8b84d0ee..80817917da 100644 --- a/tests/import/pkg6/x/__init__.py +++ b/tests/import/pkg6/x/__init__.py @@ -1,2 +1,3 @@ from .y import * -print('x') + +print("x") diff --git a/tests/import/pkg6/x/y.py b/tests/import/pkg6/x/y.py index e8d863c6cd..0abc82404d 100644 --- a/tests/import/pkg6/x/y.py +++ b/tests/import/pkg6/x/y.py @@ -1 +1 @@ -print('y') +print("y") diff --git a/tests/import/pkg7/mod1.py b/tests/import/pkg7/mod1.py index 6b574114d1..0a5eb15052 100644 --- a/tests/import/pkg7/mod1.py +++ b/tests/import/pkg7/mod1.py @@ -1,2 +1,2 @@ -print('mod1') -foo = 'mod1.foo' +print("mod1") +foo = "mod1.foo" diff --git a/tests/import/pkg7/mod2.py b/tests/import/pkg7/mod2.py index 039a5d1749..657a6fb523 100644 --- a/tests/import/pkg7/mod2.py +++ b/tests/import/pkg7/mod2.py @@ -1,2 +1,2 @@ -print('mod2') -bar = 'mod2.bar' +print("mod2") +bar = "mod2.bar" diff --git a/tests/import/pkg7/subpkg1/subpkg2/mod3.py b/tests/import/pkg7/subpkg1/subpkg2/mod3.py index c73e2081f0..0aa916d208 100644 --- a/tests/import/pkg7/subpkg1/subpkg2/mod3.py +++ b/tests/import/pkg7/subpkg1/subpkg2/mod3.py @@ -1,5 +1,6 @@ from ... import mod1 from ...mod2 import bar + print(mod1.foo) print(bar) @@ -7,4 +8,4 @@ print(bar) try: from .... import mod1 except ValueError: - print('ValueError') + print("ValueError") diff --git a/tests/import/pkg8/mod.py b/tests/import/pkg8/mod.py index b98f02ce6e..3d3d53a162 100644 --- a/tests/import/pkg8/mod.py +++ b/tests/import/pkg8/mod.py @@ -1 +1 @@ -print('foo') +print("foo") diff --git a/tests/import/try_module.py b/tests/import/try_module.py index 03a9db15b5..7c97df28b3 100644 --- a/tests/import/try_module.py +++ b/tests/import/try_module.py @@ -2,8 +2,10 @@ # its namespace stick and namespace of current module not coming back. import import1b + def func1(): - print('func1') + print("func1") + def func2(): try: @@ -12,4 +14,5 @@ def func2(): pass func1() + func2() diff --git a/tests/inlineasm/asmargs.py b/tests/inlineasm/asmargs.py index 047d9ed420..3b03f15103 100644 --- a/tests/inlineasm/asmargs.py +++ b/tests/inlineasm/asmargs.py @@ -1,29 +1,44 @@ # test passing arguments + @micropython.asm_thumb def arg0(): mov(r0, 1) + + print(arg0()) + @micropython.asm_thumb def arg1(r0): add(r0, r0, 1) + + print(arg1(1)) + @micropython.asm_thumb def arg2(r0, r1): add(r0, r0, r1) + + print(arg2(1, 2)) + @micropython.asm_thumb def arg3(r0, r1, r2): add(r0, r0, r1) add(r0, r0, r2) + + print(arg3(1, 2, 3)) + @micropython.asm_thumb def arg4(r0, r1, r2, r3): add(r0, r0, r1) add(r0, r0, r2) add(r0, r0, r3) + + print(arg4(1, 2, 3, 4)) diff --git a/tests/inlineasm/asmbcc.py b/tests/inlineasm/asmbcc.py index 540fa6591f..08967d48c7 100644 --- a/tests/inlineasm/asmbcc.py +++ b/tests/inlineasm/asmbcc.py @@ -1,6 +1,7 @@ # test bcc instructions # at the moment only tests beq, narrow and wide versions + @micropython.asm_thumb def f(r0): mov(r1, r0) @@ -21,6 +22,7 @@ def f(r0): label(end) + print(f(0)) print(f(1)) print(f(2)) diff --git a/tests/inlineasm/asmbitops.py b/tests/inlineasm/asmbitops.py index 8cf92b301f..d1c8a98235 100644 --- a/tests/inlineasm/asmbitops.py +++ b/tests/inlineasm/asmbitops.py @@ -2,12 +2,15 @@ def clz(r0): clz(r0, r0) -print(clz(0xf0)) + +print(clz(0xF0)) print(clz(0x8000)) + @micropython.asm_thumb def rbit(r0): rbit(r0, r0) -print(hex(rbit(0xf0))) + +print(hex(rbit(0xF0))) print(hex(rbit(0x8000))) diff --git a/tests/inlineasm/asmblbx.py b/tests/inlineasm/asmblbx.py index d08c0ed6b3..43585dddcc 100644 --- a/tests/inlineasm/asmblbx.py +++ b/tests/inlineasm/asmblbx.py @@ -1,5 +1,6 @@ # test bl and bx instructions + @micropython.asm_thumb def f(r0): # jump over the internal functions @@ -17,5 +18,6 @@ def f(r0): bl(func1) bl(func2) + print(f(0)) print(f(1)) diff --git a/tests/inlineasm/asmconst.py b/tests/inlineasm/asmconst.py index 299a25093c..8412dd2c72 100644 --- a/tests/inlineasm/asmconst.py +++ b/tests/inlineasm/asmconst.py @@ -1,8 +1,11 @@ # test constants in assembler + @micropython.asm_thumb def c1(): - movwt(r0, 0xffffffff) - movwt(r1, 0xf0000000) + movwt(r0, 0xFFFFFFFF) + movwt(r1, 0xF0000000) sub(r0, r0, r1) + + print(hex(c1())) diff --git a/tests/inlineasm/asmdiv.py b/tests/inlineasm/asmdiv.py index b97d566eb5..c278463846 100644 --- a/tests/inlineasm/asmdiv.py +++ b/tests/inlineasm/asmdiv.py @@ -2,15 +2,17 @@ def sdiv(r0, r1): sdiv(r0, r0, r1) + @micropython.asm_thumb def udiv(r0, r1): udiv(r0, r0, r1) + print(sdiv(1234, 3)) print(sdiv(-1234, 3)) print(sdiv(1234, -3)) print(sdiv(-1234, -3)) print(udiv(1234, 3)) -print(udiv(0xffffffff, 0x7fffffff)) -print(udiv(0xffffffff, 0xffffffff)) +print(udiv(0xFFFFFFFF, 0x7FFFFFFF)) +print(udiv(0xFFFFFFFF, 0xFFFFFFFF)) diff --git a/tests/inlineasm/asmfpaddsub.py b/tests/inlineasm/asmfpaddsub.py index b5fcecb6ce..f69c89cdc6 100644 --- a/tests/inlineasm/asmfpaddsub.py +++ b/tests/inlineasm/asmfpaddsub.py @@ -1,4 +1,4 @@ -@micropython.asm_thumb # r0 = r0+r1-r2 +@micropython.asm_thumb # r0 = r0+r1-r2 def add_sub(r0, r1, r2): vmov(s0, r0) vcvt_f32_s32(s0, s0) @@ -11,5 +11,5 @@ def add_sub(r0, r1, r2): vcvt_s32_f32(s31, s0) vmov(r0, s31) -print(add_sub(100, 20, 30)) +print(add_sub(100, 20, 30)) diff --git a/tests/inlineasm/asmfpcmp.py b/tests/inlineasm/asmfpcmp.py index d4fa1f2410..47fd99a347 100644 --- a/tests/inlineasm/asmfpcmp.py +++ b/tests/inlineasm/asmfpcmp.py @@ -1,4 +1,4 @@ -@micropython.asm_thumb # test vcmp, vmrs +@micropython.asm_thumb # test vcmp, vmrs def f(r0, r1): vmov(s0, r0) vcvt_f32_s32(s0, s0) @@ -9,6 +9,7 @@ def f(r0, r1): mov(r1, 28) lsr(r0, r1) -print(f(0,1)) -print(f(1,1)) -print(f(1,0)) + +print(f(0, 1)) +print(f(1, 1)) +print(f(1, 0)) diff --git a/tests/inlineasm/asmfpldrstr.py b/tests/inlineasm/asmfpldrstr.py index 0efb50bb0e..96cd0c23eb 100644 --- a/tests/inlineasm/asmfpldrstr.py +++ b/tests/inlineasm/asmfpldrstr.py @@ -1,12 +1,14 @@ import uarray as array -@micropython.asm_thumb # test vldr, vstr + + +@micropython.asm_thumb # test vldr, vstr def arrayadd(r0): vldr(s0, [r0, 0]) vldr(s1, [r0, 4]) vadd(s2, s0, s1) vstr(s2, [r0, 8]) + z = array.array("f", [2, 4, 10]) arrayadd(z) print(z[2]) - diff --git a/tests/inlineasm/asmfpmuldiv.py b/tests/inlineasm/asmfpmuldiv.py index edf9511bcd..930ddd053c 100644 --- a/tests/inlineasm/asmfpmuldiv.py +++ b/tests/inlineasm/asmfpmuldiv.py @@ -1,4 +1,4 @@ -@micropython.asm_thumb # r0 = (int)(r0*r1/r2) +@micropython.asm_thumb # r0 = (int)(r0*r1/r2) def muldiv(r0, r1, r2): vmov(s0, r0) vcvt_f32_s32(s0, s0) @@ -11,5 +11,5 @@ def muldiv(r0, r1, r2): vcvt_s32_f32(s31, s8) vmov(r0, s31) -print(muldiv(100, 10, 50)) +print(muldiv(100, 10, 50)) diff --git a/tests/inlineasm/asmfpsqrt.py b/tests/inlineasm/asmfpsqrt.py index f2c2d3a954..519fde4fcc 100644 --- a/tests/inlineasm/asmfpsqrt.py +++ b/tests/inlineasm/asmfpsqrt.py @@ -1,5 +1,5 @@ # test vsqrt, vneg -@micropython.asm_thumb # r0 = -(int)(sqrt(r0)*r1) +@micropython.asm_thumb # r0 = -(int)(sqrt(r0)*r1) def sqrt_test(r0, r1): vmov(s1, r0) vcvt_f32_s32(s1, s1) @@ -11,5 +11,5 @@ def sqrt_test(r0, r1): vcvt_s32_f32(s31, s7) vmov(r0, s31) -print(sqrt_test(256, 10)) +print(sqrt_test(256, 10)) diff --git a/tests/inlineasm/asmit.py b/tests/inlineasm/asmit.py index 57bfcc7f9a..640258e7c8 100644 --- a/tests/inlineasm/asmit.py +++ b/tests/inlineasm/asmit.py @@ -1,16 +1,22 @@ # test it instruction + @micropython.asm_thumb def f(r0, r1): cmp(r0, r1) it(eq) mov(r0, 100) + + print(f(0, 0), f(1, 2)) + @micropython.asm_thumb def g(r0, r1): cmp(r0, r1) ite(eq) mov(r0, 100) mov(r0, 200) + + print(g(0, 0), g(0, 1)) diff --git a/tests/inlineasm/asmpushpop.py b/tests/inlineasm/asmpushpop.py index c9005434ba..74e729dfa2 100644 --- a/tests/inlineasm/asmpushpop.py +++ b/tests/inlineasm/asmpushpop.py @@ -5,4 +5,5 @@ def f(r0, r1, r2): pop({r0}) pop({r1, r2}) + print(f(0, 1, 2)) diff --git a/tests/inlineasm/asmrettype.py b/tests/inlineasm/asmrettype.py index f1918696ee..95068795df 100644 --- a/tests/inlineasm/asmrettype.py +++ b/tests/inlineasm/asmrettype.py @@ -1,21 +1,33 @@ # test return type of inline asm + @micropython.asm_thumb def ret_obj(r0) -> object: pass + + ret_obj(print)(1) + @micropython.asm_thumb def ret_bool(r0) -> bool: pass + + print(ret_bool(0), ret_bool(1)) + @micropython.asm_thumb def ret_int(r0) -> int: lsl(r0, r0, 29) + + print(ret_int(0), hex(ret_int(1)), hex(ret_int(2)), hex(ret_int(4))) + @micropython.asm_thumb def ret_uint(r0) -> uint: lsl(r0, r0, 29) + + print(ret_uint(0), hex(ret_uint(1)), hex(ret_uint(2)), hex(ret_uint(4))) diff --git a/tests/inlineasm/asmshift.py b/tests/inlineasm/asmshift.py index 0df2187347..ba4c21b3f2 100644 --- a/tests/inlineasm/asmshift.py +++ b/tests/inlineasm/asmshift.py @@ -1,29 +1,46 @@ @micropython.asm_thumb def lsl1(r0): lsl(r0, r0, 1) + + print(hex(lsl1(0x123))) + @micropython.asm_thumb def lsl23(r0): lsl(r0, r0, 23) + + print(hex(lsl23(1))) + @micropython.asm_thumb def lsr1(r0): lsr(r0, r0, 1) + + print(hex(lsr1(0x123))) + @micropython.asm_thumb def lsr31(r0): lsr(r0, r0, 31) + + print(hex(lsr31(0x80000000))) + @micropython.asm_thumb def asr1(r0): asr(r0, r0, 1) + + print(hex(asr1(0x123))) + @micropython.asm_thumb def asr31(r0): asr(r0, r0, 31) + + print(hex(asr31(0x80000000))) diff --git a/tests/inlineasm/asmspecialregs.py b/tests/inlineasm/asmspecialregs.py index edfe4c2bd7..053ae29a4d 100644 --- a/tests/inlineasm/asmspecialregs.py +++ b/tests/inlineasm/asmspecialregs.py @@ -2,10 +2,11 @@ def getIPSR(): mrs(r0, IPSR) + @micropython.asm_thumb def getBASEPRI(): mrs(r0, BASEPRI) + print(getBASEPRI()) print(getIPSR()) - diff --git a/tests/inlineasm/asmsum.py b/tests/inlineasm/asmsum.py index 93d8eec8dc..6535a495d4 100644 --- a/tests/inlineasm/asmsum.py +++ b/tests/inlineasm/asmsum.py @@ -22,6 +22,7 @@ def asm_sum_words(r0, r1): mov(r0, r2) + @micropython.asm_thumb def asm_sum_bytes(r0, r1): @@ -46,16 +47,17 @@ def asm_sum_bytes(r0, r1): mov(r0, r2) + import uarray as array -b = array.array('l', (100, 200, 300, 400)) +b = array.array("l", (100, 200, 300, 400)) n = asm_sum_words(len(b), b) print(b, n) -b = array.array('b', (10, 20, 30, 40, 50, 60, 70, 80)) +b = array.array("b", (10, 20, 30, 40, 50, 60, 70, 80)) n = asm_sum_bytes(len(b), b) print(b, n) -b = b'\x01\x02\x03\x04' +b = b"\x01\x02\x03\x04" n = asm_sum_bytes(len(b), b) print(b, n) diff --git a/tests/internal_bench/arrayop-1-list_inplace.py b/tests/internal_bench/arrayop-1-list_inplace.py index 0ee1ef2eca..b29593c1a1 100644 --- a/tests/internal_bench/arrayop-1-list_inplace.py +++ b/tests/internal_bench/arrayop-1-list_inplace.py @@ -3,10 +3,12 @@ # method is that it doesn't require any extra memory allocation. import bench + def test(num): - for i in iter(range(num//10000)): + for i in iter(range(num // 10000)): arr = [0] * 1000 for i in range(len(arr)): arr[i] += 1 + bench.run(test) diff --git a/tests/internal_bench/arrayop-2-list_map.py b/tests/internal_bench/arrayop-2-list_map.py index 9d5095c53a..5959d3f469 100644 --- a/tests/internal_bench/arrayop-2-list_map.py +++ b/tests/internal_bench/arrayop-2-list_map.py @@ -4,9 +4,11 @@ # array). On the other hand, input array stays intact. import bench + def test(num): - for i in iter(range(num//10000)): + for i in iter(range(num // 10000)): arr = [0] * 1000 arr2 = list(map(lambda x: x + 1, arr)) + bench.run(test) diff --git a/tests/internal_bench/arrayop-3-bytearray_inplace.py b/tests/internal_bench/arrayop-3-bytearray_inplace.py index a6d6280705..fbbade2cac 100644 --- a/tests/internal_bench/arrayop-3-bytearray_inplace.py +++ b/tests/internal_bench/arrayop-3-bytearray_inplace.py @@ -3,10 +3,12 @@ # method is that it doesn't require any extra memory allocation. import bench + def test(num): - for i in iter(range(num//10000)): + for i in iter(range(num // 10000)): arr = bytearray(b"\0" * 1000) for i in range(len(arr)): arr[i] += 1 + bench.run(test) diff --git a/tests/internal_bench/arrayop-4-bytearray_map.py b/tests/internal_bench/arrayop-4-bytearray_map.py index 1b92a40961..8fa9879705 100644 --- a/tests/internal_bench/arrayop-4-bytearray_map.py +++ b/tests/internal_bench/arrayop-4-bytearray_map.py @@ -4,9 +4,11 @@ # array). On the other hand, input array stays intact. import bench + def test(num): - for i in iter(range(num//10000)): + for i in iter(range(num // 10000)): arr = bytearray(b"\0" * 1000) arr2 = bytearray(map(lambda x: x + 1, arr)) + bench.run(test) diff --git a/tests/internal_bench/bench.py b/tests/internal_bench/bench.py index 0cd40a93fc..d7087e0e09 100644 --- a/tests/internal_bench/bench.py +++ b/tests/internal_bench/bench.py @@ -3,6 +3,7 @@ import time ITERS = 20000000 + def run(f): t = time.time() f(ITERS) diff --git a/tests/internal_bench/bytealloc-1-bytes_n.py b/tests/internal_bench/bytealloc-1-bytes_n.py index 4a4bbc6fae..8b8120a530 100644 --- a/tests/internal_bench/bytealloc-1-bytes_n.py +++ b/tests/internal_bench/bytealloc-1-bytes_n.py @@ -1,7 +1,9 @@ import bench + def test(num): for i in iter(range(num // 1000)): bytes(10000) + bench.run(test) diff --git a/tests/internal_bench/bytealloc-2-repeat.py b/tests/internal_bench/bytealloc-2-repeat.py index 786a804622..8d6b5d5289 100644 --- a/tests/internal_bench/bytealloc-2-repeat.py +++ b/tests/internal_bench/bytealloc-2-repeat.py @@ -1,7 +1,9 @@ import bench + def test(num): for i in iter(range(num // 1000)): b"\0" * 10000 + bench.run(test) diff --git a/tests/internal_bench/bytebuf-1-inplace.py b/tests/internal_bench/bytebuf-1-inplace.py index 7e7d9391cc..e1b6016a57 100644 --- a/tests/internal_bench/bytebuf-1-inplace.py +++ b/tests/internal_bench/bytebuf-1-inplace.py @@ -2,10 +2,12 @@ # Inplace - the most memory efficient way import bench + def test(num): - for i in iter(range(num//10000)): + for i in iter(range(num // 10000)): ba = bytearray(b"\0" * 1000) for i in range(len(ba)): ba[i] += 1 + bench.run(test) diff --git a/tests/internal_bench/bytebuf-2-join_map_bytes.py b/tests/internal_bench/bytebuf-2-join_map_bytes.py index daa622991f..9ecee47978 100644 --- a/tests/internal_bench/bytebuf-2-join_map_bytes.py +++ b/tests/internal_bench/bytebuf-2-join_map_bytes.py @@ -4,9 +4,11 @@ # this is slowest way to do it. import bench + def test(num): - for i in iter(range(num//10000)): + for i in iter(range(num // 10000)): ba = bytearray(b"\0" * 1000) - ba2 = b''.join(map(lambda x:bytes([x + 1]), ba)) + ba2 = b"".join(map(lambda x: bytes([x + 1]), ba)) + bench.run(test) diff --git a/tests/internal_bench/bytebuf-3-bytarray_map.py b/tests/internal_bench/bytebuf-3-bytarray_map.py index 078d08e99b..2752d4e784 100644 --- a/tests/internal_bench/bytebuf-3-bytarray_map.py +++ b/tests/internal_bench/bytebuf-3-bytarray_map.py @@ -2,9 +2,11 @@ # No joins, but still map(). import bench + def test(num): - for i in iter(range(num//10000)): + for i in iter(range(num // 10000)): ba = bytearray(b"\0" * 1000) ba2 = bytearray(map(lambda x: x + 1, ba)) + bench.run(test) diff --git a/tests/internal_bench/from_iter-1-list_bound.py b/tests/internal_bench/from_iter-1-list_bound.py index d209daecc5..384d52903f 100644 --- a/tests/internal_bench/from_iter-1-list_bound.py +++ b/tests/internal_bench/from_iter-1-list_bound.py @@ -1,8 +1,10 @@ import bench + def test(num): - for i in iter(range(num//10000)): + for i in iter(range(num // 10000)): l = [0] * 1000 l2 = list(l) + bench.run(test) diff --git a/tests/internal_bench/from_iter-2-list_unbound.py b/tests/internal_bench/from_iter-2-list_unbound.py index be019c52fe..98e22d6813 100644 --- a/tests/internal_bench/from_iter-2-list_unbound.py +++ b/tests/internal_bench/from_iter-2-list_unbound.py @@ -1,8 +1,10 @@ import bench + def test(num): - for i in iter(range(num//10000)): + for i in iter(range(num // 10000)): l = [0] * 1000 l2 = list(map(lambda x: x, l)) + bench.run(test) diff --git a/tests/internal_bench/from_iter-3-tuple_bound.py b/tests/internal_bench/from_iter-3-tuple_bound.py index 7b7fa36c6e..f052f6deea 100644 --- a/tests/internal_bench/from_iter-3-tuple_bound.py +++ b/tests/internal_bench/from_iter-3-tuple_bound.py @@ -1,8 +1,10 @@ import bench + def test(num): - for i in iter(range(num//10000)): + for i in iter(range(num // 10000)): l = [0] * 1000 l2 = tuple(l) + bench.run(test) diff --git a/tests/internal_bench/from_iter-4-tuple_unbound.py b/tests/internal_bench/from_iter-4-tuple_unbound.py index 7c7f134c85..ff9d1b4df5 100644 --- a/tests/internal_bench/from_iter-4-tuple_unbound.py +++ b/tests/internal_bench/from_iter-4-tuple_unbound.py @@ -1,8 +1,10 @@ import bench + def test(num): - for i in iter(range(num//10000)): + for i in iter(range(num // 10000)): l = [0] * 1000 l2 = tuple(map(lambda x: x, l)) + bench.run(test) diff --git a/tests/internal_bench/from_iter-5-bytes_bound.py b/tests/internal_bench/from_iter-5-bytes_bound.py index b793a3207e..967cb99eea 100644 --- a/tests/internal_bench/from_iter-5-bytes_bound.py +++ b/tests/internal_bench/from_iter-5-bytes_bound.py @@ -1,8 +1,10 @@ import bench + def test(num): - for i in iter(range(num//10000)): + for i in iter(range(num // 10000)): l = [0] * 1000 l2 = bytes(l) + bench.run(test) diff --git a/tests/internal_bench/from_iter-6-bytes_unbound.py b/tests/internal_bench/from_iter-6-bytes_unbound.py index 20aa556277..b855019160 100644 --- a/tests/internal_bench/from_iter-6-bytes_unbound.py +++ b/tests/internal_bench/from_iter-6-bytes_unbound.py @@ -1,8 +1,10 @@ import bench + def test(num): - for i in iter(range(num//10000)): + for i in iter(range(num // 10000)): l = [0] * 1000 l2 = bytes(map(lambda x: x, l)) + bench.run(test) diff --git a/tests/internal_bench/from_iter-7-bytearray_bound.py b/tests/internal_bench/from_iter-7-bytearray_bound.py index 72001a05c7..d0c4c65a74 100644 --- a/tests/internal_bench/from_iter-7-bytearray_bound.py +++ b/tests/internal_bench/from_iter-7-bytearray_bound.py @@ -1,8 +1,10 @@ import bench + def test(num): - for i in iter(range(num//10000)): + for i in iter(range(num // 10000)): l = [0] * 1000 l2 = bytearray(l) + bench.run(test) diff --git a/tests/internal_bench/from_iter-8-bytearray_unbound.py b/tests/internal_bench/from_iter-8-bytearray_unbound.py index e2263b8ef9..aec2e65adf 100644 --- a/tests/internal_bench/from_iter-8-bytearray_unbound.py +++ b/tests/internal_bench/from_iter-8-bytearray_unbound.py @@ -1,8 +1,10 @@ import bench + def test(num): - for i in iter(range(num//10000)): + for i in iter(range(num // 10000)): l = [0] * 1000 l2 = bytearray(map(lambda x: x, l)) + bench.run(test) diff --git a/tests/internal_bench/func_args-1.1-pos_1.py b/tests/internal_bench/func_args-1.1-pos_1.py index eee0ea8289..cadb17768c 100644 --- a/tests/internal_bench/func_args-1.1-pos_1.py +++ b/tests/internal_bench/func_args-1.1-pos_1.py @@ -1,10 +1,13 @@ import bench + def func(a): pass + def test(num): for i in iter(range(num)): func(i) + bench.run(test) diff --git a/tests/internal_bench/func_args-1.2-pos_3.py b/tests/internal_bench/func_args-1.2-pos_3.py index 7e03ee2f85..12010d0150 100644 --- a/tests/internal_bench/func_args-1.2-pos_3.py +++ b/tests/internal_bench/func_args-1.2-pos_3.py @@ -1,10 +1,13 @@ import bench + def func(a, b, c): pass + def test(num): for i in iter(range(num)): func(i, i, i) + bench.run(test) diff --git a/tests/internal_bench/func_args-2-pos_default_2_of_3.py b/tests/internal_bench/func_args-2-pos_default_2_of_3.py index 1fa0fbda59..4dc5650902 100644 --- a/tests/internal_bench/func_args-2-pos_default_2_of_3.py +++ b/tests/internal_bench/func_args-2-pos_default_2_of_3.py @@ -1,10 +1,13 @@ import bench + def func(a, b=1, c=2): pass + def test(num): for i in iter(range(num)): func(i) + bench.run(test) diff --git a/tests/internal_bench/func_args-3.1-kw_1.py b/tests/internal_bench/func_args-3.1-kw_1.py index 7bc81e5bea..18252570c1 100644 --- a/tests/internal_bench/func_args-3.1-kw_1.py +++ b/tests/internal_bench/func_args-3.1-kw_1.py @@ -1,10 +1,13 @@ import bench + def func(a): pass + def test(num): for i in iter(range(num)): func(a=i) + bench.run(test) diff --git a/tests/internal_bench/func_args-3.2-kw_3.py b/tests/internal_bench/func_args-3.2-kw_3.py index 7f95106841..deac15cb41 100644 --- a/tests/internal_bench/func_args-3.2-kw_3.py +++ b/tests/internal_bench/func_args-3.2-kw_3.py @@ -1,10 +1,13 @@ import bench + def func(a, b, c): pass + def test(num): for i in iter(range(num)): func(c=i, b=i, a=i) + bench.run(test) diff --git a/tests/internal_bench/func_builtin-1-enum_pos.py b/tests/internal_bench/func_builtin-1-enum_pos.py index 20935164e8..c7c148df10 100644 --- a/tests/internal_bench/func_builtin-1-enum_pos.py +++ b/tests/internal_bench/func_builtin-1-enum_pos.py @@ -1,7 +1,9 @@ import bench + def test(num): - for i in iter(range(num//20)): + for i in iter(range(num // 20)): enumerate([1, 2], 1) + bench.run(test) diff --git a/tests/internal_bench/func_builtin-2-enum_kw.py b/tests/internal_bench/func_builtin-2-enum_kw.py index 6c5e44419c..a25ab241c6 100644 --- a/tests/internal_bench/func_builtin-2-enum_kw.py +++ b/tests/internal_bench/func_builtin-2-enum_kw.py @@ -1,7 +1,9 @@ import bench + def test(num): - for i in iter(range(num//20)): + for i in iter(range(num // 20)): enumerate(iterable=[1, 2], start=1) + bench.run(test) diff --git a/tests/internal_bench/funcall-1-inline.py b/tests/internal_bench/funcall-1-inline.py index fbeb79630d..8c3f0ccd59 100644 --- a/tests/internal_bench/funcall-1-inline.py +++ b/tests/internal_bench/funcall-1-inline.py @@ -2,8 +2,10 @@ # Establish a baseline for performing a trivial operation inline import bench + def test(num): for i in iter(range(num)): a = i + 1 + bench.run(test) diff --git a/tests/internal_bench/funcall-2-funcall.py b/tests/internal_bench/funcall-2-funcall.py index d5c36c60aa..a245258040 100644 --- a/tests/internal_bench/funcall-2-funcall.py +++ b/tests/internal_bench/funcall-2-funcall.py @@ -2,11 +2,14 @@ # Perform the same trivial operation as global function call import bench + def f(x): return x + 1 + def test(num): for i in iter(range(num)): a = f(i) + bench.run(test) diff --git a/tests/internal_bench/funcall-3-funcall-local.py b/tests/internal_bench/funcall-3-funcall-local.py index 1a6d728c63..d922888685 100644 --- a/tests/internal_bench/funcall-3-funcall-local.py +++ b/tests/internal_bench/funcall-3-funcall-local.py @@ -5,12 +5,15 @@ # variables are accessed by offset, not by name) import bench + def f(x): return x + 1 + def test(num): f_ = f for i in iter(range(num)): a = f_(i) + bench.run(test) diff --git a/tests/internal_bench/loop_count-1-range.py b/tests/internal_bench/loop_count-1-range.py index e22adf6cbe..fdb11eaac6 100644 --- a/tests/internal_bench/loop_count-1-range.py +++ b/tests/internal_bench/loop_count-1-range.py @@ -1,7 +1,9 @@ import bench + def test(num): for i in range(num): pass + bench.run(test) diff --git a/tests/internal_bench/loop_count-2-range_iter.py b/tests/internal_bench/loop_count-2-range_iter.py index fe4a3857e1..4189bf329d 100644 --- a/tests/internal_bench/loop_count-2-range_iter.py +++ b/tests/internal_bench/loop_count-2-range_iter.py @@ -1,7 +1,9 @@ import bench + def test(num): for i in iter(range(num)): pass + bench.run(test) diff --git a/tests/internal_bench/loop_count-3-while_up.py b/tests/internal_bench/loop_count-3-while_up.py index 1ab8054a0f..22c64403bf 100644 --- a/tests/internal_bench/loop_count-3-while_up.py +++ b/tests/internal_bench/loop_count-3-while_up.py @@ -1,8 +1,10 @@ import bench + def test(num): i = 0 while i < num: i += 1 + bench.run(test) diff --git a/tests/internal_bench/loop_count-4-while_down_gt.py b/tests/internal_bench/loop_count-4-while_down_gt.py index de8dee2ca9..47b004c2bd 100644 --- a/tests/internal_bench/loop_count-4-while_down_gt.py +++ b/tests/internal_bench/loop_count-4-while_down_gt.py @@ -1,7 +1,9 @@ import bench + def test(num): while num > 0: num -= 1 + bench.run(test) diff --git a/tests/internal_bench/loop_count-5-while_down_ne.py b/tests/internal_bench/loop_count-5-while_down_ne.py index b9a1af414b..419c817c8f 100644 --- a/tests/internal_bench/loop_count-5-while_down_ne.py +++ b/tests/internal_bench/loop_count-5-while_down_ne.py @@ -1,7 +1,9 @@ import bench + def test(num): while num != 0: num -= 1 + bench.run(test) diff --git a/tests/internal_bench/loop_count-5.1-while_down_ne_localvar.py b/tests/internal_bench/loop_count-5.1-while_down_ne_localvar.py index 96bdb9129f..d25102a630 100644 --- a/tests/internal_bench/loop_count-5.1-while_down_ne_localvar.py +++ b/tests/internal_bench/loop_count-5.1-while_down_ne_localvar.py @@ -1,8 +1,10 @@ import bench + def test(num): zero = 0 while num != zero: num -= 1 + bench.run(test) diff --git a/tests/internal_bench/var-1-constant.py b/tests/internal_bench/var-1-constant.py index eec977909c..4a24194725 100644 --- a/tests/internal_bench/var-1-constant.py +++ b/tests/internal_bench/var-1-constant.py @@ -1,8 +1,10 @@ import bench + def test(num): i = 0 while i < 20000000: i += 1 + bench.run(test) diff --git a/tests/internal_bench/var-2-global.py b/tests/internal_bench/var-2-global.py index 5758ad61aa..a47240d646 100644 --- a/tests/internal_bench/var-2-global.py +++ b/tests/internal_bench/var-2-global.py @@ -2,9 +2,11 @@ import bench ITERS = 20000000 + def test(num): i = 0 while i < ITERS: i += 1 + bench.run(test) diff --git a/tests/internal_bench/var-3-local.py b/tests/internal_bench/var-3-local.py index 124b484295..182bb95f6f 100644 --- a/tests/internal_bench/var-3-local.py +++ b/tests/internal_bench/var-3-local.py @@ -7,4 +7,5 @@ def test(num): while i < ITERS: i += 1 + bench.run(test) diff --git a/tests/internal_bench/var-4-arg.py b/tests/internal_bench/var-4-arg.py index cf050c58fd..b9734357c8 100644 --- a/tests/internal_bench/var-4-arg.py +++ b/tests/internal_bench/var-4-arg.py @@ -6,4 +6,5 @@ def test(num): while i < num: i += 1 -bench.run(lambda n:test(20000000)) + +bench.run(lambda n: test(20000000)) diff --git a/tests/internal_bench/var-5-class-attr.py b/tests/internal_bench/var-5-class-attr.py index 02ae874ac2..e10770ee5b 100644 --- a/tests/internal_bench/var-5-class-attr.py +++ b/tests/internal_bench/var-5-class-attr.py @@ -1,11 +1,14 @@ import bench + class Foo: num = 20000000 + def test(num): i = 0 while i < Foo.num: i += 1 + bench.run(test) diff --git a/tests/internal_bench/var-6-instance-attr.py b/tests/internal_bench/var-6-instance-attr.py index 787ed870fb..0124ef51b3 100644 --- a/tests/internal_bench/var-6-instance-attr.py +++ b/tests/internal_bench/var-6-instance-attr.py @@ -1,14 +1,16 @@ import bench -class Foo: +class Foo: def __init__(self): self.num = 20000000 + def test(num): o = Foo() i = 0 while i < o.num: i += 1 + bench.run(test) diff --git a/tests/internal_bench/var-6.1-instance-attr-5.py b/tests/internal_bench/var-6.1-instance-attr-5.py index e8d3383605..692cef20df 100644 --- a/tests/internal_bench/var-6.1-instance-attr-5.py +++ b/tests/internal_bench/var-6.1-instance-attr-5.py @@ -1,7 +1,7 @@ import bench -class Foo: +class Foo: def __init__(self): self.num1 = 0 self.num2 = 0 @@ -9,10 +9,12 @@ class Foo: self.num4 = 0 self.num = 20000000 + def test(num): o = Foo() i = 0 while i < o.num: i += 1 + bench.run(test) diff --git a/tests/internal_bench/var-7-instance-meth.py b/tests/internal_bench/var-7-instance-meth.py index f9d463f40a..2ed7800be5 100644 --- a/tests/internal_bench/var-7-instance-meth.py +++ b/tests/internal_bench/var-7-instance-meth.py @@ -1,17 +1,19 @@ import bench -class Foo: +class Foo: def __init__(self): self._num = 20000000 def num(self): return self._num + def test(num): o = Foo() i = 0 while i < o.num(): i += 1 + bench.run(test) diff --git a/tests/internal_bench/var-8-namedtuple-1st.py b/tests/internal_bench/var-8-namedtuple-1st.py index d862480a51..1a6daa6cdd 100644 --- a/tests/internal_bench/var-8-namedtuple-1st.py +++ b/tests/internal_bench/var-8-namedtuple-1st.py @@ -3,10 +3,12 @@ from ucollections import namedtuple T = namedtuple("Tup", ["num", "bar"]) + def test(num): t = T(20000000, 0) i = 0 while i < t.num: i += 1 + bench.run(test) diff --git a/tests/internal_bench/var-8.1-namedtuple-5th.py b/tests/internal_bench/var-8.1-namedtuple-5th.py index 0bcf661803..568ece8067 100644 --- a/tests/internal_bench/var-8.1-namedtuple-5th.py +++ b/tests/internal_bench/var-8.1-namedtuple-5th.py @@ -3,10 +3,12 @@ from ucollections import namedtuple T = namedtuple("Tup", ["foo1", "foo2", "foo3", "foo4", "num"]) + def test(num): t = T(0, 0, 0, 0, 20000000) i = 0 while i < t.num: i += 1 + bench.run(test) diff --git a/tests/io/argv.py b/tests/io/argv.py index a13f2cad21..53254da119 100644 --- a/tests/io/argv.py +++ b/tests/io/argv.py @@ -1,2 +1,3 @@ import sys + print(sys.argv) diff --git a/tests/io/builtin_print_file.py b/tests/io/builtin_print_file.py index d9b8e2a960..822356a6cc 100644 --- a/tests/io/builtin_print_file.py +++ b/tests/io/builtin_print_file.py @@ -5,13 +5,13 @@ import sys try: sys.stdout except AttributeError: - print('SKIP') + print("SKIP") raise SystemExit print(file=sys.stdout) -print('test', file=sys.stdout) +print("test", file=sys.stdout) try: print(file=1) -except (AttributeError, OSError): # CPython and uPy differ in error message - print('Error') +except (AttributeError, OSError): # CPython and uPy differ in error message + print("Error") diff --git a/tests/io/file1.py b/tests/io/file1.py index af4176b64e..2a46c9c63e 100644 --- a/tests/io/file1.py +++ b/tests/io/file1.py @@ -4,43 +4,43 @@ print(f.readline()) print(f.read()) f = open("io/data/file1") print(f.readlines()) -f = open("io/data/file1","r") +f = open("io/data/file1", "r") print(f.readlines()) -f = open("io/data/file1","rb") +f = open("io/data/file1", "rb") print(f.readlines()) -f = open("io/data/file1",mode="r") +f = open("io/data/file1", mode="r") print(f.readlines()) -f = open("io/data/file1",mode="rb") +f = open("io/data/file1", mode="rb") print(f.readlines()) # write() error -f = open('io/data/file1', 'r') +f = open("io/data/file1", "r") try: - f.write('x') + f.write("x") except OSError: - print('OSError') + print("OSError") f.close() # read(n) error on binary file -f = open('io/data/file1', 'ab') +f = open("io/data/file1", "ab") try: f.read(1) except OSError: - print('OSError') + print("OSError") f.close() # read(n) error on text file -f = open('io/data/file1', 'at') +f = open("io/data/file1", "at") try: f.read(1) except OSError: - print('OSError') + print("OSError") f.close() # read() w/o args error -f = open('io/data/file1', 'ab') +f = open("io/data/file1", "ab") try: f.read() except OSError: - print('OSError') + print("OSError") f.close() diff --git a/tests/io/file_readinto.py b/tests/io/file_readinto.py index cbefc6e040..1f3702a217 100644 --- a/tests/io/file_readinto.py +++ b/tests/io/file_readinto.py @@ -7,8 +7,8 @@ print(f.readinto(b)) print(b) # readinto() on writable file -f = open('io/data/file1', 'ab') +f = open("io/data/file1", "ab") try: f.readinto(bytearray(4)) except OSError: - print('OSError') + print("OSError") diff --git a/tests/io/file_readline.py b/tests/io/file_readline.py index 25e76597b1..86d010eaf6 100644 --- a/tests/io/file_readline.py +++ b/tests/io/file_readline.py @@ -6,9 +6,9 @@ print(f.readline(5)) print(f.readline()) # readline() on writable file -f = open('io/data/file1', 'ab') +f = open("io/data/file1", "ab") try: f.readline() except OSError: - print('OSError') + print("OSError") f.close() diff --git a/tests/io/file_seek.py b/tests/io/file_seek.py index 10fb1fd06f..2fe57692c6 100644 --- a/tests/io/file_seek.py +++ b/tests/io/file_seek.py @@ -25,10 +25,10 @@ print(f.tell()) f.close() # seek closed file -f = open('io/data/file1', 'r') +f = open("io/data/file1", "r") f.close() try: f.seek(1) except (OSError, ValueError): # CPy raises ValueError, uPy raises OSError - print('OSError or ValueError') + print("OSError or ValueError") diff --git a/tests/io/file_with.py b/tests/io/file_with.py index ee1e702422..899c0f9287 100644 --- a/tests/io/file_with.py +++ b/tests/io/file_with.py @@ -15,7 +15,7 @@ except: # Regression test: test that exception in with initialization properly # thrown and doesn't crash. try: - with open('__non_existent', 'r'): + with open("__non_existent", "r"): pass except OSError: print("OSError") diff --git a/tests/io/resource_stream.py b/tests/io/resource_stream.py index 37d985bf16..5656205b69 100644 --- a/tests/io/resource_stream.py +++ b/tests/io/resource_stream.py @@ -4,7 +4,7 @@ import sys try: uio.resource_stream except AttributeError: - print('SKIP') + print("SKIP") raise SystemExit buf = uio.resource_stream("data", "file2") diff --git a/tests/jni/list.py b/tests/jni/list.py index d58181d0ba..7630a48e89 100644 --- a/tests/jni/list.py +++ b/tests/jni/list.py @@ -1,4 +1,5 @@ import jni + try: ArrayList = jni.cls("java/util/ArrayList") except: diff --git a/tests/jni/object.py b/tests/jni/object.py index aa67615ec8..8fbdb39d39 100644 --- a/tests/jni/object.py +++ b/tests/jni/object.py @@ -1,4 +1,5 @@ import jni + try: Integer = jni.cls("java/lang/Integer") except: diff --git a/tests/jni/system_out.py b/tests/jni/system_out.py index 86c4b9e112..c34d7011f7 100644 --- a/tests/jni/system_out.py +++ b/tests/jni/system_out.py @@ -1,5 +1,6 @@ try: import jni + System = jni.cls("java/lang/System") except: print("SKIP") diff --git a/tests/micropython/const.py b/tests/micropython/const.py index 660a095f2c..1faf22be9a 100644 --- a/tests/micropython/const.py +++ b/tests/micropython/const.py @@ -7,9 +7,11 @@ Y = const(X + 456) print(X, Y + 1) + def f(): print(X, Y + 1) + f() _X = const(12) @@ -17,9 +19,11 @@ _Y = const(_X + 34) print(_X, _Y) + class A: Z = const(1) _Z = const(2) print(Z, _Z) -print(hasattr(A, 'Z'), hasattr(A, '_Z')) + +print(hasattr(A, "Z"), hasattr(A, "_Z")) diff --git a/tests/micropython/const2.py b/tests/micropython/const2.py index 60085a1e04..ed4720122e 100644 --- a/tests/micropython/const2.py +++ b/tests/micropython/const2.py @@ -8,27 +8,37 @@ Z = const(3) # import that uses a constant import micropython as X -print(globals()['X']) + +print(globals()["X"]) # function name that matches a constant def X(): - print('function X', X) -globals()['X']() + print("function X", X) + + +globals()["X"]() # arguments that match a constant def f(X, *Y, **Z): pass + + f(1) # class name that matches a constant class X: def f(self): - print('class X', X) -globals()['X']().f() + print("class X", X) + + +globals()["X"]().f() # constant within a class class A: C1 = const(4) + def X(self): - print('method X', Y, C1, self.C1) + print("method X", Y, C1, self.C1) + + A().X() diff --git a/tests/micropython/const_error.py b/tests/micropython/const_error.py index 6d3d135b56..311cfb4d5e 100644 --- a/tests/micropython/const_error.py +++ b/tests/micropython/const_error.py @@ -2,12 +2,14 @@ from micropython import const + def test_syntax(code): try: exec(code) except SyntaxError: print("SyntaxError") + # argument not a constant test_syntax("a = const(x)") diff --git a/tests/micropython/const_intbig.py b/tests/micropython/const_intbig.py index e749026526..27990c8c20 100644 --- a/tests/micropython/const_intbig.py +++ b/tests/micropython/const_intbig.py @@ -3,8 +3,8 @@ from micropython import const # check we can make consts from bignums -Z1 = const(0xffffffff) -Z2 = const(0xffffffffffffffff) +Z1 = const(0xFFFFFFFF) +Z2 = const(0xFFFFFFFFFFFFFFFF) print(hex(Z1), hex(Z2)) # check arithmetic with bignum diff --git a/tests/micropython/decorator.py b/tests/micropython/decorator.py index bf688968a0..2e7cf17776 100644 --- a/tests/micropython/decorator.py +++ b/tests/micropython/decorator.py @@ -1,7 +1,9 @@ # test micropython-specific decorators + @micropython.bytecode def f(): - return 'bytecode' + return "bytecode" + print(f()) diff --git a/tests/micropython/decorator_error.py b/tests/micropython/decorator_error.py index c7da3119f4..94772ac1e5 100644 --- a/tests/micropython/decorator_error.py +++ b/tests/micropython/decorator_error.py @@ -1,11 +1,13 @@ # test syntax errors for uPy-specific decorators + def test_syntax(code): try: exec(code) except SyntaxError: print("SyntaxError") + # invalid micropython decorators test_syntax("@micropython.a\ndef f(): pass") test_syntax("@micropython.a.b\ndef f(): pass") diff --git a/tests/micropython/emg_exc.py b/tests/micropython/emg_exc.py index 4a9fa18bc1..bca4d2d9fb 100644 --- a/tests/micropython/emg_exc.py +++ b/tests/micropython/emg_exc.py @@ -2,6 +2,7 @@ import micropython import sys + try: import uio except ImportError: @@ -14,6 +15,7 @@ try: except AttributeError: pass + def f(): micropython.heap_lock() try: @@ -31,4 +33,5 @@ def f(): else: print(l) + f() diff --git a/tests/micropython/emg_exc.py.exp b/tests/micropython/emg_exc.py.exp index fd2cfb2722..0d4b80ce2b 100644 --- a/tests/micropython/emg_exc.py.exp +++ b/tests/micropython/emg_exc.py.exp @@ -1,4 +1,4 @@ Traceback (most recent call last): -, line 20, in f +, line 22, in f ValueError: 1 diff --git a/tests/micropython/extreme_exc.py b/tests/micropython/extreme_exc.py index b9db964068..dae5b15186 100644 --- a/tests/micropython/extreme_exc.py +++ b/tests/micropython/extreme_exc.py @@ -5,8 +5,13 @@ import micropython # Check for stackless build, which can't call functions without # allocating a frame on the heap. try: - def stackless(): pass - micropython.heap_lock(); stackless(); micropython.heap_unlock() + + def stackless(): + pass + + micropython.heap_lock() + stackless() + micropython.heap_unlock() except RuntimeError: print("SKIP") raise SystemExit @@ -17,11 +22,78 @@ try: except AttributeError: pass + def main(): # create an exception with many args while heap is locked # should revert to empty tuple for args micropython.heap_lock() - e = Exception(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0) + e = Exception( + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + ) micropython.heap_unlock() print(repr(e)) @@ -29,9 +101,12 @@ def main(): # should use emergency exception buffer and truncate the message def f(): pass + micropython.heap_lock() try: - f(abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz=1) + f( + abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz=1 + ) except Exception as er: e = er micropython.heap_unlock() @@ -46,7 +121,9 @@ def main(): except MemoryError: break try: - f(abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz=1) + f( + abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz=1 + ) except Exception as er: e = er lst[0] = None @@ -57,6 +134,7 @@ def main(): # should use emergency exception and be unable to resize traceback array def g(): g() + micropython.heap_lock() try: g() @@ -67,13 +145,15 @@ def main(): # create an exception on the heap with some traceback on the heap, but then # raise it with the heap locked so it can't allocate any more traceback - exc = Exception('my exception') + exc = Exception("my exception") try: raise exc except: pass + def h(e): raise e + micropython.heap_lock() try: h(exc) @@ -82,4 +162,5 @@ def main(): micropython.heap_unlock() print(repr(e)) + main() diff --git a/tests/micropython/heap_lock.py b/tests/micropython/heap_lock.py index 6d770d9ec4..f2892a6dc5 100644 --- a/tests/micropython/heap_lock.py +++ b/tests/micropython/heap_lock.py @@ -12,13 +12,13 @@ micropython.heap_lock() try: print([]) except MemoryError: - print('MemoryError') + print("MemoryError") # expansion of a heap block try: l.extend(l2) except MemoryError: - print('MemoryError') + print("MemoryError") print(micropython.heap_unlock()) @@ -26,7 +26,7 @@ print(micropython.heap_unlock()) try: print([]) except MemoryError: - print('MemoryError') + print("MemoryError") micropython.heap_unlock() diff --git a/tests/micropython/heapalloc.py b/tests/micropython/heapalloc.py index f74bb92c85..99f157105d 100644 --- a/tests/micropython/heapalloc.py +++ b/tests/micropython/heapalloc.py @@ -5,18 +5,26 @@ import micropython # Check for stackless build, which can't call functions without # allocating a frame on heap. try: - def stackless(): pass - micropython.heap_lock(); stackless(); micropython.heap_unlock() + + def stackless(): + pass + + micropython.heap_lock() + stackless() + micropython.heap_unlock() except RuntimeError: print("SKIP") raise SystemExit + def f1(a): print(a) + def f2(a, b=2): print(a, b) + def f3(a, b, c, d): x1 = x2 = a x3 = x4 = b @@ -24,19 +32,22 @@ def f3(a, b, c, d): x7 = x8 = d print(x1, x3, x5, x7, x2 + x4 + x6 + x8) + global_var = 1 + def test(): global global_var, global_exc - global_var = 2 # set an existing global variable + global_var = 2 # set an existing global variable for i in range(2): # for loop - f1(i) # function call - f1(i * 2 + 1) # binary operation with small ints - f1(a=i) # keyword arguments - f2(i) # default arg (second one) - f2(i, i) # 2 args + f1(i) # function call + f1(i * 2 + 1) # binary operation with small ints + f1(a=i) # keyword arguments + f2(i) # default arg (second one) + f2(i, i) # 2 args f3(1, 2, 3, 4) # function with lots of local state + # call test() with heap allocation disabled micropython.heap_lock() test() diff --git a/tests/micropython/heapalloc_bytesio2.py b/tests/micropython/heapalloc_bytesio2.py index cd76f58077..3b9f141270 100644 --- a/tests/micropython/heapalloc_bytesio2.py +++ b/tests/micropython/heapalloc_bytesio2.py @@ -3,6 +3,7 @@ try: import uio import micropython + micropython.mem_total except (ImportError, AttributeError): print("SKIP") diff --git a/tests/micropython/heapalloc_exc_raise.py b/tests/micropython/heapalloc_exc_raise.py index fb63a84bf3..99810e0075 100644 --- a/tests/micropython/heapalloc_exc_raise.py +++ b/tests/micropython/heapalloc_exc_raise.py @@ -4,6 +4,7 @@ import micropython e = ValueError("error") + def func(): micropython.heap_lock() try: @@ -19,5 +20,6 @@ def func(): print(e2) micropython.heap_unlock() + func() print("ok") diff --git a/tests/micropython/heapalloc_fail_bytearray.py b/tests/micropython/heapalloc_fail_bytearray.py index fbf585c7f1..1bf7ddd600 100644 --- a/tests/micropython/heapalloc_fail_bytearray.py +++ b/tests/micropython/heapalloc_fail_bytearray.py @@ -2,9 +2,12 @@ import micropython + class GetSlice: def __getitem__(self, idx): return idx + + sl = GetSlice()[:] # create bytearray @@ -12,15 +15,15 @@ micropython.heap_lock() try: bytearray(4) except MemoryError: - print('MemoryError: bytearray create') + print("MemoryError: bytearray create") micropython.heap_unlock() # create bytearray from bytes micropython.heap_lock() try: - bytearray(b'0123') + bytearray(b"0123") except MemoryError: - print('MemoryError: bytearray create from bytes') + print("MemoryError: bytearray create from bytes") micropython.heap_unlock() # create bytearray from iterator @@ -29,25 +32,25 @@ micropython.heap_lock() try: bytearray(r) except MemoryError: - print('MemoryError: bytearray create from iter') + print("MemoryError: bytearray create from iter") micropython.heap_unlock() # bytearray add b = bytearray(4) micropython.heap_lock() try: - b + b'01' + b + b"01" except MemoryError: - print('MemoryError: bytearray.__add__') + print("MemoryError: bytearray.__add__") micropython.heap_unlock() # bytearray iadd b = bytearray(4) micropython.heap_lock() try: - b += b'01234567' + b += b"01234567" except MemoryError: - print('MemoryError: bytearray.__iadd__') + print("MemoryError: bytearray.__iadd__") micropython.heap_unlock() print(b) @@ -58,16 +61,16 @@ try: for i in range(100): b.append(1) except MemoryError: - print('MemoryError: bytearray.append') + print("MemoryError: bytearray.append") micropython.heap_unlock() # bytearray extend b = bytearray(4) micropython.heap_lock() try: - b.extend(b'01234567') + b.extend(b"01234567") except MemoryError: - print('MemoryError: bytearray.extend') + print("MemoryError: bytearray.extend") micropython.heap_unlock() # bytearray get with slice @@ -76,15 +79,15 @@ micropython.heap_lock() try: b[sl] except MemoryError: - print('MemoryError: bytearray subscr get') + print("MemoryError: bytearray subscr get") micropython.heap_unlock() # extend bytearray using slice subscr b = bytearray(4) micropython.heap_lock() try: - b[sl] = b'01234567' + b[sl] = b"01234567" except MemoryError: - print('MemoryError: bytearray subscr grow') + print("MemoryError: bytearray subscr grow") micropython.heap_unlock() print(b) diff --git a/tests/micropython/heapalloc_fail_dict.py b/tests/micropython/heapalloc_fail_dict.py index ba872bfeb6..ce2d158bd0 100644 --- a/tests/micropython/heapalloc_fail_dict.py +++ b/tests/micropython/heapalloc_fail_dict.py @@ -6,16 +6,16 @@ import micropython x = 1 micropython.heap_lock() try: - {x:x} + {x: x} except MemoryError: - print('MemoryError: create dict') + print("MemoryError: create dict") micropython.heap_unlock() # create dict view -x = {1:1} +x = {1: 1} micropython.heap_lock() try: x.items() except MemoryError: - print('MemoryError: dict.items') + print("MemoryError: dict.items") micropython.heap_unlock() diff --git a/tests/micropython/heapalloc_fail_list.py b/tests/micropython/heapalloc_fail_list.py index a54bdb6cf6..9a2e9a555f 100644 --- a/tests/micropython/heapalloc_fail_list.py +++ b/tests/micropython/heapalloc_fail_list.py @@ -2,9 +2,12 @@ import micropython + class GetSlice: def __getitem__(self, idx): return idx + + sl = GetSlice()[:] # create slice in VM @@ -13,7 +16,7 @@ micropython.heap_lock() try: print(l[0:1]) except MemoryError: - print('MemoryError: list index') + print("MemoryError: list index") micropython.heap_unlock() # get from list using slice @@ -21,7 +24,7 @@ micropython.heap_lock() try: l[sl] except MemoryError: - print('MemoryError: list get slice') + print("MemoryError: list get slice") micropython.heap_unlock() # extend list using slice subscr @@ -31,6 +34,6 @@ micropython.heap_lock() try: l[sl] = l2 except MemoryError: - print('MemoryError: list extend slice') + print("MemoryError: list extend slice") micropython.heap_unlock() print(l) diff --git a/tests/micropython/heapalloc_fail_memoryview.py b/tests/micropython/heapalloc_fail_memoryview.py index 3ba9015ff1..da2d1abffa 100644 --- a/tests/micropython/heapalloc_fail_memoryview.py +++ b/tests/micropython/heapalloc_fail_memoryview.py @@ -2,24 +2,27 @@ import micropython + class GetSlice: def __getitem__(self, idx): return idx + + sl = GetSlice()[:] # create memoryview micropython.heap_lock() try: - memoryview(b'') + memoryview(b"") except MemoryError: - print('MemoryError: memoryview create') + print("MemoryError: memoryview create") micropython.heap_unlock() # memoryview get with slice -m = memoryview(b'') +m = memoryview(b"") micropython.heap_lock() try: m[sl] except MemoryError: - print('MemoryError: memoryview subscr get') + print("MemoryError: memoryview subscr get") micropython.heap_unlock() diff --git a/tests/micropython/heapalloc_fail_set.py b/tests/micropython/heapalloc_fail_set.py index 172df27d4e..3c347660ad 100644 --- a/tests/micropython/heapalloc_fail_set.py +++ b/tests/micropython/heapalloc_fail_set.py @@ -8,7 +8,7 @@ micropython.heap_lock() try: {x} except MemoryError: - print('MemoryError: set create') + print("MemoryError: set create") micropython.heap_unlock() # set copy @@ -17,5 +17,5 @@ micropython.heap_lock() try: s.copy() except MemoryError: - print('MemoryError: set copy') + print("MemoryError: set copy") micropython.heap_unlock() diff --git a/tests/micropython/heapalloc_fail_tuple.py b/tests/micropython/heapalloc_fail_tuple.py index 1cd23fb74b..de79385e3e 100644 --- a/tests/micropython/heapalloc_fail_tuple.py +++ b/tests/micropython/heapalloc_fail_tuple.py @@ -8,5 +8,5 @@ micropython.heap_lock() try: (x,) except MemoryError: - print('MemoryError: tuple create') + print("MemoryError: tuple create") micropython.heap_unlock() diff --git a/tests/micropython/heapalloc_inst_call.py b/tests/micropython/heapalloc_inst_call.py index 3cc497b73a..14d8826bf0 100644 --- a/tests/micropython/heapalloc_inst_call.py +++ b/tests/micropython/heapalloc_inst_call.py @@ -2,22 +2,27 @@ # doesn't require heap allocation. import micropython + class Foo0: def __call__(self): print("__call__") + class Foo1: def __call__(self, a): print("__call__", a) + class Foo2: def __call__(self, a, b): print("__call__", a, b) + class Foo3: def __call__(self, a, b, c): print("__call__", a, b, c) + f0 = Foo0() f1 = Foo1() f2 = Foo2() diff --git a/tests/micropython/heapalloc_iter.py b/tests/micropython/heapalloc_iter.py index 5a44a558bb..18f5322ee1 100644 --- a/tests/micropython/heapalloc_iter.py +++ b/tests/micropython/heapalloc_iter.py @@ -16,7 +16,8 @@ except ImportError: try: from micropython import heap_lock, heap_unlock except (ImportError, AttributeError): - heap_lock = heap_unlock = lambda:0 + heap_lock = heap_unlock = lambda: 0 + def do_iter(l): heap_lock() @@ -24,16 +25,18 @@ def do_iter(l): print(i) heap_unlock() + def gen_func(): yield 1 yield 2 + # pre-create collections to iterate over -ba = bytearray(b'123') -ar = array.array('H', (123, 456)) +ba = bytearray(b"123") +ar = array.array("H", (123, 456)) t = (1, 2, 3) l = [1, 2] -d = {1:2} +d = {1: 2} s = set((1,)) fs = frozenset((1,)) g1 = (100 + x for x in range(2)) @@ -41,7 +44,7 @@ g2 = gen_func() # test containment (both success and failure) with the heap locked heap_lock() -print(49 in b'123', 255 in b'123') +print(49 in b"123", 255 in b"123") print(1 in t, -1 in t) print(1 in l, -1 in l) print(1 in d, -1 in d) @@ -49,7 +52,7 @@ print(1 in s, -1 in s) heap_unlock() # test unpacking with the heap locked -unp0 = unp1 = unp2 = None # preallocate slots for globals +unp0 = unp1 = unp2 = None # preallocate slots for globals heap_lock() unp0, unp1, unp2 = t print(unp0, unp1, unp2) @@ -65,7 +68,7 @@ print(sum(t)) heap_unlock() # test iterating over collections with the heap locked -do_iter(b'123') +do_iter(b"123") do_iter(ba) do_iter(ar) do_iter(t) diff --git a/tests/micropython/heapalloc_super.py b/tests/micropython/heapalloc_super.py index a8c23393e4..51afae3d83 100644 --- a/tests/micropython/heapalloc_super.py +++ b/tests/micropython/heapalloc_super.py @@ -4,21 +4,30 @@ import micropython # Check for stackless build, which can't call functions without # allocating a frame on heap. try: - def stackless(): pass - micropython.heap_lock(); stackless(); micropython.heap_unlock() + + def stackless(): + pass + + micropython.heap_lock() + stackless() + micropython.heap_unlock() except RuntimeError: print("SKIP") raise SystemExit + class A: def foo(self): - print('A foo') + print("A foo") return 42 + + class B(A): def foo(self): - print('B foo') + print("B foo") print(super().foo()) + b = B() micropython.heap_lock() diff --git a/tests/micropython/heapalloc_traceback.py b/tests/micropython/heapalloc_traceback.py index 813dea4b21..eabd09388b 100644 --- a/tests/micropython/heapalloc_traceback.py +++ b/tests/micropython/heapalloc_traceback.py @@ -2,6 +2,7 @@ import micropython import sys + try: import uio except ImportError: @@ -15,6 +16,7 @@ try: except: pass + def test(): micropython.heap_lock() global global_exc @@ -22,9 +24,10 @@ def test(): try: raise global_exc except StopIteration: - print('StopIteration') + print("StopIteration") micropython.heap_unlock() + # call test() with heap allocation disabled test() diff --git a/tests/micropython/heapalloc_traceback.py.exp b/tests/micropython/heapalloc_traceback.py.exp index facd0af137..71929db93d 100644 --- a/tests/micropython/heapalloc_traceback.py.exp +++ b/tests/micropython/heapalloc_traceback.py.exp @@ -1,5 +1,5 @@ StopIteration Traceback (most recent call last): - File , line 23, in test + File , line 25, in test StopIteration: diff --git a/tests/micropython/heapalloc_yield_from.py b/tests/micropython/heapalloc_yield_from.py index 8443210f3a..58788b1dbc 100644 --- a/tests/micropython/heapalloc_yield_from.py +++ b/tests/micropython/heapalloc_yield_from.py @@ -6,8 +6,12 @@ import micropython def sub_gen(a): for i in range(a): yield i + + def gen(g): yield from g + + g = gen(sub_gen(4)) micropython.heap_lock() print(next(g)) @@ -18,12 +22,16 @@ micropython.heap_unlock() class G: def __init__(self): self.value = 0 + def __iter__(self): return self + def __next__(self): v = self.value self.value += 1 return v + + g = gen(G()) micropython.heap_lock() print(next(g)) diff --git a/tests/micropython/kbd_intr.py b/tests/micropython/kbd_intr.py index 879c9a229f..81977aaa52 100644 --- a/tests/micropython/kbd_intr.py +++ b/tests/micropython/kbd_intr.py @@ -5,7 +5,7 @@ import micropython try: micropython.kbd_intr except AttributeError: - print('SKIP') + print("SKIP") raise SystemExit # just check we can actually call it diff --git a/tests/micropython/meminfo.py b/tests/micropython/meminfo.py index 698bbbd21c..9df341fbb8 100644 --- a/tests/micropython/meminfo.py +++ b/tests/micropython/meminfo.py @@ -3,8 +3,8 @@ import micropython # these functions are not always available -if not hasattr(micropython, 'mem_info'): - print('SKIP') +if not hasattr(micropython, "mem_info"): + print("SKIP") else: micropython.mem_info() micropython.mem_info(1) diff --git a/tests/micropython/memstats.py b/tests/micropython/memstats.py index 78e4d24736..dee3a4ce2f 100644 --- a/tests/micropython/memstats.py +++ b/tests/micropython/memstats.py @@ -3,8 +3,8 @@ import micropython # these functions are not always available -if not hasattr(micropython, 'mem_total'): - print('SKIP') +if not hasattr(micropython, "mem_total"): + print("SKIP") else: t = micropython.mem_total() c = micropython.mem_current() diff --git a/tests/micropython/native_closure.py b/tests/micropython/native_closure.py index 6c0592e52d..07014e90da 100644 --- a/tests/micropython/native_closure.py +++ b/tests/micropython/native_closure.py @@ -4,11 +4,15 @@ @micropython.native def f(): x = 1 + @micropython.native def g(): nonlocal x return x + return g + + print(f()()) # closing over an argument @@ -18,15 +22,22 @@ def f(x): def g(): nonlocal x return x + return g + + print(f(2)()) # closing over an argument and a normal local @micropython.native def f(x): y = 2 * x + @micropython.native def g(z): return x + y + z + return g + + print(f(2)(3)) diff --git a/tests/micropython/native_const.py b/tests/micropython/native_const.py index 37b491cf4a..b48499550e 100644 --- a/tests/micropython/native_const.py +++ b/tests/micropython/native_const.py @@ -1,14 +1,21 @@ # test loading constants in native functions + @micropython.native def f(): - return b'bytes' + return b"bytes" + + print(f()) + @micropython.native def f(): @micropython.native def g(): return 123 + return g + + print(f()()) diff --git a/tests/micropython/native_const_intbig.py b/tests/micropython/native_const_intbig.py index 611b39d8fe..69bc1d2163 100644 --- a/tests/micropython/native_const_intbig.py +++ b/tests/micropython/native_const_intbig.py @@ -1,7 +1,9 @@ # check loading constants + @micropython.native def f(): return 123456789012345678901234567890 + print(f()) diff --git a/tests/micropython/native_gen.py b/tests/micropython/native_gen.py index 30c4c37bea..fb42f9e25e 100644 --- a/tests/micropython/native_gen.py +++ b/tests/micropython/native_gen.py @@ -6,6 +6,8 @@ def gen1(x): yield x yield x + 1 return x + 2 + + g = gen1(3) print(next(g)) print(next(g)) @@ -18,4 +20,6 @@ except StopIteration as e: @micropython.native def gen2(x): yield from range(x) + + print(list(gen2(3))) diff --git a/tests/micropython/native_misc.py b/tests/micropython/native_misc.py index 0cd521de6c..7c5415375e 100644 --- a/tests/micropython/native_misc.py +++ b/tests/micropython/native_misc.py @@ -4,10 +4,13 @@ @micropython.native def native_test(x): print(1, [], x) + + native_test(2) # check that GC doesn't collect the native function import gc + gc.collect() native_test(3) @@ -15,17 +18,23 @@ native_test(3) @micropython.native def f(a, b): print(a + b) + + f(1, 2) # native with 3 args @micropython.native def f(a, b, c): print(a + b + c) + + f(1, 2, 3) # check not operator @micropython.native def f(a): print(not a) + + f(False) f(True) diff --git a/tests/micropython/native_try.py b/tests/micropython/native_try.py index 2e41bf2ea1..492b59085c 100644 --- a/tests/micropython/native_try.py +++ b/tests/micropython/native_try.py @@ -6,11 +6,13 @@ def f(): try: fail finally: - print('finally') + print("finally") + + try: f() except NameError: - print('NameError') + print("NameError") # nested try-except with try-finally @micropython.native @@ -19,9 +21,11 @@ def f(): try: fail finally: - print('finally') + print("finally") except NameError: - print('NameError') + print("NameError") + + f() # check that locals written to in try blocks keep their values @@ -36,4 +40,6 @@ def f(): print(a) a = 300 print(a) + + f() diff --git a/tests/micropython/native_try_deep.py b/tests/micropython/native_try_deep.py index 7fac4f0f38..3d31248df0 100644 --- a/tests/micropython/native_try_deep.py +++ b/tests/micropython/native_try_deep.py @@ -30,5 +30,7 @@ def f(): finally: print(1) except ValueError: - print('ValueError') + print("ValueError") + + f() diff --git a/tests/micropython/native_with.py b/tests/micropython/native_with.py index 343f3e8d38..4e20b23856 100644 --- a/tests/micropython/native_with.py +++ b/tests/micropython/native_with.py @@ -1,18 +1,24 @@ # test with handling within a native function + class C: def __init__(self): - print('__init__') + print("__init__") + def __enter__(self): - print('__enter__') + print("__enter__") + def __exit__(self, a, b, c): - print('__exit__', a, b, c) + print("__exit__", a, b, c) + # basic with @micropython.native def f(): with C(): print(1) + + f() # nested with and try-except @@ -24,5 +30,7 @@ def f(): fail print(2) except NameError: - print('NameError') + print("NameError") + + f() diff --git a/tests/micropython/opt_level.py b/tests/micropython/opt_level.py index 4e2f2f4ea3..dd5493a7a3 100644 --- a/tests/micropython/opt_level.py +++ b/tests/micropython/opt_level.py @@ -8,7 +8,7 @@ print(micropython.opt_level()) # check that the optimisation levels actually differ micropython.opt_level(0) -exec('print(__debug__)') +exec("print(__debug__)") micropython.opt_level(1) -exec('print(__debug__)') -exec('assert 0') +exec("print(__debug__)") +exec("assert 0") diff --git a/tests/micropython/opt_level_lineno.py b/tests/micropython/opt_level_lineno.py index 00e5739605..d8253e54b4 100644 --- a/tests/micropython/opt_level_lineno.py +++ b/tests/micropython/opt_level_lineno.py @@ -3,4 +3,4 @@ import micropython as micropython # check that level 3 doesn't store line numbers # the expected output is that any line is printed as "line 1" micropython.opt_level(3) -exec('try:\n xyz\nexcept NameError as er:\n import sys\n sys.print_exception(er)') +exec("try:\n xyz\nexcept NameError as er:\n import sys\n sys.print_exception(er)") diff --git a/tests/micropython/schedule.py b/tests/micropython/schedule.py index 74f90cb2de..6a91459ea3 100644 --- a/tests/micropython/schedule.py +++ b/tests/micropython/schedule.py @@ -5,16 +5,18 @@ import micropython try: micropython.schedule except AttributeError: - print('SKIP') + print("SKIP") raise SystemExit # Basic test of scheduling a function. + def callback(arg): global done print(arg) done = True + done = False micropython.schedule(callback, 1) while not done: @@ -23,20 +25,23 @@ while not done: # Test that callbacks can be scheduled from within a callback, but # that they don't execute until the outer callback is finished. + def callback_inner(arg): global done - print('inner') + print("inner") done += 1 + def callback_outer(arg): global done micropython.schedule(callback_inner, 0) # need a loop so that the VM can check for pending events for i in range(2): pass - print('outer') + print("outer") done += 1 + done = 0 micropython.schedule(callback_outer, 0) while done != 2: @@ -45,15 +50,17 @@ while done != 2: # Test that scheduling too many callbacks leads to an exception. To do this we # must schedule from within a callback to guarantee that the scheduler is locked. + def callback(arg): global done try: for i in range(100): - micropython.schedule(lambda x:x, None) + micropython.schedule(lambda x: x, None) except RuntimeError: - print('RuntimeError') + print("RuntimeError") done = True + done = False micropython.schedule(callback, None) while not done: diff --git a/tests/micropython/stack_use.py b/tests/micropython/stack_use.py index bc714755a1..266885d9d1 100644 --- a/tests/micropython/stack_use.py +++ b/tests/micropython/stack_use.py @@ -1,7 +1,7 @@ # tests stack_use function in micropython module import micropython -if not hasattr(micropython, 'stack_use'): - print('SKIP') +if not hasattr(micropython, "stack_use"): + print("SKIP") else: - print(type(micropython.stack_use())) # output varies + print(type(micropython.stack_use())) # output varies diff --git a/tests/micropython/viper_addr.py b/tests/micropython/viper_addr.py index 0d8efb90b6..84bc6c002e 100644 --- a/tests/micropython/viper_addr.py +++ b/tests/micropython/viper_addr.py @@ -1,39 +1,43 @@ # test passing addresses to viper -@micropython.viper -def get_addr(x:ptr) -> ptr: - return x @micropython.viper -def memset(dest:ptr8, c:int, n:int): +def get_addr(x: ptr) -> ptr: + return x + + +@micropython.viper +def memset(dest: ptr8, c: int, n: int): for i in range(n): dest[i] = c + @micropython.viper -def memsum(src:ptr8, n:int) -> int: +def memsum(src: ptr8, n: int) -> int: s = 0 for i in range(n): s += src[i] return s + # create array and get its address -ar = bytearray('0000') +ar = bytearray("0000") addr = get_addr(ar) print(type(ar)) print(type(addr)) print(ar) # pass array as an object -memset(ar, ord('1'), len(ar)) +memset(ar, ord("1"), len(ar)) print(ar) # pass direct pointer to array buffer -memset(addr, ord('2'), len(ar)) +memset(addr, ord("2"), len(ar)) print(ar) # pass direct pointer to array buffer, with offset -memset(addr + 2, ord('3'), len(ar) - 2) +memset(addr + 2, ord("3"), len(ar) - 2) print(ar) # pass a read-only bytes object in -print(memsum(b'\x01\x02\x03\x04', 4)) +print(memsum(b"\x01\x02\x03\x04", 4)) diff --git a/tests/micropython/viper_args.py b/tests/micropython/viper_args.py index ee8e82321f..8e3225331a 100644 --- a/tests/micropython/viper_args.py +++ b/tests/micropython/viper_args.py @@ -1,44 +1,67 @@ # test calling viper functions with different number of args + @micropython.viper def f0(): print(0) + + f0() + @micropython.viper -def f1(x1:int): +def f1(x1: int): print(x1) + + f1(1) + @micropython.viper -def f2(x1:int, x2:int): +def f2(x1: int, x2: int): print(x1, x2) + + f2(1, 2) + @micropython.viper -def f3(x1:int, x2:int, x3:int): +def f3(x1: int, x2: int, x3: int): print(x1, x2, x3) + + f3(1, 2, 3) + @micropython.viper -def f4(x1:int, x2:int, x3:int, x4:int): +def f4(x1: int, x2: int, x3: int, x4: int): print(x1, x2, x3, x4) + + f4(1, 2, 3, 4) -@micropython.viper -def f5(x1:int, x2:int, x3:int, x4:int, x5:int): - print(x1, x2, x3, x4, x5) -f5(1, 2, 3, 4, 5) @micropython.viper -def f6(x1:int, x2:int, x3:int, x4:int, x5:int, x6:int): +def f5(x1: int, x2: int, x3: int, x4: int, x5: int): + print(x1, x2, x3, x4, x5) + + +f5(1, 2, 3, 4, 5) + + +@micropython.viper +def f6(x1: int, x2: int, x3: int, x4: int, x5: int, x6: int): print(x1, x2, x3, x4, x5, x6) + + f6(1, 2, 3, 4, 5, 6) # test compiling *x, **x, * args (currently unsupported at runtime) @micropython.viper def f(*x, **y): pass + + @micropython.viper def f(*): pass diff --git a/tests/micropython/viper_binop_arith.py b/tests/micropython/viper_binop_arith.py index 4d711f1a9f..2691404b7b 100644 --- a/tests/micropython/viper_binop_arith.py +++ b/tests/micropython/viper_binop_arith.py @@ -1,27 +1,36 @@ # test arithmetic operators + @micropython.viper -def add(x:int, y:int): +def add(x: int, y: int): print(x + y) print(y + x) + + add(1, 2) add(42, 3) add(-1, 2) add(-42, -3) + @micropython.viper -def sub(x:int, y:int): +def sub(x: int, y: int): print(x - y) print(y - x) + + sub(1, 2) sub(42, 3) sub(-1, 2) sub(-42, -3) + @micropython.viper -def mul(x:int, y:int): +def mul(x: int, y: int): print(x * y) print(y * x) + + mul(0, 1) mul(1, -1) mul(1, 2) @@ -29,41 +38,56 @@ mul(8, 3) mul(-3, 4) mul(-9, -6) + @micropython.viper -def shl(x:int, y:int): +def shl(x: int, y: int): print(x << y) + + shl(1, 0) shl(1, 3) shl(1, 30) shl(42, 10) shl(-42, 10) + @micropython.viper -def shr(x:int, y:int): +def shr(x: int, y: int): print(x >> y) + + shr(1, 0) shr(1, 3) shr(42, 2) shr(-42, 2) -@micropython.viper -def and_(x:int, y:int): - print(x & y, y & x) -and_(1, 0) -and_(1, 3) -and_(0xf0, 0x3f) -and_(-42, 6) @micropython.viper -def or_(x:int, y:int): +def and_(x: int, y: int): + print(x & y, y & x) + + +and_(1, 0) +and_(1, 3) +and_(0xF0, 0x3F) +and_(-42, 6) + + +@micropython.viper +def or_(x: int, y: int): print(x | y, y | x) + + or_(1, 0) or_(1, 2) or_(-42, 5) + @micropython.viper -def xor(x:int, y:int): +def xor(x: int, y: int): print(x ^ y, y ^ x) + + xor(1, 0) xor(1, 2) xor(-42, 5) diff --git a/tests/micropython/viper_binop_comp.py b/tests/micropython/viper_binop_comp.py index dcf91ed89d..a4c0809c85 100644 --- a/tests/micropython/viper_binop_comp.py +++ b/tests/micropython/viper_binop_comp.py @@ -1,6 +1,6 @@ # test comparison operators @micropython.viper -def f(x:int, y:int): +def f(x: int, y: int): if x < y: print(x, "<", y) if x > y: @@ -14,6 +14,7 @@ def f(x:int, y:int): if x != y: print(x, "!=", y) + f(1, 1) f(2, 1) f(1, 2) diff --git a/tests/micropython/viper_binop_comp_imm.py b/tests/micropython/viper_binop_comp_imm.py index c7c0408959..daab8fcfb5 100644 --- a/tests/micropython/viper_binop_comp_imm.py +++ b/tests/micropython/viper_binop_comp_imm.py @@ -3,6 +3,7 @@ def f(a: int): print(a == -1, a == -255, a == -256, a == -257) + f(-1) f(-255) f(-256) diff --git a/tests/micropython/viper_binop_divmod.py b/tests/micropython/viper_binop_divmod.py index 822424982a..4b74b527d3 100644 --- a/tests/micropython/viper_binop_divmod.py +++ b/tests/micropython/viper_binop_divmod.py @@ -1,16 +1,20 @@ # test floor-division and modulo operators -@micropython.viper -def div(x:int, y:int) -> int: - return x // y @micropython.viper -def mod(x:int, y:int) -> int: +def div(x: int, y: int) -> int: + return x // y + + +@micropython.viper +def mod(x: int, y: int) -> int: return x % y + def dm(x, y): print(div(x, y), mod(x, y)) + for x in (-6, 6): for y in range(-7, 8): if y == 0: diff --git a/tests/micropython/viper_binop_multi_comp.py b/tests/micropython/viper_binop_multi_comp.py index 8065db291b..997c397d4c 100644 --- a/tests/micropython/viper_binop_multi_comp.py +++ b/tests/micropython/viper_binop_multi_comp.py @@ -1,6 +1,6 @@ # test multi comparison operators @micropython.viper -def f(x:int, y:int): +def f(x: int, y: int): if 0 < x < y: print(x, "<", y) if 3 > x > y: @@ -14,6 +14,7 @@ def f(x:int, y:int): if 2 == x != y: print(x, "!=", y) + f(1, 1) f(2, 1) f(1, 2) diff --git a/tests/micropython/viper_cond.py b/tests/micropython/viper_cond.py index bbb3f69233..d5ebf837bd 100644 --- a/tests/micropython/viper_cond.py +++ b/tests/micropython/viper_cond.py @@ -6,6 +6,8 @@ def f(): pass else: print("not x", x) + + f() # using True as a conditional @@ -14,6 +16,8 @@ def f(): x = True if x: print("x", x) + + f() # using an int as a conditional @@ -22,6 +26,8 @@ def g(): y = 1 if y: print("y", y) + + g() # using an int as a conditional that has the lower 16-bits clear @@ -30,4 +36,6 @@ def h(): z = 0x10000 if z: print("z", z) + + h() diff --git a/tests/micropython/viper_const.py b/tests/micropython/viper_const.py index 5085ede90f..230b282f23 100644 --- a/tests/micropython/viper_const.py +++ b/tests/micropython/viper_const.py @@ -1,14 +1,21 @@ # test loading constants in viper functions + @micropython.viper def f(): - return b'bytes' + return b"bytes" + + print(f()) + @micropython.viper def f(): @micropython.viper def g() -> int: return 123 + return g + + print(f()()) diff --git a/tests/micropython/viper_const_intbig.py b/tests/micropython/viper_const_intbig.py index 6b44973880..42574820a3 100644 --- a/tests/micropython/viper_const_intbig.py +++ b/tests/micropython/viper_const_intbig.py @@ -1,7 +1,9 @@ # check loading constants + @micropython.viper def f(): return 123456789012345678901234567890 + print(f()) diff --git a/tests/micropython/viper_error.py b/tests/micropython/viper_error.py index ff32f54739..790f3d75c4 100644 --- a/tests/micropython/viper_error.py +++ b/tests/micropython/viper_error.py @@ -1,11 +1,13 @@ # test syntax and type errors specific to viper code generation + def test(code): try: exec(code) except (SyntaxError, ViperTypeError, NotImplementedError) as e: print(repr(e)) + # viper: annotations must be identifiers test("@micropython.viper\ndef f(a:1): pass") test("@micropython.viper\ndef f() -> 1: pass") @@ -14,30 +16,36 @@ test("@micropython.viper\ndef f() -> 1: pass") test("@micropython.viper\ndef f(x:unknown_type): pass") # local used before type known -test(""" +test( + """ @micropython.viper def f(): print(x) x = 1 -""") +""" +) # type mismatch storing to local -test(""" +test( + """ @micropython.viper def f(): x = 1 y = [] x = y -""") +""" +) # can't implicitly convert type to bool -test(""" +test( + """ @micropython.viper def f(): x = ptr(0) if x: pass -""") +""" +) # incorrect return type test("@micropython.viper\ndef f() -> int: return []") diff --git a/tests/micropython/viper_globals.py b/tests/micropython/viper_globals.py index 9c68dc3da8..9532dfd895 100644 --- a/tests/micropython/viper_globals.py +++ b/tests/micropython/viper_globals.py @@ -2,18 +2,21 @@ gl = {} -exec(""" +exec( + """ @micropython.viper def f(): return x -""", gl) +""", + gl, +) # x is not yet in the globals, f should not see it try: - print(gl['f']()) + print(gl["f"]()) except NameError: - print('NameError') + print("NameError") # x is in globals, f should now see it -gl['x'] = 123 -print(gl['f']()) +gl["x"] = 123 +print(gl["f"]()) diff --git a/tests/micropython/viper_import.py b/tests/micropython/viper_import.py index 9878007444..3df23e17a7 100644 --- a/tests/micropython/viper_import.py +++ b/tests/micropython/viper_import.py @@ -1,10 +1,15 @@ # test import within viper function + @micropython.viper def f(): import micropython + print(micropython.const(1)) from micropython import const + print(const(2)) + + f() diff --git a/tests/micropython/viper_misc.py b/tests/micropython/viper_misc.py index 021e03f2ca..41389c751d 100644 --- a/tests/micropython/viper_misc.py +++ b/tests/micropython/viper_misc.py @@ -2,61 +2,79 @@ import micropython # viper function taking and returning ints @micropython.viper -def viper_int(x:int, y:int) -> int: +def viper_int(x: int, y: int) -> int: return x + y + 3 + + print(viper_int(1, 2)) # viper function taking and returning objects @micropython.viper -def viper_object(x:object, y:object) -> object: +def viper_object(x: object, y: object) -> object: return x + y + + print(viper_object(1, 2)) # return None as non-object (should return 0) @micropython.viper def viper_ret_none() -> int: return None + + print(viper_ret_none()) # return Ellipsis as object @micropython.viper def viper_ret_ellipsis() -> object: return ... + + print(viper_ret_ellipsis()) # 3 args @micropython.viper -def viper_3args(a:int, b:int, c:int) -> int: +def viper_3args(a: int, b: int, c: int) -> int: return a + b + c + + print(viper_3args(1, 2, 3)) # 4 args @micropython.viper -def viper_4args(a:int, b:int, c:int, d:int) -> int: +def viper_4args(a: int, b: int, c: int, d: int) -> int: return a + b + c + d + + # viper call with 4 args not yet supported -#print(viper_4args(1, 2, 3, 4)) +# print(viper_4args(1, 2, 3, 4)) # a local (should have automatic type int) @micropython.viper -def viper_local(x:int) -> int: +def viper_local(x: int) -> int: y = 4 return x + y + + print(viper_local(3)) # without type annotation, types should default to object @micropython.viper def viper_no_annotation(x, y): return x * y + + print(viper_no_annotation(4, 5)) # a for loop @micropython.viper -def viper_for(a:int, b:int) -> int: +def viper_for(a: int, b: int) -> int: total = 0 for x in range(a, b): total += x return total + + print(viper_for(10, 10000)) # accessing a global @@ -65,42 +83,56 @@ def viper_access_global(): global gl gl = 1 return gl + + print(viper_access_global(), gl) # calling print with object and int types @micropython.viper -def viper_print(x, y:int): +def viper_print(x, y: int): print(x, y + 1) + + viper_print(1, 2) # convert constants to objects in tuple @micropython.viper def viper_tuple_consts(x): return (x, 1, False, True) + + print(viper_tuple_consts(0)) # making a tuple from an object and an int @micropython.viper -def viper_tuple(x, y:int): +def viper_tuple(x, y: int): return (x, y + 1) + + print(viper_tuple(1, 2)) # making a list from an object and an int @micropython.viper -def viper_list(x, y:int): +def viper_list(x, y: int): return [x, y + 1] + + print(viper_list(1, 2)) # making a set from an object and an int @micropython.viper -def viper_set(x, y:int): +def viper_set(x, y: int): return {x, y + 1} + + print(sorted(list(viper_set(1, 2)))) # raising an exception @micropython.viper -def viper_raise(x:int): +def viper_raise(x: int): raise OSError(x) + + try: viper_raise(1) except OSError as e: @@ -110,7 +142,10 @@ except OSError as e: @micropython.viper def viper_gc() -> int: return 1 + + print(viper_gc()) import gc + gc.collect() print(viper_gc()) diff --git a/tests/micropython/viper_misc_intbig.py b/tests/micropython/viper_misc_intbig.py index e036435c7a..055c08d8e5 100644 --- a/tests/micropython/viper_misc_intbig.py +++ b/tests/micropython/viper_misc_intbig.py @@ -4,5 +4,8 @@ import micropython @micropython.viper def viper_uint() -> uint: return uint(-1) + + import sys + print(viper_uint() == (sys.maxsize << 1 | 1)) diff --git a/tests/micropython/viper_ptr16_load.py b/tests/micropython/viper_ptr16_load.py index 0b865eb9e7..30c85d0669 100644 --- a/tests/micropython/viper_ptr16_load.py +++ b/tests/micropython/viper_ptr16_load.py @@ -1,21 +1,25 @@ # test loading from ptr16 type # only works on little endian machines + @micropython.viper -def get(src:ptr16) -> int: +def get(src: ptr16) -> int: return src[0] -@micropython.viper -def get1(src:ptr16) -> int: - return src[1] @micropython.viper -def memadd(src:ptr16, n:int) -> int: +def get1(src: ptr16) -> int: + return src[1] + + +@micropython.viper +def memadd(src: ptr16, n: int) -> int: sum = 0 for i in range(n): sum += src[i] return sum + @micropython.viper def memadd2(src_in) -> int: src = ptr16(src_in) @@ -25,7 +29,8 @@ def memadd2(src_in) -> int: sum += src[i] return sum -b = bytearray(b'1234') + +b = bytearray(b"1234") print(b) print(get(b), get1(b)) print(memadd(b, 2)) diff --git a/tests/micropython/viper_ptr16_store.py b/tests/micropython/viper_ptr16_store.py index 5a5f25d170..3ca5a027c0 100644 --- a/tests/micropython/viper_ptr16_store.py +++ b/tests/micropython/viper_ptr16_store.py @@ -1,25 +1,30 @@ # test ptr16 type + @micropython.viper -def set(dest:ptr16, val:int): +def set(dest: ptr16, val: int): dest[0] = val -@micropython.viper -def set1(dest:ptr16, val:int): - dest[1] = val @micropython.viper -def memset(dest:ptr16, val:int, n:int): +def set1(dest: ptr16, val: int): + dest[1] = val + + +@micropython.viper +def memset(dest: ptr16, val: int, n: int): for i in range(n): dest[i] = val + @micropython.viper -def memset2(dest_in, val:int): +def memset2(dest_in, val: int): dest = ptr16(dest_in) n = int(len(dest_in)) >> 1 for i in range(n): dest[i] = val + b = bytearray(4) print(b) diff --git a/tests/micropython/viper_ptr32_load.py b/tests/micropython/viper_ptr32_load.py index 4d8b3846de..b0b90bcaf5 100644 --- a/tests/micropython/viper_ptr32_load.py +++ b/tests/micropython/viper_ptr32_load.py @@ -1,20 +1,24 @@ # test loading from ptr32 type + @micropython.viper -def get(src:ptr32) -> int: +def get(src: ptr32) -> int: return src[0] -@micropython.viper -def get1(src:ptr32) -> int: - return src[1] @micropython.viper -def memadd(src:ptr32, n:int) -> int: +def get1(src: ptr32) -> int: + return src[1] + + +@micropython.viper +def memadd(src: ptr32, n: int) -> int: sum = 0 for i in range(n): sum += src[i] return sum + @micropython.viper def memadd2(src_in) -> int: src = ptr32(src_in) @@ -24,7 +28,8 @@ def memadd2(src_in) -> int: sum += src[i] return sum -b = bytearray(b'\x12\x12\x12\x12\x34\x34\x34\x34') + +b = bytearray(b"\x12\x12\x12\x12\x34\x34\x34\x34") print(b) print(hex(get(b)), hex(get1(b))) print(hex(memadd(b, 2))) diff --git a/tests/micropython/viper_ptr32_store.py b/tests/micropython/viper_ptr32_store.py index 973086e4ad..ff0c371ab8 100644 --- a/tests/micropython/viper_ptr32_store.py +++ b/tests/micropython/viper_ptr32_store.py @@ -1,25 +1,30 @@ # test store to ptr32 type + @micropython.viper -def set(dest:ptr32, val:int): +def set(dest: ptr32, val: int): dest[0] = val -@micropython.viper -def set1(dest:ptr32, val:int): - dest[1] = val @micropython.viper -def memset(dest:ptr32, val:int, n:int): +def set1(dest: ptr32, val: int): + dest[1] = val + + +@micropython.viper +def memset(dest: ptr32, val: int, n: int): for i in range(n): dest[i] = val + @micropython.viper -def memset2(dest_in, val:int): +def memset2(dest_in, val: int): dest = ptr32(dest_in) n = int(len(dest_in)) >> 2 for i in range(n): dest[i] = val + b = bytearray(8) print(b) diff --git a/tests/micropython/viper_ptr8_load.py b/tests/micropython/viper_ptr8_load.py index 0ccf8a1d76..d871bfb689 100644 --- a/tests/micropython/viper_ptr8_load.py +++ b/tests/micropython/viper_ptr8_load.py @@ -1,20 +1,24 @@ # test loading from ptr8 type + @micropython.viper -def get(src:ptr8) -> int: +def get(src: ptr8) -> int: return src[0] -@micropython.viper -def get1(src:ptr8) -> int: - return src[1] @micropython.viper -def memadd(src:ptr8, n:int) -> int: +def get1(src: ptr8) -> int: + return src[1] + + +@micropython.viper +def memadd(src: ptr8, n: int) -> int: sum = 0 for i in range(n): sum += src[i] return sum + @micropython.viper def memadd2(src_in) -> int: src = ptr8(src_in) @@ -24,7 +28,8 @@ def memadd2(src_in) -> int: sum += src[i] return sum -b = bytearray(b'1234') + +b = bytearray(b"1234") print(b) print(get(b), get1(b)) print(memadd(b, 4)) diff --git a/tests/micropython/viper_ptr8_store.py b/tests/micropython/viper_ptr8_store.py index 5a8622eb10..baa9e2c6d4 100644 --- a/tests/micropython/viper_ptr8_store.py +++ b/tests/micropython/viper_ptr8_store.py @@ -1,25 +1,30 @@ # test ptr8 type + @micropython.viper -def set(dest:ptr8, val:int): +def set(dest: ptr8, val: int): dest[0] = val -@micropython.viper -def set1(dest:ptr8, val:int): - dest[1] = val @micropython.viper -def memset(dest:ptr8, val:int, n:int): +def set1(dest: ptr8, val: int): + dest[1] = val + + +@micropython.viper +def memset(dest: ptr8, val: int, n: int): for i in range(n): dest[i] = val + @micropython.viper -def memset2(dest_in, val:int): +def memset2(dest_in, val: int): dest = ptr8(dest_in) n = int(len(dest_in)) for i in range(n): dest[i] = val + b = bytearray(4) print(b) diff --git a/tests/micropython/viper_subscr.py b/tests/micropython/viper_subscr.py index 2198ed7313..bcaabd3fb4 100644 --- a/tests/micropython/viper_subscr.py +++ b/tests/micropython/viper_subscr.py @@ -1,15 +1,18 @@ # test standard Python subscr using viper types + @micropython.viper -def get(dest, i:int): +def get(dest, i: int): i += 1 return dest[i] + @micropython.viper -def set(dest, i:int, val:int): +def set(dest, i: int, val: int): i += 1 dest[i] = val + 1 + ar = [i for i in range(3)] for i in range(len(ar)): diff --git a/tests/micropython/viper_try.py b/tests/micropython/viper_try.py index d75b3418e3..61335af221 100644 --- a/tests/micropython/viper_try.py +++ b/tests/micropython/viper_try.py @@ -6,11 +6,13 @@ def f(): try: fail finally: - print('finally') + print("finally") + + try: f() except NameError: - print('NameError') + print("NameError") # nested try-except with try-finally @micropython.viper @@ -19,9 +21,11 @@ def f(): try: fail finally: - print('finally') + print("finally") except NameError: - print('NameError') + print("NameError") + + f() # check that locals written to in try blocks keep their values @@ -36,5 +40,6 @@ def f(): print(a) a = 300 print(a) -f() + +f() diff --git a/tests/micropython/viper_types.py b/tests/micropython/viper_types.py index ae72c0cf30..3af148171e 100644 --- a/tests/micropython/viper_types.py +++ b/tests/micropython/viper_types.py @@ -4,8 +4,10 @@ import micropython # converting incoming arg to bool @micropython.viper -def f1(x:bool): +def f1(x: bool): print(x) + + f1(0) f1(1) f1([]) @@ -13,8 +15,10 @@ f1([1]) # taking and returning a bool @micropython.viper -def f2(x:bool) -> bool: +def f2(x: bool) -> bool: return x + + print(f2([])) print(f2([1])) @@ -22,5 +26,7 @@ print(f2([1])) @micropython.viper def f3(x) -> bool: return bool(x) + + print(f3([])) print(f3(-1)) diff --git a/tests/micropython/viper_with.py b/tests/micropython/viper_with.py index 2bc3c4f1b2..d640c8ae0f 100644 --- a/tests/micropython/viper_with.py +++ b/tests/micropython/viper_with.py @@ -1,18 +1,24 @@ # test with handling within a viper function + class C: def __init__(self): - print('__init__') + print("__init__") + def __enter__(self): - print('__enter__') + print("__enter__") + def __exit__(self, a, b, c): - print('__exit__', a, b, c) + print("__exit__", a, b, c) + # basic with @micropython.viper def f(): with C(): print(1) + + f() # nested with and try-except @@ -24,5 +30,7 @@ def f(): fail print(2) except NameError: - print('NameError') + print("NameError") + + f() diff --git a/tests/misc/features.py b/tests/misc/features.py index 874945bfcf..455b44fb1e 100644 --- a/tests/misc/features.py +++ b/tests/misc/features.py @@ -7,159 +7,199 @@ except AttributeError: # mad.py # Alf Clement 27-Mar-2014 # -zero=0 -three=3 +zero = 0 +three = 3 print("1") print("2") print(three) print("{}".format(4)) -five=25//5 +five = 25 // 5 print(int(five)) -j=0 +j = 0 for i in range(4): - j += i + j += i print(j) -print(3+4) +print(3 + 4) try: - a=4//zero + a = 4 // zero except: - print(8) + print(8) print("xxxxxxxxx".count("x")) + + def ten(): - return 10 + return 10 + + print(ten()) -a=[] +a = [] for i in range(13): - a.append(i) -print(a[11]) + a.append(i) +print(a[11]) print(a[-1]) -str="0123456789" -print(str[1]+str[3]) +str = "0123456789" +print(str[1] + str[3]) + + def p(s): - print(s) + print(s) + + p("14") p(15) + + class A: - def __init__(self): - self.a=16 - def print(self): - print(self.a) - def set(self,b): - self.a=b -a=A() + def __init__(self): + self.a = 16 + + def print(self): + print(self.a) + + def set(self, b): + self.a = b + + +a = A() a.print() a.set(17) a.print() -b=A() +b = A() b.set(a.a + 1) b.print() for i in range(20): - pass + pass print(i) if 20 > 30: - a="1" + a = "1" else: - a="2" + a = "2" if 0 < 4: - print(a+"0") + print(a + "0") else: - print(a+"1") -a=[20,21,22,23,24] + print(a + "1") +a = [20, 21, 22, 23, 24] for i in a: - if i < 21: - continue - if i > 21: - break - print(i) -b=[a,a,a] + if i < 21: + continue + if i > 21: + break + print(i) +b = [a, a, a] print(b[1][2]) -print(161//7) -a=24 +print(161 // 7) +a = 24 while True: - try: - def gcheck(): - global a - print(a) - gcheck() - class c25(): - x=25 - x=c25() - print(x.x) - raise - except: - print(26) - print(27+zero) - break + try: + + def gcheck(): + global a + print(a) + + gcheck() + + class c25: + x = 25 + + x = c25() + print(x.x) + raise + except: + print(26) + print(27 + zero) + break print(28) -k=29 +k = 29 + + def f(): - global k - k = yield k + global k + k = yield k + + print(next(f())) while True: - k+= 1 - if k < 30: - continue - break + k += 1 + if k < 30: + continue + break print(k) -for i in [1,2,3]: - class A(): - def __init__(self, c): - self.a = i+10*c - b = A(3) - print(b.a) +for i in [1, 2, 3]: + + class A: + def __init__(self, c): + self.a = i + 10 * c + + b = A(3) + print(b.a) print(34) -p=0 +p = 0 for i in range(35, -1, -1): - print(i) - p = p + 1 - if p > 0: - break -p=36 + print(i) + p = p + 1 + if p > 0: + break +p = 36 while p == 36: - print(p) - p=37 + print(p) + p = 37 print(p) for i in [38]: - print(i) -print(int(exec("def foo(): return 38") == None)+foo()) + print(i) +print(int(exec("def foo(): return 38") == None) + foo()) d = {} exec("def bar(): return 40", d) print(d["bar"]()) + + def fib2(n): - result = [] - a, b = 0, 1 - while a < n: - result.append(a) - a, b = b, a+b - return result -print(fib2(100)[-2]-14) -Answer={} -Answer["ForAll"]=42 + result = [] + a, b = 0, 1 + while a < n: + result.append(a) + a, b = b, a + b + return result + + +print(fib2(100)[-2] - 14) +Answer = {} +Answer["ForAll"] = 42 print(Answer["ForAll"]) i = 43 + + def f(i=i): print(i) + + i = 44 f() print(i) while True: - try: - if None != True: - print(45) - break - else: - print(0) - except: - print(0) + try: + if None != True: + print(45) + break + else: + print(0) + except: + print(0) print(46) -print(46+1) +print(46 + 1) + + def u(p): - if p > 3: - return 3*p - else: - return u(2*p)-3*u(p) + if p > 3: + return 3 * p + else: + return u(2 * p) - 3 * u(p) + + print(u(16)) + + def u49(): - return 49 + return 49 + + print(u49()) diff --git a/tests/misc/non_compliant.py b/tests/misc/non_compliant.py index ea67382227..ebba9b16aa 100644 --- a/tests/misc/non_compliant.py +++ b/tests/misc/non_compliant.py @@ -9,143 +9,153 @@ except ImportError: # when super can't find self try: - exec('def f(): super()') + exec("def f(): super()") except SyntaxError: - print('SyntaxError') + print("SyntaxError") # store to exception attribute is not allowed try: ValueError().x = 0 except AttributeError: - print('AttributeError') + print("AttributeError") # array deletion not implemented try: - a = array.array('b', (1, 2, 3)) + a = array.array("b", (1, 2, 3)) del a[1] except TypeError: - print('TypeError') + print("TypeError") # slice with step!=1 not implemented try: - a = array.array('b', (1, 2, 3)) + a = array.array("b", (1, 2, 3)) print(a[3:2:2]) except NotImplementedError: - print('NotImplementedError') + print("NotImplementedError") # containment, looking for integer not implemented try: - print(1 in array.array('B', b'12')) + print(1 in array.array("B", b"12")) except NotImplementedError: - print('NotImplementedError') + print("NotImplementedError") # uPy raises TypeError, shold be ValueError try: - '%c' % b'\x01\x02' + "%c" % b"\x01\x02" except (TypeError, ValueError): - print('TypeError, ValueError') + print("TypeError, ValueError") # attributes/subscr not implemented try: - print('{a[0]}'.format(a=[1, 2])) + print("{a[0]}".format(a=[1, 2])) except NotImplementedError: - print('NotImplementedError') + print("NotImplementedError") # str(...) with keywords not implemented try: - str(b'abc', encoding='utf8') + str(b"abc", encoding="utf8") except NotImplementedError: - print('NotImplementedError') + print("NotImplementedError") # str.rsplit(None, n) not implemented try: - 'a a a'.rsplit(None, 1) + "a a a".rsplit(None, 1) except NotImplementedError: - print('NotImplementedError') + print("NotImplementedError") # str.endswith(s, start) not implemented try: - 'abc'.endswith('c', 1) + "abc".endswith("c", 1) except NotImplementedError: - print('NotImplementedError') + print("NotImplementedError") # str subscr with step!=1 not implemented try: - print('abc'[1:2:3]) + print("abc"[1:2:3]) except NotImplementedError: - print('NotImplementedError') + print("NotImplementedError") # bytes(...) with keywords not implemented try: - bytes('abc', encoding='utf8') + bytes("abc", encoding="utf8") except NotImplementedError: - print('NotImplementedError') + print("NotImplementedError") # bytes subscr with step!=1 not implemented try: - b'123'[0:3:2] + b"123"[0:3:2] except NotImplementedError: - print('NotImplementedError') + print("NotImplementedError") # tuple load with step!=1 not implemented try: ()[2:3:4] except NotImplementedError: - print('NotImplementedError') + print("NotImplementedError") # list store with step!=1 not implemented try: [][2:3:4] = [] except NotImplementedError: - print('NotImplementedError') + print("NotImplementedError") # list delete with step!=1 not implemented try: del [][2:3:4] except NotImplementedError: - print('NotImplementedError') + print("NotImplementedError") # struct pack with too many args, not checked by uPy -print(ustruct.pack('bb', 1, 2, 3)) +print(ustruct.pack("bb", 1, 2, 3)) # struct pack with too few args, not checked by uPy -print(ustruct.pack('bb', 1)) +print(ustruct.pack("bb", 1)) # array slice assignment with unsupported RHS try: bytearray(4)[0:1] = [1, 2] except NotImplementedError: - print('NotImplementedError') + print("NotImplementedError") # can't assign attributes to a function def f(): pass + + try: f.x = 1 except AttributeError: - print('AttributeError') + print("AttributeError") # can't call a function type (ie make new instances of a function) try: type(f)() except TypeError: - print('TypeError') + print("TypeError") # test when object explicitly listed at not-last position in parent tuple # this is not compliant with CPython because of illegal MRO class A: def foo(self): - print('A.foo') + print("A.foo") + + class B(object, A): pass + + B().foo() # can't assign property (or other special accessors) to already-subclassed class class A: pass + + class B(A): pass + + try: A.bar = property() except AttributeError: - print('AttributeError') + print("AttributeError") diff --git a/tests/misc/non_compliant_lexer.py b/tests/misc/non_compliant_lexer.py index 7e50d2836c..e1c21f3d71 100644 --- a/tests/misc/non_compliant_lexer.py +++ b/tests/misc/non_compliant_lexer.py @@ -1,31 +1,33 @@ # lexer tests for things that are not implemented, or have non-compliant behaviour + def test(code): try: exec(code) - print('no Error') + print("no Error") except SyntaxError: - print('SyntaxError') + print("SyntaxError") except NotImplementedError: - print('NotImplementedError') + print("NotImplementedError") + # uPy requires spaces between literal numbers and keywords, CPy doesn't try: - eval('1and 0') + eval("1and 0") except SyntaxError: - print('SyntaxError') + print("SyntaxError") try: - eval('1or 0') + eval("1or 0") except SyntaxError: - print('SyntaxError') + print("SyntaxError") try: - eval('1if 1else 0') + eval("1if 1else 0") except SyntaxError: - print('SyntaxError') + print("SyntaxError") try: - eval('1if 0else 0') + eval("1if 0else 0") except SyntaxError: - print('SyntaxError') + print("SyntaxError") # unicode name escapes are not implemented test('"\\N{LATIN SMALL LETTER A}"') diff --git a/tests/misc/print_exception.py b/tests/misc/print_exception.py index 2067030bf9..f26c1fd5ac 100644 --- a/tests/misc/print_exception.py +++ b/tests/misc/print_exception.py @@ -1,4 +1,5 @@ import sys + try: try: import uio as io @@ -8,12 +9,14 @@ except ImportError: print("SKIP") raise SystemExit -if hasattr(sys, 'print_exception'): +if hasattr(sys, "print_exception"): print_exception = sys.print_exception else: import traceback + print_exception = lambda e, f: traceback.print_exception(None, e, sys.exc_info()[2], file=f) + def print_exc(e): buf = io.StringIO() print_exception(e, buf) @@ -29,22 +32,27 @@ def print_exc(e): elif not l.startswith(" "): print(l) + # basic exception message try: - raise Exception('msg') + raise Exception("msg") except Exception as e: - print('caught') + print("caught") print_exc(e) # exception message with more than 1 source-code line def f(): g() + + def g(): - raise Exception('fail') + raise Exception("fail") + + try: f() except Exception as e: - print('caught') + print("caught") print_exc(e) # Test that an exception propagated through a finally doesn't have a traceback added there @@ -52,9 +60,9 @@ try: try: f() finally: - print('finally') + print("finally") except Exception as e: - print('caught') + print("caught") print_exc(e) # Test that re-raising an exception doesn't add traceback info @@ -62,25 +70,27 @@ try: try: f() except Exception as e: - print('reraise') + print("reraise") print_exc(e) raise except Exception as e: - print('caught') + print("caught") print_exc(e) # Here we have a function with lots of bytecode generated for a single source-line, and # there is an error right at the end of the bytecode. It should report the correct line. def f(): - f([1, 2], [1, 2], [1, 2], {1:1, 1:1, 1:1, 1:1, 1:1, 1:1, 1:f.X}) + f([1, 2], [1, 2], [1, 2], {1: 1, 1: 1, 1: 1, 1: 1, 1: 1, 1: 1, 1: f.X}) return 1 + + try: f() except Exception as e: print_exc(e) # Test non-stream object passed as output object, only valid for uPy -if hasattr(sys, 'print_exception'): +if hasattr(sys, "print_exception"): try: sys.print_exception(Exception, 1) had_exception = False diff --git a/tests/misc/rge_sm.py b/tests/misc/rge_sm.py index 5bbf9d48b5..f3bb4189f7 100644 --- a/tests/misc/rge_sm.py +++ b/tests/misc/rge_sm.py @@ -3,30 +3,31 @@ import math + class RungeKutta(object): def __init__(self, functions, initConditions, t0, dh, save=True): - self.Trajectory, self.save = [[t0] + initConditions], save - self.functions = [lambda *args: 1.0] + list(functions) - self.N, self.dh = len(self.functions), dh - self.coeff = [1.0/6.0, 2.0/6.0, 2.0/6.0, 1.0/6.0] - self.InArgCoeff = [0.0, 0.5, 0.5, 1.0] + self.Trajectory, self.save = [[t0] + initConditions], save + self.functions = [lambda *args: 1.0] + list(functions) + self.N, self.dh = len(self.functions), dh + self.coeff = [1.0 / 6.0, 2.0 / 6.0, 2.0 / 6.0, 1.0 / 6.0] + self.InArgCoeff = [0.0, 0.5, 0.5, 1.0] def iterate(self): - step = self.Trajectory[-1][:] - istep, iac = step[:], self.InArgCoeff + step = self.Trajectory[-1][:] + istep, iac = step[:], self.InArgCoeff k, ktmp = self.N * [0.0], self.N * [0.0] for ic, c in enumerate(self.coeff): for if_, f in enumerate(self.functions): - arguments = [ (x + k[i]*iac[ic]) for i, x in enumerate(istep)] + arguments = [(x + k[i] * iac[ic]) for i, x in enumerate(istep)] try: feval = f(*arguments) except OverflowError: return False - if abs(feval) > 1e2: # stop integrating + if abs(feval) > 1e2: # stop integrating return False - ktmp[if_] = self.dh * feval + ktmp[if_] = self.dh * feval k = ktmp[:] - step = [s + c*k[ik] for ik,s in enumerate(step)] + step = [s + c * k[ik] for ik, s in enumerate(step)] if self.save: self.Trajectory += [step] else: @@ -46,23 +47,45 @@ class RungeKutta(object): def series(self): return zip(*self.Trajectory) + # 1-loop RGES for the main parameters of the SM # couplings are: g1, g2, g3 of U(1), SU(2), SU(3); yt (top Yukawa), lambda (Higgs quartic) # see arxiv.org/abs/0812.4950, eqs 10-15 sysSM = ( - lambda *a: 41.0 / 96.0 / math.pi**2 * a[1]**3, # g1 - lambda *a: -19.0 / 96.0 / math.pi**2 * a[2]**3, # g2 - lambda *a: -42.0 / 96.0 / math.pi**2 * a[3]**3, # g3 - lambda *a: 1.0 / 16.0 / math.pi**2 * (9.0 / 2.0 * a[4]**3 - 8.0 * a[3]**2 * a[4] - 9.0 / 4.0 * a[2]**2 * a[4] - 17.0 / 12.0 * a[1]**2 * a[4]), # yt - lambda *a: 1.0 / 16.0 / math.pi**2 * (24.0 * a[5]**2 + 12.0 * a[4]**2 * a[5] - 9.0 * a[5] * (a[2]**2 + 1.0 / 3.0 * a[1]**2) - 6.0 * a[4]**4 + 9.0 / 8.0 * a[2]**4 + 3.0 / 8.0 * a[1]**4 + 3.0 / 4.0 * a[2]**2 * a[1]**2), # lambda + lambda *a: 41.0 / 96.0 / math.pi ** 2 * a[1] ** 3, # g1 + lambda *a: -19.0 / 96.0 / math.pi ** 2 * a[2] ** 3, # g2 + lambda *a: -42.0 / 96.0 / math.pi ** 2 * a[3] ** 3, # g3 + lambda *a: 1.0 + / 16.0 + / math.pi ** 2 + * ( + 9.0 / 2.0 * a[4] ** 3 + - 8.0 * a[3] ** 2 * a[4] + - 9.0 / 4.0 * a[2] ** 2 * a[4] + - 17.0 / 12.0 * a[1] ** 2 * a[4] + ), # yt + lambda *a: 1.0 + / 16.0 + / math.pi ** 2 + * ( + 24.0 * a[5] ** 2 + + 12.0 * a[4] ** 2 * a[5] + - 9.0 * a[5] * (a[2] ** 2 + 1.0 / 3.0 * a[1] ** 2) + - 6.0 * a[4] ** 4 + + 9.0 / 8.0 * a[2] ** 4 + + 3.0 / 8.0 * a[1] ** 4 + + 3.0 / 4.0 * a[2] ** 2 * a[1] ** 2 + ), # lambda ) + def drange(start, stop, step): r = start while r < stop: yield r r += step + def phaseDiagram(system, trajStart, trajPlot, h=0.1, tend=1.0, range=1.0): tstart = 0.0 for i in drange(0, range, 0.1 * range): @@ -82,10 +105,10 @@ def phaseDiagram(system, trajStart, trajPlot, h=0.1, tend=1.0, range=1.0): p2 = rk.Trajectory[2 * l] x1, y1 = trajPlot(p1) x2, y2 = trajPlot(p2) - dx = -0.5 * (y2 - y1) # orthogonal to line + dx = -0.5 * (y2 - y1) # orthogonal to line dy = 0.5 * (x2 - x1) # orthogonal to line - #l = math.sqrt(dx*dx + dy*dy) - #if abs(l) > 1e-3: + # l = math.sqrt(dx*dx + dy*dy) + # if abs(l) > 1e-3: # l = 0.1 / l # dx *= l # dy *= l @@ -94,6 +117,7 @@ def phaseDiagram(system, trajStart, trajPlot, h=0.1, tend=1.0, range=1.0): print(x1 - dx, y1 - dy) print() + def singleTraj(system, trajStart, h=0.02, tend=1.0): tstart = 0.0 @@ -106,9 +130,12 @@ def singleTraj(system, trajStart, h=0.02, tend=1.0): for i in range(len(rk.Trajectory)): tr = rk.Trajectory[i] - print(' '.join(["{:.4f}".format(t) for t in tr])) + print(" ".join(["{:.4f}".format(t) for t in tr])) -#phaseDiagram(sysSM, (lambda i, j: [0.354, 0.654, 1.278, 0.8 + 0.2 * i, 0.1 + 0.1 * j]), (lambda a: (a[4], a[5])), h=0.1, tend=math.log(10**17)) + +# phaseDiagram(sysSM, (lambda i, j: [0.354, 0.654, 1.278, 0.8 + 0.2 * i, 0.1 + 0.1 * j]), (lambda a: (a[4], a[5])), h=0.1, tend=math.log(10**17)) # initial conditions at M_Z -singleTraj(sysSM, [0.354, 0.654, 1.278, 0.983, 0.131], h=0.5, tend=math.log(10**17)) # true values +singleTraj( + sysSM, [0.354, 0.654, 1.278, 0.983, 0.131], h=0.5, tend=math.log(10 ** 17) +) # true values diff --git a/tests/misc/sys_atexit.py b/tests/misc/sys_atexit.py index f5317953c2..e9c5693f97 100644 --- a/tests/misc/sys_atexit.py +++ b/tests/misc/sys_atexit.py @@ -1,17 +1,20 @@ # test sys.atexit() function import sys + try: sys.atexit except AttributeError: - print('SKIP') + print("SKIP") raise SystemExit some_var = None + def do_at_exit(): print("done at exit:", some_var) + sys.atexit(do_at_exit) some_var = "ok" diff --git a/tests/misc/sys_exc_info.py b/tests/misc/sys_exc_info.py index bf9438e462..d7e8a2d943 100644 --- a/tests/misc/sys_exc_info.py +++ b/tests/misc/sys_exc_info.py @@ -1,15 +1,18 @@ import sys + try: sys.exc_info except: print("SKIP") raise SystemExit + def f(): print(sys.exc_info()[0:2]) + try: - raise ValueError('value', 123) + raise ValueError("value", 123) except: print(sys.exc_info()[0:2]) f() diff --git a/tests/misc/sys_settrace_features.py b/tests/misc/sys_settrace_features.py index 932e430de7..a123044892 100644 --- a/tests/misc/sys_settrace_features.py +++ b/tests/misc/sys_settrace_features.py @@ -6,83 +6,100 @@ except AttributeError: print("SKIP") raise SystemExit + def print_stacktrace(frame, level=0): # Ignore CPython specific helpers. - if frame.f_globals['__name__'].find('importlib') != -1: + if frame.f_globals["__name__"].find("importlib") != -1: print_stacktrace(frame.f_back, level) return - print("%2d: %s@%s:%s => %s:%d" % ( - level, " ", - frame.f_globals['__name__'], - frame.f_code.co_name, - # reduce full path to some pseudo-relative - 'misc' + ''.join(frame.f_code.co_filename.split('tests/misc')[-1:]), - frame.f_lineno, - )) + print( + "%2d: %s@%s:%s => %s:%d" + % ( + level, + " ", + frame.f_globals["__name__"], + frame.f_code.co_name, + # reduce full path to some pseudo-relative + "misc" + "".join(frame.f_code.co_filename.split("tests/misc")[-1:]), + frame.f_lineno, + ) + ) if frame.f_back: print_stacktrace(frame.f_back, level + 1) + class _Prof: - trace_count = 0; + trace_count = 0 def trace_tick(self, frame, event, arg): self.trace_count += 1 print_stacktrace(frame) + __prof__ = _Prof() alice_handler_set = False + + def trace_tick_handler_alice(frame, event, arg): print("### trace_handler::Alice event:", event) __prof__.trace_tick(frame, event, arg) return trace_tick_handler_alice + bob_handler_set = False + + def trace_tick_handler_bob(frame, event, arg): print("### trace_handler::Bob event:", event) __prof__.trace_tick(frame, event, arg) return trace_tick_handler_bob + def trace_tick_handler(frame, event, arg): # Ignore CPython specific helpers. - if frame.f_globals['__name__'].find('importlib') != -1: + if frame.f_globals["__name__"].find("importlib") != -1: return print("### trace_handler::main event:", event) __prof__.trace_tick(frame, event, arg) - if frame.f_code.co_name != 'factorial': + if frame.f_code.co_name != "factorial": return trace_tick_handler global alice_handler_set - if event == 'call' and not alice_handler_set: + if event == "call" and not alice_handler_set: alice_handler_set = True return trace_tick_handler_alice global bob_handler_set - if event == 'call' and not bob_handler_set: + if event == "call" and not bob_handler_set: bob_handler_set = True return trace_tick_handler_bob return trace_tick_handler + def factorial(n): if n == 0: return 1 else: return n * factorial(n - 1) + def do_tests(): # These commands are here to demonstrate some execution being traced. print("Who loves the sun?") print("Not every-", factorial(3)) from sys_settrace_subdir import trace_generic + trace_generic.run_tests() return + sys.settrace(trace_tick_handler) do_tests() sys.settrace(None) diff --git a/tests/misc/sys_settrace_generator.py b/tests/misc/sys_settrace_generator.py index e955d6b626..4ace0f50e8 100644 --- a/tests/misc/sys_settrace_generator.py +++ b/tests/misc/sys_settrace_generator.py @@ -8,21 +8,28 @@ except AttributeError: print("SKIP") raise SystemExit + def print_stacktrace(frame, level=0): - print("%2d: %s@%s:%s => %s:%d" % ( - level, " ", - frame.f_globals['__name__'], - frame.f_code.co_name, - # reduce full path to some pseudo-relative - 'misc' + ''.join(frame.f_code.co_filename.split('tests/misc')[-1:]), - frame.f_lineno, - )) + print( + "%2d: %s@%s:%s => %s:%d" + % ( + level, + " ", + frame.f_globals["__name__"], + frame.f_code.co_name, + # reduce full path to some pseudo-relative + "misc" + "".join(frame.f_code.co_filename.split("tests/misc")[-1:]), + frame.f_lineno, + ) + ) if frame.f_back: print_stacktrace(frame.f_back, level + 1) + trace_count = 0 + def trace_tick_handler(frame, event, arg): global trace_count print("### trace_handler::main event:", event) @@ -30,12 +37,13 @@ def trace_tick_handler(frame, event, arg): print_stacktrace(frame) return trace_tick_handler + def test_generator(): def make_gen(): - yield 1<<0 - yield 1<<1 - yield 1<<2 - return 1<<3 + yield 1 << 0 + yield 1 << 1 + yield 1 << 2 + return 1 << 3 gen = make_gen() r = 0 @@ -56,6 +64,7 @@ def test_generator(): r += i print(r) + sys.settrace(trace_tick_handler) test_generator() sys.settrace(None) diff --git a/tests/misc/sys_settrace_generator.py.exp b/tests/misc/sys_settrace_generator.py.exp index 5329cdfe71..de9d0bf1c3 100644 --- a/tests/misc/sys_settrace_generator.py.exp +++ b/tests/misc/sys_settrace_generator.py.exp @@ -1,195 +1,195 @@ ### trace_handler::main event: call - 0: @__main__:test_generator => miscmisc/sys_settrace_generator.py:33 - 1: @__main__: => miscmisc/sys_settrace_generator.py:60 -### trace_handler::main event: line - 0: @__main__:test_generator => miscmisc/sys_settrace_generator.py:34 - 1: @__main__: => miscmisc/sys_settrace_generator.py:60 -### trace_handler::main event: line - 0: @__main__:test_generator => miscmisc/sys_settrace_generator.py:40 - 1: @__main__: => miscmisc/sys_settrace_generator.py:60 -### trace_handler::main event: line 0: @__main__:test_generator => miscmisc/sys_settrace_generator.py:41 - 1: @__main__: => miscmisc/sys_settrace_generator.py:60 + 1: @__main__: => miscmisc/sys_settrace_generator.py:69 ### trace_handler::main event: line 0: @__main__:test_generator => miscmisc/sys_settrace_generator.py:42 - 1: @__main__: => miscmisc/sys_settrace_generator.py:60 -### trace_handler::main event: line - 0: @__main__:test_generator => miscmisc/sys_settrace_generator.py:44 - 1: @__main__: => miscmisc/sys_settrace_generator.py:60 -### trace_handler::main event: call - 0: @__main__:make_gen => miscmisc/sys_settrace_generator.py:34 - 1: @__main__:test_generator => miscmisc/sys_settrace_generator.py:44 - 2: @__main__: => miscmisc/sys_settrace_generator.py:60 -### trace_handler::main event: line - 0: @__main__:make_gen => miscmisc/sys_settrace_generator.py:35 - 1: @__main__:test_generator => miscmisc/sys_settrace_generator.py:44 - 2: @__main__: => miscmisc/sys_settrace_generator.py:60 -### trace_handler::main event: return - 0: @__main__:make_gen => miscmisc/sys_settrace_generator.py:35 - 1: @__main__:test_generator => miscmisc/sys_settrace_generator.py:44 - 2: @__main__: => miscmisc/sys_settrace_generator.py:60 + 1: @__main__: => miscmisc/sys_settrace_generator.py:69 ### trace_handler::main event: line 0: @__main__:test_generator => miscmisc/sys_settrace_generator.py:48 - 1: @__main__: => miscmisc/sys_settrace_generator.py:60 -### trace_handler::main event: call - 0: @__main__:make_gen => miscmisc/sys_settrace_generator.py:35 - 1: @__main__:test_generator => miscmisc/sys_settrace_generator.py:48 - 2: @__main__: => miscmisc/sys_settrace_generator.py:60 + 1: @__main__: => miscmisc/sys_settrace_generator.py:69 ### trace_handler::main event: line - 0: @__main__:make_gen => miscmisc/sys_settrace_generator.py:35 - 1: @__main__:test_generator => miscmisc/sys_settrace_generator.py:48 - 2: @__main__: => miscmisc/sys_settrace_generator.py:60 -### trace_handler::main event: line - 0: @__main__:make_gen => miscmisc/sys_settrace_generator.py:36 - 1: @__main__:test_generator => miscmisc/sys_settrace_generator.py:48 - 2: @__main__: => miscmisc/sys_settrace_generator.py:60 -### trace_handler::main event: return - 0: @__main__:make_gen => miscmisc/sys_settrace_generator.py:36 - 1: @__main__:test_generator => miscmisc/sys_settrace_generator.py:48 - 2: @__main__: => miscmisc/sys_settrace_generator.py:60 -### trace_handler::main event: call - 0: @__main__:make_gen => miscmisc/sys_settrace_generator.py:36 - 1: @__main__:test_generator => miscmisc/sys_settrace_generator.py:48 - 2: @__main__: => miscmisc/sys_settrace_generator.py:60 -### trace_handler::main event: line - 0: @__main__:make_gen => miscmisc/sys_settrace_generator.py:36 - 1: @__main__:test_generator => miscmisc/sys_settrace_generator.py:48 - 2: @__main__: => miscmisc/sys_settrace_generator.py:60 -### trace_handler::main event: line - 0: @__main__:make_gen => miscmisc/sys_settrace_generator.py:37 - 1: @__main__:test_generator => miscmisc/sys_settrace_generator.py:48 - 2: @__main__: => miscmisc/sys_settrace_generator.py:60 -### trace_handler::main event: return - 0: @__main__:make_gen => miscmisc/sys_settrace_generator.py:37 - 1: @__main__:test_generator => miscmisc/sys_settrace_generator.py:48 - 2: @__main__: => miscmisc/sys_settrace_generator.py:60 -### trace_handler::main event: call - 0: @__main__:make_gen => miscmisc/sys_settrace_generator.py:37 - 1: @__main__:test_generator => miscmisc/sys_settrace_generator.py:48 - 2: @__main__: => miscmisc/sys_settrace_generator.py:60 -### trace_handler::main event: line - 0: @__main__:make_gen => miscmisc/sys_settrace_generator.py:37 - 1: @__main__:test_generator => miscmisc/sys_settrace_generator.py:48 - 2: @__main__: => miscmisc/sys_settrace_generator.py:60 -### trace_handler::main event: line - 0: @__main__:make_gen => miscmisc/sys_settrace_generator.py:38 - 1: @__main__:test_generator => miscmisc/sys_settrace_generator.py:48 - 2: @__main__: => miscmisc/sys_settrace_generator.py:60 -### trace_handler::main event: return - 0: @__main__:make_gen => miscmisc/sys_settrace_generator.py:38 - 1: @__main__:test_generator => miscmisc/sys_settrace_generator.py:48 - 2: @__main__: => miscmisc/sys_settrace_generator.py:60 -### trace_handler::main event: exception - 0: @__main__:test_generator => miscmisc/sys_settrace_generator.py:48 - 1: @__main__: => miscmisc/sys_settrace_generator.py:60 + 0: @__main__:test_generator => miscmisc/sys_settrace_generator.py:49 + 1: @__main__: => miscmisc/sys_settrace_generator.py:69 ### trace_handler::main event: line 0: @__main__:test_generator => miscmisc/sys_settrace_generator.py:50 - 1: @__main__: => miscmisc/sys_settrace_generator.py:60 + 1: @__main__: => miscmisc/sys_settrace_generator.py:69 ### trace_handler::main event: line - 0: @__main__:test_generator => miscmisc/sys_settrace_generator.py:51 - 1: @__main__: => miscmisc/sys_settrace_generator.py:60 + 0: @__main__:test_generator => miscmisc/sys_settrace_generator.py:52 + 1: @__main__: => miscmisc/sys_settrace_generator.py:69 +### trace_handler::main event: call + 0: @__main__:make_gen => miscmisc/sys_settrace_generator.py:42 + 1: @__main__:test_generator => miscmisc/sys_settrace_generator.py:52 + 2: @__main__: => miscmisc/sys_settrace_generator.py:69 +### trace_handler::main event: line + 0: @__main__:make_gen => miscmisc/sys_settrace_generator.py:43 + 1: @__main__:test_generator => miscmisc/sys_settrace_generator.py:52 + 2: @__main__: => miscmisc/sys_settrace_generator.py:69 +### trace_handler::main event: return + 0: @__main__:make_gen => miscmisc/sys_settrace_generator.py:43 + 1: @__main__:test_generator => miscmisc/sys_settrace_generator.py:52 + 2: @__main__: => miscmisc/sys_settrace_generator.py:69 +### trace_handler::main event: line + 0: @__main__:test_generator => miscmisc/sys_settrace_generator.py:56 + 1: @__main__: => miscmisc/sys_settrace_generator.py:69 +### trace_handler::main event: call + 0: @__main__:make_gen => miscmisc/sys_settrace_generator.py:43 + 1: @__main__:test_generator => miscmisc/sys_settrace_generator.py:56 + 2: @__main__: => miscmisc/sys_settrace_generator.py:69 +### trace_handler::main event: line + 0: @__main__:make_gen => miscmisc/sys_settrace_generator.py:43 + 1: @__main__:test_generator => miscmisc/sys_settrace_generator.py:56 + 2: @__main__: => miscmisc/sys_settrace_generator.py:69 +### trace_handler::main event: line + 0: @__main__:make_gen => miscmisc/sys_settrace_generator.py:44 + 1: @__main__:test_generator => miscmisc/sys_settrace_generator.py:56 + 2: @__main__: => miscmisc/sys_settrace_generator.py:69 +### trace_handler::main event: return + 0: @__main__:make_gen => miscmisc/sys_settrace_generator.py:44 + 1: @__main__:test_generator => miscmisc/sys_settrace_generator.py:56 + 2: @__main__: => miscmisc/sys_settrace_generator.py:69 +### trace_handler::main event: call + 0: @__main__:make_gen => miscmisc/sys_settrace_generator.py:44 + 1: @__main__:test_generator => miscmisc/sys_settrace_generator.py:56 + 2: @__main__: => miscmisc/sys_settrace_generator.py:69 +### trace_handler::main event: line + 0: @__main__:make_gen => miscmisc/sys_settrace_generator.py:44 + 1: @__main__:test_generator => miscmisc/sys_settrace_generator.py:56 + 2: @__main__: => miscmisc/sys_settrace_generator.py:69 +### trace_handler::main event: line + 0: @__main__:make_gen => miscmisc/sys_settrace_generator.py:45 + 1: @__main__:test_generator => miscmisc/sys_settrace_generator.py:56 + 2: @__main__: => miscmisc/sys_settrace_generator.py:69 +### trace_handler::main event: return + 0: @__main__:make_gen => miscmisc/sys_settrace_generator.py:45 + 1: @__main__:test_generator => miscmisc/sys_settrace_generator.py:56 + 2: @__main__: => miscmisc/sys_settrace_generator.py:69 +### trace_handler::main event: call + 0: @__main__:make_gen => miscmisc/sys_settrace_generator.py:45 + 1: @__main__:test_generator => miscmisc/sys_settrace_generator.py:56 + 2: @__main__: => miscmisc/sys_settrace_generator.py:69 +### trace_handler::main event: line + 0: @__main__:make_gen => miscmisc/sys_settrace_generator.py:45 + 1: @__main__:test_generator => miscmisc/sys_settrace_generator.py:56 + 2: @__main__: => miscmisc/sys_settrace_generator.py:69 +### trace_handler::main event: line + 0: @__main__:make_gen => miscmisc/sys_settrace_generator.py:46 + 1: @__main__:test_generator => miscmisc/sys_settrace_generator.py:56 + 2: @__main__: => miscmisc/sys_settrace_generator.py:69 +### trace_handler::main event: return + 0: @__main__:make_gen => miscmisc/sys_settrace_generator.py:46 + 1: @__main__:test_generator => miscmisc/sys_settrace_generator.py:56 + 2: @__main__: => miscmisc/sys_settrace_generator.py:69 +### trace_handler::main event: exception + 0: @__main__:test_generator => miscmisc/sys_settrace_generator.py:56 + 1: @__main__: => miscmisc/sys_settrace_generator.py:69 +### trace_handler::main event: line + 0: @__main__:test_generator => miscmisc/sys_settrace_generator.py:58 + 1: @__main__: => miscmisc/sys_settrace_generator.py:69 +### trace_handler::main event: line + 0: @__main__:test_generator => miscmisc/sys_settrace_generator.py:59 + 1: @__main__: => miscmisc/sys_settrace_generator.py:69 test_generator 7 8 ### trace_handler::main event: line - 0: @__main__:test_generator => miscmisc/sys_settrace_generator.py:53 - 1: @__main__: => miscmisc/sys_settrace_generator.py:60 + 0: @__main__:test_generator => miscmisc/sys_settrace_generator.py:61 + 1: @__main__: => miscmisc/sys_settrace_generator.py:69 ### trace_handler::main event: line - 0: @__main__:test_generator => miscmisc/sys_settrace_generator.py:54 - 1: @__main__: => miscmisc/sys_settrace_generator.py:60 + 0: @__main__:test_generator => miscmisc/sys_settrace_generator.py:62 + 1: @__main__: => miscmisc/sys_settrace_generator.py:69 ### trace_handler::main event: line - 0: @__main__:test_generator => miscmisc/sys_settrace_generator.py:55 - 1: @__main__: => miscmisc/sys_settrace_generator.py:60 + 0: @__main__:test_generator => miscmisc/sys_settrace_generator.py:63 + 1: @__main__: => miscmisc/sys_settrace_generator.py:69 ### trace_handler::main event: call - 0: @__main__:make_gen => miscmisc/sys_settrace_generator.py:34 - 1: @__main__:test_generator => miscmisc/sys_settrace_generator.py:55 - 2: @__main__: => miscmisc/sys_settrace_generator.py:60 + 0: @__main__:make_gen => miscmisc/sys_settrace_generator.py:42 + 1: @__main__:test_generator => miscmisc/sys_settrace_generator.py:63 + 2: @__main__: => miscmisc/sys_settrace_generator.py:69 ### trace_handler::main event: line - 0: @__main__:make_gen => miscmisc/sys_settrace_generator.py:35 - 1: @__main__:test_generator => miscmisc/sys_settrace_generator.py:55 - 2: @__main__: => miscmisc/sys_settrace_generator.py:60 + 0: @__main__:make_gen => miscmisc/sys_settrace_generator.py:43 + 1: @__main__:test_generator => miscmisc/sys_settrace_generator.py:63 + 2: @__main__: => miscmisc/sys_settrace_generator.py:69 ### trace_handler::main event: return - 0: @__main__:make_gen => miscmisc/sys_settrace_generator.py:35 - 1: @__main__:test_generator => miscmisc/sys_settrace_generator.py:55 - 2: @__main__: => miscmisc/sys_settrace_generator.py:60 + 0: @__main__:make_gen => miscmisc/sys_settrace_generator.py:43 + 1: @__main__:test_generator => miscmisc/sys_settrace_generator.py:63 + 2: @__main__: => miscmisc/sys_settrace_generator.py:69 ### trace_handler::main event: line - 0: @__main__:test_generator => miscmisc/sys_settrace_generator.py:55 - 1: @__main__: => miscmisc/sys_settrace_generator.py:60 + 0: @__main__:test_generator => miscmisc/sys_settrace_generator.py:63 + 1: @__main__: => miscmisc/sys_settrace_generator.py:69 ### trace_handler::main event: line - 0: @__main__:test_generator => miscmisc/sys_settrace_generator.py:56 - 1: @__main__: => miscmisc/sys_settrace_generator.py:60 + 0: @__main__:test_generator => miscmisc/sys_settrace_generator.py:64 + 1: @__main__: => miscmisc/sys_settrace_generator.py:69 ### trace_handler::main event: line - 0: @__main__:test_generator => miscmisc/sys_settrace_generator.py:55 - 1: @__main__: => miscmisc/sys_settrace_generator.py:60 + 0: @__main__:test_generator => miscmisc/sys_settrace_generator.py:63 + 1: @__main__: => miscmisc/sys_settrace_generator.py:69 ### trace_handler::main event: call - 0: @__main__:make_gen => miscmisc/sys_settrace_generator.py:35 - 1: @__main__:test_generator => miscmisc/sys_settrace_generator.py:55 - 2: @__main__: => miscmisc/sys_settrace_generator.py:60 + 0: @__main__:make_gen => miscmisc/sys_settrace_generator.py:43 + 1: @__main__:test_generator => miscmisc/sys_settrace_generator.py:63 + 2: @__main__: => miscmisc/sys_settrace_generator.py:69 ### trace_handler::main event: line - 0: @__main__:make_gen => miscmisc/sys_settrace_generator.py:35 - 1: @__main__:test_generator => miscmisc/sys_settrace_generator.py:55 - 2: @__main__: => miscmisc/sys_settrace_generator.py:60 + 0: @__main__:make_gen => miscmisc/sys_settrace_generator.py:43 + 1: @__main__:test_generator => miscmisc/sys_settrace_generator.py:63 + 2: @__main__: => miscmisc/sys_settrace_generator.py:69 ### trace_handler::main event: line - 0: @__main__:make_gen => miscmisc/sys_settrace_generator.py:36 - 1: @__main__:test_generator => miscmisc/sys_settrace_generator.py:55 - 2: @__main__: => miscmisc/sys_settrace_generator.py:60 + 0: @__main__:make_gen => miscmisc/sys_settrace_generator.py:44 + 1: @__main__:test_generator => miscmisc/sys_settrace_generator.py:63 + 2: @__main__: => miscmisc/sys_settrace_generator.py:69 ### trace_handler::main event: return - 0: @__main__:make_gen => miscmisc/sys_settrace_generator.py:36 - 1: @__main__:test_generator => miscmisc/sys_settrace_generator.py:55 - 2: @__main__: => miscmisc/sys_settrace_generator.py:60 + 0: @__main__:make_gen => miscmisc/sys_settrace_generator.py:44 + 1: @__main__:test_generator => miscmisc/sys_settrace_generator.py:63 + 2: @__main__: => miscmisc/sys_settrace_generator.py:69 ### trace_handler::main event: line - 0: @__main__:test_generator => miscmisc/sys_settrace_generator.py:55 - 1: @__main__: => miscmisc/sys_settrace_generator.py:60 + 0: @__main__:test_generator => miscmisc/sys_settrace_generator.py:63 + 1: @__main__: => miscmisc/sys_settrace_generator.py:69 ### trace_handler::main event: line - 0: @__main__:test_generator => miscmisc/sys_settrace_generator.py:56 - 1: @__main__: => miscmisc/sys_settrace_generator.py:60 + 0: @__main__:test_generator => miscmisc/sys_settrace_generator.py:64 + 1: @__main__: => miscmisc/sys_settrace_generator.py:69 ### trace_handler::main event: line - 0: @__main__:test_generator => miscmisc/sys_settrace_generator.py:55 - 1: @__main__: => miscmisc/sys_settrace_generator.py:60 + 0: @__main__:test_generator => miscmisc/sys_settrace_generator.py:63 + 1: @__main__: => miscmisc/sys_settrace_generator.py:69 ### trace_handler::main event: call - 0: @__main__:make_gen => miscmisc/sys_settrace_generator.py:36 - 1: @__main__:test_generator => miscmisc/sys_settrace_generator.py:55 - 2: @__main__: => miscmisc/sys_settrace_generator.py:60 + 0: @__main__:make_gen => miscmisc/sys_settrace_generator.py:44 + 1: @__main__:test_generator => miscmisc/sys_settrace_generator.py:63 + 2: @__main__: => miscmisc/sys_settrace_generator.py:69 ### trace_handler::main event: line - 0: @__main__:make_gen => miscmisc/sys_settrace_generator.py:36 - 1: @__main__:test_generator => miscmisc/sys_settrace_generator.py:55 - 2: @__main__: => miscmisc/sys_settrace_generator.py:60 + 0: @__main__:make_gen => miscmisc/sys_settrace_generator.py:44 + 1: @__main__:test_generator => miscmisc/sys_settrace_generator.py:63 + 2: @__main__: => miscmisc/sys_settrace_generator.py:69 ### trace_handler::main event: line - 0: @__main__:make_gen => miscmisc/sys_settrace_generator.py:37 - 1: @__main__:test_generator => miscmisc/sys_settrace_generator.py:55 - 2: @__main__: => miscmisc/sys_settrace_generator.py:60 + 0: @__main__:make_gen => miscmisc/sys_settrace_generator.py:45 + 1: @__main__:test_generator => miscmisc/sys_settrace_generator.py:63 + 2: @__main__: => miscmisc/sys_settrace_generator.py:69 ### trace_handler::main event: return - 0: @__main__:make_gen => miscmisc/sys_settrace_generator.py:37 - 1: @__main__:test_generator => miscmisc/sys_settrace_generator.py:55 - 2: @__main__: => miscmisc/sys_settrace_generator.py:60 + 0: @__main__:make_gen => miscmisc/sys_settrace_generator.py:45 + 1: @__main__:test_generator => miscmisc/sys_settrace_generator.py:63 + 2: @__main__: => miscmisc/sys_settrace_generator.py:69 ### trace_handler::main event: line - 0: @__main__:test_generator => miscmisc/sys_settrace_generator.py:55 - 1: @__main__: => miscmisc/sys_settrace_generator.py:60 + 0: @__main__:test_generator => miscmisc/sys_settrace_generator.py:63 + 1: @__main__: => miscmisc/sys_settrace_generator.py:69 ### trace_handler::main event: line - 0: @__main__:test_generator => miscmisc/sys_settrace_generator.py:56 - 1: @__main__: => miscmisc/sys_settrace_generator.py:60 + 0: @__main__:test_generator => miscmisc/sys_settrace_generator.py:64 + 1: @__main__: => miscmisc/sys_settrace_generator.py:69 ### trace_handler::main event: line - 0: @__main__:test_generator => miscmisc/sys_settrace_generator.py:55 - 1: @__main__: => miscmisc/sys_settrace_generator.py:60 + 0: @__main__:test_generator => miscmisc/sys_settrace_generator.py:63 + 1: @__main__: => miscmisc/sys_settrace_generator.py:69 ### trace_handler::main event: call - 0: @__main__:make_gen => miscmisc/sys_settrace_generator.py:37 - 1: @__main__:test_generator => miscmisc/sys_settrace_generator.py:55 - 2: @__main__: => miscmisc/sys_settrace_generator.py:60 + 0: @__main__:make_gen => miscmisc/sys_settrace_generator.py:45 + 1: @__main__:test_generator => miscmisc/sys_settrace_generator.py:63 + 2: @__main__: => miscmisc/sys_settrace_generator.py:69 ### trace_handler::main event: line - 0: @__main__:make_gen => miscmisc/sys_settrace_generator.py:37 - 1: @__main__:test_generator => miscmisc/sys_settrace_generator.py:55 - 2: @__main__: => miscmisc/sys_settrace_generator.py:60 + 0: @__main__:make_gen => miscmisc/sys_settrace_generator.py:45 + 1: @__main__:test_generator => miscmisc/sys_settrace_generator.py:63 + 2: @__main__: => miscmisc/sys_settrace_generator.py:69 ### trace_handler::main event: line - 0: @__main__:make_gen => miscmisc/sys_settrace_generator.py:38 - 1: @__main__:test_generator => miscmisc/sys_settrace_generator.py:55 - 2: @__main__: => miscmisc/sys_settrace_generator.py:60 + 0: @__main__:make_gen => miscmisc/sys_settrace_generator.py:46 + 1: @__main__:test_generator => miscmisc/sys_settrace_generator.py:63 + 2: @__main__: => miscmisc/sys_settrace_generator.py:69 ### trace_handler::main event: return - 0: @__main__:make_gen => miscmisc/sys_settrace_generator.py:38 - 1: @__main__:test_generator => miscmisc/sys_settrace_generator.py:55 - 2: @__main__: => miscmisc/sys_settrace_generator.py:60 + 0: @__main__:make_gen => miscmisc/sys_settrace_generator.py:46 + 1: @__main__:test_generator => miscmisc/sys_settrace_generator.py:63 + 2: @__main__: => miscmisc/sys_settrace_generator.py:69 ### trace_handler::main event: line - 0: @__main__:test_generator => miscmisc/sys_settrace_generator.py:57 - 1: @__main__: => miscmisc/sys_settrace_generator.py:60 + 0: @__main__:test_generator => miscmisc/sys_settrace_generator.py:65 + 1: @__main__: => miscmisc/sys_settrace_generator.py:69 7 ### trace_handler::main event: return - 0: @__main__:test_generator => miscmisc/sys_settrace_generator.py:57 - 1: @__main__: => miscmisc/sys_settrace_generator.py:60 + 0: @__main__:test_generator => miscmisc/sys_settrace_generator.py:65 + 1: @__main__: => miscmisc/sys_settrace_generator.py:69 Total traces executed: 54 diff --git a/tests/misc/sys_settrace_loop.py b/tests/misc/sys_settrace_loop.py index 9ae0f41a1d..06d0dc17bf 100644 --- a/tests/misc/sys_settrace_loop.py +++ b/tests/misc/sys_settrace_loop.py @@ -8,21 +8,28 @@ except AttributeError: print("SKIP") raise SystemExit + def print_stacktrace(frame, level=0): - print("%2d: %s@%s:%s => %s:%d" % ( - level, " ", - frame.f_globals['__name__'], - frame.f_code.co_name, - # reduce full path to some pseudo-relative - 'misc' + ''.join(frame.f_code.co_filename.split('tests/misc')[-1:]), - frame.f_lineno, - )) + print( + "%2d: %s@%s:%s => %s:%d" + % ( + level, + " ", + frame.f_globals["__name__"], + frame.f_code.co_name, + # reduce full path to some pseudo-relative + "misc" + "".join(frame.f_code.co_filename.split("tests/misc")[-1:]), + frame.f_lineno, + ) + ) if frame.f_back: print_stacktrace(frame.f_back, level + 1) + trace_count = 0 + def trace_tick_handler(frame, event, arg): global trace_count print("### trace_handler::main event:", event) @@ -30,6 +37,7 @@ def trace_tick_handler(frame, event, arg): print_stacktrace(frame) return trace_tick_handler + def test_loop(): # for loop r = 0 @@ -45,6 +53,7 @@ def test_loop(): i += 1 print("test_while_loop", i) + sys.settrace(trace_tick_handler) test_loop() sys.settrace(None) diff --git a/tests/misc/sys_settrace_loop.py.exp b/tests/misc/sys_settrace_loop.py.exp index 3d3da5b6f7..f56f98fae0 100644 --- a/tests/misc/sys_settrace_loop.py.exp +++ b/tests/misc/sys_settrace_loop.py.exp @@ -1,72 +1,72 @@ ### trace_handler::main event: call - 0: @__main__:test_loop => miscmisc/sys_settrace_loop.py:33 - 1: @__main__: => miscmisc/sys_settrace_loop.py:49 -### trace_handler::main event: line - 0: @__main__:test_loop => miscmisc/sys_settrace_loop.py:35 - 1: @__main__: => miscmisc/sys_settrace_loop.py:49 -### trace_handler::main event: line - 0: @__main__:test_loop => miscmisc/sys_settrace_loop.py:36 - 1: @__main__: => miscmisc/sys_settrace_loop.py:49 -### trace_handler::main event: line - 0: @__main__:test_loop => miscmisc/sys_settrace_loop.py:37 - 1: @__main__: => miscmisc/sys_settrace_loop.py:49 -### trace_handler::main event: line - 0: @__main__:test_loop => miscmisc/sys_settrace_loop.py:36 - 1: @__main__: => miscmisc/sys_settrace_loop.py:49 -### trace_handler::main event: line - 0: @__main__:test_loop => miscmisc/sys_settrace_loop.py:37 - 1: @__main__: => miscmisc/sys_settrace_loop.py:49 -### trace_handler::main event: line - 0: @__main__:test_loop => miscmisc/sys_settrace_loop.py:36 - 1: @__main__: => miscmisc/sys_settrace_loop.py:49 -### trace_handler::main event: line - 0: @__main__:test_loop => miscmisc/sys_settrace_loop.py:37 - 1: @__main__: => miscmisc/sys_settrace_loop.py:49 -### trace_handler::main event: line - 0: @__main__:test_loop => miscmisc/sys_settrace_loop.py:36 - 1: @__main__: => miscmisc/sys_settrace_loop.py:49 -### trace_handler::main event: line - 0: @__main__:test_loop => miscmisc/sys_settrace_loop.py:37 - 1: @__main__: => miscmisc/sys_settrace_loop.py:49 -### trace_handler::main event: line - 0: @__main__:test_loop => miscmisc/sys_settrace_loop.py:38 - 1: @__main__: => miscmisc/sys_settrace_loop.py:49 -test_for_loop 3 -### trace_handler::main event: line 0: @__main__:test_loop => miscmisc/sys_settrace_loop.py:41 - 1: @__main__: => miscmisc/sys_settrace_loop.py:49 -### trace_handler::main event: line - 0: @__main__:test_loop => miscmisc/sys_settrace_loop.py:42 - 1: @__main__: => miscmisc/sys_settrace_loop.py:49 + 1: @__main__: => miscmisc/sys_settrace_loop.py:58 ### trace_handler::main event: line 0: @__main__:test_loop => miscmisc/sys_settrace_loop.py:43 - 1: @__main__: => miscmisc/sys_settrace_loop.py:49 -### trace_handler::main event: line - 0: @__main__:test_loop => miscmisc/sys_settrace_loop.py:45 - 1: @__main__: => miscmisc/sys_settrace_loop.py:49 + 1: @__main__: => miscmisc/sys_settrace_loop.py:58 ### trace_handler::main event: line 0: @__main__:test_loop => miscmisc/sys_settrace_loop.py:44 - 1: @__main__: => miscmisc/sys_settrace_loop.py:49 + 1: @__main__: => miscmisc/sys_settrace_loop.py:58 ### trace_handler::main event: line 0: @__main__:test_loop => miscmisc/sys_settrace_loop.py:45 - 1: @__main__: => miscmisc/sys_settrace_loop.py:49 + 1: @__main__: => miscmisc/sys_settrace_loop.py:58 ### trace_handler::main event: line 0: @__main__:test_loop => miscmisc/sys_settrace_loop.py:44 - 1: @__main__: => miscmisc/sys_settrace_loop.py:49 + 1: @__main__: => miscmisc/sys_settrace_loop.py:58 ### trace_handler::main event: line 0: @__main__:test_loop => miscmisc/sys_settrace_loop.py:45 - 1: @__main__: => miscmisc/sys_settrace_loop.py:49 + 1: @__main__: => miscmisc/sys_settrace_loop.py:58 ### trace_handler::main event: line 0: @__main__:test_loop => miscmisc/sys_settrace_loop.py:44 - 1: @__main__: => miscmisc/sys_settrace_loop.py:49 + 1: @__main__: => miscmisc/sys_settrace_loop.py:58 ### trace_handler::main event: line 0: @__main__:test_loop => miscmisc/sys_settrace_loop.py:45 - 1: @__main__: => miscmisc/sys_settrace_loop.py:49 + 1: @__main__: => miscmisc/sys_settrace_loop.py:58 +### trace_handler::main event: line + 0: @__main__:test_loop => miscmisc/sys_settrace_loop.py:44 + 1: @__main__: => miscmisc/sys_settrace_loop.py:58 +### trace_handler::main event: line + 0: @__main__:test_loop => miscmisc/sys_settrace_loop.py:45 + 1: @__main__: => miscmisc/sys_settrace_loop.py:58 ### trace_handler::main event: line 0: @__main__:test_loop => miscmisc/sys_settrace_loop.py:46 - 1: @__main__: => miscmisc/sys_settrace_loop.py:49 + 1: @__main__: => miscmisc/sys_settrace_loop.py:58 +test_for_loop 3 +### trace_handler::main event: line + 0: @__main__:test_loop => miscmisc/sys_settrace_loop.py:49 + 1: @__main__: => miscmisc/sys_settrace_loop.py:58 +### trace_handler::main event: line + 0: @__main__:test_loop => miscmisc/sys_settrace_loop.py:50 + 1: @__main__: => miscmisc/sys_settrace_loop.py:58 +### trace_handler::main event: line + 0: @__main__:test_loop => miscmisc/sys_settrace_loop.py:51 + 1: @__main__: => miscmisc/sys_settrace_loop.py:58 +### trace_handler::main event: line + 0: @__main__:test_loop => miscmisc/sys_settrace_loop.py:53 + 1: @__main__: => miscmisc/sys_settrace_loop.py:58 +### trace_handler::main event: line + 0: @__main__:test_loop => miscmisc/sys_settrace_loop.py:52 + 1: @__main__: => miscmisc/sys_settrace_loop.py:58 +### trace_handler::main event: line + 0: @__main__:test_loop => miscmisc/sys_settrace_loop.py:53 + 1: @__main__: => miscmisc/sys_settrace_loop.py:58 +### trace_handler::main event: line + 0: @__main__:test_loop => miscmisc/sys_settrace_loop.py:52 + 1: @__main__: => miscmisc/sys_settrace_loop.py:58 +### trace_handler::main event: line + 0: @__main__:test_loop => miscmisc/sys_settrace_loop.py:53 + 1: @__main__: => miscmisc/sys_settrace_loop.py:58 +### trace_handler::main event: line + 0: @__main__:test_loop => miscmisc/sys_settrace_loop.py:52 + 1: @__main__: => miscmisc/sys_settrace_loop.py:58 +### trace_handler::main event: line + 0: @__main__:test_loop => miscmisc/sys_settrace_loop.py:53 + 1: @__main__: => miscmisc/sys_settrace_loop.py:58 +### trace_handler::main event: line + 0: @__main__:test_loop => miscmisc/sys_settrace_loop.py:54 + 1: @__main__: => miscmisc/sys_settrace_loop.py:58 test_while_loop 3 ### trace_handler::main event: return - 0: @__main__:test_loop => miscmisc/sys_settrace_loop.py:46 - 1: @__main__: => miscmisc/sys_settrace_loop.py:49 + 0: @__main__:test_loop => miscmisc/sys_settrace_loop.py:54 + 1: @__main__: => miscmisc/sys_settrace_loop.py:58 Total traces executed: 23 diff --git a/tests/misc/sys_settrace_subdir/trace_generic.py b/tests/misc/sys_settrace_subdir/trace_generic.py index 3239a019c7..111a9d19ff 100644 --- a/tests/misc/sys_settrace_subdir/trace_generic.py +++ b/tests/misc/sys_settrace_subdir/trace_generic.py @@ -7,14 +7,15 @@ def test_func(): test_sub_func() + # closure def test_closure(msg): - def make_closure(): print(msg) return make_closure + # exception def test_exception(): try: @@ -22,41 +23,49 @@ def test_exception(): except Exception: pass - + finally: pass + # listcomp def test_listcomp(): print("test_listcomp", [x for x in range(3)]) + # lambda def test_lambda(): func_obj_1 = lambda a, b: a + b print(func_obj_1(10, 20)) + # import def test_import(): from sys_settrace_subdir import trace_importme + trace_importme.dummy() trace_importme.saysomething() + # class -class TLClass(): +class TLClass: def method(): pass + pass + def test_class(): class TestClass: __anynum = -9 + def method(self): print("test_class_method") self.__anynum += 1 - + def prprty_getter(self): return self.__anynum - + def prprty_setter(self, what): self.__anynum = what @@ -79,4 +88,5 @@ def run_tests(): test_class() test_import() + print("And it's done!") diff --git a/tests/misc/sys_settrace_subdir/trace_importme.py b/tests/misc/sys_settrace_subdir/trace_importme.py index 0ff7c6d5bb..de561ef217 100644 --- a/tests/misc/sys_settrace_subdir/trace_importme.py +++ b/tests/misc/sys_settrace_subdir/trace_importme.py @@ -3,7 +3,7 @@ print("Yep, I got imported.") try: x = const(1) except NameError: - print('const not defined') + print("const not defined") const = lambda x: x @@ -12,13 +12,17 @@ _CNT02 = const(123) A123 = const(123) a123 = const(123) + def dummy(): return False + def saysomething(): print("There, I said it.") + def neverexecuted(): print("Never got here!") + print("Yep, got here") diff --git a/tests/net_hosted/accept_nonblock.py b/tests/net_hosted/accept_nonblock.py index 56f3288e28..941965e178 100644 --- a/tests/net_hosted/accept_nonblock.py +++ b/tests/net_hosted/accept_nonblock.py @@ -6,11 +6,11 @@ except: import socket s = socket.socket() -s.bind(socket.getaddrinfo('127.0.0.1', 8123)[0][-1]) +s.bind(socket.getaddrinfo("127.0.0.1", 8123)[0][-1]) s.setblocking(False) s.listen(1) try: s.accept() except OSError as er: - print(er.args[0] == 11) # 11 is EAGAIN + print(er.args[0] == 11) # 11 is EAGAIN s.close() diff --git a/tests/net_hosted/accept_timeout.py b/tests/net_hosted/accept_timeout.py index 44b3b8c7cd..ff989110ae 100644 --- a/tests/net_hosted/accept_timeout.py +++ b/tests/net_hosted/accept_timeout.py @@ -8,15 +8,15 @@ except: try: socket.socket.settimeout except AttributeError: - print('SKIP') + print("SKIP") raise SystemExit s = socket.socket() -s.bind(socket.getaddrinfo('127.0.0.1', 8123)[0][-1]) +s.bind(socket.getaddrinfo("127.0.0.1", 8123)[0][-1]) s.settimeout(1) s.listen(1) try: s.accept() except OSError as er: - print(er.args[0] in (110, 'timed out')) # 110 is ETIMEDOUT; CPython uses a string + print(er.args[0] in (110, "timed out")) # 110 is ETIMEDOUT; CPython uses a string s.close() diff --git a/tests/net_hosted/connect_nonblock.py b/tests/net_hosted/connect_nonblock.py index 6479978bea..3a3eaa2ba0 100644 --- a/tests/net_hosted/connect_nonblock.py +++ b/tests/net_hosted/connect_nonblock.py @@ -12,9 +12,9 @@ def test(peer_addr): try: s.connect(peer_addr) except OSError as er: - print(er.args[0] == 115) # 115 is EINPROGRESS + print(er.args[0] == 115) # 115 is EINPROGRESS s.close() if __name__ == "__main__": - test(socket.getaddrinfo('micropython.org', 80)[0][-1]) + test(socket.getaddrinfo("micropython.org", 80)[0][-1]) diff --git a/tests/net_hosted/connect_poll.py b/tests/net_hosted/connect_poll.py index 7aeba8f6d4..b2739e36e9 100644 --- a/tests/net_hosted/connect_poll.py +++ b/tests/net_hosted/connect_poll.py @@ -28,4 +28,4 @@ def test(peer_addr): if __name__ == "__main__": - test(socket.getaddrinfo('micropython.org', 80)[0][-1]) + test(socket.getaddrinfo("micropython.org", 80)[0][-1]) diff --git a/tests/net_hosted/ssl_getpeercert.py b/tests/net_hosted/ssl_getpeercert.py index e265c830d0..dee5fcfd89 100644 --- a/tests/net_hosted/ssl_getpeercert.py +++ b/tests/net_hosted/ssl_getpeercert.py @@ -18,4 +18,4 @@ def test(peer_addr): if __name__ == "__main__": - test(socket.getaddrinfo('micropython.org', 443)[0][-1]) + test(socket.getaddrinfo("micropython.org", 443)[0][-1]) diff --git a/tests/net_inet/test_tls_sites.py b/tests/net_inet/test_tls_sites.py index bf8071d087..876343acfc 100644 --- a/tests/net_inet/test_tls_sites.py +++ b/tests/net_inet/test_tls_sites.py @@ -6,6 +6,7 @@ try: import ussl as ssl except: import ssl + # CPython only supports server_hostname with SSLContext ssl = ssl.SSLContext() @@ -24,9 +25,9 @@ def test_one(site, opts): else: s = ssl.wrap_socket(s) - s.write(b"GET / HTTP/1.0\r\nHost: %s\r\n\r\n" % bytes(site, 'latin')) + s.write(b"GET / HTTP/1.0\r\nHost: %s\r\n\r\n" % bytes(site, "latin")) resp = s.read(4096) -# print(resp) + # print(resp) finally: s.close() @@ -37,7 +38,7 @@ SITES = [ "www.google.com", "api.telegram.org", {"host": "api.pushbullet.com", "sni": True}, -# "w9rybpfril.execute-api.ap-southeast-2.amazonaws.com", + # "w9rybpfril.execute-api.ap-southeast-2.amazonaws.com", {"host": "w9rybpfril.execute-api.ap-southeast-2.amazonaws.com", "sni": True}, ] diff --git a/tests/net_inet/uasyncio_tcp_read_headers.py b/tests/net_inet/uasyncio_tcp_read_headers.py index 8e4375a4f3..e8087aeedf 100644 --- a/tests/net_inet/uasyncio_tcp_read_headers.py +++ b/tests/net_inet/uasyncio_tcp_read_headers.py @@ -22,7 +22,11 @@ async def http_get_headers(url): line = line.strip() if not line: break - if line.find(b"Date") == -1 and line.find(b"Modified") == -1 and line.find(b"Server") == -1: + if ( + line.find(b"Date") == -1 + and line.find(b"Modified") == -1 + and line.find(b"Server") == -1 + ): print(line) print("close") diff --git a/tests/perf_bench/benchrun.py b/tests/perf_bench/benchrun.py index 9cbc9695ac..90c303dd29 100644 --- a/tests/perf_bench/benchrun.py +++ b/tests/perf_bench/benchrun.py @@ -3,6 +3,7 @@ def bm_run(N, M): from utime import ticks_us, ticks_diff except ImportError: import time + ticks_us = lambda: int(time.perf_counter() * 1000000) ticks_diff = lambda a, b: a - b @@ -14,7 +15,7 @@ def bm_run(N, M): cur_nm = nm param = p if param is None: - print(-1, -1, 'no matching params') + print(-1, -1, "no matching params") return # Run and time benchmark diff --git a/tests/perf_bench/bm_chaos.py b/tests/perf_bench/bm_chaos.py index 04e04531ca..55d282561f 100644 --- a/tests/perf_bench/bm_chaos.py +++ b/tests/perf_bench/bm_chaos.py @@ -9,7 +9,6 @@ import random class GVector(object): - def __init__(self, x=0, y=0, z=0): self.x = x self.y = y @@ -19,9 +18,9 @@ class GVector(object): return math.sqrt(self.x ** 2 + self.y ** 2 + self.z ** 2) def dist(self, other): - return math.sqrt((self.x - other.x) ** 2 - + (self.y - other.y) ** 2 - + (self.z - other.z) ** 2) + return math.sqrt( + (self.x - other.x) ** 2 + (self.y - other.y) ** 2 + (self.z - other.z) ** 2 + ) def __add__(self, other): if not isinstance(other, GVector): @@ -35,14 +34,15 @@ class GVector(object): def __mul__(self, other): v = GVector(self.x * other, self.y * other, self.z * other) return v + __rmul__ = __mul__ def linear_combination(self, other, l1, l2=None): if l2 is None: l2 = 1 - l1 - v = GVector(self.x * l1 + other.x * l2, - self.y * l1 + other.y * l2, - self.z * l1 + other.z * l2) + v = GVector( + self.x * l1 + other.x * l2, self.y * l1 + other.y * l2, self.z * l1 + other.z * l2 + ) return v def __str__(self): @@ -75,8 +75,7 @@ class Spline(object): def GetDomain(self): """Returns the domain of the B-Spline""" - return (self.knots[self.degree - 1], - self.knots[len(self.knots) - self.degree]) + return (self.knots[self.degree - 1], self.knots[len(self.knots) - self.degree]) def __call__(self, u): """Calculates a point of the B-Spline using de Boors Algorithm""" @@ -88,8 +87,7 @@ class Spline(object): if u == dom[1]: return self.points[-1] I = self.GetIndex(u) - d = [self.points[I - self.degree + 1 + ii] - for ii in range(self.degree + 1)] + d = [self.points[I - self.degree + 1 + ii] for ii in range(self.degree + 1)] U = self.knots for ik in range(1, self.degree + 1): for ii in range(I - self.degree + ik + 1, I + 2): @@ -120,16 +118,15 @@ class Spline(object): def write_ppm(im, w, h, filename): with open(filename, "wb") as f: - f.write(b'P6\n%i %i\n255\n' % (w, h)) + f.write(b"P6\n%i %i\n255\n" % (w, h)) for j in range(h): for i in range(w): val = im[j * w + i] c = val * 255 - f.write(b'%c%c%c' % (c, c, c)) + f.write(b"%c%c%c" % (c, c, c)) class Chaosgame(object): - def __init__(self, splines, thickness, subdivs): self.splines = splines self.thickness = thickness @@ -178,10 +175,8 @@ class Chaosgame(object): neighbour = self.splines[trafo[0]](t + 1 / 50000) derivative = basepoint - neighbour if derivative.Mag() != 0: - basepoint.x += derivative.y / derivative.Mag() * (y - 0.5) * \ - self.thickness - basepoint.y += -derivative.x / derivative.Mag() * (y - 0.5) * \ - self.thickness + basepoint.x += derivative.y / derivative.Mag() * (y - 0.5) * self.thickness + basepoint.y += -derivative.x / derivative.Mag() * (y - 0.5) * self.thickness else: # can happen, especially with single precision float pass @@ -204,8 +199,7 @@ class Chaosgame(object): random.seed(rng_seed) im = bytearray(w * h) - point = GVector((self.maxx + self.minx) / 2, - (self.maxy + self.miny) / 2, 0) + point = GVector((self.maxx + self.minx) / 2, (self.maxy + self.miny) / 2, 0) for _ in range(iterations): point = self.transform_point(point) x = (point.x - self.minx) / self.width * w @@ -230,29 +224,42 @@ bm_params = { (5000, 1000): (0.25, 400, 500, 500, 7000, 1234), } + def bm_setup(params): splines = [ - Spline([ - GVector(1.597, 3.304, 0.0), - GVector(1.576, 4.123, 0.0), - GVector(1.313, 5.288, 0.0), - GVector(1.619, 5.330, 0.0), - GVector(2.890, 5.503, 0.0), - GVector(2.373, 4.382, 0.0), - GVector(1.662, 4.360, 0.0)], - 3, [0, 0, 0, 1, 1, 1, 2, 2, 2]), - Spline([ - GVector(2.805, 4.017, 0.0), - GVector(2.551, 3.525, 0.0), - GVector(1.979, 2.620, 0.0), - GVector(1.979, 2.620, 0.0)], - 3, [0, 0, 0, 1, 1, 1]), - Spline([ - GVector(2.002, 4.011, 0.0), - GVector(2.335, 3.313, 0.0), - GVector(2.367, 3.233, 0.0), - GVector(2.367, 3.233, 0.0)], - 3, [0, 0, 0, 1, 1, 1]) + Spline( + [ + GVector(1.597, 3.304, 0.0), + GVector(1.576, 4.123, 0.0), + GVector(1.313, 5.288, 0.0), + GVector(1.619, 5.330, 0.0), + GVector(2.890, 5.503, 0.0), + GVector(2.373, 4.382, 0.0), + GVector(1.662, 4.360, 0.0), + ], + 3, + [0, 0, 0, 1, 1, 1, 2, 2, 2], + ), + Spline( + [ + GVector(2.805, 4.017, 0.0), + GVector(2.551, 3.525, 0.0), + GVector(1.979, 2.620, 0.0), + GVector(1.979, 2.620, 0.0), + ], + 3, + [0, 0, 0, 1, 1, 1], + ), + Spline( + [ + GVector(2.002, 4.011, 0.0), + GVector(2.335, 3.313, 0.0), + GVector(2.367, 3.233, 0.0), + GVector(2.367, 3.233, 0.0), + ], + 3, + [0, 0, 0, 1, 1, 1], + ), ] chaos = Chaosgame(splines, params[0], params[1]) @@ -267,7 +274,7 @@ def bm_setup(params): norm = params[4] # Images are not the same when floating point behaviour is different, # so return percentage of pixels that are set (rounded to int). - #write_ppm(image, params[2], params[3], 'out-.ppm') + # write_ppm(image, params[2], params[3], 'out-.ppm') pix = int(100 * sum(image) / len(image)) return norm, pix diff --git a/tests/perf_bench/bm_fannkuch.py b/tests/perf_bench/bm_fannkuch.py index c9782e3e9a..9f7ae797f0 100644 --- a/tests/perf_bench/bm_fannkuch.py +++ b/tests/perf_bench/bm_fannkuch.py @@ -5,6 +5,7 @@ # http://benchmarksgame.alioth.debian.org/ # Contributed by Sokolov Yura, modified by Tupteq. + def fannkuch(n): count = list(range(1, n + 1)) max_flips = 0 @@ -29,7 +30,7 @@ def fannkuch(n): flips_count = 0 k = perm[0] while k: - perm[:k + 1] = perm[k::-1] + perm[: k + 1] = perm[k::-1] flips_count += 1 k = perm[0] @@ -57,11 +58,15 @@ bm_params = { (5000, 10): (9,), } + def bm_setup(params): state = None + def run(): nonlocal state state = fannkuch(params[0]) + def result(): return params[0], state + return run, result diff --git a/tests/perf_bench/bm_fft.py b/tests/perf_bench/bm_fft.py index 9ea8b08f49..fb79a9fd28 100644 --- a/tests/perf_bench/bm_fft.py +++ b/tests/perf_bench/bm_fft.py @@ -3,6 +3,7 @@ import math, cmath + def transform_radix2(vector, inverse): # Returns the integer whose value is the reverse of the lowest 'bits' bits of the integer 'x'. def reverse(x, bits): @@ -34,6 +35,7 @@ def transform_radix2(vector, inverse): size *= 2 return vector + ########################################################################### # Benchmark interface @@ -44,6 +46,7 @@ bm_params = { (5000, 1000): (100, 512), } + def bm_setup(params): state = None signal = [math.cos(2 * math.pi * i / params[1]) + 0j for i in range(params[1])] diff --git a/tests/perf_bench/bm_float.py b/tests/perf_bench/bm_float.py index 5a66b9bb3e..9e55deaee5 100644 --- a/tests/perf_bench/bm_float.py +++ b/tests/perf_bench/bm_float.py @@ -7,7 +7,7 @@ from math import sin, cos, sqrt class Point(object): - __slots__ = ('x', 'y', 'z') + __slots__ = ("x", "y", "z") def __init__(self, i): self.x = x = sin(i) @@ -59,12 +59,16 @@ bm_params = { (5000, 1000): (20, 3000), } + def bm_setup(params): state = None + def run(): nonlocal state for _ in range(params[0]): state = benchmark(params[1]) + def result(): - return params[0] * params[1], 'Point(%.4f, %.4f, %.4f)' % (state.x, state.y, state.z) + return params[0] * params[1], "Point(%.4f, %.4f, %.4f)" % (state.x, state.y, state.z) + return run, result diff --git a/tests/perf_bench/bm_hexiom.py b/tests/perf_bench/bm_hexiom.py index 3a6f1f6c4b..84eda9a909 100644 --- a/tests/perf_bench/bm_hexiom.py +++ b/tests/perf_bench/bm_hexiom.py @@ -9,18 +9,12 @@ ################################## class Dir(object): - def __init__(self, x, y): self.x = x self.y = y -DIRS = [Dir(1, 0), - Dir(-1, 0), - Dir(0, 1), - Dir(0, -1), - Dir(1, 1), - Dir(-1, -1)] +DIRS = [Dir(1, 0), Dir(-1, 0), Dir(0, 1), Dir(0, -1), Dir(1, 1), Dir(-1, -1)] EMPTY = 7 @@ -37,8 +31,7 @@ class Done(object): def __init__(self, count, empty=False): self.count = count - self.cells = None if empty else [ - [0, 1, 2, 3, 4, 5, 6, EMPTY] for i in range(count)] + self.cells = None if empty else [[0, 1, 2, 3, 4, 5, 6, EMPTY] for i in range(count)] def clone(self): ret = Done(self.count, True) @@ -100,7 +93,7 @@ class Done(object): maxval = -1 maxi = -1 for i in range(self.count): - if (not self.already_done(i)): + if not self.already_done(i): maxvali = max(k for k in self.cells[i] if k != EMPTY) if maxval < maxvali: maxval = maxvali @@ -109,7 +102,7 @@ class Done(object): def next_cell_first(self): for i in range(self.count): - if (not self.already_done(i)): + if not self.already_done(i): return i return -1 @@ -119,8 +112,10 @@ class Done(object): for i in range(self.count): if not self.already_done(i): cells_around = pos.hex.get_by_id(i).links - n = sum(1 if (self.already_done(nid) and (self[nid][0] != EMPTY)) else 0 - for nid in cells_around) + n = sum( + 1 if (self.already_done(nid) and (self[nid][0] != EMPTY)) else 0 + for nid in cells_around + ) if n > maxn: maxn = n maxi = i @@ -132,8 +127,10 @@ class Done(object): for i in range(self.count): if not self.already_done(i): cells_around = pos.hex.get_by_id(i).links - n = sum(1 if (self.already_done(nid) and (self[nid][0] != EMPTY)) else 0 - for nid in cells_around) + n = sum( + 1 if (self.already_done(nid) and (self[nid][0] != EMPTY)) else 0 + for nid in cells_around + ) if n < minn: minn = n mini = i @@ -155,21 +152,21 @@ class Done(object): else: raise Exception("Wrong strategy: %d" % strategy) + ################################## class Node(object): - def __init__(self, pos, id, links): self.pos = pos self.id = id self.links = links + ################################## class Hex(object): - def __init__(self, size): self.size = size self.count = 3 * size * (size - 1) + 1 @@ -213,7 +210,6 @@ class Hex(object): ################################## class Pos(object): - def __init__(self, hex, tiles, done=None): self.hex = hex self.tiles = tiles @@ -222,6 +218,7 @@ class Pos(object): def clone(self): return Pos(self.hex, self.tiles, self.done.clone()) + ################################## @@ -231,8 +228,7 @@ def constraint_pass(pos, last_move=None): done = pos.done # Remove impossible values from free cells - free_cells = (range(done.count) if last_move is None - else pos.hex.get_by_id(last_move).links) + free_cells = range(done.count) if last_move is None else pos.hex.get_by_id(last_move).links for i in free_cells: if not done.already_done(i): vmax = 0 @@ -273,8 +269,7 @@ def constraint_pass(pos, last_move=None): changed = True # Force empty or non-empty around filled cells - filled_cells = (range(done.count) if last_move is None - else [last_move]) + filled_cells = range(done.count) if last_move is None else [last_move] for i in filled_cells: if done.already_done(i): num = done[i][0] @@ -320,8 +315,7 @@ def find_moves(pos, strategy, order): return [(cell_id, v) for v in done[cell_id]] else: # Try higher values first and EMPTY last - moves = list(reversed([(cell_id, v) - for v in done[cell_id] if v != EMPTY])) + moves = list(reversed([(cell_id, v) for v in done[cell_id] if v != EMPTY])) if EMPTY in done[cell_id]: moves.append((cell_id, EMPTY)) return moves @@ -378,7 +372,7 @@ def solved(pos, output, verbose=False): elif done.already_done(i): num = done[i][0] tiles[num] -= 1 - if (tiles[num] < 0): + if tiles[num] < 0: return IMPOSSIBLE vmax = 0 vmin = 0 @@ -448,8 +442,7 @@ def check_valid(pos): tiles[i] = 0 # check total if tot != hex.count: - raise Exception( - "Invalid input. Expected %d tiles, got %d." % (hex.count, tot)) + raise Exception("Invalid input. Expected %d tiles, got %d." % (hex.count, tot)) def solve(pos, strategy, order, output): @@ -459,6 +452,7 @@ def solve(pos, strategy, order, output): # TODO Write an 'iterator' to go over all x,y positions + def read_file(file): lines = [line.strip("\r\n") for line in file.splitlines()] size = int(lines[0]) @@ -467,10 +461,10 @@ def read_file(file): tiles = 8 * [0] done = Done(hex.count) for y in range(size): - line = lines[linei][size - y - 1:] + line = lines[linei][size - y - 1 :] p = 0 for x in range(size + y): - tile = line[p:p + 2] + tile = line[p : p + 2] p += 2 if tile[1] == ".": inctile = EMPTY @@ -489,7 +483,7 @@ def read_file(file): line = lines[linei][y:] p = 0 for x in range(y, size * 2 - 1): - tile = line[p:p + 2] + tile = line[p : p + 2] p += 2 if tile[1] == ".": inctile = EMPTY @@ -514,63 +508,76 @@ def solve_file(file, strategy, order, output): LEVELS = {} -LEVELS[2] = (""" +LEVELS[2] = ( + """ 2 . 1 . 1 1 1 . -""", """\ +""", + """\ 1 1 . . . 1 1 -""") +""", +) -LEVELS[10] = (""" +LEVELS[10] = ( + """ 3 +.+. . +. 0 . 2 . 1+2 1 . 2 . 0+. .+.+. -""", """\ +""", + """\ . . 1 . 1 . 2 0 . 2 2 . . . . . 0 . . -""") +""", +) -LEVELS[20] = (""" +LEVELS[20] = ( + """ 3 . 5 4 . 2+.+1 . 3+2 3 . +2+. 5 . . 3 . -""", """\ +""", + """\ 3 3 2 4 5 . 1 3 5 2 . . 2 . . . . . . -""") +""", +) -LEVELS[25] = (""" +LEVELS[25] = ( + """ 3 4 . . . . 2 . 4 3 2 . 4 2 2 3 . 4 2 4 -""", """\ +""", + """\ 3 4 2 2 4 4 . . . . 4 2 . 2 4 3 . 2 . -""") +""", +) -LEVELS[30] = (""" +LEVELS[30] = ( + """ 4 5 5 . . 3 . 2+2 6 @@ -579,7 +586,8 @@ LEVELS[30] = (""" 4 5 4 . 5 4 5+2 . . 3 4 . . . -""", """\ +""", + """\ 3 4 3 . 4 6 5 2 . 2 5 5 . . 2 @@ -587,9 +595,11 @@ LEVELS[30] = (""" . 3 5 4 5 4 . 2 . 3 3 . . . . -""") +""", +) -LEVELS[36] = (""" +LEVELS[36] = ( + """ 4 2 1 1 2 3 3 3 . . @@ -598,7 +608,8 @@ LEVELS[36] = (""" 2 2 . . . 2 4 3 4 . . 3 2 3 3 -""", """\ +""", + """\ 3 4 3 2 3 4 4 . 3 2 . . 3 4 3 @@ -606,7 +617,8 @@ LEVELS[36] = (""" 3 3 . 2 . 2 3 . 2 . 2 2 2 . 1 -""") +""", +) ########################################################################### @@ -618,6 +630,7 @@ bm_params = { (5000, 1000): (10, 25, DESCENDING, Done.FIRST_STRATEGY), } + def bm_setup(params): try: import uio as io @@ -641,7 +654,7 @@ def bm_setup(params): def result(): norm = params[0] * params[1] - out = '\n'.join(line.rstrip() for line in output.splitlines()) + out = "\n".join(line.rstrip() for line in output.splitlines()) return norm, ((out == expected), out) return run, result diff --git a/tests/perf_bench/bm_nqueens.py b/tests/perf_bench/bm_nqueens.py index 87e7245c04..773dd3f7ed 100644 --- a/tests/perf_bench/bm_nqueens.py +++ b/tests/perf_bench/bm_nqueens.py @@ -19,7 +19,7 @@ def permutations(iterable, r=None): for i in reversed(range(r)): cycles[i] -= 1 if cycles[i] == 0: - indices[i:] = indices[i + 1:] + indices[i:i + 1] + indices[i:] = indices[i + 1 :] + indices[i : i + 1] cycles[i] = n - i else: j = cycles[i] @@ -29,6 +29,7 @@ def permutations(iterable, r=None): else: return + # From http://code.activestate.com/recipes/576647/ def n_queens(queen_count): """N-Queens solver. @@ -37,10 +38,10 @@ def n_queens(queen_count): """ cols = range(queen_count) for vec in permutations(cols): - if (queen_count == len(set(vec[i] + i for i in cols)) - == len(set(vec[i] - i for i in cols))): + if queen_count == len(set(vec[i] + i for i in cols)) == len(set(vec[i] - i for i in cols)): yield vec + ########################################################################### # Benchmark interface @@ -51,12 +52,16 @@ bm_params = { (5000, 100): (1, 8), } + def bm_setup(params): res = None + def run(): nonlocal res for _ in range(params[0]): res = len(list(n_queens(params[1]))) + def result(): return params[0] * 10 ** (params[1] - 3), res + return run, result diff --git a/tests/perf_bench/bm_pidigits.py b/tests/perf_bench/bm_pidigits.py index ca2e5297d0..5949b93063 100644 --- a/tests/perf_bench/bm_pidigits.py +++ b/tests/perf_bench/bm_pidigits.py @@ -9,10 +9,7 @@ def compose(a, b): aq, ar, as_, at = a bq, br, bs, bt = b - return (aq * bq, - aq * br + ar * bt, - as_ * bq + at * bs, - as_ * br + at * bt) + return (aq * bq, aq * br + ar * bt, as_ * bq + at * bs, as_ * br + at * bt) def extract(z, j): @@ -45,6 +42,7 @@ bm_params = { (5000, 1000): (3, 350), } + def bm_setup(params): state = None @@ -53,10 +51,10 @@ def bm_setup(params): nloop, ndig = params ndig = params[1] for _ in range(nloop): - state = None # free previous result + state = None # free previous result state = gen_pi_digits(ndig) def result(): - return params[0] * params[1], ''.join(str(d) for d in state) + return params[0] * params[1], "".join(str(d) for d in state) return run, result diff --git a/tests/perf_bench/misc_aes.py b/tests/perf_bench/misc_aes.py index 5413a06b12..0743737cb7 100644 --- a/tests/perf_bench/misc_aes.py +++ b/tests/perf_bench/misc_aes.py @@ -12,6 +12,7 @@ # discrete arithmetic routines, mostly from a precomputed table # non-linear, invertible, substitution box +# fmt: off aes_s_box_table = bytes(( 0x63,0x7c,0x77,0x7b,0xf2,0x6b,0x6f,0xc5,0x30,0x01,0x67,0x2b,0xfe,0xd7,0xab,0x76, 0xca,0x82,0xc9,0x7d,0xfa,0x59,0x47,0xf0,0xad,0xd4,0xa2,0xaf,0x9c,0xa4,0x72,0xc0, @@ -30,31 +31,36 @@ aes_s_box_table = bytes(( 0xe1,0xf8,0x98,0x11,0x69,0xd9,0x8e,0x94,0x9b,0x1e,0x87,0xe9,0xce,0x55,0x28,0xdf, 0x8c,0xa1,0x89,0x0d,0xbf,0xe6,0x42,0x68,0x41,0x99,0x2d,0x0f,0xb0,0x54,0xbb,0x16, )) +# fmt: on # multiplication of polynomials modulo x^8 + x^4 + x^3 + x + 1 = 0x11b def aes_gf8_mul_2(x): if x & 0x80: - return (x << 1) ^ 0x11b + return (x << 1) ^ 0x11B else: return x << 1 + def aes_gf8_mul_3(x): return x ^ aes_gf8_mul_2(x) + # non-linear, invertible, substitution box def aes_s_box(a): - return aes_s_box_table[a & 0xff] + return aes_s_box_table[a & 0xFF] + # return 0x02^(a-1) in GF(2^8) def aes_r_con(a): ans = 1 while a > 1: - ans <<= 1; + ans <<= 1 if ans & 0x100: - ans ^= 0x11b + ans ^= 0x11B a -= 1 return ans + ################################################################## # basic AES algorithm; see FIPS-197 @@ -63,6 +69,7 @@ def aes_add_round_key(state, w): for i in range(16): state[i] ^= w[i] + # combined sub_bytes, shift_rows, mix_columns, add_round_key # all inputs must be size 16 def aes_sb_sr_mc_ark(state, w, w_idx, temp): @@ -72,7 +79,7 @@ def aes_sb_sr_mc_ark(state, w, w_idx, temp): x1 = aes_s_box_table[state[1 + ((i + 1) & 3) * 4]] x2 = aes_s_box_table[state[2 + ((i + 2) & 3) * 4]] x3 = aes_s_box_table[state[3 + ((i + 3) & 3) * 4]] - temp[temp_idx] = aes_gf8_mul_2(x0) ^ aes_gf8_mul_3(x1) ^ x2 ^ x3 ^ w[w_idx] + temp[temp_idx] = aes_gf8_mul_2(x0) ^ aes_gf8_mul_3(x1) ^ x2 ^ x3 ^ w[w_idx] temp[temp_idx + 1] = x0 ^ aes_gf8_mul_2(x1) ^ aes_gf8_mul_3(x2) ^ x3 ^ w[w_idx + 1] temp[temp_idx + 2] = x0 ^ x1 ^ aes_gf8_mul_2(x2) ^ aes_gf8_mul_3(x3) ^ w[w_idx + 2] temp[temp_idx + 3] = aes_gf8_mul_3(x0) ^ x1 ^ x2 ^ aes_gf8_mul_2(x3) ^ w[w_idx + 3] @@ -81,6 +88,7 @@ def aes_sb_sr_mc_ark(state, w, w_idx, temp): for i in range(16): state[i] = temp[i] + # combined sub_bytes, shift_rows, add_round_key # all inputs must be size 16 def aes_sb_sr_ark(state, w, w_idx, temp): @@ -90,7 +98,7 @@ def aes_sb_sr_ark(state, w, w_idx, temp): x1 = aes_s_box_table[state[1 + ((i + 1) & 3) * 4]] x2 = aes_s_box_table[state[2 + ((i + 2) & 3) * 4]] x3 = aes_s_box_table[state[3 + ((i + 3) & 3) * 4]] - temp[temp_idx] = x0 ^ w[w_idx] + temp[temp_idx] = x0 ^ w[w_idx] temp[temp_idx + 1] = x1 ^ w[w_idx + 1] temp[temp_idx + 2] = x2 ^ w[w_idx + 2] temp[temp_idx + 3] = x3 ^ w[w_idx + 3] @@ -99,6 +107,7 @@ def aes_sb_sr_ark(state, w, w_idx, temp): for i in range(16): state[i] = temp[i] + # take state as input and change it to the next state in the sequence # state and temp have size 16, w has size 16 * (Nr + 1), Nr >= 1 def aes_state(state, w, temp, nr): @@ -109,6 +118,7 @@ def aes_state(state, w, temp, nr): w_idx += 16 aes_sb_sr_ark(state, w, w_idx, temp) + # expand 'key' to 'w' for use with aes_state # key has size 4 * Nk, w has size 16 * (Nr + 1), temp has size 16 def aes_key_expansion(key, w, temp, nk, nr): @@ -132,9 +142,11 @@ def aes_key_expansion(key, w, temp, nk, nr): for j in range(4): w[w_idx + j] = w[w_idx + j - 4 * nk] ^ t[t_idx + j] + ################################################################## # simple use of AES algorithm, using output feedback (OFB) mode + class AES: def __init__(self, keysize): if keysize == 128: @@ -160,7 +172,7 @@ class AES: def set_iv(self, iv): for i in range(16): self.state[i] = iv[i] - self.state_pos = 16; + self.state_pos = 16 def get_some_state(self, n_needed): if self.state_pos >= 16: @@ -182,6 +194,7 @@ class AES: idx += ln self.state_pos += n + ########################################################################### # Benchmark interface @@ -192,6 +205,7 @@ bm_params = { (5000, 1000): (20, 256), } + def bm_setup(params): nloop, datalen = params diff --git a/tests/perf_bench/misc_mandel.py b/tests/perf_bench/misc_mandel.py index a4b789136d..fe26e3f4c2 100644 --- a/tests/perf_bench/misc_mandel.py +++ b/tests/perf_bench/misc_mandel.py @@ -1,5 +1,6 @@ # Compute the Mandelbrot set, to test complex numbers + def mandelbrot(w, h): def in_set(c): z = 0 @@ -11,21 +12,23 @@ def mandelbrot(w, h): img = bytearray(w * h) - xscale = ((w - 1) / 2.4) - yscale = ((h - 1) / 3.2) + xscale = (w - 1) / 2.4 + yscale = (h - 1) / 3.2 for v in range(h): - line = memoryview(img)[v * w:v * w + w] + line = memoryview(img)[v * w : v * w + w] for u in range(w): c = in_set(complex(v / yscale - 2.3, u / xscale - 1.2)) line[u] = c return img + bm_params = { (100, 100): (20, 20), (1000, 1000): (80, 80), (5000, 1000): (150, 150), } + def bm_setup(ps): return lambda: mandelbrot(ps[0], ps[1]), lambda: (ps[0] * ps[1], None) diff --git a/tests/perf_bench/misc_pystone.py b/tests/perf_bench/misc_pystone.py index 88626774b2..26f91c7bec 100644 --- a/tests/perf_bench/misc_pystone.py +++ b/tests/perf_bench/misc_pystone.py @@ -16,10 +16,9 @@ __version__ = "1.2" [Ident1, Ident2, Ident3, Ident4, Ident5] = range(1, 6) -class Record: - def __init__(self, PtrComp = None, Discr = 0, EnumComp = 0, - IntComp = 0, StringComp = 0): +class Record: + def __init__(self, PtrComp=None, Discr=0, EnumComp=0, IntComp=0, StringComp=0): self.PtrComp = PtrComp self.Discr = Discr self.EnumComp = EnumComp @@ -27,12 +26,13 @@ class Record: self.StringComp = StringComp def copy(self): - return Record(self.PtrComp, self.Discr, self.EnumComp, - self.IntComp, self.StringComp) + return Record(self.PtrComp, self.Discr, self.EnumComp, self.IntComp, self.StringComp) + TRUE = 1 FALSE = 0 + def Setup(): global IntGlob global BoolGlob @@ -43,10 +43,11 @@ def Setup(): IntGlob = 0 BoolGlob = FALSE - Char1Glob = '\0' - Char2Glob = '\0' - Array1Glob = [0]*51 - Array2Glob = [x[:] for x in [Array1Glob]*51] + Char1Glob = "\0" + Char2Glob = "\0" + Array1Glob = [0] * 51 + Array2Glob = [x[:] for x in [Array1Glob] * 51] + def Proc0(loops): global IntGlob @@ -82,16 +83,17 @@ def Proc0(loops): IntLoc1 = IntLoc1 + 1 Proc8(Array1Glob, Array2Glob, IntLoc1, IntLoc3) PtrGlb = Proc1(PtrGlb) - CharIndex = 'A' + CharIndex = "A" while CharIndex <= Char2Glob: - if EnumLoc == Func1(CharIndex, 'C'): + if EnumLoc == Func1(CharIndex, "C"): EnumLoc = Proc6(Ident1) - CharIndex = chr(ord(CharIndex)+1) + CharIndex = chr(ord(CharIndex) + 1) IntLoc3 = IntLoc2 * IntLoc1 IntLoc2 = IntLoc3 // IntLoc1 IntLoc2 = 7 * (IntLoc3 - IntLoc2) - IntLoc1 IntLoc1 = Proc2(IntLoc1) + def Proc1(PtrParIn): PtrParIn.PtrComp = NextRecord = PtrGlb.copy() PtrParIn.IntComp = 5 @@ -108,10 +110,11 @@ def Proc1(PtrParIn): NextRecord.PtrComp = None return PtrParIn + def Proc2(IntParIO): IntLoc = IntParIO + 10 while 1: - if Char1Glob == 'A': + if Char1Glob == "A": IntLoc = IntLoc - 1 IntParIO = IntLoc - IntGlob EnumLoc = Ident1 @@ -119,6 +122,7 @@ def Proc2(IntParIO): break return IntParIO + def Proc3(PtrParOut): global IntGlob @@ -129,20 +133,23 @@ def Proc3(PtrParOut): PtrGlb.IntComp = Proc7(10, IntGlob) return PtrParOut + def Proc4(): global Char2Glob - BoolLoc = Char1Glob == 'A' + BoolLoc = Char1Glob == "A" BoolLoc = BoolLoc or BoolGlob - Char2Glob = 'B' + Char2Glob = "B" + def Proc5(): global Char1Glob global BoolGlob - Char1Glob = 'A' + Char1Glob = "A" BoolGlob = FALSE + def Proc6(EnumParIn): EnumParOut = EnumParIn if not Func3(EnumParIn): @@ -162,24 +169,27 @@ def Proc6(EnumParIn): EnumParOut = Ident3 return EnumParOut + def Proc7(IntParI1, IntParI2): IntLoc = IntParI1 + 2 IntParOut = IntParI2 + IntLoc return IntParOut + def Proc8(Array1Par, Array2Par, IntParI1, IntParI2): global IntGlob IntLoc = IntParI1 + 5 Array1Par[IntLoc] = IntParI2 - Array1Par[IntLoc+1] = Array1Par[IntLoc] - Array1Par[IntLoc+30] = IntLoc - for IntIndex in range(IntLoc, IntLoc+2): + Array1Par[IntLoc + 1] = Array1Par[IntLoc] + Array1Par[IntLoc + 30] = IntLoc + for IntIndex in range(IntLoc, IntLoc + 2): Array2Par[IntLoc][IntIndex] = IntLoc - Array2Par[IntLoc][IntLoc-1] = Array2Par[IntLoc][IntLoc-1] + 1 - Array2Par[IntLoc+20][IntLoc] = Array1Par[IntLoc] + Array2Par[IntLoc][IntLoc - 1] = Array2Par[IntLoc][IntLoc - 1] + 1 + Array2Par[IntLoc + 20][IntLoc] = Array1Par[IntLoc] IntGlob = 5 + def Func1(CharPar1, CharPar2): CharLoc1 = CharPar1 CharLoc2 = CharLoc1 @@ -188,15 +198,16 @@ def Func1(CharPar1, CharPar2): else: return Ident2 + def Func2(StrParI1, StrParI2): IntLoc = 1 while IntLoc <= 1: - if Func1(StrParI1[IntLoc], StrParI2[IntLoc+1]) == Ident1: - CharLoc = 'A' + if Func1(StrParI1[IntLoc], StrParI2[IntLoc + 1]) == Ident1: + CharLoc = "A" IntLoc = IntLoc + 1 - if CharLoc >= 'W' and CharLoc <= 'Z': + if CharLoc >= "W" and CharLoc <= "Z": IntLoc = 7 - if CharLoc == 'X': + if CharLoc == "X": return TRUE else: if StrParI1 > StrParI2: @@ -205,9 +216,11 @@ def Func2(StrParI1, StrParI2): else: return FALSE + def Func3(EnumParIn): EnumLoc = EnumParIn - if EnumLoc == Ident3: return TRUE + if EnumLoc == Ident3: + return TRUE return FALSE @@ -221,6 +234,7 @@ bm_params = { (5000, 10): (20000,), } + def bm_setup(params): Setup() return lambda: Proc0(params[0]), lambda: (params[0], 0) diff --git a/tests/perf_bench/misc_raytrace.py b/tests/perf_bench/misc_raytrace.py index 76d4194bce..b51acaccac 100644 --- a/tests/perf_bench/misc_raytrace.py +++ b/tests/perf_bench/misc_raytrace.py @@ -4,6 +4,7 @@ INF = 1e30 EPS = 1e-6 + class Vec: def __init__(self, x, y, z): self.x, self.y, self.z = x, y, z @@ -30,12 +31,15 @@ class Vec: def dot(self, rhs): return self.x * rhs.x + self.y * rhs.y + self.z * rhs.z + RGB = Vec + class Ray: def __init__(self, p, d): self.p, self.d = p, d + class View: def __init__(self, width, height, depth, pos, xdir, ydir, zdir): self.width = width @@ -49,12 +53,14 @@ class View: def calc_dir(self, dx, dy): return (self.xdir * dx + self.ydir * dy + self.zdir * self.depth).normalise() + class Light: def __init__(self, pos, colour, casts_shadows): self.pos = pos self.colour = colour self.casts_shadows = casts_shadows + class Surface: def __init__(self, diffuse, specular, spec_idx, reflect, transp, colour): self.diffuse = diffuse @@ -76,6 +82,7 @@ class Surface: def transparent(colour): return Surface(0.2, 0.9, 32, 0.0, 0.8, colour * 0.3) + class Sphere: def __init__(self, surface, centre, radius): self.surface = surface @@ -99,6 +106,7 @@ class Sphere: def surface_at(self, v): return self.surface, (v - self.centre).normalise() + class Plane: def __init__(self, surface, centre, normal): self.surface = surface @@ -116,12 +124,14 @@ class Plane: def surface_at(self, p): return self.surface, self.normal + class Scene: def __init__(self, ambient, light, objs): self.ambient = ambient self.light = light self.objs = objs + def trace_scene(canvas, view, scene, max_depth): for v in range(canvas.height): y = (-v + 0.5 * (canvas.height - 1)) * view.height / canvas.height @@ -131,6 +141,7 @@ def trace_scene(canvas, view, scene, max_depth): c = trace_ray(scene, ray, max_depth) canvas.put_pix(u, v, c) + def trace_ray(scene, ray, depth): # Find closest intersecting object hit_t = INF @@ -181,6 +192,7 @@ def trace_ray(scene, ray, depth): return col + def trace_to_light(scene, ray, light_dist): col = scene.light.colour for obj in scene.objs: @@ -189,6 +201,7 @@ def trace_to_light(scene, ray, light_dist): col *= obj.surface.transp return col + class Canvas: def __init__(self, width, height): self.width = width @@ -202,10 +215,11 @@ class Canvas: self.data[off + 2] = min(255, max(0, int(255 * c.z))) def write_ppm(self, filename): - with open(filename, 'wb') as f: - f.write(bytes('P6 %d %d 255\n' % (self.width, self.height), 'ascii')) + with open(filename, "wb") as f: + f.write(bytes("P6 %d %d 255\n" % (self.width, self.height), "ascii")) f.write(self.data) + def main(w, h, d): canvas = Canvas(w, h) view = View(32, 32, 64, Vec(0, 0, 50), Vec(1, 0, 0), Vec(0, 1, 0), Vec(0, 0, -1)) @@ -221,13 +235,14 @@ def main(w, h, d): Sphere(Surface.shiny(RGB(1, 1, 1)), Vec(-5, -4, 3), 4), Sphere(Surface.dull(RGB(0, 0, 1)), Vec(4, -5, 0), 4), Sphere(Surface.transparent(RGB(0.2, 0.2, 0.2)), Vec(6, -1, 8), 4), - ] + ], ) trace_scene(canvas, view, scene, d) return canvas + # For testing -#main(256, 256, 4).write_ppm('rt.ppm') +# main(256, 256, 4).write_ppm('rt.ppm') ########################################################################### # Benchmark interface @@ -238,5 +253,6 @@ bm_params = { (5000, 100): (40, 40, 3), } + def bm_setup(params): return lambda: main(*params), lambda: (params[0] * params[1] * params[2], None) diff --git a/tests/perf_bench/viper_call0.py b/tests/perf_bench/viper_call0.py index 0f476b127b..903e2b5e58 100644 --- a/tests/perf_bench/viper_call0.py +++ b/tests/perf_bench/viper_call0.py @@ -2,12 +2,14 @@ def f0(): pass + @micropython.native def call(r): f = f0 for _ in r: f() + bm_params = { (50, 10): (15000,), (100, 10): (30000,), @@ -15,5 +17,6 @@ bm_params = { (5000, 10): (1500000,), } + def bm_setup(params): return lambda: call(range(params[0])), lambda: (params[0] // 1000, None) diff --git a/tests/perf_bench/viper_call1a.py b/tests/perf_bench/viper_call1a.py index 2bb4a28fd3..76adef60a1 100644 --- a/tests/perf_bench/viper_call1a.py +++ b/tests/perf_bench/viper_call1a.py @@ -2,12 +2,14 @@ def f1a(x): return x + @micropython.native def call(r): f = f1a for _ in r: f(1) + bm_params = { (50, 10): (15000,), (100, 10): (30000,), @@ -15,5 +17,6 @@ bm_params = { (5000, 10): (1500000,), } + def bm_setup(params): return lambda: call(range(params[0])), lambda: (params[0] // 1000, None) diff --git a/tests/perf_bench/viper_call1b.py b/tests/perf_bench/viper_call1b.py index cda64007fe..b52693c15d 100644 --- a/tests/perf_bench/viper_call1b.py +++ b/tests/perf_bench/viper_call1b.py @@ -2,12 +2,14 @@ def f1b(x) -> int: return int(x) + @micropython.native def call(r): f = f1b for _ in r: f(1) + bm_params = { (50, 10): (15000,), (100, 10): (30000,), @@ -15,5 +17,6 @@ bm_params = { (5000, 10): (1500000,), } + def bm_setup(params): return lambda: call(range(params[0])), lambda: (params[0] // 1000, None) diff --git a/tests/perf_bench/viper_call1c.py b/tests/perf_bench/viper_call1c.py index c653eb8d3e..31578c5bac 100644 --- a/tests/perf_bench/viper_call1c.py +++ b/tests/perf_bench/viper_call1c.py @@ -1,13 +1,15 @@ @micropython.viper -def f1c(x:int) -> int: +def f1c(x: int) -> int: return x + @micropython.native def call(r): f = f1c for _ in r: f(1) + bm_params = { (50, 10): (15000,), (100, 10): (30000,), @@ -15,5 +17,6 @@ bm_params = { (5000, 10): (1500000,), } + def bm_setup(params): return lambda: call(range(params[0])), lambda: (params[0] // 1000, None) diff --git a/tests/perf_bench/viper_call2a.py b/tests/perf_bench/viper_call2a.py index 6204f985f9..d0520b46bc 100644 --- a/tests/perf_bench/viper_call2a.py +++ b/tests/perf_bench/viper_call2a.py @@ -2,12 +2,14 @@ def f2a(x, y): return x + @micropython.native def call(r): f = f2a for _ in r: f(1, 2) + bm_params = { (50, 10): (15000,), (100, 10): (30000,), @@ -15,5 +17,6 @@ bm_params = { (5000, 10): (1500000,), } + def bm_setup(params): return lambda: call(range(params[0])), lambda: (params[0] // 1000, None) diff --git a/tests/perf_bench/viper_call2b.py b/tests/perf_bench/viper_call2b.py index 087cf8ab0c..1171b7d576 100644 --- a/tests/perf_bench/viper_call2b.py +++ b/tests/perf_bench/viper_call2b.py @@ -1,13 +1,15 @@ @micropython.viper -def f2b(x:int, y:int) -> int: +def f2b(x: int, y: int) -> int: return x + y + @micropython.native def call(r): f = f2b for _ in r: f(1, 2) + bm_params = { (50, 10): (15000,), (100, 10): (30000,), @@ -15,5 +17,6 @@ bm_params = { (5000, 10): (1500000,), } + def bm_setup(params): return lambda: call(range(params[0])), lambda: (params[0] // 1000, None) diff --git a/tests/pyb/accel.py b/tests/pyb/accel.py index 9aa60c1859..7a5e072be0 100644 --- a/tests/pyb/accel.py +++ b/tests/pyb/accel.py @@ -1,7 +1,7 @@ import pyb -if not hasattr(pyb, 'Accel'): - print('SKIP') +if not hasattr(pyb, "Accel"): + print("SKIP") raise SystemExit accel = pyb.Accel() diff --git a/tests/pyb/adc.py b/tests/pyb/adc.py index ef42065388..875d31d732 100644 --- a/tests/pyb/adc.py +++ b/tests/pyb/adc.py @@ -1,8 +1,8 @@ from pyb import ADC, Timer -adct = ADC(16) # Temperature 930 -> 20C +adct = ADC(16) # Temperature 930 -> 20C print(str(adct)[:19]) -adcv = ADC(17) # Voltage 1500 -> 3.3V +adcv = ADC(17) # Voltage 1500 -> 3.3V print(adcv) # read single sample; 2.5V-5V is pass range @@ -13,7 +13,7 @@ assert val > 1000 and val < 2000 tim = Timer(5, freq=500) # read into bytearray -buf = bytearray(b'\xff' * 50) +buf = bytearray(b"\xff" * 50) adcv.read_timed(buf, tim) print(len(buf)) for i in buf: @@ -21,21 +21,22 @@ for i in buf: # read into arrays with different element sizes import array -arv = array.array('h', 25 * [0x7fff]) + +arv = array.array("h", 25 * [0x7FFF]) adcv.read_timed(arv, tim) print(len(arv)) for i in arv: assert i > 1000 and i < 2000 -arv = array.array('i', 30 * [-1]) +arv = array.array("i", 30 * [-1]) adcv.read_timed(arv, tim) print(len(arv)) for i in arv: assert i > 1000 and i < 2000 # Test read_timed_multi -arv = bytearray(b'\xff'*50) -art = bytearray(b'\xff'*50) +arv = bytearray(b"\xff" * 50) +art = bytearray(b"\xff" * 50) ADC.read_timed_multi((adcv, adct), (arv, art), tim) for i in arv: assert i > 60 and i < 125 @@ -43,8 +44,8 @@ for i in arv: for i in art: assert i > 15 and i < 200 -arv = array.array('i', 25 * [-1]) -art = array.array('i', 25 * [-1]) +arv = array.array("i", 25 * [-1]) +art = array.array("i", 25 * [-1]) ADC.read_timed_multi((adcv, adct), (arv, art), tim) for i in arv: assert i > 1000 and i < 2000 @@ -52,8 +53,8 @@ for i in arv: for i in art: assert i > 50 and i < 2000 -arv = array.array('h', 25 * [0x7fff]) -art = array.array('h', 25 * [0x7fff]) +arv = array.array("h", 25 * [0x7FFF]) +art = array.array("h", 25 * [0x7FFF]) ADC.read_timed_multi((adcv, adct), (arv, art), tim) for i in arv: assert i > 1000 and i < 2000 diff --git a/tests/pyb/board_pybv1x.py b/tests/pyb/board_pybv1x.py index f4aeeb99eb..ea66270b29 100644 --- a/tests/pyb/board_pybv1x.py +++ b/tests/pyb/board_pybv1x.py @@ -2,8 +2,8 @@ import os, pyb -if not 'PYBv1.' in os.uname().machine: - print('SKIP') +if not "PYBv1." in os.uname().machine: + print("SKIP") raise SystemExit # test creating UART by id/name diff --git a/tests/pyb/can.py b/tests/pyb/can.py index 71de724c76..4ea29b0f63 100644 --- a/tests/pyb/can.py +++ b/tests/pyb/can.py @@ -1,7 +1,7 @@ try: from pyb import CAN except ImportError: - print('SKIP') + print("SKIP") raise SystemExit from array import array @@ -40,23 +40,23 @@ print(can.info()) # Catch all filter can.setfilter(0, CAN.MASK16, 0, (0, 0, 0, 0)) -can.send('abcd', 123, timeout=5000) +can.send("abcd", 123, timeout=5000) print(can.any(0), can.info()) print(can.recv(0)) -can.send('abcd', -1, timeout=5000) +can.send("abcd", -1, timeout=5000) print(can.recv(0)) -can.send('abcd', 0x7FF + 1, timeout=5000) +can.send("abcd", 0x7FF + 1, timeout=5000) print(can.recv(0)) # Test too long message try: - can.send('abcdefghi', 0x7FF, timeout=5000) + can.send("abcdefghi", 0x7FF, timeout=5000) except ValueError: - print('passed') + print("passed") else: - print('failed') + print("failed") # Test that recv can work without allocating memory on the heap @@ -66,22 +66,22 @@ l2 = None micropython.heap_lock() -can.send('', 42) +can.send("", 42) l2 = can.recv(0, l) assert l is l2 print(l, len(l[3]), buf) -can.send('1234', 42) +can.send("1234", 42) l2 = can.recv(0, l) assert l is l2 print(l, len(l[3]), buf) -can.send('01234567', 42) +can.send("01234567", 42) l2 = can.recv(0, l) assert l is l2 print(l, len(l[3]), buf) -can.send('abc', 42) +can.send("abc", 42) l2 = can.recv(0, l) assert l is l2 print(l, len(l[3]), buf) @@ -89,65 +89,65 @@ print(l, len(l[3]), buf) micropython.heap_unlock() # Test that recv can work with different arrays behind the memoryview -can.send('abc', 1) -print(bytes(can.recv(0, [0, 0, 0, memoryview(array('B', range(8)))])[3])) -can.send('def', 1) -print(bytes(can.recv(0, [0, 0, 0, memoryview(array('b', range(8)))])[3])) +can.send("abc", 1) +print(bytes(can.recv(0, [0, 0, 0, memoryview(array("B", range(8)))])[3])) +can.send("def", 1) +print(bytes(can.recv(0, [0, 0, 0, memoryview(array("b", range(8)))])[3])) # Test for non-list passed as second arg to recv -can.send('abc', 1) +can.send("abc", 1) try: can.recv(0, 1) except TypeError: - print('TypeError') + print("TypeError") # Test for too-short-list passed as second arg to recv -can.send('abc', 1) +can.send("abc", 1) try: can.recv(0, [0, 0, 0]) except ValueError: - print('ValueError') + print("ValueError") # Test for non-memoryview passed as 4th element to recv -can.send('abc', 1) +can.send("abc", 1) try: can.recv(0, [0, 0, 0, 0]) except TypeError: - print('TypeError') + print("TypeError") # Test for read-only-memoryview passed as 4th element to recv -can.send('abc', 1) +can.send("abc", 1) try: can.recv(0, [0, 0, 0, memoryview(bytes(8))]) except ValueError: - print('ValueError') + print("ValueError") # Test for bad-typecode-memoryview passed as 4th element to recv -can.send('abc', 1) +can.send("abc", 1) try: - can.recv(0, [0, 0, 0, memoryview(array('i', range(8)))]) + can.recv(0, [0, 0, 0, memoryview(array("i", range(8)))]) except ValueError: - print('ValueError') + print("ValueError") del can # Testing extended IDs -can = CAN(1, CAN.LOOPBACK, extframe = True) +can = CAN(1, CAN.LOOPBACK, extframe=True) # Catch all filter can.setfilter(0, CAN.MASK32, 0, (0, 0)) print(can) try: - can.send('abcde', 0x7FF + 1, timeout=5000) + can.send("abcde", 0x7FF + 1, timeout=5000) except ValueError: - print('failed') + print("failed") else: r = can.recv(0) - if r[0] == 0x7FF+1 and r[3] == b'abcde': - print('passed') + if r[0] == 0x7FF + 1 and r[3] == b"abcde": + print("passed") else: - print('failed, wrong data received') + print("failed, wrong data received") # Test filters for n in [0, 8, 16, 24]: @@ -159,7 +159,7 @@ for n in [0, 8, 16, 24]: can.clearfilter(0) can.setfilter(0, pyb.CAN.MASK32, 0, (filter_id, filter_mask)) - can.send('ok', id_ok, timeout=3) + can.send("ok", id_ok, timeout=3) if can.any(0): msg = can.recv(0) print((hex(filter_id), hex(filter_mask), hex(msg[0]), msg[3])) @@ -175,57 +175,62 @@ del can can = CAN(1, CAN.LOOPBACK) can.setfilter(0, CAN.LIST16, 0, (1, 2, 3, 4)) can.setfilter(1, CAN.LIST16, 1, (5, 6, 7, 8)) + + def cb0(bus, reason): - print('cb0') + print("cb0") if reason == 0: - print('pending') + print("pending") if reason == 1: - print('full') + print("full") if reason == 2: - print('overflow') + print("overflow") + def cb1(bus, reason): - print('cb1') + print("cb1") if reason == 0: - print('pending') + print("pending") if reason == 1: - print('full') + print("full") if reason == 2: - print('overflow') + print("overflow") + def cb0a(bus, reason): - print('cb0a') + print("cb0a") if reason == 0: - print('pending') + print("pending") if reason == 1: - print('full') + print("full") if reason == 2: - print('overflow') + print("overflow") + def cb1a(bus, reason): - print('cb1a') + print("cb1a") if reason == 0: - print('pending') + print("pending") if reason == 1: - print('full') + print("full") if reason == 2: - print('overflow') + print("overflow") can.rxcallback(0, cb0) can.rxcallback(1, cb1) -can.send('11111111',1, timeout=5000) -can.send('22222222',2, timeout=5000) -can.send('33333333',3, timeout=5000) +can.send("11111111", 1, timeout=5000) +can.send("22222222", 2, timeout=5000) +can.send("33333333", 3, timeout=5000) can.rxcallback(0, cb0a) -can.send('44444444',4, timeout=5000) +can.send("44444444", 4, timeout=5000) -can.send('55555555',5, timeout=5000) -can.send('66666666',6, timeout=5000) -can.send('77777777',7, timeout=5000) +can.send("55555555", 5, timeout=5000) +can.send("66666666", 6, timeout=5000) +can.send("77777777", 7, timeout=5000) can.rxcallback(1, cb1a) -can.send('88888888',8, timeout=5000) +can.send("88888888", 8, timeout=5000) print(can.recv(0)) print(can.recv(0)) @@ -234,8 +239,8 @@ print(can.recv(1)) print(can.recv(1)) print(can.recv(1)) -can.send('11111111',1, timeout=5000) -can.send('55555555',5, timeout=5000) +can.send("11111111", 1, timeout=5000) +can.send("55555555", 5, timeout=5000) print(can.recv(0)) print(can.recv(1)) @@ -249,7 +254,7 @@ can.setfilter(0, CAN.MASK16, 0, (0, 0, 0, 0)) while can.any(0): can.recv(0) -can.send('abcde', 1, timeout=0) +can.send("abcde", 1, timeout=0) print(can.any(0)) while not can.any(0): pass @@ -257,15 +262,15 @@ while not can.any(0): print(can.recv(0)) try: - can.send('abcde', 2, timeout=0) - can.send('abcde', 3, timeout=0) - can.send('abcde', 4, timeout=0) - can.send('abcde', 5, timeout=0) + can.send("abcde", 2, timeout=0) + can.send("abcde", 3, timeout=0) + can.send("abcde", 4, timeout=0) + can.send("abcde", 5, timeout=0) except OSError as e: - if str(e) == '16': - print('passed') + if str(e) == "16": + print("passed") else: - print('failed') + print("failed") pyb.delay(500) while can.any(0): @@ -279,22 +284,22 @@ bus1.setfilter(0, CAN.LIST16, 0, (1, 2, 3, 4)) bus1.setfilter(1, CAN.LIST16, 0, (5, 6, 7, 8), rtr=(True, True, True, True)) bus1.setfilter(2, CAN.MASK16, 0, (64, 64, 32, 32), rtr=(False, True)) -bus1.send('',1,rtr=True) +bus1.send("", 1, rtr=True) print(bus1.any(0)) -bus1.send('',5,rtr=True) +bus1.send("", 5, rtr=True) print(bus1.recv(0)) -bus1.send('',6,rtr=True) +bus1.send("", 6, rtr=True) print(bus1.recv(0)) -bus1.send('',7,rtr=True) +bus1.send("", 7, rtr=True) print(bus1.recv(0)) -bus1.send('',16,rtr=True) +bus1.send("", 16, rtr=True) print(bus1.any(0)) -bus1.send('',32,rtr=True) +bus1.send("", 32, rtr=True) print(bus1.recv(0)) # test HAL error, timeout can = pyb.CAN(1, pyb.CAN.NORMAL) try: - can.send('1', 1, timeout=50) + can.send("1", 1, timeout=50) except OSError as e: print(repr(e)) diff --git a/tests/pyb/can2.py b/tests/pyb/can2.py index 440ae4925b..46237ad84f 100644 --- a/tests/pyb/can2.py +++ b/tests/pyb/can2.py @@ -1,8 +1,9 @@ try: from pyb import CAN + CAN(2) except (ImportError, ValueError): - print('SKIP') + print("SKIP") raise SystemExit # Testing rtr messages @@ -14,11 +15,11 @@ bus2.setfilter(1, CAN.LIST32, 0, (3, 4), rtr=(True, False)) bus2.setfilter(2, CAN.MASK32, 0, (16, 16), rtr=(False,)) bus2.setfilter(2, CAN.MASK32, 0, (32, 32), rtr=(True,)) -bus2.send('',1,rtr=True) +bus2.send("", 1, rtr=True) print(bus2.recv(0)) -bus2.send('',2,rtr=True) +bus2.send("", 2, rtr=True) print(bus2.recv(0)) -bus2.send('',3,rtr=True) +bus2.send("", 3, rtr=True) print(bus2.recv(0)) -bus2.send('',4,rtr=True) +bus2.send("", 4, rtr=True) print(bus2.any(0)) diff --git a/tests/pyb/dac.py b/tests/pyb/dac.py index ca68ec7098..506cf272b3 100644 --- a/tests/pyb/dac.py +++ b/tests/pyb/dac.py @@ -1,7 +1,7 @@ import pyb -if not hasattr(pyb, 'DAC'): - print('SKIP') +if not hasattr(pyb, "DAC"): + print("SKIP") raise SystemExit dac = pyb.DAC(1) diff --git a/tests/pyb/extint.py b/tests/pyb/extint.py index 8b6bc56517..5510600020 100644 --- a/tests/pyb/extint.py +++ b/tests/pyb/extint.py @@ -1,7 +1,7 @@ import pyb # test basic functionality -ext = pyb.ExtInt('X5', pyb.ExtInt.IRQ_RISING, pyb.Pin.PULL_DOWN, lambda l:print('line:', l)) +ext = pyb.ExtInt("X5", pyb.ExtInt.IRQ_RISING, pyb.Pin.PULL_DOWN, lambda l: print("line:", l)) ext.disable() ext.enable() print(ext.line()) diff --git a/tests/pyb/i2c_accel.py b/tests/pyb/i2c_accel.py index e42cba178a..8c74fa60e6 100644 --- a/tests/pyb/i2c_accel.py +++ b/tests/pyb/i2c_accel.py @@ -3,13 +3,13 @@ import pyb from pyb import I2C -if not hasattr(pyb, 'Accel'): - print('SKIP') +if not hasattr(pyb, "Accel"): + print("SKIP") raise SystemExit accel_addr = 76 -pyb.Accel() # this will init the MMA for us +pyb.Accel() # this will init the MMA for us i2c = I2C(1, I2C.MASTER, baudrate=400000) diff --git a/tests/pyb/i2c_error.py b/tests/pyb/i2c_error.py index e0f721179f..b17a26325d 100644 --- a/tests/pyb/i2c_error.py +++ b/tests/pyb/i2c_error.py @@ -3,8 +3,8 @@ import pyb from pyb import I2C -if not hasattr(pyb, 'Accel'): - print('SKIP') +if not hasattr(pyb, "Accel"): + print("SKIP") raise SystemExit # init accelerometer @@ -15,40 +15,40 @@ i2c = I2C(1, I2C.MASTER, dma=True) # test polling mem_read pyb.disable_irq() -i2c.mem_read(1, 76, 0x0a) # should succeed +i2c.mem_read(1, 76, 0x0A) # should succeed pyb.enable_irq() try: pyb.disable_irq() - i2c.mem_read(1, 77, 0x0a) # should fail + i2c.mem_read(1, 77, 0x0A) # should fail except OSError as e: pyb.enable_irq() print(repr(e)) -i2c.mem_read(1, 76, 0x0a) # should succeed +i2c.mem_read(1, 76, 0x0A) # should succeed # test polling mem_write pyb.disable_irq() -i2c.mem_write(1, 76, 0x0a) # should succeed +i2c.mem_write(1, 76, 0x0A) # should succeed pyb.enable_irq() try: pyb.disable_irq() - i2c.mem_write(1, 77, 0x0a) # should fail + i2c.mem_write(1, 77, 0x0A) # should fail except OSError as e: pyb.enable_irq() print(repr(e)) -i2c.mem_write(1, 76, 0x0a) # should succeed +i2c.mem_write(1, 76, 0x0A) # should succeed # test DMA mem_read -i2c.mem_read(1, 76, 0x0a) # should succeed +i2c.mem_read(1, 76, 0x0A) # should succeed try: - i2c.mem_read(1, 77, 0x0a) # should fail + i2c.mem_read(1, 77, 0x0A) # should fail except OSError as e: print(repr(e)) -i2c.mem_read(1, 76, 0x0a) # should succeed +i2c.mem_read(1, 76, 0x0A) # should succeed # test DMA mem_write -i2c.mem_write(1, 76, 0x0a) # should succeed +i2c.mem_write(1, 76, 0x0A) # should succeed try: - i2c.mem_write(1, 77, 0x0a) # should fail + i2c.mem_write(1, 77, 0x0A) # should fail except OSError as e: print(repr(e)) -i2c.mem_write(1, 76, 0x0a) # should succeed +i2c.mem_write(1, 76, 0x0A) # should succeed diff --git a/tests/pyb/irq.py b/tests/pyb/irq.py index 42d276568e..04e70a7b79 100644 --- a/tests/pyb/irq.py +++ b/tests/pyb/irq.py @@ -1,10 +1,11 @@ import pyb + def test_irq(): # test basic disable/enable i1 = pyb.disable_irq() print(i1) - pyb.enable_irq() # by default should enable IRQ + pyb.enable_irq() # by default should enable IRQ # check that interrupts are enabled by waiting for ticks pyb.delay(10) @@ -19,4 +20,5 @@ def test_irq(): # check that interrupts are enabled by waiting for ticks pyb.delay(10) + test_irq() diff --git a/tests/pyb/led.py b/tests/pyb/led.py index 38e9993cb0..1702c189eb 100644 --- a/tests/pyb/led.py +++ b/tests/pyb/led.py @@ -1,14 +1,14 @@ import os, pyb machine = os.uname().machine -if 'PYBv1.' in machine or 'PYBLITEv1.' in machine: +if "PYBv1." in machine or "PYBLITEv1." in machine: leds = [pyb.LED(i) for i in range(1, 5)] pwm_leds = leds[2:] -elif 'PYBD' in machine: +elif "PYBD" in machine: leds = [pyb.LED(i) for i in range(1, 4)] pwm_leds = [] else: - print('SKIP') + print("SKIP") raise SystemExit # test printing diff --git a/tests/pyb/modtime.py b/tests/pyb/modtime.py index d45440a63c..396f832667 100644 --- a/tests/pyb/modtime.py +++ b/tests/pyb/modtime.py @@ -2,12 +2,14 @@ import time DAYS_PER_MONTH = [0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31] + def is_leap(year): return (year % 4) == 0 + def test(): seconds = 0 - wday = 5 # Jan 1, 2000 was a Saturday + wday = 5 # Jan 1, 2000 was a Saturday for year in range(2000, 2034): print("Testing %d" % year) yday = 1 @@ -19,32 +21,48 @@ def test(): for day in range(1, DAYS_PER_MONTH[month] + 1): secs = time.mktime((year, month, day, 0, 0, 0, 0, 0)) if secs != seconds: - print("mktime failed for %d-%02d-%02d got %d expected %d" % (year, month, day, secs, seconds)) + print( + "mktime failed for %d-%02d-%02d got %d expected %d" + % (year, month, day, secs, seconds) + ) tuple = time.localtime(seconds) secs = time.mktime(tuple) if secs != seconds: - print("localtime failed for %d-%02d-%02d got %d expected %d" % (year, month, day, secs, seconds)) + print( + "localtime failed for %d-%02d-%02d got %d expected %d" + % (year, month, day, secs, seconds) + ) return seconds += 86400 if yday != tuple[7]: - print("locatime for %d-%02d-%02d got yday %d, expecting %d" % (year, month, day, tuple[7], yday)) + print( + "locatime for %d-%02d-%02d got yday %d, expecting %d" + % (year, month, day, tuple[7], yday) + ) return if wday != tuple[6]: - print("locatime for %d-%02d-%02d got wday %d, expecting %d" % (year, month, day, tuple[6], wday)) + print( + "locatime for %d-%02d-%02d got wday %d, expecting %d" + % (year, month, day, tuple[6], wday) + ) return yday += 1 wday = (wday + 1) % 7 + def spot_test(seconds, expected_time): actual_time = time.localtime(seconds) for i in range(len(actual_time)): if actual_time[i] != expected_time[i]: - print("time.localtime(", seconds, ") returned", actual_time, "expecting", expected_time) + print( + "time.localtime(", seconds, ") returned", actual_time, "expecting", expected_time + ) return print("time.localtime(", seconds, ") returned", actual_time, "(pass)") test() +# fmt: off spot_test( 0, (2000, 1, 1, 0, 0, 0, 5, 1)) spot_test( 1, (2000, 1, 1, 0, 0, 1, 5, 1)) spot_test( 59, (2000, 1, 1, 0, 0, 59, 5, 1)) @@ -57,3 +75,4 @@ spot_test( -940984933, (1970, 3, 7, 23, 17, 47, 5, 66)) spot_test(-1072915199, (1966, 1, 1, 0, 0, 1, 5, 1)) spot_test(-1072915200, (1966, 1, 1, 0, 0, 0, 5, 1)) spot_test(-1072915201, (1965, 12, 31, 23, 59, 59, 4, 365)) +# fmt: on diff --git a/tests/pyb/pin.py b/tests/pyb/pin.py index ea42cc206f..3d2bef97e3 100644 --- a/tests/pyb/pin.py +++ b/tests/pyb/pin.py @@ -1,14 +1,14 @@ from pyb import Pin -p = Pin('X8', Pin.IN) +p = Pin("X8", Pin.IN) print(p) print(p.name()) print(p.pin()) print(p.port()) -p = Pin('X8', Pin.IN, Pin.PULL_UP) -p = Pin('X8', Pin.IN, pull=Pin.PULL_UP) -p = Pin('X8', mode=Pin.IN, pull=Pin.PULL_UP) +p = Pin("X8", Pin.IN, Pin.PULL_UP) +p = Pin("X8", Pin.IN, pull=Pin.PULL_UP) +p = Pin("X8", mode=Pin.IN, pull=Pin.PULL_UP) print(p) print(p.value()) diff --git a/tests/pyb/pyb1.py b/tests/pyb/pyb1.py index 443722ca85..e9626ecf4e 100644 --- a/tests/pyb/pyb1.py +++ b/tests/pyb/pyb1.py @@ -10,7 +10,7 @@ pyb.delay(1) start = pyb.millis() pyb.delay(17) -print((pyb.millis() - start) // 5) # should print 3 +print((pyb.millis() - start) // 5) # should print 3 # test udelay @@ -20,7 +20,7 @@ pyb.udelay(1) start = pyb.millis() pyb.udelay(17000) -print((pyb.millis() - start) // 5) # should print 3 +print((pyb.millis() - start) // 5) # should print 3 # other diff --git a/tests/pyb/pyb_f405.py b/tests/pyb/pyb_f405.py index f49dd1bc75..243381056e 100644 --- a/tests/pyb/pyb_f405.py +++ b/tests/pyb/pyb_f405.py @@ -2,8 +2,8 @@ import os, pyb -if not 'STM32F405' in os.uname().machine: - print('SKIP') +if not "STM32F405" in os.uname().machine: + print("SKIP") raise SystemExit print(pyb.freq()) @@ -15,4 +15,3 @@ try: i2c.recv(1, 1) except OSError as e: print(repr(e)) - diff --git a/tests/pyb/pyb_f411.py b/tests/pyb/pyb_f411.py index 50de302823..58d5fa2d41 100644 --- a/tests/pyb/pyb_f411.py +++ b/tests/pyb/pyb_f411.py @@ -2,8 +2,8 @@ import os, pyb -if not 'STM32F411' in os.uname().machine: - print('SKIP') +if not "STM32F411" in os.uname().machine: + print("SKIP") raise SystemExit print(pyb.freq()) diff --git a/tests/pyb/rtc.py b/tests/pyb/rtc.py index 844526b4b9..41b52f260d 100644 --- a/tests/pyb/rtc.py +++ b/tests/pyb/rtc.py @@ -10,10 +10,12 @@ rtc.datetime((2014, 1, 1, 1, 0, 0, 0, 0)) pyb.delay(1002) print(rtc.datetime()[:7]) + def set_and_print(datetime): rtc.datetime(datetime) print(rtc.datetime()[:7]) + # make sure that setting works correctly set_and_print((2000, 1, 1, 1, 0, 0, 0, 0)) set_and_print((2000, 1, 31, 1, 0, 0, 0, 0)) @@ -34,10 +36,12 @@ set_and_print((2099, 12, 31, 7, 23, 59, 59, 0)) # save existing calibration value: cal_tmp = rtc.calibration() + def set_and_print_calib(cal): rtc.calibration(cal) print(rtc.calibration()) + set_and_print_calib(512) set_and_print_calib(511) set_and_print_calib(345) @@ -56,12 +60,13 @@ def set_and_print_wakeup(ms): try: rtc.wakeup(ms) wucksel = stm.mem32[stm.RTC + stm.RTC_CR] & 7 - wut = stm.mem32[stm.RTC + stm.RTC_WUTR] & 0xffff + wut = stm.mem32[stm.RTC + stm.RTC_WUTR] & 0xFFFF except ValueError: wucksel = -1 wut = -1 print((wucksel, wut)) + set_and_print_wakeup(0) set_and_print_wakeup(1) set_and_print_wakeup(4000) @@ -72,8 +77,8 @@ set_and_print_wakeup(16000) set_and_print_wakeup(16001) set_and_print_wakeup(32000) set_and_print_wakeup(32001) -set_and_print_wakeup(0x10000*1000) -set_and_print_wakeup(0x10001*1000) -set_and_print_wakeup(0x1ffff*1000) -set_and_print_wakeup(0x20000*1000) -set_and_print_wakeup(0x20001*1000) # exception +set_and_print_wakeup(0x10000 * 1000) +set_and_print_wakeup(0x10001 * 1000) +set_and_print_wakeup(0x1FFFF * 1000) +set_and_print_wakeup(0x20000 * 1000) +set_and_print_wakeup(0x20001 * 1000) # exception diff --git a/tests/pyb/spi.py b/tests/pyb/spi.py index 577737420f..73d39e7245 100644 --- a/tests/pyb/spi.py +++ b/tests/pyb/spi.py @@ -14,7 +14,7 @@ print(spi) spi = SPI(1, SPI.MASTER) spi = SPI(1, SPI.MASTER, baudrate=500000) spi = SPI(1, SPI.MASTER, 500000, polarity=1, phase=0, bits=8, firstbit=SPI.MSB, ti=False, crc=None) -print(str(spi)[:28], str(spi)[49:]) # don't print baudrate/prescaler +print(str(spi)[:28], str(spi)[49:]) # don't print baudrate/prescaler spi.init(SPI.SLAVE, phase=1) print(spi) diff --git a/tests/pyb/timer.py b/tests/pyb/timer.py index 0e24ff4ad4..251a06c081 100644 --- a/tests/pyb/timer.py +++ b/tests/pyb/timer.py @@ -16,4 +16,4 @@ print(tim.period()) tim = Timer(2, freq=100) print(tim.freq()) tim.freq(0.001) -print('{:.3f}'.format(tim.freq())) +print("{:.3f}".format(tim.freq())) diff --git a/tests/pyb/timer_callback.py b/tests/pyb/timer_callback.py index 864dd479ed..51242fba4b 100644 --- a/tests/pyb/timer_callback.py +++ b/tests/pyb/timer_callback.py @@ -8,19 +8,24 @@ def cb1(t): print("cb1") t.callback(None) + # callback function that disables the timer when called def cb2(t): print("cb2") t.deinit() + # callback where cb4 closes over cb3.y def cb3(x): y = x + def cb4(t): print("cb4", y) t.callback(None) + return cb4 + # create a timer with a callback, using callback(None) to stop tim = Timer(1, freq=100, callback=cb1) pyb.delay(5) diff --git a/tests/pyb/uart.py b/tests/pyb/uart.py index 9dcb1f75cd..53b0ea6ade 100644 --- a/tests/pyb/uart.py +++ b/tests/pyb/uart.py @@ -17,8 +17,8 @@ uart.init(2400) print(uart) print(uart.any()) -print(uart.write('123')) -print(uart.write(b'abcd')) +print(uart.write("123")) +print(uart.write(b"abcd")) print(uart.writechar(1)) # make sure this method exists @@ -26,8 +26,8 @@ uart.sendbreak() # non-blocking mode uart = UART(1, 9600, timeout=0) -print(uart.write(b'1')) -print(uart.write(b'abcd')) +print(uart.write(b"1")) +print(uart.write(b"abcd")) print(uart.writechar(1)) print(uart.read(100)) diff --git a/tests/pybnative/for.py b/tests/pybnative/for.py index 309c6c14fd..50177a9ba4 100644 --- a/tests/pybnative/for.py +++ b/tests/pybnative/for.py @@ -1,15 +1,19 @@ import pyb + @micropython.native def f1(n): for i in range(n): print(i) + f1(4) + @micropython.native def f2(r): for i in r: print(i) + f2(range(4)) diff --git a/tests/pybnative/while.py b/tests/pybnative/while.py index 3ea7221ea7..0f397dd377 100644 --- a/tests/pybnative/while.py +++ b/tests/pybnative/while.py @@ -1,5 +1,6 @@ import pyb + @micropython.native def f(led, n, d): led.off() @@ -11,5 +12,6 @@ def f(led, n, d): i += 1 led.off() + f(pyb.LED(1), 2, 150) f(pyb.LED(2), 4, 50) diff --git a/tests/run-internalbench.py b/tests/run-internalbench.py index f6294572f0..63392814a8 100755 --- a/tests/run-internalbench.py +++ b/tests/run-internalbench.py @@ -11,12 +11,13 @@ from collections import defaultdict # Tests require at least CPython 3.3. If your default python3 executable # is of lower version, you can point MICROPY_CPYTHON3 environment var # to the correct executable. -if os.name == 'nt': - CPYTHON3 = os.getenv('MICROPY_CPYTHON3', 'python3.exe') - MICROPYTHON = os.getenv('MICROPY_MICROPYTHON', '../ports/windows/micropython.exe') +if os.name == "nt": + CPYTHON3 = os.getenv("MICROPY_CPYTHON3", "python3.exe") + MICROPYTHON = os.getenv("MICROPY_MICROPYTHON", "../ports/windows/micropython.exe") else: - CPYTHON3 = os.getenv('MICROPY_CPYTHON3', 'python3') - MICROPYTHON = os.getenv('MICROPY_MICROPYTHON', '../ports/unix/micropython') + CPYTHON3 = os.getenv("MICROPY_CPYTHON3", "python3") + MICROPYTHON = os.getenv("MICROPY_MICROPYTHON", "../ports/unix/micropython") + def run_tests(pyb, test_dict): test_count = 0 @@ -30,16 +31,18 @@ def run_tests(pyb, test_dict): if pyb is None: # run on PC try: - output_mupy = subprocess.check_output([MICROPYTHON, '-X', 'emit=bytecode', test_file[0]]) + output_mupy = subprocess.check_output( + [MICROPYTHON, "-X", "emit=bytecode", test_file[0]] + ) except subprocess.CalledProcessError: - output_mupy = b'CRASH' + output_mupy = b"CRASH" else: # run on pyboard pyb.enter_raw_repl() try: - output_mupy = pyb.execfile(test_file).replace(b'\r\n', b'\n') + output_mupy = pyb.execfile(test_file).replace(b"\r\n", b"\n") except pyboard.PyboardError: - output_mupy = b'CRASH' + output_mupy = b"CRASH" output_mupy = float(output_mupy.strip()) test_file[1] = output_mupy @@ -57,16 +60,18 @@ def run_tests(pyb, test_dict): # all tests succeeded return True + def main(): - cmd_parser = argparse.ArgumentParser(description='Run tests for MicroPython.') - cmd_parser.add_argument('--pyboard', action='store_true', help='run the tests on the pyboard') - cmd_parser.add_argument('files', nargs='*', help='input test files') + cmd_parser = argparse.ArgumentParser(description="Run tests for MicroPython.") + cmd_parser.add_argument("--pyboard", action="store_true", help="run the tests on the pyboard") + cmd_parser.add_argument("files", nargs="*", help="input test files") args = cmd_parser.parse_args() # Note pyboard support is copied over from run-tests, not testes, and likely needs revamping if args.pyboard: import pyboard - pyb = pyboard.Pyboard('/dev/ttyACM0') + + pyb = pyboard.Pyboard("/dev/ttyACM0") pyb.enter_raw_repl() else: pyb = None @@ -74,11 +79,15 @@ def main(): if len(args.files) == 0: if pyb is None: # run PC tests - test_dirs = ('internal_bench',) + test_dirs = ("internal_bench",) else: # run pyboard tests - test_dirs = ('basics', 'float', 'pyb') - tests = sorted(test_file for test_files in (glob('{}/*.py'.format(dir)) for dir in test_dirs) for test_file in test_files) + test_dirs = ("basics", "float", "pyb") + tests = sorted( + test_file + for test_files in (glob("{}/*.py".format(dir)) for dir in test_dirs) + for test_file in test_files + ) else: # tests explicitly given tests = sorted(args.files) @@ -93,5 +102,6 @@ def main(): if not run_tests(pyb, test_dict): sys.exit(1) + if __name__ == "__main__": main() diff --git a/tests/run-multitests.py b/tests/run-multitests.py index 4e5bfc3b05..c8e537d4b2 100755 --- a/tests/run-multitests.py +++ b/tests/run-multitests.py @@ -383,7 +383,7 @@ def main(): cmd_args = cmd_parser.parse_args() # clear search path to make sure tests use only builtin modules and those in extmod - os.environ['MICROPYPATH'] = os.pathsep + '../extmod' + os.environ["MICROPYPATH"] = os.pathsep + "../extmod" test_files = prepare_test_file_list(cmd_args.files) max_instances = max(t[1] for t in test_files) diff --git a/tests/run-natmodtests.py b/tests/run-natmodtests.py index 46f21f81d7..f88ca0b788 100755 --- a/tests/run-natmodtests.py +++ b/tests/run-natmodtests.py @@ -9,23 +9,23 @@ import subprocess import sys import argparse -sys.path.append('../tools') +sys.path.append("../tools") import pyboard # Paths for host executables -CPYTHON3 = os.getenv('MICROPY_CPYTHON3', 'python3') -MICROPYTHON = os.getenv('MICROPY_MICROPYTHON', '../ports/unix/micropython-coverage') +CPYTHON3 = os.getenv("MICROPY_CPYTHON3", "python3") +MICROPYTHON = os.getenv("MICROPY_MICROPYTHON", "../ports/unix/micropython-coverage") -NATMOD_EXAMPLE_DIR = '../examples/natmod/' +NATMOD_EXAMPLE_DIR = "../examples/natmod/" # Supported tests and their corresponding mpy module TEST_MAPPINGS = { - 'btree': 'btree/btree_$(ARCH).mpy', - 'framebuf': 'framebuf/framebuf_$(ARCH).mpy', - 'uheapq': 'uheapq/uheapq_$(ARCH).mpy', - 'urandom': 'urandom/urandom_$(ARCH).mpy', - 'ure': 'ure/ure_$(ARCH).mpy', - 'uzlib': 'uzlib/uzlib_$(ARCH).mpy', + "btree": "btree/btree_$(ARCH).mpy", + "framebuf": "framebuf/framebuf_$(ARCH).mpy", + "uheapq": "uheapq/uheapq_$(ARCH).mpy", + "urandom": "urandom/urandom_$(ARCH).mpy", + "ure": "ure/ure_$(ARCH).mpy", + "uzlib": "uzlib/uzlib_$(ARCH).mpy", } # Code to allow a target MicroPython to import an .mpy from RAM @@ -57,6 +57,7 @@ uos.chdir('/__remote') sys.modules['{}'] = __import__('__injected') """ + class TargetSubprocess: def __init__(self, cmd): self.cmd = cmd @@ -66,10 +67,13 @@ class TargetSubprocess: def run_script(self, script): try: - p = subprocess.run(self.cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, input=script) + p = subprocess.run( + self.cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, input=script + ) return p.stdout, None except subprocess.CalledProcessError as er: - return b'', er + return b"", er + class TargetPyboard: def __init__(self, pyb): @@ -84,10 +88,11 @@ class TargetPyboard: try: self.pyb.enter_raw_repl() output = self.pyb.exec_(script) - output = output.replace(b'\r\n', b'\n') + output = output.replace(b"\r\n", b"\n") return output, None except pyboard.PyboardError as er: - return b'', er + return b"", er + def run_tests(target_truth, target, args, stats): for test_file in args.files: @@ -95,70 +100,79 @@ def run_tests(target_truth, target, args, stats): for k, v in TEST_MAPPINGS.items(): if test_file.find(k) != -1: test_module = k - test_mpy = v.replace('$(ARCH)', args.arch) + test_mpy = v.replace("$(ARCH)", args.arch) break else: - print('---- {} - no matching mpy'.format(test_file)) + print("---- {} - no matching mpy".format(test_file)) continue # Read test script - with open(test_file, 'rb') as f: + with open(test_file, "rb") as f: test_file_data = f.read() # Create full test with embedded .mpy try: - with open(NATMOD_EXAMPLE_DIR + test_mpy, 'rb') as f: - test_script = b'__buf=' + bytes(repr(f.read()), 'ascii') + b'\n' + with open(NATMOD_EXAMPLE_DIR + test_mpy, "rb") as f: + test_script = b"__buf=" + bytes(repr(f.read()), "ascii") + b"\n" except OSError: - print('---- {} - mpy file not compiled'.format(test_file)) + print("---- {} - mpy file not compiled".format(test_file)) continue - test_script += bytes(injected_import_hook_code.format(test_module), 'ascii') + test_script += bytes(injected_import_hook_code.format(test_module), "ascii") test_script += test_file_data # Run test under MicroPython result_out, error = target.run_script(test_script) # Work out result of test - extra = '' - if error is None and result_out == b'SKIP\n': - result = 'SKIP' + extra = "" + if error is None and result_out == b"SKIP\n": + result = "SKIP" elif error is not None: - result = 'FAIL' - extra = ' - ' + str(error) + result = "FAIL" + extra = " - " + str(error) else: # Check result against truth try: - with open(test_file + '.exp', 'rb') as f: + with open(test_file + ".exp", "rb") as f: result_exp = f.read() error = None except OSError: result_exp, error = target_truth.run_script(test_file_data) if error is not None: - result = 'TRUTH FAIL' + result = "TRUTH FAIL" elif result_out != result_exp: - result = 'FAIL' + result = "FAIL" print(result_out) else: - result = 'pass' + result = "pass" # Accumulate statistics - stats['total'] += 1 - if result == 'pass': - stats['pass'] += 1 - elif result == 'SKIP': - stats['skip'] += 1 + stats["total"] += 1 + if result == "pass": + stats["pass"] += 1 + elif result == "SKIP": + stats["skip"] += 1 else: - stats['fail'] += 1 + stats["fail"] += 1 # Print result - print('{:4} {}{}'.format(result, test_file, extra)) + print("{:4} {}{}".format(result, test_file, extra)) + def main(): - cmd_parser = argparse.ArgumentParser(description='Run dynamic-native-module tests under MicroPython') - cmd_parser.add_argument('-p', '--pyboard', action='store_true', help='run tests via pyboard.py') - cmd_parser.add_argument('-d', '--device', default='/dev/ttyACM0', help='the device for pyboard.py') - cmd_parser.add_argument('-a', '--arch', default='x64', help='native architecture of the target') - cmd_parser.add_argument('files', nargs='*', help='input test files') + cmd_parser = argparse.ArgumentParser( + description="Run dynamic-native-module tests under MicroPython" + ) + cmd_parser.add_argument( + "-p", "--pyboard", action="store_true", help="run tests via pyboard.py" + ) + cmd_parser.add_argument( + "-d", "--device", default="/dev/ttyACM0", help="the device for pyboard.py" + ) + cmd_parser.add_argument( + "-a", "--arch", default="x64", help="native architecture of the target" + ) + cmd_parser.add_argument("files", nargs="*", help="input test files") args = cmd_parser.parse_args() target_truth = TargetSubprocess([CPYTHON3]) @@ -168,21 +182,22 @@ def main(): else: target = TargetSubprocess([MICROPYTHON]) - stats = {'total': 0, 'pass': 0, 'fail':0, 'skip': 0} + stats = {"total": 0, "pass": 0, "fail": 0, "skip": 0} run_tests(target_truth, target, args, stats) target.close() target_truth.close() - print('{} tests performed'.format(stats['total'])) - print('{} tests passed'.format(stats['pass'])) - if stats['fail']: - print('{} tests failed'.format(stats['fail'])) - if stats['skip']: - print('{} tests skipped'.format(stats['skip'])) + print("{} tests performed".format(stats["total"])) + print("{} tests passed".format(stats["pass"])) + if stats["fail"]: + print("{} tests failed".format(stats["fail"])) + if stats["skip"]: + print("{} tests skipped".format(stats["skip"])) - if stats['fail']: + if stats["fail"]: sys.exit(1) + if __name__ == "__main__": main() diff --git a/tests/run-perfbench.py b/tests/run-perfbench.py index d02021719a..8b71ae64ce 100755 --- a/tests/run-perfbench.py +++ b/tests/run-perfbench.py @@ -10,20 +10,21 @@ import sys import argparse from glob import glob -sys.path.append('../tools') +sys.path.append("../tools") import pyboard # Paths for host executables -if os.name == 'nt': - CPYTHON3 = os.getenv('MICROPY_CPYTHON3', 'python3.exe') - MICROPYTHON = os.getenv('MICROPY_MICROPYTHON', '../ports/windows/micropython.exe') +if os.name == "nt": + CPYTHON3 = os.getenv("MICROPY_CPYTHON3", "python3.exe") + MICROPYTHON = os.getenv("MICROPY_MICROPYTHON", "../ports/windows/micropython.exe") else: - CPYTHON3 = os.getenv('MICROPY_CPYTHON3', 'python3') - MICROPYTHON = os.getenv('MICROPY_MICROPYTHON', '../ports/unix/micropython') + CPYTHON3 = os.getenv("MICROPY_CPYTHON3", "python3") + MICROPYTHON = os.getenv("MICROPY_MICROPYTHON", "../ports/unix/micropython") PYTHON_TRUTH = CPYTHON3 -BENCH_SCRIPT_DIR = 'perf_bench/' +BENCH_SCRIPT_DIR = "perf_bench/" + def compute_stats(lst): avg = 0 @@ -35,8 +36,9 @@ def compute_stats(lst): var = max(0, var / len(lst) - avg ** 2) return avg, var ** 0.5 + def run_script_on_target(target, script): - output = b'' + output = b"" err = None if isinstance(target, pyboard.Pyboard): @@ -49,21 +51,25 @@ def run_script_on_target(target, script): else: # Run local executable try: - p = subprocess.run(target, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, input=script) + p = subprocess.run( + target, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, input=script + ) output = p.stdout except subprocess.CalledProcessError as er: err = er - return str(output.strip(), 'ascii'), err + return str(output.strip(), "ascii"), err + def run_feature_test(target, test): - with open('feature_check/' + test + '.py', 'rb') as f: + with open("feature_check/" + test + ".py", "rb") as f: script = f.read() output, err = run_script_on_target(target, script) if err is None: return output else: - return 'CRASH: %r' % err + return "CRASH: %r" % err + def run_benchmark_on_target(target, script): output, err = run_script_on_target(target, script) @@ -72,36 +78,39 @@ def run_benchmark_on_target(target, script): try: return int(time), int(norm), result except ValueError: - return -1, -1, 'CRASH: %r' % output + return -1, -1, "CRASH: %r" % output else: - return -1, -1, 'CRASH: %r' % err + return -1, -1, "CRASH: %r" % err + def run_benchmarks(target, param_n, param_m, n_average, test_list): - skip_complex = run_feature_test(target, 'complex') != 'complex' - skip_native = run_feature_test(target, 'native_check') != '' + skip_complex = run_feature_test(target, "complex") != "complex" + skip_native = run_feature_test(target, "native_check") != "" for test_file in sorted(test_list): - print(test_file + ': ', end='') + print(test_file + ": ", end="") # Check if test should be skipped skip = ( - skip_complex and test_file.find('bm_fft') != -1 - or skip_native and test_file.find('viper_') != -1 + skip_complex + and test_file.find("bm_fft") != -1 + or skip_native + and test_file.find("viper_") != -1 ) if skip: - print('skip') + print("skip") continue # Create test script - with open(test_file, 'rb') as f: + with open(test_file, "rb") as f: test_script = f.read() - with open(BENCH_SCRIPT_DIR + 'benchrun.py', 'rb') as f: + with open(BENCH_SCRIPT_DIR + "benchrun.py", "rb") as f: test_script += f.read() - test_script += b'bm_run(%u, %u)\n' % (param_n, param_m) + test_script += b"bm_run(%u, %u)\n" % (param_n, param_m) # Write full test script if needed if 0: - with open('%s.full' % test_file, 'wb') as f: + with open("%s.full" % test_file, "wb") as f: f.write(test_script) # Run MicroPython a given number of times @@ -117,43 +126,49 @@ def run_benchmarks(target, param_n, param_m, n_average, test_list): if result_out is None: result_out = result elif result != result_out: - error = 'FAIL self' + error = "FAIL self" break times.append(time) scores.append(1e6 * norm / time) # Check result against truth if needed - if error is None and result_out != 'None': + if error is None and result_out != "None": _, _, result_exp = run_benchmark_on_target(PYTHON_TRUTH, test_script) if result_out != result_exp: - error = 'FAIL truth' + error = "FAIL truth" if error is not None: print(error) else: t_avg, t_sd = compute_stats(times) s_avg, s_sd = compute_stats(scores) - print('{:.2f} {:.4f} {:.2f} {:.4f}'.format(t_avg, 100 * t_sd / t_avg, s_avg, 100 * s_sd / s_avg)) + print( + "{:.2f} {:.4f} {:.2f} {:.4f}".format( + t_avg, 100 * t_sd / t_avg, s_avg, 100 * s_sd / s_avg + ) + ) if 0: - print(' times: ', times) - print(' scores:', scores) + print(" times: ", times) + print(" scores:", scores) sys.stdout.flush() + def parse_output(filename): with open(filename) as f: params = f.readline() n, m, _ = params.strip().split() - n = int(n.split('=')[1]) - m = int(m.split('=')[1]) + n = int(n.split("=")[1]) + m = int(m.split("=")[1]) data = [] for l in f: - if l.find(': ') != -1 and l.find(': skip') == -1 and l.find('CRASH: ') == -1: - name, values = l.strip().split(': ') + if l.find(": ") != -1 and l.find(": skip") == -1 and l.find("CRASH: ") == -1: + name, values = l.strip().split(": ") values = tuple(float(v) for v in values.split()) data.append((name,) + values) return n, m, data + def compute_diff(file1, file2, diff_score): # Parse output data from previous runs n1, m1, d1 = parse_output(file1) @@ -161,14 +176,18 @@ def compute_diff(file1, file2, diff_score): # Print header if diff_score: - print('diff of scores (higher is better)') + print("diff of scores (higher is better)") else: - print('diff of microsecond times (lower is better)') + print("diff of microsecond times (lower is better)") if n1 == n2 and m1 == m2: - hdr = 'N={} M={}'.format(n1, m1) + hdr = "N={} M={}".format(n1, m1) else: - hdr = 'N={} M={} vs N={} M={}'.format(n1, m1, n2, m2) - print('{:24} {:>10} -> {:>10} {:>10} {:>7}% (error%)'.format(hdr, file1, file2, 'diff', 'diff')) + hdr = "N={} M={} vs N={} M={}".format(n1, m1, n2, m2) + print( + "{:24} {:>10} -> {:>10} {:>10} {:>7}% (error%)".format( + hdr, file1, file2, "diff", "diff" + ) + ) # Print entries while d1 and d2: @@ -176,32 +195,47 @@ def compute_diff(file1, file2, diff_score): # Found entries with matching names entry1 = d1.pop(0) entry2 = d2.pop(0) - name = entry1[0].rsplit('/')[-1] + name = entry1[0].rsplit("/")[-1] av1, sd1 = entry1[1 + 2 * diff_score], entry1[2 + 2 * diff_score] av2, sd2 = entry2[1 + 2 * diff_score], entry2[2 + 2 * diff_score] - sd1 *= av1 / 100 # convert from percent sd to absolute sd - sd2 *= av2 / 100 # convert from percent sd to absolute sd + sd1 *= av1 / 100 # convert from percent sd to absolute sd + sd2 *= av2 / 100 # convert from percent sd to absolute sd av_diff = av2 - av1 sd_diff = (sd1 ** 2 + sd2 ** 2) ** 0.5 percent = 100 * av_diff / av1 percent_sd = 100 * sd_diff / av1 - print('{:24} {:10.2f} -> {:10.2f} : {:+10.2f} = {:+7.3f}% (+/-{:.2f}%)'.format(name, av1, av2, av_diff, percent, percent_sd)) + print( + "{:24} {:10.2f} -> {:10.2f} : {:+10.2f} = {:+7.3f}% (+/-{:.2f}%)".format( + name, av1, av2, av_diff, percent, percent_sd + ) + ) elif d1[0][0] < d2[0][0]: d1.pop(0) else: d2.pop(0) + def main(): - cmd_parser = argparse.ArgumentParser(description='Run benchmarks for MicroPython') - cmd_parser.add_argument('-t', '--diff-time', action='store_true', help='diff time outputs from a previous run') - cmd_parser.add_argument('-s', '--diff-score', action='store_true', help='diff score outputs from a previous run') - cmd_parser.add_argument('-p', '--pyboard', action='store_true', help='run tests via pyboard.py') - cmd_parser.add_argument('-d', '--device', default='/dev/ttyACM0', help='the device for pyboard.py') - cmd_parser.add_argument('-a', '--average', default='8', help='averaging number') - cmd_parser.add_argument('--emit', default='bytecode', help='MicroPython emitter to use (bytecode or native)') - cmd_parser.add_argument('N', nargs=1, help='N parameter (approximate target CPU frequency)') - cmd_parser.add_argument('M', nargs=1, help='M parameter (approximate target heap in kbytes)') - cmd_parser.add_argument('files', nargs='*', help='input test files') + cmd_parser = argparse.ArgumentParser(description="Run benchmarks for MicroPython") + cmd_parser.add_argument( + "-t", "--diff-time", action="store_true", help="diff time outputs from a previous run" + ) + cmd_parser.add_argument( + "-s", "--diff-score", action="store_true", help="diff score outputs from a previous run" + ) + cmd_parser.add_argument( + "-p", "--pyboard", action="store_true", help="run tests via pyboard.py" + ) + cmd_parser.add_argument( + "-d", "--device", default="/dev/ttyACM0", help="the device for pyboard.py" + ) + cmd_parser.add_argument("-a", "--average", default="8", help="averaging number") + cmd_parser.add_argument( + "--emit", default="bytecode", help="MicroPython emitter to use (bytecode or native)" + ) + cmd_parser.add_argument("N", nargs=1, help="N parameter (approximate target CPU frequency)") + cmd_parser.add_argument("M", nargs=1, help="M parameter (approximate target heap in kbytes)") + cmd_parser.add_argument("files", nargs="*", help="input test files") args = cmd_parser.parse_args() if args.diff_time or args.diff_score: @@ -219,21 +253,22 @@ def main(): target = pyboard.Pyboard(args.device) target.enter_raw_repl() else: - target = [MICROPYTHON, '-X', 'emit=' + args.emit] + target = [MICROPYTHON, "-X", "emit=" + args.emit] if len(args.files) == 0: - tests_skip = ('benchrun.py',) + tests_skip = ("benchrun.py",) if M <= 25: # These scripts are too big to be compiled by the target - tests_skip += ('bm_chaos.py', 'bm_hexiom.py', 'misc_raytrace.py') + tests_skip += ("bm_chaos.py", "bm_hexiom.py", "misc_raytrace.py") tests = sorted( - BENCH_SCRIPT_DIR + test_file for test_file in os.listdir(BENCH_SCRIPT_DIR) - if test_file.endswith('.py') and test_file not in tests_skip + BENCH_SCRIPT_DIR + test_file + for test_file in os.listdir(BENCH_SCRIPT_DIR) + if test_file.endswith(".py") and test_file not in tests_skip ) else: tests = sorted(args.files) - print('N={} M={} n_average={}'.format(N, M, n_average)) + print("N={} M={} n_average={}".format(N, M, n_average)) run_benchmarks(target, N, M, n_average, tests) @@ -241,5 +276,6 @@ def main(): target.exit_raw_repl() target.close() + if __name__ == "__main__": main() diff --git a/tests/run-tests-exp.py b/tests/run-tests-exp.py index 3af8feae7c..34c6f650f8 100644 --- a/tests/run-tests-exp.py +++ b/tests/run-tests-exp.py @@ -9,12 +9,9 @@ import sys import uos as os -tests = [ - "basics", "micropython", "float", "import", "io", - " misc", "unicode", "extmod", "unix" -] +tests = ["basics", "micropython", "float", "import", "io", " misc", "unicode", "extmod", "unix"] -if sys.platform == 'win32': +if sys.platform == "win32": MICROPYTHON = "micropython.exe" else: MICROPYTHON = "micropython" @@ -26,13 +23,14 @@ def should_skip(test): if test.startswith("viper"): return True + test_count = 0 passed_count = 0 skip_count = 0 for suite in tests: - #print("Running in: %s" % suite) - if sys.platform == 'win32': + # print("Running in: %s" % suite) + if sys.platform == "win32": # dir /b prints only contained filenames, one on a line # http://www.microsoft.com/resources/documentation/windows/xp/all/proddocs/en-us/dir.mspx r = os.system("dir /b %s/*.py >tests.lst" % suite) @@ -44,7 +42,7 @@ for suite in tests: testcases = f.readlines() testcases = [l[:-1] for l in testcases] assert testcases, "No tests found in dir '%s', which is implausible" % suite - #print(testcases) + # print(testcases) for t in testcases: if t == "native_check.py": continue @@ -65,7 +63,7 @@ for suite in tests: pass if exp is not None: - #print("run " + qtest) + # print("run " + qtest) r = os.system(MICROPYTHON + " %s >.tst.out" % qtest) if r == 0: f = open(".tst.out") diff --git a/tests/stress/dict_copy.py b/tests/stress/dict_copy.py index 36db9bb7e8..73d3a5b51d 100644 --- a/tests/stress/dict_copy.py +++ b/tests/stress/dict_copy.py @@ -1,6 +1,6 @@ # copying a large dictionary -a = {i:2*i for i in range(1000)} +a = {i: 2 * i for i in range(1000)} b = a.copy() for i in range(1000): print(i, b[i]) diff --git a/tests/stress/gc_trace.py b/tests/stress/gc_trace.py index 72dc7b6276..f952ad36a6 100644 --- a/tests/stress/gc_trace.py +++ b/tests/stress/gc_trace.py @@ -12,6 +12,8 @@ gc.collect() print(lst) # test a deep object -lst = [[[[[(i, j, k, l)] for i in range(3)] for j in range(3)] for k in range(3)] for l in range(3)] +lst = [ + [[[[(i, j, k, l)] for i in range(3)] for j in range(3)] for k in range(3)] for l in range(3) +] gc.collect() print(lst) diff --git a/tests/stress/qstr_limit.py b/tests/stress/qstr_limit.py index 889ab7e51c..d8ce0cf7cd 100644 --- a/tests/stress/qstr_limit.py +++ b/tests/stress/qstr_limit.py @@ -1,28 +1,32 @@ # Test interning qstrs that go over the limit of the maximum qstr length # (which is 255 bytes for the default configuration) -def make_id(n, base='a'): - return ''.join(chr(ord(base) + i % 26) for i in range(n)) + +def make_id(n, base="a"): + return "".join(chr(ord(base) + i % 26) for i in range(n)) + # identifiers in parser for l in range(254, 259): g = {} var = make_id(l) try: - exec(var + '=1', g) + exec(var + "=1", g) except RuntimeError: - print('RuntimeError', l) + print("RuntimeError", l) continue print(var in g) # calling a function with kwarg def f(**k): print(k) + + for l in range(254, 259): try: - exec('f({}=1)'.format(make_id(l))) + exec("f({}=1)".format(make_id(l))) except RuntimeError: - print('RuntimeError', l) + print("RuntimeError", l) # type construction for l in range(254, 259): @@ -30,38 +34,40 @@ for l in range(254, 259): try: print(type(id, (), {}).__name__) except RuntimeError: - print('RuntimeError', l) + print("RuntimeError", l) # hasattr, setattr, getattr class A: pass + + for l in range(254, 259): id = make_id(l) a = A() try: setattr(a, id, 123) except RuntimeError: - print('RuntimeError', l) + print("RuntimeError", l) try: print(hasattr(a, id), getattr(a, id)) except RuntimeError: - print('RuntimeError', l) + print("RuntimeError", l) # format with keys for l in range(254, 259): id = make_id(l) try: - print(('{' + id + '}').format(**{id: l})) + print(("{" + id + "}").format(**{id: l})) except RuntimeError: - print('RuntimeError', l) + print("RuntimeError", l) # modulo format with keys for l in range(254, 259): id = make_id(l) try: - print(('%(' + id + ')d') % {id: l}) + print(("%(" + id + ")d") % {id: l}) except RuntimeError: - print('RuntimeError', l) + print("RuntimeError", l) # import module # (different OS's have different results so only run those that are consistent) @@ -69,15 +75,15 @@ for l in (100, 101, 256, 257, 258): try: __import__(make_id(l)) except ImportError: - print('ok', l) + print("ok", l) except RuntimeError: - print('RuntimeError', l) + print("RuntimeError", l) # import package for l in (100, 101, 102, 128, 129): try: - exec('import ' + make_id(l) + '.' + make_id(l, 'A')) + exec("import " + make_id(l) + "." + make_id(l, "A")) except ImportError: - print('ok', l) + print("ok", l) except RuntimeError: - print('RuntimeError', l) + print("RuntimeError", l) diff --git a/tests/stress/recursion.py b/tests/stress/recursion.py index 227f48396a..c2d831bb82 100644 --- a/tests/stress/recursion.py +++ b/tests/stress/recursion.py @@ -1,6 +1,7 @@ def foo(): foo() + try: foo() except RuntimeError: diff --git a/tests/stress/recursive_gen.py b/tests/stress/recursive_gen.py index 0e0d3914ee..8c21397658 100644 --- a/tests/stress/recursive_gen.py +++ b/tests/stress/recursive_gen.py @@ -3,16 +3,20 @@ # simple "yield from" recursion def gen(): yield from gen() + + try: list(gen()) except RuntimeError: - print('RuntimeError') + print("RuntimeError") # recursion via an iterator over a generator def gen2(): for x in gen2(): yield x + + try: next(gen2()) except RuntimeError: - print('RuntimeError') + print("RuntimeError") diff --git a/tests/thread/mutate_bytearray.py b/tests/thread/mutate_bytearray.py index f3276f1b2d..67c01d91cf 100644 --- a/tests/thread/mutate_bytearray.py +++ b/tests/thread/mutate_bytearray.py @@ -23,10 +23,11 @@ def th(n, lo, hi): global n_finished n_finished += 1 + lock = _thread.allocate_lock() n_thread = 4 n_finished = 0 -n_repeat = 4 # use 40 for more stressful test (uses more heap) +n_repeat = 4 # use 40 for more stressful test (uses more heap) # spawn threads for i in range(n_thread): @@ -42,4 +43,3 @@ count = [0 for _ in range(256)] for b in ba: count[b] += 1 print(count) - diff --git a/tests/thread/mutate_dict.py b/tests/thread/mutate_dict.py index c57d332d51..89c93f4eee 100644 --- a/tests/thread/mutate_dict.py +++ b/tests/thread/mutate_dict.py @@ -5,7 +5,7 @@ import _thread # the shared dict -di = {'a':'A', 'b':'B', 'c':'C', 'd':'D'} +di = {"a": "A", "b": "B", "c": "C", "d": "D"} # main thread function def th(n, lo, hi): @@ -26,6 +26,7 @@ def th(n, lo, hi): global n_finished n_finished += 1 + lock = _thread.allocate_lock() n_thread = 4 n_finished = 0 diff --git a/tests/thread/mutate_instance.py b/tests/thread/mutate_instance.py index a1ae428b54..939a0b8acd 100644 --- a/tests/thread/mutate_instance.py +++ b/tests/thread/mutate_instance.py @@ -7,25 +7,28 @@ import _thread # the shared user class and instance class User: def __init__(self): - self.a = 'A' - self.b = 'B' - self.c = 'C' + self.a = "A" + self.b = "B" + self.c = "C" + + user = User() # main thread function def th(n, lo, hi): for repeat in range(n): for i in range(lo, hi): - setattr(user, 'attr_%u' % i, repeat + i) - assert getattr(user, 'attr_%u' % i) == repeat + i + setattr(user, "attr_%u" % i, repeat + i) + assert getattr(user, "attr_%u" % i) == repeat + i with lock: global n_finished n_finished += 1 + lock = _thread.allocate_lock() n_repeat = 30 -n_range = 50 # 300 for stressful test (uses more heap) +n_range = 50 # 300 for stressful test (uses more heap) n_thread = 4 n_finished = 0 @@ -40,4 +43,4 @@ while n_finished < n_thread: # check user instance has correct contents print(user.a, user.b, user.c) for i in range(n_thread * n_range): - assert getattr(user, 'attr_%u' % i) == n_repeat - 1 + i + assert getattr(user, "attr_%u" % i) == n_repeat - 1 + i diff --git a/tests/thread/mutate_list.py b/tests/thread/mutate_list.py index 764a9bd99e..c1849e6729 100644 --- a/tests/thread/mutate_list.py +++ b/tests/thread/mutate_list.py @@ -27,6 +27,7 @@ def th(n, lo, hi): global n_finished n_finished += 1 + lock = _thread.allocate_lock() n_thread = 4 n_finished = 0 diff --git a/tests/thread/mutate_set.py b/tests/thread/mutate_set.py index 5492d86313..924124611b 100644 --- a/tests/thread/mutate_set.py +++ b/tests/thread/mutate_set.py @@ -21,6 +21,7 @@ def th(n, lo, hi): global n_finished n_finished += 1 + lock = _thread.allocate_lock() n_thread = 4 n_finished = 0 diff --git a/tests/thread/stress_aes.py b/tests/thread/stress_aes.py index df75e616c6..f73da557cb 100644 --- a/tests/thread/stress_aes.py +++ b/tests/thread/stress_aes.py @@ -17,6 +17,7 @@ # discrete arithmetic routines, mostly from a precomputed table # non-linear, invertible, substitution box +# fmt: off aes_s_box_table = bytes(( 0x63,0x7c,0x77,0x7b,0xf2,0x6b,0x6f,0xc5,0x30,0x01,0x67,0x2b,0xfe,0xd7,0xab,0x76, 0xca,0x82,0xc9,0x7d,0xfa,0x59,0x47,0xf0,0xad,0xd4,0xa2,0xaf,0x9c,0xa4,0x72,0xc0, @@ -35,31 +36,36 @@ aes_s_box_table = bytes(( 0xe1,0xf8,0x98,0x11,0x69,0xd9,0x8e,0x94,0x9b,0x1e,0x87,0xe9,0xce,0x55,0x28,0xdf, 0x8c,0xa1,0x89,0x0d,0xbf,0xe6,0x42,0x68,0x41,0x99,0x2d,0x0f,0xb0,0x54,0xbb,0x16, )) +# fmt: on # multiplication of polynomials modulo x^8 + x^4 + x^3 + x + 1 = 0x11b def aes_gf8_mul_2(x): if x & 0x80: - return (x << 1) ^ 0x11b + return (x << 1) ^ 0x11B else: return x << 1 + def aes_gf8_mul_3(x): return x ^ aes_gf8_mul_2(x) + # non-linear, invertible, substitution box def aes_s_box(a): - return aes_s_box_table[a & 0xff] + return aes_s_box_table[a & 0xFF] + # return 0x02^(a-1) in GF(2^8) def aes_r_con(a): ans = 1 while a > 1: - ans <<= 1; + ans <<= 1 if ans & 0x100: - ans ^= 0x11b + ans ^= 0x11B a -= 1 return ans + ################################################################## # basic AES algorithm; see FIPS-197 # @@ -79,6 +85,7 @@ def aes_add_round_key(state, w): for i in range(16): state[i] ^= w[i] + # combined sub_bytes, shift_rows, mix_columns, add_round_key # all inputs must be size 16 def aes_sb_sr_mc_ark(state, w, w_idx, temp): @@ -88,7 +95,7 @@ def aes_sb_sr_mc_ark(state, w, w_idx, temp): x1 = aes_s_box_table[state[1 + ((i + 1) & 3) * 4]] x2 = aes_s_box_table[state[2 + ((i + 2) & 3) * 4]] x3 = aes_s_box_table[state[3 + ((i + 3) & 3) * 4]] - temp[temp_idx] = aes_gf8_mul_2(x0) ^ aes_gf8_mul_3(x1) ^ x2 ^ x3 ^ w[w_idx] + temp[temp_idx] = aes_gf8_mul_2(x0) ^ aes_gf8_mul_3(x1) ^ x2 ^ x3 ^ w[w_idx] temp[temp_idx + 1] = x0 ^ aes_gf8_mul_2(x1) ^ aes_gf8_mul_3(x2) ^ x3 ^ w[w_idx + 1] temp[temp_idx + 2] = x0 ^ x1 ^ aes_gf8_mul_2(x2) ^ aes_gf8_mul_3(x3) ^ w[w_idx + 2] temp[temp_idx + 3] = aes_gf8_mul_3(x0) ^ x1 ^ x2 ^ aes_gf8_mul_2(x3) ^ w[w_idx + 3] @@ -97,6 +104,7 @@ def aes_sb_sr_mc_ark(state, w, w_idx, temp): for i in range(16): state[i] = temp[i] + # combined sub_bytes, shift_rows, add_round_key # all inputs must be size 16 def aes_sb_sr_ark(state, w, w_idx, temp): @@ -106,7 +114,7 @@ def aes_sb_sr_ark(state, w, w_idx, temp): x1 = aes_s_box_table[state[1 + ((i + 1) & 3) * 4]] x2 = aes_s_box_table[state[2 + ((i + 2) & 3) * 4]] x3 = aes_s_box_table[state[3 + ((i + 3) & 3) * 4]] - temp[temp_idx] = x0 ^ w[w_idx] + temp[temp_idx] = x0 ^ w[w_idx] temp[temp_idx + 1] = x1 ^ w[w_idx + 1] temp[temp_idx + 2] = x2 ^ w[w_idx + 2] temp[temp_idx + 3] = x3 ^ w[w_idx + 3] @@ -115,6 +123,7 @@ def aes_sb_sr_ark(state, w, w_idx, temp): for i in range(16): state[i] = temp[i] + # take state as input and change it to the next state in the sequence # state and temp have size 16, w has size 16 * (Nr + 1), Nr >= 1 def aes_state(state, w, temp, nr): @@ -125,6 +134,7 @@ def aes_state(state, w, temp, nr): w_idx += 16 aes_sb_sr_ark(state, w, w_idx, temp) + # expand 'key' to 'w' for use with aes_state # key has size 4 * Nk, w has size 16 * (Nr + 1), temp has size 16 def aes_key_expansion(key, w, temp, nk, nr): @@ -148,9 +158,11 @@ def aes_key_expansion(key, w, temp, nk, nr): for j in range(4): w[w_idx + j] = w[w_idx + j - 4 * nk] ^ t[t_idx + j] + ################################################################## # simple use of AES algorithm, using output feedback (OFB) mode + class AES: def __init__(self, keysize): if keysize == 128: @@ -176,7 +188,7 @@ class AES: def set_iv(self, iv): for i in range(16): self.state[i] = iv[i] - self.state_pos = 16; + self.state_pos = 16 def get_some_state(self, n_needed): if self.state_pos >= 16: @@ -198,6 +210,7 @@ class AES: idx += ln self.state_pos += n + ################################################################## # test code @@ -207,6 +220,7 @@ except ImportError: import time import _thread + class LockedCounter: def __init__(self): self.lock = _thread.allocate_lock() @@ -217,8 +231,10 @@ class LockedCounter: self.value += val self.lock.release() + count = LockedCounter() + def thread_entry(): global count @@ -247,7 +263,8 @@ def thread_entry(): count.add(1) -if __name__ == '__main__': + +if __name__ == "__main__": n_thread = 20 for i in range(n_thread): _thread.start_new_thread(thread_entry, ()) diff --git a/tests/thread/stress_create.py b/tests/thread/stress_create.py index 2399746cca..eda768fa7b 100644 --- a/tests/thread/stress_create.py +++ b/tests/thread/stress_create.py @@ -6,9 +6,11 @@ except ImportError: import time import _thread + def thread_entry(n): pass + thread_num = 0 while thread_num < 500: try: @@ -19,4 +21,4 @@ while thread_num < 500: # wait for the last threads to terminate time.sleep(1) -print('done') +print("done") diff --git a/tests/thread/stress_heap.py b/tests/thread/stress_heap.py index 5482a9ac6f..2ad91ae147 100644 --- a/tests/thread/stress_heap.py +++ b/tests/thread/stress_heap.py @@ -9,9 +9,11 @@ except ImportError: import time import _thread + def last(l): return l[-1] + def thread_entry(n): # allocate a bytearray and fill it data = bytearray(i for i in range(256)) @@ -33,6 +35,7 @@ def thread_entry(n): global n_finished n_finished += 1 + lock = _thread.allocate_lock() n_thread = 10 n_finished = 0 diff --git a/tests/thread/stress_recurse.py b/tests/thread/stress_recurse.py index 68367c4dd7..73b3a40f33 100644 --- a/tests/thread/stress_recurse.py +++ b/tests/thread/stress_recurse.py @@ -4,17 +4,20 @@ import _thread + def foo(): foo() + def thread_entry(): try: foo() except RuntimeError: - print('RuntimeError') + print("RuntimeError") global finished finished = True + finished = False _thread.start_new_thread(thread_entry, ()) @@ -22,4 +25,4 @@ _thread.start_new_thread(thread_entry, ()) # busy wait for thread to finish while not finished: pass -print('done') +print("done") diff --git a/tests/thread/thread_exc1.py b/tests/thread/thread_exc1.py index 10fb94b4fb..16483d7778 100644 --- a/tests/thread/thread_exc1.py +++ b/tests/thread/thread_exc1.py @@ -4,9 +4,11 @@ import _thread + def foo(): raise ValueError + def thread_entry(): try: foo() @@ -16,6 +18,7 @@ def thread_entry(): global n_finished n_finished += 1 + lock = _thread.allocate_lock() n_thread = 4 n_finished = 0 @@ -27,4 +30,4 @@ for i in range(n_thread): # busy wait for threads to finish while n_finished < n_thread: pass -print('done') +print("done") diff --git a/tests/thread/thread_exc2.py b/tests/thread/thread_exc2.py index 35cb324412..2863e1dec1 100644 --- a/tests/thread/thread_exc2.py +++ b/tests/thread/thread_exc2.py @@ -2,9 +2,11 @@ import utime import _thread + def thread_entry(): raise ValueError + _thread.start_new_thread(thread_entry, ()) utime.sleep(1) -print('done') +print("done") diff --git a/tests/thread/thread_exc2.py.exp b/tests/thread/thread_exc2.py.exp index cc7a20aa26..469516dacc 100644 --- a/tests/thread/thread_exc2.py.exp +++ b/tests/thread/thread_exc2.py.exp @@ -1,5 +1,5 @@ Unhandled exception in thread started by Traceback (most recent call last): - File \.\+, line 6, in thread_entry + File \.\+, line 7, in thread_entry ValueError: done diff --git a/tests/thread/thread_exit1.py b/tests/thread/thread_exit1.py index 88cdd165c7..c4a93c45a3 100644 --- a/tests/thread/thread_exit1.py +++ b/tests/thread/thread_exit1.py @@ -8,12 +8,14 @@ except ImportError: import time import _thread + def thread_entry(): _thread.exit() + _thread.start_new_thread(thread_entry, ()) _thread.start_new_thread(thread_entry, ()) # wait for threads to finish time.sleep(1) -print('done') +print("done") diff --git a/tests/thread/thread_exit2.py b/tests/thread/thread_exit2.py index 368a11bba4..0cd80e6909 100644 --- a/tests/thread/thread_exit2.py +++ b/tests/thread/thread_exit2.py @@ -8,12 +8,14 @@ except ImportError: import time import _thread + def thread_entry(): raise SystemExit + _thread.start_new_thread(thread_entry, ()) _thread.start_new_thread(thread_entry, ()) # wait for threads to finish time.sleep(1) -print('done') +print("done") diff --git a/tests/thread/thread_gc1.py b/tests/thread/thread_gc1.py index 8dcbf7e07a..dd1e64d894 100644 --- a/tests/thread/thread_gc1.py +++ b/tests/thread/thread_gc1.py @@ -5,6 +5,7 @@ import gc import _thread + def thread_entry(n): # allocate a bytearray and fill it data = bytearray(i for i in range(256)) @@ -21,6 +22,7 @@ def thread_entry(n): global n_finished n_finished += 1 + lock = _thread.allocate_lock() n_thread = 4 n_finished = 0 diff --git a/tests/thread/thread_ident1.py b/tests/thread/thread_ident1.py index 217fce73b1..390193accc 100644 --- a/tests/thread/thread_ident1.py +++ b/tests/thread/thread_ident1.py @@ -4,18 +4,20 @@ import _thread + def thread_entry(): tid = _thread.get_ident() - print('thread', type(tid) == int, tid != 0, tid != tid_main) + print("thread", type(tid) == int, tid != 0, tid != tid_main) global finished finished = True + tid_main = _thread.get_ident() -print('main', type(tid_main) == int, tid_main != 0) +print("main", type(tid_main) == int, tid_main != 0) finished = False _thread.start_new_thread(thread_entry, ()) while not finished: pass -print('done') +print("done") diff --git a/tests/thread/thread_lock1.py b/tests/thread/thread_lock1.py index ba5c7dff06..342c554f4a 100644 --- a/tests/thread/thread_lock1.py +++ b/tests/thread/thread_lock1.py @@ -36,11 +36,11 @@ try: print(lock.locked()) raise KeyError except KeyError: - print('KeyError') + print("KeyError") print(lock.locked()) # test that we can't release an unlocked lock try: lock.release() except RuntimeError: - print('RuntimeError') + print("RuntimeError") diff --git a/tests/thread/thread_lock2.py b/tests/thread/thread_lock2.py index 405f10b0b6..b842f69c93 100644 --- a/tests/thread/thread_lock2.py +++ b/tests/thread/thread_lock2.py @@ -10,15 +10,17 @@ import _thread lock = _thread.allocate_lock() + def thread_entry(): lock.acquire() - print('have it') + print("have it") lock.release() + # spawn the threads for i in range(4): _thread.start_new_thread(thread_entry, ()) # wait for threads to finish time.sleep(1) -print('done') +print("done") diff --git a/tests/thread/thread_lock3.py b/tests/thread/thread_lock3.py index 607898dad8..a927dc6829 100644 --- a/tests/thread/thread_lock3.py +++ b/tests/thread/thread_lock3.py @@ -8,16 +8,18 @@ lock = _thread.allocate_lock() n_thread = 10 n_finished = 0 + def thread_entry(idx): global n_finished while True: with lock: if n_finished == idx: break - print('my turn:', idx) + print("my turn:", idx) with lock: n_finished += 1 + # spawn threads for i in range(n_thread): _thread.start_new_thread(thread_entry, (i,)) diff --git a/tests/thread/thread_lock4.py b/tests/thread/thread_lock4.py index 2f9d42d6b5..bbf9043996 100644 --- a/tests/thread/thread_lock4.py +++ b/tests/thread/thread_lock4.py @@ -8,12 +8,14 @@ except ImportError: import time import _thread + def fac(n): x = 1 for i in range(1, n + 1): x *= i return x + def thread_entry(): while True: with jobs_lock: @@ -25,6 +27,7 @@ def thread_entry(): with output_lock: output.append((arg, ans)) + # create a list of jobs jobs = [(fac, i) for i in range(20, 80)] jobs_lock = _thread.allocate_lock() diff --git a/tests/thread/thread_qstr1.py b/tests/thread/thread_qstr1.py index f4136d9646..40ee2910cb 100644 --- a/tests/thread/thread_qstr1.py +++ b/tests/thread/thread_qstr1.py @@ -13,6 +13,7 @@ def check(s, val): assert type(s) == str assert int(s) == val + # main thread function def th(base, n): for i in range(n): @@ -23,10 +24,11 @@ def th(base, n): global n_finished n_finished += 1 + lock = _thread.allocate_lock() n_thread = 4 n_finished = 0 -n_qstr_per_thread = 100 # make 1000 for a more stressful test (uses more heap) +n_qstr_per_thread = 100 # make 1000 for a more stressful test (uses more heap) # spawn threads for i in range(n_thread): @@ -36,4 +38,4 @@ for i in range(n_thread): while n_finished < n_thread: time.sleep(1) -print('pass') +print("pass") diff --git a/tests/thread/thread_shared1.py b/tests/thread/thread_shared1.py index 13c6651cc4..582b01fc34 100644 --- a/tests/thread/thread_shared1.py +++ b/tests/thread/thread_shared1.py @@ -4,9 +4,11 @@ import _thread + def foo(i): pass + def thread_entry(n, tup): for i in tup: foo(i) @@ -14,6 +16,7 @@ def thread_entry(n, tup): global n_finished n_finished += 1 + lock = _thread.allocate_lock() n_thread = 2 n_finished = 0 diff --git a/tests/thread/thread_shared2.py b/tests/thread/thread_shared2.py index e4bfe78022..a1223c2b94 100644 --- a/tests/thread/thread_shared2.py +++ b/tests/thread/thread_shared2.py @@ -5,9 +5,11 @@ import _thread + def foo(lst, i): lst[i] += 1 + def thread_entry(n, lst, idx): for i in range(n): foo(lst, idx) @@ -15,6 +17,7 @@ def thread_entry(n, lst, idx): global n_finished n_finished += 1 + lock = _thread.allocate_lock() n_thread = 2 n_finished = 0 diff --git a/tests/thread/thread_sleep1.py b/tests/thread/thread_sleep1.py index 032ec17543..18fa4e05a1 100644 --- a/tests/thread/thread_sleep1.py +++ b/tests/thread/thread_sleep1.py @@ -4,9 +4,11 @@ try: import utime + sleep_ms = utime.sleep_ms except ImportError: import time + sleep_ms = lambda t: time.sleep(t / 1000) import _thread @@ -15,6 +17,7 @@ lock = _thread.allocate_lock() n_thread = 4 n_finished = 0 + def thread_entry(t): global n_finished sleep_ms(t) @@ -22,10 +25,11 @@ def thread_entry(t): with lock: n_finished += 1 + for i in range(n_thread): _thread.start_new_thread(thread_entry, (10 * i,)) # wait for threads to finish while n_finished < n_thread: sleep_ms(100) -print('done', n_thread) +print("done", n_thread) diff --git a/tests/thread/thread_stacksize1.py b/tests/thread/thread_stacksize1.py index 62b6e5e40d..39fe235b22 100644 --- a/tests/thread/thread_stacksize1.py +++ b/tests/thread/thread_stacksize1.py @@ -6,20 +6,23 @@ import sys import _thread # different implementations have different minimum sizes -if sys.implementation.name == 'micropython': +if sys.implementation.name == "micropython": sz = 2 * 1024 else: sz = 32 * 1024 + def foo(): pass + def thread_entry(): foo() with lock: global n_finished n_finished += 1 + # reset stack size to default _thread.stack_size() @@ -44,4 +47,4 @@ _thread.stack_size() # busy wait for threads to finish while n_finished < n_thread: pass -print('done') +print("done") diff --git a/tests/thread/thread_start1.py b/tests/thread/thread_start1.py index d23a74aa21..f0e696840e 100644 --- a/tests/thread/thread_start1.py +++ b/tests/thread/thread_start1.py @@ -8,16 +8,19 @@ except ImportError: import time import _thread + def foo(): pass + def thread_entry(n): for i in range(n): foo() + _thread.start_new_thread(thread_entry, (10,)) _thread.start_new_thread(thread_entry, (20,)) # wait for threads to finish time.sleep(1) -print('done') +print("done") diff --git a/tests/thread/thread_start2.py b/tests/thread/thread_start2.py index d0913e37cd..d68ea94329 100644 --- a/tests/thread/thread_start2.py +++ b/tests/thread/thread_start2.py @@ -8,11 +8,13 @@ except ImportError: import time import _thread + def thread_entry(a0, a1, a2, a3): - print('thread', a0, a1, a2, a3) + print("thread", a0, a1, a2, a3) + # spawn thread using kw args -_thread.start_new_thread(thread_entry, (10, 20), {'a2': 0, 'a3': 1}) +_thread.start_new_thread(thread_entry, (10, 20), {"a2": 0, "a3": 1}) # wait for thread to finish time.sleep(1) @@ -21,6 +23,6 @@ time.sleep(1) try: _thread.start_new_thread(thread_entry, (), ()) except TypeError: - print('TypeError') + print("TypeError") -print('done') +print("done") diff --git a/tests/unicode/file2.py b/tests/unicode/file2.py index 8c45f91faf..1a5b933c89 100644 --- a/tests/unicode/file2.py +++ b/tests/unicode/file2.py @@ -1,11 +1,12 @@ # test reading a given number of characters + def do(mode): - if mode == 'rb': + if mode == "rb": enc = None else: - enc = 'utf-8' - f = open('unicode/data/utf-8_2.txt', mode=mode, encoding=enc) + enc = "utf-8" + f = open("unicode/data/utf-8_2.txt", mode=mode, encoding=enc) print(f.read(1)) print(f.read(1)) print(f.read(2)) @@ -15,12 +16,13 @@ def do(mode): f.readline() # check 3-byte utf-8 char - print(f.read(1 if mode == 'rt' else 3)) + print(f.read(1 if mode == "rt" else 3)) # check 4-byte utf-8 char - print(f.read(1 if mode == 'rt' else 4)) + print(f.read(1 if mode == "rt" else 4)) f.close() -do('rb') -do('rt') + +do("rb") +do("rt") diff --git a/tests/unicode/unicode.py b/tests/unicode/unicode.py index b3d4b09eeb..072e049fde 100644 --- a/tests/unicode/unicode.py +++ b/tests/unicode/unicode.py @@ -1,17 +1,17 @@ # Test a UTF-8 encoded literal s = "asdf©qwer" for i in range(len(s)): - print("s[%d]: %s %X"%(i, s[i], ord(s[i]))) + print("s[%d]: %s %X" % (i, s[i], ord(s[i]))) # Test all three forms of Unicode escape, and # all blocks of UTF-8 byte patterns s = "a\xA9\xFF\u0123\u0800\uFFEE\U0001F44C" for i in range(-len(s), len(s)): - print("s[%d]: %s %X"%(i, s[i], ord(s[i]))) - print("s[:%d]: %d chars, '%s'"%(i, len(s[:i]), s[:i])) + print("s[%d]: %s %X" % (i, s[i], ord(s[i]))) + print("s[:%d]: %d chars, '%s'" % (i, len(s[:i]), s[:i])) for j in range(i, len(s)): - print("s[%d:%d]: %d chars, '%s'"%(i, j, len(s[i:j]), s[i:j])) - print("s[%d:]: %d chars, '%s'"%(i, len(s[i:]), s[i:])) + print("s[%d:%d]: %d chars, '%s'" % (i, j, len(s[i:j]), s[i:j])) + print("s[%d:]: %d chars, '%s'" % (i, len(s[i:]), s[i:])) # Test UTF-8 encode and decode enc = s.encode() @@ -19,35 +19,35 @@ print(enc, enc.decode() == s) # printing of unicode chars using repr # NOTE: for some characters (eg \u10ff) we differ to CPython -print(repr('a\uffff')) -print(repr('a\U0001ffff')) +print(repr("a\uffff")) +print(repr("a\U0001ffff")) # test invalid escape code try: eval('"\\U00110000"') except SyntaxError: - print('SyntaxError') + print("SyntaxError") # test unicode string given to int try: - int('\u0200') + int("\u0200") except ValueError: - print('ValueError') + print("ValueError") # test invalid UTF-8 string try: - str(b'ab\xa1', 'utf8') + str(b"ab\xa1", "utf8") except UnicodeError: - print('UnicodeError') + print("UnicodeError") try: - str(b'ab\xf8', 'utf8') + str(b"ab\xf8", "utf8") except UnicodeError: - print('UnicodeError') + print("UnicodeError") try: - str(bytearray(b'ab\xc0a'), 'utf8') + str(bytearray(b"ab\xc0a"), "utf8") except UnicodeError: - print('UnicodeError') + print("UnicodeError") try: - str(b'\xf0\xe0\xed\xe8', 'utf8') + str(b"\xf0\xe0\xed\xe8", "utf8") except UnicodeError: - print('UnicodeError') + print("UnicodeError") diff --git a/tests/unicode/unicode_id.py b/tests/unicode/unicode_id.py index 10f540c503..3a58e3f72b 100644 --- a/tests/unicode/unicode_id.py +++ b/tests/unicode/unicode_id.py @@ -14,14 +14,19 @@ print(α, αβγ, bβ, βb) def α(β, γ): δ = β + γ print(β, γ, δ) + + α(1, 2) # class, method identifiers class φ: def __init__(self): pass + def δ(self, ϵ): print(ϵ) + + zζzζz = φ() if hasattr(zζzζz, "δ"): zζzζz.δ(ϵ=123) diff --git a/tests/unicode/unicode_ord.py b/tests/unicode/unicode_ord.py index 47cfa1c2d7..73577050bf 100644 --- a/tests/unicode/unicode_ord.py +++ b/tests/unicode/unicode_ord.py @@ -1,3 +1,3 @@ # test builtin ord with unicode characters -print(ord('α')) +print(ord("α")) diff --git a/tests/unicode/unicode_str_format.py b/tests/unicode/unicode_str_format.py index bf8505a31a..1a60e7be4a 100644 --- a/tests/unicode/unicode_str_format.py +++ b/tests/unicode/unicode_str_format.py @@ -1,4 +1,4 @@ # test handling of unicode chars in format strings -print('α'.format()) -print('{α}'.format(α=1)) +print("α".format()) +print("{α}".format(α=1)) diff --git a/tests/unicode/unicode_str_modulo.py b/tests/unicode/unicode_str_modulo.py index e9b152473c..42211d0b05 100644 --- a/tests/unicode/unicode_str_modulo.py +++ b/tests/unicode/unicode_str_modulo.py @@ -1,3 +1,3 @@ # test handling of unicode chars in string % formatting -print('α' % ()) +print("α" % ()) diff --git a/tests/unicode/unicode_subscr.py b/tests/unicode/unicode_subscr.py index a2f434de58..5028910077 100644 --- a/tests/unicode/unicode_subscr.py +++ b/tests/unicode/unicode_subscr.py @@ -1,4 +1,4 @@ -a = '¢пр' +a = "¢пр" print(a[0], a[0:1]) print(a[1], a[1:2]) diff --git a/tests/unix/extra_coverage.py b/tests/unix/extra_coverage.py index 09bb48f0f1..36105f6bad 100644 --- a/tests/unix/extra_coverage.py +++ b/tests/unix/extra_coverage.py @@ -13,33 +13,33 @@ data = extra_coverage() print(data[0], data[1]) print(hash(data[0])) print(hash(data[1])) -print(hash(bytes(data[0], 'utf8'))) -print(hash(str(data[1], 'utf8'))) +print(hash(bytes(data[0], "utf8"))) +print(hash(str(data[1], "utf8"))) # test streams -stream = data[2] # has set_error and set_buf. Write always returns error -stream.set_error(uerrno.EAGAIN) # non-blocking error -print(stream.read()) # read all encounters non-blocking error -print(stream.read(1)) # read 1 byte encounters non-blocking error -print(stream.readline()) # readline encounters non-blocking error -print(stream.readinto(bytearray(10))) # readinto encounters non-blocking error -print(stream.write(b'1')) # write encounters non-blocking error -print(stream.write1(b'1')) # write1 encounters non-blocking error -stream.set_buf(b'123') -print(stream.read(4)) # read encounters non-blocking error after successful reads -stream.set_buf(b'123') -print(stream.read1(4)) # read1 encounters non-blocking error after successful reads -stream.set_buf(b'123') -print(stream.readline(4)) # readline encounters non-blocking error after successful reads +stream = data[2] # has set_error and set_buf. Write always returns error +stream.set_error(uerrno.EAGAIN) # non-blocking error +print(stream.read()) # read all encounters non-blocking error +print(stream.read(1)) # read 1 byte encounters non-blocking error +print(stream.readline()) # readline encounters non-blocking error +print(stream.readinto(bytearray(10))) # readinto encounters non-blocking error +print(stream.write(b"1")) # write encounters non-blocking error +print(stream.write1(b"1")) # write1 encounters non-blocking error +stream.set_buf(b"123") +print(stream.read(4)) # read encounters non-blocking error after successful reads +stream.set_buf(b"123") +print(stream.read1(4)) # read1 encounters non-blocking error after successful reads +stream.set_buf(b"123") +print(stream.readline(4)) # readline encounters non-blocking error after successful reads try: - print(stream.ioctl(0, 0)) # ioctl encounters non-blocking error; raises OSError + print(stream.ioctl(0, 0)) # ioctl encounters non-blocking error; raises OSError except OSError: - print('OSError') + print("OSError") stream.set_error(0) -print(stream.ioctl(0, bytearray(10))) # successful ioctl call +print(stream.ioctl(0, bytearray(10))) # successful ioctl call -stream2 = data[3] # is textio -print(stream2.read(1)) # read 1 byte encounters non-blocking error with textio stream +stream2 = data[3] # is textio +print(stream2.read(1)) # read 1 byte encounters non-blocking error with textio stream # test BufferedWriter with stream errors stream.set_error(uerrno.EAGAIN) @@ -48,33 +48,41 @@ print(buf.write(bytearray(16))) # test basic import of frozen scripts import frzstr1 + print(frzstr1.__file__) import frzmpy1 + print(frzmpy1.__file__) # test import of frozen packages with __init__.py import frzstr_pkg1 + print(frzstr_pkg1.__file__, frzstr_pkg1.x) import frzmpy_pkg1 + print(frzmpy_pkg1.__file__, frzmpy_pkg1.x) # test import of frozen packages without __init__.py from frzstr_pkg2.mod import Foo + print(Foo.x) from frzmpy_pkg2.mod import Foo + print(Foo.x) # test raising exception in frozen script try: import frzmpy2 except ZeroDivisionError: - print('ZeroDivisionError') + print("ZeroDivisionError") # test loading a resource from a frozen string import uio -buf = uio.resource_stream('frzstr_pkg2', 'mod.py') + +buf = uio.resource_stream("frzstr_pkg2", "mod.py") print(buf.read(21)) # test for MP_QSTR_NULL regression from frzqstr import returns_NULL + print(returns_NULL()) diff --git a/tests/unix/ffi_callback.py b/tests/unix/ffi_callback.py index 23b058bcec..21bfccf251 100644 --- a/tests/unix/ffi_callback.py +++ b/tests/unix/ffi_callback.py @@ -15,16 +15,19 @@ def ffi_open(names): err = e raise err -libc = ffi_open(('libc.so', 'libc.so.0', 'libc.so.6', 'libc.dylib')) + +libc = ffi_open(("libc.so", "libc.so.0", "libc.so.6", "libc.dylib")) qsort = libc.func("v", "qsort", "piip") + def cmp(pa, pb): a = ffi.as_bytearray(pa, 1) b = ffi.as_bytearray(pb, 1) - #print("cmp:", a, b) + # print("cmp:", a, b) return a[0] - b[0] + cmp_c = ffi.callback("i", cmp, "pp") s = bytearray(b"foobar") diff --git a/tests/unix/ffi_float.py b/tests/unix/ffi_float.py index 317436855b..d039398965 100644 --- a/tests/unix/ffi_float.py +++ b/tests/unix/ffi_float.py @@ -16,7 +16,8 @@ def ffi_open(names): err = e raise err -libc = ffi_open(('libc.so', 'libc.so.0', 'libc.so.6', 'libc.dylib')) + +libc = ffi_open(("libc.so", "libc.so.0", "libc.so.6", "libc.dylib")) try: strtof = libc.func("f", "strtof", "sp") @@ -26,14 +27,14 @@ except OSError: print("SKIP") raise SystemExit -print('%.6f' % strtof('1.23', None)) +print("%.6f" % strtof("1.23", None)) strtod = libc.func("d", "strtod", "sp") -print('%.6f' % strtod('1.23', None)) +print("%.6f" % strtod("1.23", None)) # test passing double and float args -libm = ffi_open(('libm.so', 'libm.so.6', 'libc.so.0', 'libc.so.6', 'libc.dylib')) -tgamma = libm.func('d', 'tgamma', 'd') +libm = ffi_open(("libm.so", "libm.so.6", "libc.so.0", "libc.so.6", "libc.dylib")) +tgamma = libm.func("d", "tgamma", "d") for fun in (tgamma,): for val in (0.5, 1, 1.0, 1.5, 4, 4.0): - print('%.6f' % fun(val)) + print("%.6f" % fun(val)) diff --git a/tests/unix/ffi_float2.py b/tests/unix/ffi_float2.py index 721eb4d192..bbed696662 100644 --- a/tests/unix/ffi_float2.py +++ b/tests/unix/ffi_float2.py @@ -16,16 +16,17 @@ def ffi_open(names): err = e raise err -libm = ffi_open(('libm.so', 'libm.so.6', 'libc.so.0', 'libc.so.6', 'libc.dylib')) + +libm = ffi_open(("libm.so", "libm.so.6", "libc.so.0", "libc.so.6", "libc.dylib")) # Some libc's implement tgammaf as header macro with tgamma(), so don't assume # it'll be in library. try: - tgammaf = libm.func('f', 'tgammaf', 'f') + tgammaf = libm.func("f", "tgammaf", "f") except OSError: print("SKIP") raise SystemExit for fun in (tgammaf,): for val in (0.5, 1, 1.0, 1.5, 4, 4.0): - print('%.6f' % fun(val)) + print("%.6f" % fun(val)) diff --git a/tests/unix/time.py b/tests/unix/time.py index 35eddbe095..55a4b18aae 100644 --- a/tests/unix/time.py +++ b/tests/unix/time.py @@ -7,12 +7,14 @@ DAYS_PER_MONTH = [0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31] tzseconds = -time.mktime((1970, 1, 1, 14, 0, 0, 0, 0, 0)) + def is_leap(year): return (year % 4) == 0 + def test(): seconds = 0 - wday = 3 # Jan 1, 1970 was a Thursday + wday = 3 # Jan 1, 1970 was a Thursday for year in range(1970, 2038): print("Testing %d" % year) yday = 1 @@ -24,21 +26,34 @@ def test(): for day in range(1, DAYS_PER_MONTH[month] + 1): secs = time.mktime((year, month, day, 14, 0, 0, 0, 0, 0)) + tzseconds if secs != seconds: - print("mktime failed for %d-%02d-%02d got %d expected %d" % (year, month, day, secs, seconds)) + print( + "mktime failed for %d-%02d-%02d got %d expected %d" + % (year, month, day, secs, seconds) + ) return tuple = time.localtime(seconds) secs = time.mktime(tuple) if secs != seconds: - print("localtime failed for %d-%02d-%02d got %d expected %d" % (year, month, day, secs, seconds)) + print( + "localtime failed for %d-%02d-%02d got %d expected %d" + % (year, month, day, secs, seconds) + ) return seconds += 86400 if yday != tuple[7]: - print("locatime for %d-%02d-%02d got yday %d, expecting %d" % (year, month, day, tuple[7], yday)) + print( + "locatime for %d-%02d-%02d got yday %d, expecting %d" + % (year, month, day, tuple[7], yday) + ) return if wday != tuple[6]: - print("locatime for %d-%02d-%02d got wday %d, expecting %d" % (year, month, day, tuple[6], wday)) + print( + "locatime for %d-%02d-%02d got wday %d, expecting %d" + % (year, month, day, tuple[6], wday) + ) return yday += 1 wday = (wday + 1) % 7 + test() diff --git a/tests/wipy/adc.py b/tests/wipy/adc.py index 6fd4373dbd..73264113f3 100644 --- a/tests/wipy/adc.py +++ b/tests/wipy/adc.py @@ -1,19 +1,19 @@ -''' +""" ADC test for the CC3200 based boards. -''' +""" from machine import ADC import os mch = os.uname().machine -if 'LaunchPad' in mch: - adc_pin = 'GP5' +if "LaunchPad" in mch: + adc_pin = "GP5" adc_channel = 3 -elif 'WiPy' in mch: - adc_pin = 'GP3' +elif "WiPy" in mch: + adc_pin = "GP3" adc_channel = 1 else: - raise Exception('Board not supported!') + raise Exception("Board not supported!") adc = ADC(0) print(adc) @@ -49,7 +49,7 @@ print(apin) print(apin() > 3000) # check for memory leaks... -for i in range (0, 1000): +for i in range(0, 1000): adc = ADC() apin = adc.channel(adc_channel) @@ -57,56 +57,56 @@ for i in range (0, 1000): try: adc = ADC(bits=17) except: - print('Exception') + print("Exception") try: adc = ADC(id=1) except: - print('Exception') + print("Exception") try: adc = ADC(0, 16) except: - print('Exception') + print("Exception") adc = ADC() try: apin = adc.channel(4) except: - print('Exception') + print("Exception") try: apin = adc.channel(-1) except: - print('Exception') + print("Exception") try: - apin = adc.channel(0, pin='GP3') + apin = adc.channel(0, pin="GP3") except: - print('Exception') + print("Exception") apin = adc.channel(1) apin.deinit() try: apin() except: - print('Exception') + print("Exception") try: apin.value() except: - print('Exception') + print("Exception") adc.deinit() try: apin.value() except: - print('Exception') + print("Exception") try: apin = adc.channel(1) except: - print('Exception') + print("Exception") # re-init must work adc.init() diff --git a/tests/wipy/i2c.py b/tests/wipy/i2c.py index 6931554191..c7d32f6639 100644 --- a/tests/wipy/i2c.py +++ b/tests/wipy/i2c.py @@ -1,19 +1,19 @@ -''' +""" I2C test for the CC3200 based boards. A MPU-9150 sensor must be connected to the I2C bus. -''' +""" from machine import I2C import os import time mch = os.uname().machine -if 'LaunchPad' in mch: - i2c_pins = ('GP11', 'GP10') -elif 'WiPy' in mch: - i2c_pins = ('GP15', 'GP10') +if "LaunchPad" in mch: + i2c_pins = ("GP11", "GP10") +elif "WiPy" in mch: + i2c_pins = ("GP15", "GP10") else: - raise Exception('Board not supported!') + raise Exception("Board not supported!") i2c = I2C(0, I2C.MASTER, baudrate=400000) # try initing without the peripheral id @@ -41,26 +41,26 @@ reg[0] |= 0x80 print(1 == i2c.writeto_mem(addr, 107, reg)) time.sleep_ms(100) # wait for the sensor to reset... -print(1 == i2c.readfrom_mem_into(addr, 107, reg)) # read the power management register 1 +print(1 == i2c.readfrom_mem_into(addr, 107, reg)) # read the power management register 1 print(0x40 == reg[0]) # now just read one byte -data = i2c.readfrom_mem(addr, 117, 1) # read the "who am I?" register +data = i2c.readfrom_mem(addr, 117, 1) # read the "who am I?" register print(0x68 == data[0]) print(len(data) == 1) -print(1 == i2c.readfrom_mem_into(addr, 117, reg)) # read the "who am I?" register again +print(1 == i2c.readfrom_mem_into(addr, 117, reg)) # read the "who am I?" register again print(0x68 == reg[0]) # now try reading two bytes -data = i2c.readfrom_mem(addr, 116, 2) # read the "who am I?" register +data = i2c.readfrom_mem(addr, 116, 2) # read the "who am I?" register print(0x68 == data[1]) -print(data == b'\x00\x68') +print(data == b"\x00\x68") print(len(data) == 2) -print(2 == i2c.readfrom_mem_into(addr, 116, reg2)) # read the "who am I?" register again +print(2 == i2c.readfrom_mem_into(addr, 116, reg2)) # read the "who am I?" register again print(0x68 == reg2[1]) -print(reg2 == b'\x00\x68') +print(reg2 == b"\x00\x68") -print(1 == i2c.readfrom_mem_into(addr, 107, reg)) # read the power management register 1 +print(1 == i2c.readfrom_mem_into(addr, 107, reg)) # read the power management register 1 print(0x40 == reg[0]) # clear the sleep bit reg[0] = 0 @@ -100,13 +100,13 @@ print(1 == i2c.writeto_mem(addr, 107, reg)) time.sleep_ms(100) # wait for the sensor to reset... # try some raw read and writes -reg[0] = 117 # register address -print(1 == i2c.writeto(addr, reg, stop=False)) # just write the register address +reg[0] = 117 # register address +print(1 == i2c.writeto(addr, reg, stop=False)) # just write the register address # now read print(1 == i2c.readfrom_into(addr, reg)) print(reg[0] == 0x68) -reg[0] = 117 # register address -print(1 == i2c.writeto(addr, reg, stop=False)) # just write the register address +reg[0] = 117 # register address +print(1 == i2c.writeto(addr, reg, stop=False)) # just write the register address # now read print(0x68 == i2c.readfrom(addr, 1)[0]) @@ -114,14 +114,14 @@ i2c.readfrom_mem_into(addr, 107, reg2) print(0x40 == reg2[0]) print(0x00 == reg2[1]) -reg2[0] = 107 # register address +reg2[0] = 107 # register address reg2[1] = 0 -print(2 == i2c.writeto(addr, reg2, stop=True)) # write the register address and the data -i2c.readfrom_mem_into(addr, 107, reg) # check it back +print(2 == i2c.writeto(addr, reg2, stop=True)) # write the register address and the data +i2c.readfrom_mem_into(addr, 107, reg) # check it back print(reg[0] == 0) # check for memory leaks... -for i in range (0, 1000): +for i in range(0, 1000): i2c = I2C(0, I2C.MASTER, baudrate=100000) # test deinit @@ -173,4 +173,3 @@ except Exception: # reinitialization must work i2c.init(baudrate=400000) print(i2c) - diff --git a/tests/wipy/modwipy.py b/tests/wipy/modwipy.py index 7571af0753..59df3ae90a 100644 --- a/tests/wipy/modwipy.py +++ b/tests/wipy/modwipy.py @@ -1,13 +1,13 @@ -''' +""" wipy module test for the CC3200 based boards -''' +""" import os import wipy mch = os.uname().machine -if not 'LaunchPad' in mch and not'WiPy' in mch: - raise Exception('Board not supported!') +if not "LaunchPad" in mch and not "WiPy" in mch: + raise Exception("Board not supported!") print(wipy.heartbeat() == True) wipy.heartbeat(False) @@ -18,4 +18,4 @@ print(wipy.heartbeat() == True) try: wipy.heartbeat(True, 1) except: - print('Exception') + print("Exception") diff --git a/tests/wipy/os.py b/tests/wipy/os.py index 0596a16b52..1f4debcade 100644 --- a/tests/wipy/os.py +++ b/tests/wipy/os.py @@ -1,164 +1,164 @@ -''' +""" os module test for the CC3200 based boards -''' +""" from machine import SD import os mch = os.uname().machine -if 'LaunchPad' in mch: - sd_pins = ('GP16', 'GP17', 'GP15') -elif 'WiPy' in mch: - sd_pins = ('GP10', 'GP11', 'GP15') +if "LaunchPad" in mch: + sd_pins = ("GP16", "GP17", "GP15") +elif "WiPy" in mch: + sd_pins = ("GP10", "GP11", "GP15") else: - raise Exception('Board not supported!') + raise Exception("Board not supported!") sd = SD(pins=sd_pins) -os.mount(sd, '/sd') -os.mkfs('/sd') -os.chdir('/flash') +os.mount(sd, "/sd") +os.mkfs("/sd") +os.chdir("/flash") print(os.listdir()) -os.chdir('/sd') +os.chdir("/sd") print(os.listdir()) # create a test directory in flash -os.mkdir('/flash/test') -os.chdir('/flash/test') +os.mkdir("/flash/test") +os.chdir("/flash/test") print(os.getcwd()) -os.chdir('..') +os.chdir("..") print(os.getcwd()) -os.chdir('test') +os.chdir("test") print(os.getcwd()) # create a new file -f = open('test.txt', 'w') +f = open("test.txt", "w") test_bytes = os.urandom(1024) n_w = f.write(test_bytes) print(n_w == len(test_bytes)) f.close() -f = open('test.txt', 'r') -r = bytes(f.read(), 'ascii') +f = open("test.txt", "r") +r = bytes(f.read(), "ascii") # check that we can write and read it correctly print(r == test_bytes) f.close() -os.rename('test.txt', 'newtest.txt') +os.rename("test.txt", "newtest.txt") print(os.listdir()) -os.rename('/flash/test', '/flash/newtest') -print(os.listdir('/flash')) -os.remove('newtest.txt') -os.chdir('..') -os.rmdir('newtest') +os.rename("/flash/test", "/flash/newtest") +print(os.listdir("/flash")) +os.remove("newtest.txt") +os.chdir("..") +os.rmdir("newtest") # create a test directory in the sd card -os.mkdir('/sd/test') -os.chdir('/sd/test') +os.mkdir("/sd/test") +os.chdir("/sd/test") print(os.getcwd()) -os.chdir('..') +os.chdir("..") print(os.getcwd()) -os.chdir('test') +os.chdir("test") print(os.getcwd()) # create a new file -f = open('test.txt', 'w') +f = open("test.txt", "w") test_bytes = os.urandom(1024) n_w = f.write(test_bytes) print(n_w == len(test_bytes)) f.close() -f = open('test.txt', 'r') -r = bytes(f.read(), 'ascii') +f = open("test.txt", "r") +r = bytes(f.read(), "ascii") # check that we can write and read it correctly print(r == test_bytes) f.close() -print('CC3200' in os.uname().machine) -print('WiPy' == os.uname().sysname) +print("CC3200" in os.uname().machine) +print("WiPy" == os.uname().sysname) os.sync() -os.stat('/flash') -os.stat('/flash/sys') -os.stat('/flash/boot.py') -os.stat('/sd') -os.stat('/') -os.chdir('/sd/test') -os.remove('test.txt') -os.chdir('/sd') -os.rmdir('test') -os.listdir('/sd') -print(os.listdir('/')) -os.unmount('/sd') -print(os.listdir('/')) +os.stat("/flash") +os.stat("/flash/sys") +os.stat("/flash/boot.py") +os.stat("/sd") +os.stat("/") +os.chdir("/sd/test") +os.remove("test.txt") +os.chdir("/sd") +os.rmdir("test") +os.listdir("/sd") +print(os.listdir("/")) +os.unmount("/sd") +print(os.listdir("/")) os.mkfs(sd) -os.mount(sd, '/sd') -print(os.listdir('/')) -os.chdir('/flash') +os.mount(sd, "/sd") +print(os.listdir("/")) +os.chdir("/flash") # next ones must raise sd.deinit() try: - os.listdir('/sd') + os.listdir("/sd") except: - print('Exception') + print("Exception") -#re-initialization must work +# re-initialization must work sd.init() -print(os.listdir('/sd')) +print(os.listdir("/sd")) try: - os.mount(sd, '/sd') + os.mount(sd, "/sd") except: - print('Exception') + print("Exception") try: - os.mount(sd, '/sd2') + os.mount(sd, "/sd2") except: - print('Exception') + print("Exception") -os.unmount('/sd') +os.unmount("/sd") try: - os.listdir('/sd') + os.listdir("/sd") except: - print('Exception') + print("Exception") try: - os.unmount('/flash') + os.unmount("/flash") except: - print('Exception') + print("Exception") try: - os.unmount('/something') + os.unmount("/something") except: - print('Exception') + print("Exception") try: - os.unmount('something') + os.unmount("something") except: - print('Exception') + print("Exception") try: - os.mkfs('flash') # incorrect path format + os.mkfs("flash") # incorrect path format except: - print('Exception') + print("Exception") try: - os.remove('/flash/nofile.txt') + os.remove("/flash/nofile.txt") except: - print('Exception') + print("Exception") try: - os.rename('/flash/nofile.txt', '/flash/nofile2.txt') + os.rename("/flash/nofile.txt", "/flash/nofile2.txt") except: - print('Exception') + print("Exception") try: - os.chdir('/flash/nodir') + os.chdir("/flash/nodir") except: - print('Exception') + print("Exception") try: - os.listdir('/flash/nodir') + os.listdir("/flash/nodir") except: - print('Exception') + print("Exception") -os.mount(sd, '/sd') -print(os.listdir('/')) -os.unmount('/sd') +os.mount(sd, "/sd") +print(os.listdir("/")) +os.unmount("/sd") diff --git a/tests/wipy/pin.py b/tests/wipy/pin.py index 22c7c6176c..9ffd152e93 100644 --- a/tests/wipy/pin.py +++ b/tests/wipy/pin.py @@ -7,27 +7,61 @@ from machine import Pin import os mch = os.uname().machine -if 'LaunchPad' in mch: - pin_map = ['GP24', 'GP12', 'GP14', 'GP15', 'GP16', 'GP17', 'GP28', 'GP8', 'GP6', 'GP30', 'GP31', 'GP3', 'GP0', 'GP4', 'GP5'] +if "LaunchPad" in mch: + pin_map = [ + "GP24", + "GP12", + "GP14", + "GP15", + "GP16", + "GP17", + "GP28", + "GP8", + "GP6", + "GP30", + "GP31", + "GP3", + "GP0", + "GP4", + "GP5", + ] max_af_idx = 15 -elif 'WiPy' in mch: - pin_map = ['GP23', 'GP24', 'GP12', 'GP13', 'GP14', 'GP9', 'GP17', 'GP28', 'GP22', 'GP8', 'GP30', 'GP31', 'GP0', 'GP4', 'GP5'] +elif "WiPy" in mch: + pin_map = [ + "GP23", + "GP24", + "GP12", + "GP13", + "GP14", + "GP9", + "GP17", + "GP28", + "GP22", + "GP8", + "GP30", + "GP31", + "GP0", + "GP4", + "GP5", + ] max_af_idx = 15 else: - raise Exception('Board not supported!') + raise Exception("Board not supported!") # test initial value -p = Pin('GP12', Pin.IN) -Pin('GP17', Pin.OUT, value=1) +p = Pin("GP12", Pin.IN) +Pin("GP17", Pin.OUT, value=1) print(p() == 1) -Pin('GP17', Pin.OUT, value=0) +Pin("GP17", Pin.OUT, value=0) print(p() == 0) + def test_noinit(): for p in pin_map: pin = Pin(p) pin.value() + def test_pin_read(pull): # enable the pull resistor on all pins, then read the value for p in pin_map: @@ -35,6 +69,7 @@ def test_pin_read(pull): for p in pin_map: print(pin()) + def test_pin_af(): for p in pin_map: for af in Pin(p).alt_list(): @@ -42,6 +77,7 @@ def test_pin_af(): Pin(p, mode=Pin.ALT, alt=af[1]) Pin(p, mode=Pin.ALT_OPEN_DRAIN, alt=af[1]) + # test un-initialized pins test_noinit() # test with pull-up and pull-down @@ -65,7 +101,7 @@ pin = Pin(pin_map[0], mode=Pin.OUT, drive=pin.LOW_POWER) pin = Pin(pin_map[0], Pin.OUT, Pin.PULL_DOWN) pin = Pin(pin_map[0], Pin.ALT, Pin.PULL_UP) pin = Pin(pin_map[0], Pin.ALT_OPEN_DRAIN, Pin.PULL_UP) -test_pin_af() # try the entire af range on all pins +test_pin_af() # try the entire af range on all pins # test pin init and printing pin = Pin(pin_map[0]) @@ -81,9 +117,9 @@ print(pin) # test value in OUT mode pin = Pin(pin_map[0], mode=Pin.OUT) pin.value(0) -pin.toggle() # test toggle +pin.toggle() # test toggle print(pin()) -pin.toggle() # test toggle again +pin.toggle() # test toggle again print(pin()) # test different value settings pin(1) @@ -116,67 +152,66 @@ print(pin.id() == pin_map[0]) # all the next ones MUST raise try: - pin = Pin(pin_map[0], mode=Pin.OUT, pull=Pin.PULL_UP, drive=pin.IN) # incorrect drive value + pin = Pin(pin_map[0], mode=Pin.OUT, pull=Pin.PULL_UP, drive=pin.IN) # incorrect drive value except Exception: - print('Exception') + print("Exception") try: - pin = Pin(pin_map[0], mode=Pin.LOW_POWER, pull=Pin.PULL_UP) # incorrect mode value + pin = Pin(pin_map[0], mode=Pin.LOW_POWER, pull=Pin.PULL_UP) # incorrect mode value except Exception: - print('Exception') + print("Exception") try: - pin = Pin(pin_map[0], mode=Pin.IN, pull=Pin.HIGH_POWER) # incorrect pull value + pin = Pin(pin_map[0], mode=Pin.IN, pull=Pin.HIGH_POWER) # incorrect pull value except Exception: - print('Exception') + print("Exception") try: - pin = Pin('A0', Pin.OUT, Pin.PULL_DOWN) # incorrect pin id + pin = Pin("A0", Pin.OUT, Pin.PULL_DOWN) # incorrect pin id except Exception: - print('Exception') + print("Exception") try: - pin = Pin(pin_map[0], Pin.IN, Pin.PULL_UP, alt=0) # af specified in GPIO mode + pin = Pin(pin_map[0], Pin.IN, Pin.PULL_UP, alt=0) # af specified in GPIO mode except Exception: - print('Exception') + print("Exception") try: - pin = Pin(pin_map[0], Pin.OUT, Pin.PULL_UP, alt=7) # af specified in GPIO mode + pin = Pin(pin_map[0], Pin.OUT, Pin.PULL_UP, alt=7) # af specified in GPIO mode except Exception: - print('Exception') + print("Exception") try: - pin = Pin(pin_map[0], Pin.ALT, Pin.PULL_UP, alt=0) # incorrect af + pin = Pin(pin_map[0], Pin.ALT, Pin.PULL_UP, alt=0) # incorrect af except Exception: - print('Exception') + print("Exception") try: - pin = Pin(pin_map[0], Pin.ALT_OPEN_DRAIN, Pin.PULL_UP, alt=-1) # incorrect af + pin = Pin(pin_map[0], Pin.ALT_OPEN_DRAIN, Pin.PULL_UP, alt=-1) # incorrect af except Exception: - print('Exception') + print("Exception") try: - pin = Pin(pin_map[0], Pin.ALT_OPEN_DRAIN, Pin.PULL_UP, alt=16) # incorrect af + pin = Pin(pin_map[0], Pin.ALT_OPEN_DRAIN, Pin.PULL_UP, alt=16) # incorrect af except Exception: - print('Exception') + print("Exception") try: - pin.mode(Pin.PULL_UP) # incorrect pin mode + pin.mode(Pin.PULL_UP) # incorrect pin mode except Exception: - print('Exception') + print("Exception") try: - pin.pull(Pin.OUT) # incorrect pull + pin.pull(Pin.OUT) # incorrect pull except Exception: - print('Exception') + print("Exception") try: - pin.drive(Pin.IN) # incorrect drive strength + pin.drive(Pin.IN) # incorrect drive strength except Exception: - print('Exception') + print("Exception") try: - pin.id('ABC') # id cannot be set + pin.id("ABC") # id cannot be set except Exception: - print('Exception') - + print("Exception") diff --git a/tests/wipy/pin_irq.py b/tests/wipy/pin_irq.py index 875f1f9397..be5e1f426c 100644 --- a/tests/wipy/pin_irq.py +++ b/tests/wipy/pin_irq.py @@ -1,6 +1,6 @@ -''' +""" Pin IRQ test for the CC3200 based boards. -''' +""" from machine import Pin import machine @@ -8,17 +8,18 @@ import os import time mch = os.uname().machine -if 'LaunchPad' in mch: - pins = ['GP16', 'GP13'] -elif 'WiPy' in mch: - pins = ['GP16', 'GP13'] +if "LaunchPad" in mch: + pins = ["GP16", "GP13"] +elif "WiPy" in mch: + pins = ["GP16", "GP13"] else: - raise Exception('Board not supported!') + raise Exception("Board not supported!") pin0 = Pin(pins[0], mode=Pin.OUT, value=1) pin1 = Pin(pins[1], mode=Pin.IN, pull=Pin.PULL_UP) -def pin_handler (pin_o): + +def pin_handler(pin_o): global pin_irq_count_trigger global pin_irq_count_total global _trigger @@ -26,11 +27,12 @@ def pin_handler (pin_o): pin_irq_count_trigger += 1 pin_irq_count_total += 1 + pin_irq_count_trigger = 0 pin_irq_count_total = 0 _trigger = Pin.IRQ_FALLING pin1_irq = pin1.irq(trigger=_trigger, handler=pin_handler) -for i in range (0, 10): +for i in range(0, 10): pin0.toggle() time.sleep_ms(5) print(pin_irq_count_trigger == 5) @@ -40,7 +42,7 @@ pin_irq_count_trigger = 0 pin_irq_count_total = 0 _trigger = Pin.IRQ_RISING pin1_irq = pin1.irq(trigger=_trigger, handler=pin_handler) -for i in range (0, 200): +for i in range(0, 200): pin0.toggle() time.sleep_ms(5) print(pin_irq_count_trigger == 100) @@ -69,7 +71,7 @@ print(pin_irq_count_total == 2) pin1_irq.disable() pin_irq_count_trigger = 0 pin_irq_count_total = 0 -for i in range (0, 10): +for i in range(0, 10): pin0.toggle() time.sleep_ms(5) print(pin_irq_count_trigger == 0) @@ -81,7 +83,7 @@ t0 = time.ticks_ms() pin1_irq.init(trigger=Pin.IRQ_LOW_LEVEL, wake=machine.SLEEP) machine.sleep() print(time.ticks_ms() - t0 < 10) -print('Awake') +print("Awake") # test waking up from suspended mode on high level pin0(1) @@ -89,7 +91,7 @@ t0 = time.ticks_ms() pin1_irq.init(trigger=Pin.IRQ_HIGH_LEVEL, wake=machine.SLEEP) machine.sleep() print(time.ticks_ms() - t0 < 10) -print('Awake') +print("Awake") # check for memory leaks for i in range(0, 1000): @@ -100,17 +102,19 @@ for i in range(0, 1000): try: pin1_irq.init(trigger=123456, handler=pin_handler) except: - print('Exception') + print("Exception") try: pin1_irq.init(trigger=Pin.IRQ_LOW_LEVEL, wake=1789456) except: - print('Exception') + print("Exception") try: - pin0_irq = pin0.irq(trigger=Pin.IRQ_RISING, wake=machine.SLEEP) # GP16 can't wake up from DEEPSLEEP + pin0_irq = pin0.irq( + trigger=Pin.IRQ_RISING, wake=machine.SLEEP + ) # GP16 can't wake up from DEEPSLEEP except: - print('Exception') + print("Exception") pin0_irq.disable() pin1_irq.disable() diff --git a/tests/wipy/reset/reset.py b/tests/wipy/reset/reset.py index 35a970c673..8d314f3b49 100644 --- a/tests/wipy/reset/reset.py +++ b/tests/wipy/reset/reset.py @@ -1,16 +1,16 @@ -''' +""" Reset script for the cc3200 boards This is needed to force the board to reboot with the default WLAN AP settings -''' +""" from machine import WDT import time import os mch = os.uname().machine -if not 'LaunchPad' in mch and not 'WiPy' in mch: - raise Exception('Board not supported!') +if not "LaunchPad" in mch and not "WiPy" in mch: + raise Exception("Board not supported!") wdt = WDT(timeout=1000) print(wdt) diff --git a/tests/wipy/rtc.py b/tests/wipy/rtc.py index 2737ebe73a..c62e400fe3 100644 --- a/tests/wipy/rtc.py +++ b/tests/wipy/rtc.py @@ -1,14 +1,14 @@ -''' +""" RTC test for the CC3200 based boards. -''' +""" from machine import RTC import os import time mch = os.uname().machine -if not 'LaunchPad' in mch and not 'WiPy' in mch: - raise Exception('Board not supported!') +if not "LaunchPad" in mch and not "WiPy" in mch: + raise Exception("Board not supported!") rtc = RTC() print(rtc) @@ -41,10 +41,12 @@ print(rtc.now()[4]) rtc.init((2015, 9, 19)) print(rtc.now()[3]) + def set_and_print(datetime): rtc.init(datetime) print(rtc.now()[:6]) + # make sure that setting works correctly set_and_print((2000, 1, 1, 0, 0, 0, 0, None)) set_and_print((2000, 1, 31, 0, 0, 0, 0, None)) @@ -66,7 +68,7 @@ rtc.alarm(0, 5000) rtc.alarm(time=2000) time.sleep_ms(1000) left = rtc.alarm_left() -print(abs(left-1000) <= 10) +print(abs(left - 1000) <= 10) time.sleep_ms(1000) print(rtc.alarm_left() == 0) time.sleep_ms(100) @@ -75,13 +77,13 @@ print(rtc.alarm_left(0) == 0) rtc.alarm(time=1000, repeat=True) time.sleep_ms(1500) left = rtc.alarm_left() -print(abs(left-500) <= 15) +print(abs(left - 500) <= 15) rtc.init((2015, 8, 29, 9, 0, 0, 0, None)) rtc.alarm(time=(2015, 8, 29, 9, 0, 45)) time.sleep_ms(1000) left = rtc.alarm_left() -print(abs(left-44000) <= 90) +print(abs(left - 44000) <= 90) rtc.alarm_cancel() rtc.deinit() @@ -89,29 +91,29 @@ rtc.deinit() try: rtc.alarm(5000) except: - print('Exception') + print("Exception") try: rtc.alarm_left(1) except: - print('Exception') + print("Exception") try: rtc.alarm_cancel(1) except: - print('Exception') + print("Exception") try: rtc.alarm(5000) except: - print('Exception') + print("Exception") try: rtc = RTC(200000000) except: - print('Exception') + print("Exception") try: rtc = RTC((2015, 8, 29, 9, 0, 0, 0, None)) except: - print('Exception') + print("Exception") diff --git a/tests/wipy/sd.py b/tests/wipy/sd.py index 92746e01ed..381d46f30a 100644 --- a/tests/wipy/sd.py +++ b/tests/wipy/sd.py @@ -1,17 +1,17 @@ -''' +""" SD card test for the CC3200 based boards. -''' +""" from machine import SD import os mch = os.uname().machine -if 'LaunchPad' in mch: - sd_pins = ('GP16', 'GP17', 'GP15') -elif 'WiPy' in mch: - sd_pins = ('GP10', 'GP11', 'GP15') +if "LaunchPad" in mch: + sd_pins = ("GP16", "GP17", "GP15") +elif "WiPy" in mch: + sd_pins = ("GP10", "GP11", "GP15") else: - raise Exception('Board not supported!') + raise Exception("Board not supported!") sd = SD(pins=sd_pins) print(sd) @@ -35,12 +35,11 @@ except Exception: print("Exception") try: - sd = SD(pins=('GP10', 'GP11', 'GP8')) + sd = SD(pins=("GP10", "GP11", "GP8")) except Exception: print("Exception") try: - sd = SD(pins=('GP10', 'GP11')) + sd = SD(pins=("GP10", "GP11")) except Exception: print("Exception") - diff --git a/tests/wipy/skipped/rtc_irq.py b/tests/wipy/skipped/rtc_irq.py index ec3baa5524..99712f8d18 100644 --- a/tests/wipy/skipped/rtc_irq.py +++ b/tests/wipy/skipped/rtc_irq.py @@ -1,6 +1,6 @@ -''' +""" RTC IRQ test for the CC3200 based boards. -''' +""" from machine import RTC import machine @@ -8,21 +8,25 @@ import os import time mch = os.uname().machine -if not 'LaunchPad' in mch and not 'WiPy' in mch: - raise Exception('Board not supported!') +if not "LaunchPad" in mch and not "WiPy" in mch: + raise Exception("Board not supported!") + def rtc_ticks_ms(rtc): timedate = rtc.now() return (timedate[5] * 1000) + (timedate[6] // 1000) + rtc_irq_count = 0 -def alarm_handler (rtc_o): + +def alarm_handler(rtc_o): global rtc_irq global rtc_irq_count if rtc_irq.flags() & RTC.ALARM0: rtc_irq_count += 1 + rtc = RTC() rtc.alarm(time=500, repeat=True) rtc_irq = rtc.irq(trigger=RTC.ALARM0, handler=alarm_handler) @@ -81,9 +85,9 @@ while rtc_irq_count < 3: try: rtc_irq = rtc.irq(trigger=10, handler=alarm_handler) except: - print('Exception') + print("Exception") try: rtc_irq = rtc.irq(trigger=RTC.ALARM0, wake=1789456) except: - print('Exception') + print("Exception") diff --git a/tests/wipy/spi.py b/tests/wipy/spi.py index 6bd7aabce1..a3509d8542 100644 --- a/tests/wipy/spi.py +++ b/tests/wipy/spi.py @@ -1,17 +1,17 @@ -''' +""" SPI test for the CC3200 based boards. -''' +""" from machine import SPI import os mch = os.uname().machine -if 'LaunchPad' in mch: - spi_pins = ('GP14', 'GP16', 'GP30') -elif 'WiPy' in mch: - spi_pins = ('GP14', 'GP16', 'GP30') +if "LaunchPad" in mch: + spi_pins = ("GP14", "GP16", "GP30") +elif "WiPy" in mch: + spi_pins = ("GP14", "GP16", "GP30") else: - raise Exception('Board not supported!') + raise Exception("Board not supported!") spi = SPI(0, SPI.MASTER, baudrate=2000000, polarity=0, phase=0, firstbit=SPI.MSB, pins=spi_pins) print(spi) @@ -27,15 +27,15 @@ spi = SPI(0, SPI.MASTER, baudrate=10000000, polarity=1, phase=1) print(spi) spi.init(baudrate=20000000, polarity=0, phase=0) print(spi) -spi=SPI() +spi = SPI() print(spi) SPI(mode=SPI.MASTER) SPI(mode=SPI.MASTER, pins=spi_pins) -SPI(id=0, mode=SPI.MASTER, polarity=0, phase=0, pins=('GP14', 'GP16', 'GP15')) -SPI(0, SPI.MASTER, polarity=0, phase=0, pins=('GP31', 'GP16', 'GP15')) +SPI(id=0, mode=SPI.MASTER, polarity=0, phase=0, pins=("GP14", "GP16", "GP15")) +SPI(0, SPI.MASTER, polarity=0, phase=0, pins=("GP31", "GP16", "GP15")) spi = SPI(0, SPI.MASTER, baudrate=10000000, polarity=0, phase=0, pins=spi_pins) -print(spi.write('123456') == 6) +print(spi.write("123456") == 6) buffer_r = bytearray(10) print(spi.readinto(buffer_r) == 10) print(spi.readinto(buffer_r, write=0x55) == 10) @@ -76,7 +76,7 @@ print(spi.write_readinto(buffer_w, buffer_r) == 12) print(buffer_w == buffer_r) # check for memory leaks... -for i in range (0, 1000): +for i in range(0, 1000): spi = SPI(0, SPI.MASTER, baudrate=1000000) # test deinit @@ -112,7 +112,7 @@ except: print("Exception") try: - spi = SPI(0, mode=SPI.MASTER, baudrate=2000000, polarity=2, phase=0, pins=('GP1', 'GP2')) + spi = SPI(0, mode=SPI.MASTER, baudrate=2000000, polarity=2, phase=0, pins=("GP1", "GP2")) except: print("Exception") @@ -133,7 +133,7 @@ except Exception: print("Exception") try: - spi.spi.write('abc') + spi.spi.write("abc") except Exception: print("Exception") diff --git a/tests/wipy/time.py b/tests/wipy/time.py index e6237de356..4a550b9494 100644 --- a/tests/wipy/time.py +++ b/tests/wipy/time.py @@ -2,12 +2,14 @@ import time DAYS_PER_MONTH = [0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31] + def is_leap(year): return (year % 4) == 0 + def test(): seconds = 0 - wday = 5 # Jan 1, 2000 was a Saturday + wday = 5 # Jan 1, 2000 was a Saturday for year in range(2000, 2049): print("Testing %d" % year) yday = 1 @@ -19,31 +21,48 @@ def test(): for day in range(1, DAYS_PER_MONTH[month] + 1): secs = time.mktime((year, month, day, 0, 0, 0, 0, 0)) if secs != seconds: - print("mktime failed for %d-%02d-%02d got %d expected %d" % (year, month, day, secs, seconds)) + print( + "mktime failed for %d-%02d-%02d got %d expected %d" + % (year, month, day, secs, seconds) + ) tuple = time.localtime(seconds) secs = time.mktime(tuple) if secs != seconds: - print("localtime failed for %d-%02d-%02d got %d expected %d" % (year, month, day, secs, seconds)) + print( + "localtime failed for %d-%02d-%02d got %d expected %d" + % (year, month, day, secs, seconds) + ) return seconds += 86400 if yday != tuple[7]: - print("locatime for %d-%02d-%02d got yday %d, expecting %d" % (year, month, day, tuple[7], yday)) + print( + "locatime for %d-%02d-%02d got yday %d, expecting %d" + % (year, month, day, tuple[7], yday) + ) return if wday != tuple[6]: - print("locatime for %d-%02d-%02d got wday %d, expecting %d" % (year, month, day, tuple[6], wday)) + print( + "locatime for %d-%02d-%02d got wday %d, expecting %d" + % (year, month, day, tuple[6], wday) + ) return yday += 1 wday = (wday + 1) % 7 + def spot_test(seconds, expected_time): actual_time = time.localtime(seconds) for i in range(len(actual_time)): if actual_time[i] != expected_time[i]: - print("time.localtime(", seconds, ") returned", actual_time, "expecting", expected_time) + print( + "time.localtime(", seconds, ") returned", actual_time, "expecting", expected_time + ) return print("time.localtime(", seconds, ") returned", actual_time, "(pass)") + test() +# fmt: off spot_test( 0, (2000, 1, 1, 0, 0, 0, 5, 1)) spot_test( 1, (2000, 1, 1, 0, 0, 1, 5, 1)) spot_test( 59, (2000, 1, 1, 0, 0, 59, 5, 1)) @@ -56,16 +75,17 @@ spot_test( -940984933, (1970, 3, 7, 23, 17, 47, 5, 66)) spot_test(-1072915199, (1966, 1, 1, 0, 0, 1, 5, 1)) spot_test(-1072915200, (1966, 1, 1, 0, 0, 0, 5, 1)) spot_test(-1072915201, (1965, 12, 31, 23, 59, 59, 4, 365)) +# fmt: on t1 = time.time() time.sleep(2) t2 = time.time() -print(abs(time.ticks_diff(t1, t2) -2) <= 1) +print(abs(time.ticks_diff(t1, t2) - 2) <= 1) t1 = time.ticks_ms() time.sleep_ms(50) t2 = time.ticks_ms() -print(abs(time.ticks_diff(t1, t2)- 50) <= 1) +print(abs(time.ticks_diff(t1, t2) - 50) <= 1) t1 = time.ticks_us() time.sleep_us(1000) diff --git a/tests/wipy/timer.py b/tests/wipy/timer.py index f62899b472..db25870db0 100644 --- a/tests/wipy/timer.py +++ b/tests/wipy/timer.py @@ -1,18 +1,18 @@ -''' +""" Timer test for the CC3200 based boards. -''' +""" from machine import Timer import os import time mch = os.uname().machine -if 'LaunchPad' in mch: - pwm_pin = ('GP24') -elif 'WiPy' in mch: - pwm_pin = ('GP24') +if "LaunchPad" in mch: + pwm_pin = "GP24" +elif "WiPy" in mch: + pwm_pin = "GP24" else: - raise Exception('Board not supported!') + raise Exception("Board not supported!") for i in range(4): tim = Timer(i, mode=Timer.PERIODIC) @@ -49,6 +49,7 @@ class TimerTest: def timer_isr(self, tim_ch): self.int_count += 1 + timer_test = TimerTest() ch = timer_test.tim.channel(Timer.A, freq=5) print(ch.freq() == 5) @@ -92,26 +93,26 @@ for i in range(1000): try: tim = Timer(0, mode=12) except: - print('Exception') + print("Exception") try: tim = Timer(4, mode=Timer.ONE_SHOT) except: - print('Exception') + print("Exception") try: tim = Timer(0, mode=Timer.PWM, width=32) except: - print('Exception') + print("Exception") tim = Timer(0, mode=Timer.PWM) try: ch = tim.channel(TIMER_A | TIMER_B, freq=10) except: - print('Exception') + print("Exception") try: ch = tim.channel(TIMER_A, freq=4) except: - print('Exception') + print("Exception") diff --git a/tests/wipy/uart.py b/tests/wipy/uart.py index 8e794015de..9498d95545 100644 --- a/tests/wipy/uart.py +++ b/tests/wipy/uart.py @@ -1,7 +1,7 @@ -''' +""" UART test for the CC3200 based boards. UART0 and UART1 must be connected together for this test to pass. -''' +""" from machine import UART from machine import Pin @@ -9,14 +9,20 @@ import os import time mch = os.uname().machine -if 'LaunchPad' in mch: +if "LaunchPad" in mch: uart_id_range = range(0, 2) - uart_pins = [[('GP12', 'GP13'), ('GP12', 'GP13', 'GP7', 'GP6')], [('GP16', 'GP17'), ('GP16', 'GP17', 'GP7', 'GP6')]] -elif 'WiPy' in mch: + uart_pins = [ + [("GP12", "GP13"), ("GP12", "GP13", "GP7", "GP6")], + [("GP16", "GP17"), ("GP16", "GP17", "GP7", "GP6")], + ] +elif "WiPy" in mch: uart_id_range = range(0, 2) - uart_pins = [[('GP12', 'GP13'), ('GP12', 'GP13', 'GP7', 'GP6')], [('GP16', 'GP17'), ('GP16', 'GP17', 'GP7', 'GP6')]] + uart_pins = [ + [("GP12", "GP13"), ("GP12", "GP13", "GP7", "GP6")], + [("GP16", "GP17"), ("GP16", "GP17", "GP7", "GP6")], + ] else: - raise Exception('Board not supported!') + raise Exception("Board not supported!") # just in case we have the repl duplicated on any of the uarts os.dupterm(None) @@ -33,13 +39,13 @@ for uart_id in uart_id_range: uart = UART(baudrate=1000000) uart = UART() print(uart) -uart = UART(baudrate=38400, pins=('GP12', 'GP13')) +uart = UART(baudrate=38400, pins=("GP12", "GP13")) print(uart) -uart = UART(pins=('GP12', 'GP13')) +uart = UART(pins=("GP12", "GP13")) print(uart) -uart = UART(pins=(None, 'GP17')) +uart = UART(pins=(None, "GP17")) print(uart) -uart = UART(baudrate=57600, pins=('GP16', 'GP17')) +uart = UART(baudrate=57600, pins=("GP16", "GP17")) print(uart) # now it's time for some loopback tests between the uarts @@ -48,104 +54,104 @@ print(uart0) uart1 = UART(1, 1000000, pins=uart_pins[1][0]) print(uart1) -print(uart0.write(b'123456') == 6) -print(uart1.read() == b'123456') +print(uart0.write(b"123456") == 6) +print(uart1.read() == b"123456") -print(uart1.write(b'123') == 3) -print(uart0.read(1) == b'1') -print(uart0.read(2) == b'23') +print(uart1.write(b"123") == 3) +print(uart0.read(1) == b"1") +print(uart0.read(2) == b"23") print(uart0.read() == None) -uart0.write(b'123') +uart0.write(b"123") buf = bytearray(3) -print(uart1.readinto(buf, 1) == 1) +print(uart1.readinto(buf, 1) == 1) print(buf) print(uart1.readinto(buf) == 2) print(buf) # try initializing without the id uart0 = UART(baudrate=1000000, pins=uart_pins[0][0]) -uart0.write(b'1234567890') -time.sleep_ms(2) # because of the fifo interrupt levels +uart0.write(b"1234567890") +time.sleep_ms(2) # because of the fifo interrupt levels print(uart1.any() == 10) -print(uart1.readline() == b'1234567890') +print(uart1.readline() == b"1234567890") print(uart1.any() == 0) -uart0.write(b'1234567890') -print(uart1.read() == b'1234567890') +uart0.write(b"1234567890") +print(uart1.read() == b"1234567890") # tx only mode -uart0 = UART(0, 1000000, pins=('GP12', None)) -print(uart0.write(b'123456') == 6) -print(uart1.read() == b'123456') -print(uart1.write(b'123') == 3) +uart0 = UART(0, 1000000, pins=("GP12", None)) +print(uart0.write(b"123456") == 6) +print(uart1.read() == b"123456") +print(uart1.write(b"123") == 3) print(uart0.read() == None) # rx only mode -uart0 = UART(0, 1000000, pins=(None, 'GP13')) -print(uart0.write(b'123456') == 6) +uart0 = UART(0, 1000000, pins=(None, "GP13")) +print(uart0.write(b"123456") == 6) print(uart1.read() == None) -print(uart1.write(b'123') == 3) -print(uart0.read() == b'123') +print(uart1.write(b"123") == 3) +print(uart0.read() == b"123") # leave pins as they were (rx only mode) uart0 = UART(0, 1000000, pins=None) -print(uart0.write(b'123456') == 6) +print(uart0.write(b"123456") == 6) print(uart1.read() == None) -print(uart1.write(b'123') == 3) -print(uart0.read() == b'123') +print(uart1.write(b"123") == 3) +print(uart0.read() == b"123") # no pin assignment uart0 = UART(0, 1000000, pins=(None, None)) -print(uart0.write(b'123456789') == 9) +print(uart0.write(b"123456789") == 9) print(uart1.read() == None) -print(uart1.write(b'123456789') == 9) +print(uart1.write(b"123456789") == 9) print(uart0.read() == None) print(Pin.board.GP12) print(Pin.board.GP13) # check for memory leaks... -for i in range (0, 1000): +for i in range(0, 1000): uart0 = UART(0, 1000000) uart1 = UART(1, 1000000) # next ones must raise try: - UART(0, 9600, parity=None, pins=('GP12', 'GP13', 'GP7')) + UART(0, 9600, parity=None, pins=("GP12", "GP13", "GP7")) except Exception: - print('Exception') + print("Exception") try: - UART(0, 9600, parity=UART.ODD, pins=('GP12', 'GP7')) + UART(0, 9600, parity=UART.ODD, pins=("GP12", "GP7")) except Exception: - print('Exception') + print("Exception") uart0 = UART(0, 1000000) uart0.deinit() try: uart0.any() except Exception: - print('Exception') + print("Exception") try: uart0.read() except Exception: - print('Exception') + print("Exception") try: - uart0.write('abc') + uart0.write("abc") except Exception: - print('Exception') + print("Exception") try: - uart0.sendbreak('abc') + uart0.sendbreak("abc") except Exception: - print('Exception') + print("Exception") try: UART(2, 9600) except Exception: - print('Exception') + print("Exception") for uart_id in uart_id_range: uart = UART(uart_id, 1000000) diff --git a/tests/wipy/uart_irq.py b/tests/wipy/uart_irq.py index d4cd900585..e631e46a9c 100644 --- a/tests/wipy/uart_irq.py +++ b/tests/wipy/uart_irq.py @@ -1,18 +1,24 @@ -''' +""" UART IRQ test for the CC3200 based boards. -''' +""" from machine import UART import os import time mch = os.uname().machine -if 'LaunchPad' in mch: - uart_pins = [[('GP12', 'GP13'), ('GP12', 'GP13', 'GP7', 'GP6')], [('GP16', 'GP17'), ('GP16', 'GP17', 'GP7', 'GP6')]] -elif 'WiPy' in mch: - uart_pins = [[('GP12', 'GP13'), ('GP12', 'GP13', 'GP7', 'GP6')], [('GP16', 'GP17'), ('GP16', 'GP17', 'GP7', 'GP6')]] +if "LaunchPad" in mch: + uart_pins = [ + [("GP12", "GP13"), ("GP12", "GP13", "GP7", "GP6")], + [("GP16", "GP17"), ("GP16", "GP17", "GP7", "GP6")], + ] +elif "WiPy" in mch: + uart_pins = [ + [("GP12", "GP13"), ("GP12", "GP13", "GP7", "GP6")], + [("GP16", "GP17"), ("GP16", "GP17", "GP7", "GP6")], + ] else: - raise Exception('Board not supported!') + raise Exception("Board not supported!") # just in case we have stdio duplicated on any of the uarts os.dupterm(None) @@ -23,22 +29,25 @@ uart1 = UART(1, 1000000, pins=uart_pins[1][0]) uart0_int_count = 0 uart1_int_count = 0 -def uart0_handler (uart_o): + +def uart0_handler(uart_o): global uart0_irq global uart0_int_count - if (uart0_irq.flags() & UART.RX_ANY): + if uart0_irq.flags() & UART.RX_ANY: uart0_int_count += 1 -def uart1_handler (uart_o): + +def uart1_handler(uart_o): global uart1_irq global uart1_int_count - if (uart1_irq.flags() & UART.RX_ANY): + if uart1_irq.flags() & UART.RX_ANY: uart1_int_count += 1 + uart0_irq = uart0.irq(trigger=UART.RX_ANY, handler=uart0_handler) uart1_irq = uart1.irq(trigger=UART.RX_ANY, handler=uart1_handler) -uart0.write(b'123') +uart0.write(b"123") # wait for the characters to be received while not uart1.any(): pass @@ -48,9 +57,9 @@ print(uart1.any() == 3) print(uart1_int_count > 0) print(uart1_irq.flags() == 0) print(uart0_irq.flags() == 0) -print(uart1.read() == b'123') +print(uart1.read() == b"123") -uart1.write(b'12345') +uart1.write(b"12345") # wait for the characters to be received while not uart0.any(): pass @@ -60,11 +69,11 @@ print(uart0.any() == 5) print(uart0_int_count > 0) print(uart0_irq.flags() == 0) print(uart1_irq.flags() == 0) -print(uart0.read() == b'12345') +print(uart0.read() == b"12345") # do it again uart1_int_count = 0 -uart0.write(b'123') +uart0.write(b"123") # wait for the characters to be received while not uart1.any(): pass @@ -74,29 +83,29 @@ print(uart1.any() == 3) print(uart1_int_count > 0) print(uart1_irq.flags() == 0) print(uart0_irq.flags() == 0) -print(uart1.read() == b'123') +print(uart1.read() == b"123") # disable the interrupt uart1_irq.disable() # do it again uart1_int_count = 0 -uart0.write(b'123') +uart0.write(b"123") # wait for the characters to be received while not uart1.any(): pass time.sleep_us(100) print(uart1.any() == 3) -print(uart1_int_count == 0) # no interrupt triggered this time +print(uart1_int_count == 0) # no interrupt triggered this time print(uart1_irq.flags() == 0) print(uart0_irq.flags() == 0) -print(uart1.read() == b'123') +print(uart1.read() == b"123") # enable the interrupt uart1_irq.enable() # do it again uart1_int_count = 0 -uart0.write(b'123') +uart0.write(b"123") # wait for the characters to be received while not uart1.any(): pass @@ -106,22 +115,22 @@ print(uart1.any() == 3) print(uart1_int_count > 0) print(uart1_irq.flags() == 0) print(uart0_irq.flags() == 0) -print(uart1.read() == b'123') +print(uart1.read() == b"123") -uart1_irq.init(trigger=UART.RX_ANY, handler=None) # No handler +uart1_irq.init(trigger=UART.RX_ANY, handler=None) # No handler # do it again uart1_int_count = 0 -uart0.write(b'123') +uart0.write(b"123") # wait for the characters to be received while not uart1.any(): pass time.sleep_us(100) print(uart1.any() == 3) -print(uart1_int_count == 0) # no interrupt handler called +print(uart1_int_count == 0) # no interrupt handler called print(uart1_irq.flags() == 0) print(uart0_irq.flags() == 0) -print(uart1.read() == b'123') +print(uart1.read() == b"123") # check for memory leaks for i in range(0, 1000): @@ -132,17 +141,17 @@ for i in range(0, 1000): try: uart0_irq = uart0.irq(trigger=100, handler=uart0_handler) except: - print('Exception') + print("Exception") try: uart0_irq = uart0.irq(trigger=0) except: - print('Exception') + print("Exception") try: uart0_irq = uart0.irq(trigger=UART.RX_ANY, wake=Sleep.SUSPENDED) except: - print('Exception') + print("Exception") uart0_irq.disable() uart1_irq.disable() diff --git a/tests/wipy/wdt.py b/tests/wipy/wdt.py index a894b88fd8..56f6ea8d95 100644 --- a/tests/wipy/wdt.py +++ b/tests/wipy/wdt.py @@ -1,6 +1,6 @@ -''' +""" WDT test for the CC3200 based boards -''' +""" from machine import WDT import time diff --git a/tests/wipy/wlan/machine.py b/tests/wipy/wlan/machine.py index 2ee5299651..f69b117b74 100644 --- a/tests/wipy/wlan/machine.py +++ b/tests/wipy/wlan/machine.py @@ -1,14 +1,14 @@ -''' +""" machine test for the CC3200 based boards. -''' +""" import machine import os from network import WLAN mch = os.uname().machine -if not 'LaunchPad' in mch and not'WiPy' in mch: - raise Exception('Board not supported!') +if not "LaunchPad" in mch and not "WiPy" in mch: + raise Exception("Board not supported!") wifi = WLAN() @@ -17,7 +17,7 @@ machine.idle() print(machine.freq() == (80000000,)) print(machine.unique_id() == wifi.mac()) -machine.main('main.py') +machine.main("main.py") rand_nums = [] for i in range(0, 100): @@ -25,7 +25,7 @@ for i in range(0, 100): if rand not in rand_nums: rand_nums.append(rand) else: - print('RNG number repeated') + print("RNG number repeated") break for i in range(0, 10): @@ -39,4 +39,4 @@ print(machine.wake_reason() >= 0) try: machine.main(123456) except: - print('Exception') + print("Exception") diff --git a/tests/wipy/wlan/server.py b/tests/wipy/wlan/server.py index 05847e3761..40f56745c9 100644 --- a/tests/wipy/wlan/server.py +++ b/tests/wipy/wlan/server.py @@ -1,13 +1,13 @@ -''' +""" network server test for the CC3200 based boards. -''' +""" import os import network mch = os.uname().machine -if not 'LaunchPad' in mch and not'WiPy' in mch: - raise Exception('Board not supported!') +if not "LaunchPad" in mch and not "WiPy" in mch: + raise Exception("Board not supported!") server = network.Server() @@ -16,7 +16,7 @@ print(server.isrunning() == True) server.deinit() print(server.isrunning() == False) -server.init(login=('test-user', 'test-password'), timeout=60) +server.init(login=("test-user", "test-password"), timeout=60) print(server.isrunning() == True) print(server.timeout() == 60) @@ -28,14 +28,14 @@ print(server.isrunning() == True) try: server.init(1) except: - print('Exception') + print("Exception") try: - server.init(0, login=('0000000000011111111111222222222222333333', 'abc')) + server.init(0, login=("0000000000011111111111222222222222333333", "abc")) except: - print('Exception') + print("Exception") try: server.timeout(1) except: - print('Exception') + print("Exception") diff --git a/tests/wipy/wlan/wlan.py b/tests/wipy/wlan/wlan.py index 49e2e4af6a..dd85c86967 100644 --- a/tests/wipy/wlan/wlan.py +++ b/tests/wipy/wlan/wlan.py @@ -1,6 +1,6 @@ -''' +""" WLAN test for the CC3200 based boards. -''' +""" from network import WLAN import os @@ -8,8 +8,8 @@ import time import testconfig mch = os.uname().machine -if not 'LaunchPad' in mch and not 'WiPy' in mch: - raise Exception('Board not supported!') +if not "LaunchPad" in mch and not "WiPy" in mch: + raise Exception("Board not supported!") def wait_for_connection(wifi, timeout=10): @@ -17,9 +17,9 @@ def wait_for_connection(wifi, timeout=10): time.sleep(1) timeout -= 1 if wifi.isconnected(): - print('Connected') + print("Connected") else: - print('Connection failed!') + print("Connection failed!") wifi = WLAN(0, WLAN.STA) @@ -31,16 +31,16 @@ print(wifi.mode() == WLAN.AP) print(wifi.channel() == 1) print(wifi.auth() == None) print(wifi.antenna() == WLAN.INT_ANT) -wifi = WLAN(0, mode=WLAN.AP, ssid='test-wlan', auth=(WLAN.WPA, '123456abc'), channel=7) +wifi = WLAN(0, mode=WLAN.AP, ssid="test-wlan", auth=(WLAN.WPA, "123456abc"), channel=7) print(wifi.mode() == WLAN.AP) print(wifi.channel() == 7) -print(wifi.ssid() == 'test-wlan') -print(wifi.auth() == (WLAN.WPA, '123456abc')) +print(wifi.ssid() == "test-wlan") +print(wifi.auth() == (WLAN.WPA, "123456abc")) print(wifi.antenna() == WLAN.INT_ANT) wifi = WLAN(mode=WLAN.STA) print(wifi.mode() == WLAN.STA) -time.sleep(5) # this ensures a full network scan +time.sleep(5) # this ensures a full network scan scan_r = wifi.scan() print(len(scan_r) > 3) for net in scan_r: @@ -50,30 +50,30 @@ for net in scan_r: print(net.channel == None) print(net.sec == testconfig.wlan_auth[0]) print(net.rssi < 0) - print('Network found') + print("Network found") break wifi.mode(WLAN.STA) print(wifi.mode() == WLAN.STA) wifi.channel(7) print(wifi.channel() == 7) -wifi.ssid('t-wlan') -print(wifi.ssid() == 't-wlan') +wifi.ssid("t-wlan") +print(wifi.ssid() == "t-wlan") wifi.auth(None) print(wifi.auth() == None) -wifi.auth((WLAN.WEP, '11223344556677889900')) -print(wifi.auth() == (WLAN.WEP, '11223344556677889900')) +wifi.auth((WLAN.WEP, "11223344556677889900")) +print(wifi.auth() == (WLAN.WEP, "11223344556677889900")) wifi.antenna(WLAN.INT_ANT) print(wifi.antenna() == WLAN.INT_ANT) wifi.antenna(WLAN.EXT_ANT) print(wifi.antenna() == WLAN.EXT_ANT) -time.sleep(2) # this ensures a full network scan +time.sleep(2) # this ensures a full network scan scan_r = wifi.scan() print(len(scan_r) > 3) for net in scan_r: if net.ssid == testconfig.wlan_ssid: - print('Network found') + print("Network found") break wifi.antenna(WLAN.INT_ANT) @@ -82,12 +82,12 @@ print(wifi.mode() == WLAN.STA) wifi.connect(testconfig.wlan_ssid, auth=testconfig.wlan_auth, timeout=10000) wait_for_connection(wifi) -wifi.ifconfig(config='dhcp') +wifi.ifconfig(config="dhcp") wait_for_connection(wifi) -print('0.0.0.0' not in wifi.ifconfig()) -wifi.ifconfig(0, ('192.168.178.109', '255.255.255.0', '192.168.178.1', '8.8.8.8')) +print("0.0.0.0" not in wifi.ifconfig()) +wifi.ifconfig(0, ("192.168.178.109", "255.255.255.0", "192.168.178.1", "8.8.8.8")) wait_for_connection(wifi) -print(wifi.ifconfig(0) == ('192.168.178.109', '255.255.255.0', '192.168.178.1', '8.8.8.8')) +print(wifi.ifconfig(0) == ("192.168.178.109", "255.255.255.0", "192.168.178.1", "8.8.8.8")) wait_for_connection(wifi) print(wifi.isconnected() == True) @@ -102,7 +102,7 @@ wifi.disconnect() print(wifi.isconnected() == False) # test init again -wifi.init(WLAN.AP, ssid='www.wipy.io', auth=None, channel=5, antenna=WLAN.INT_ANT) +wifi.init(WLAN.AP, ssid="www.wipy.io", auth=None, channel=5, antenna=WLAN.INT_ANT) print(wifi.mode() == WLAN.AP) # get the current instance without re-init @@ -118,65 +118,66 @@ print(len(wifi.mac()) == 6) try: wifi.init(mode=12345) except: - print('Exception') + print("Exception") try: wifi.init(1, mode=WLAN.AP) except: - print('Exception') + print("Exception") try: wifi.init(mode=WLAN.AP, ssid=None) except: - print('Exception') + print("Exception") try: wifi = WLAN(mode=WLAN.AP, channel=12) except: - print('Exception') + print("Exception") try: wifi.antenna(2) except: - print('Exception') + print("Exception") try: wifi.mode(10) except: - print('Exception') + print("Exception") try: - wifi.ssid('11111sdfasdfasdfasdf564sdf654asdfasdf123451245ssdgfsdf1111111111111111111111111234123412341234asdfasdf') + wifi.ssid( + "11111sdfasdfasdfasdf564sdf654asdfasdf123451245ssdgfsdf1111111111111111111111111234123412341234asdfasdf" + ) except: - print('Exception') + print("Exception") try: wifi.auth((0)) except: - print('Exception') + print("Exception") try: wifi.auth((0, None)) except: - print('Exception') + print("Exception") try: wifi.auth((10, 10)) except: - print('Exception') + print("Exception") try: wifi.channel(0) except: - print('Exception') + print("Exception") try: - wifi.ifconfig(1, 'dhcp') + wifi.ifconfig(1, "dhcp") except: - print('Exception') + print("Exception") try: wifi.ifconfig(config=()) except: - print('Exception') - + print("Exception") diff --git a/tools/codeformat.py b/tools/codeformat.py index dba00fafd7..0a8bf2e0f4 100755 --- a/tools/codeformat.py +++ b/tools/codeformat.py @@ -50,6 +50,7 @@ PATHS = [ "ports/**/*.py", "py/**/*.py", "tools/**/*.py", + "tests/**/*.py", ] EXCLUSIONS = [ @@ -57,6 +58,10 @@ EXCLUSIONS = [ "ports/*/build*", # gitignore in ports/unix ignores *.py, so also do it here. "ports/unix/*.py", + # not real python files + "tests/**/repl_*.py", + # needs careful attention before applying automatic formatting + "tests/basics/*.py", ] # Path to repo top-level dir.