summaryrefslogtreecommitdiff
path: root/tests
diff options
context:
space:
mode:
authormicroDev <70126934+microDev1@users.noreply.github.com>2021-03-15 19:27:36 +0530
committermicroDev <70126934+microDev1@users.noreply.github.com>2021-03-15 19:27:36 +0530
commita52eb88031620a81521b937f2a0651dbac2bb350 (patch)
tree017cbf8f686b252241182ef61ce48e8457aa1577 /tests
parent090b6ba42fcdfbb16844f77892087f91aa6ea201 (diff)
run code formatting script
Diffstat (limited to 'tests')
-rw-r--r--tests/bench/arrayop-1-list_inplace.py4
-rw-r--r--tests/bench/arrayop-2-list_map.py4
-rw-r--r--tests/bench/arrayop-3-bytearray_inplace.py4
-rw-r--r--tests/bench/arrayop-4-bytearray_map.py4
-rw-r--r--tests/bench/bench.py1
-rw-r--r--tests/bench/bytealloc-1-bytes_n.py2
-rw-r--r--tests/bench/bytealloc-2-repeat.py2
-rw-r--r--tests/bench/bytebuf-1-inplace.py4
-rw-r--r--tests/bench/bytebuf-2-join_map_bytes.py6
-rw-r--r--tests/bench/bytebuf-3-bytarray_map.py4
-rw-r--r--tests/bench/from_iter-1-list_bound.py4
-rw-r--r--tests/bench/from_iter-2-list_unbound.py4
-rw-r--r--tests/bench/from_iter-3-tuple_bound.py4
-rw-r--r--tests/bench/from_iter-4-tuple_unbound.py4
-rw-r--r--tests/bench/from_iter-5-bytes_bound.py4
-rw-r--r--tests/bench/from_iter-6-bytes_unbound.py4
-rw-r--r--tests/bench/from_iter-7-bytearray_bound.py4
-rw-r--r--tests/bench/from_iter-8-bytearray_unbound.py4
-rw-r--r--tests/bench/func_args-1.1-pos_1.py3
-rw-r--r--tests/bench/func_args-1.2-pos_3.py3
-rw-r--r--tests/bench/func_args-2-pos_default_2_of_3.py3
-rw-r--r--tests/bench/func_args-3.1-kw_1.py3
-rw-r--r--tests/bench/func_args-3.2-kw_3.py3
-rw-r--r--tests/bench/func_builtin-1-enum_pos.py4
-rw-r--r--tests/bench/func_builtin-2-enum_kw.py4
-rw-r--r--tests/bench/funcall-1-inline.py2
-rw-r--r--tests/bench/funcall-2-funcall.py3
-rw-r--r--tests/bench/funcall-3-funcall-local.py3
-rw-r--r--tests/bench/loop_count-1-range.py2
-rw-r--r--tests/bench/loop_count-2-range_iter.py2
-rw-r--r--tests/bench/loop_count-3-while_up.py2
-rw-r--r--tests/bench/loop_count-4-while_down_gt.py2
-rw-r--r--tests/bench/loop_count-5-while_down_ne.py2
-rw-r--r--tests/bench/loop_count-5.1-while_down_ne_localvar.py2
-rw-r--r--tests/bench/var-1-constant.py2
-rw-r--r--tests/bench/var-2-global.py2
-rw-r--r--tests/bench/var-3-local.py1
-rw-r--r--tests/bench/var-4-arg.py3
-rw-r--r--tests/bench/var-5-class-attr.py3
-rw-r--r--tests/bench/var-6-instance-attr.py4
-rw-r--r--tests/bench/var-6.1-instance-attr-5.py4
-rw-r--r--tests/bench/var-7-instance-meth.py4
-rw-r--r--tests/bench/var-8-namedtuple-1st.py2
-rw-r--r--tests/bench/var-8.1-namedtuple-5th.py2
-rw-r--r--tests/circuitpython-manual/audiobusio/i2s_sample_loop.py3
-rw-r--r--tests/circuitpython-manual/audiobusio/pdmin_rms.py7
-rw-r--r--tests/circuitpython-manual/audiopwmio/single_buffer_loop.py7
-rw-r--r--tests/circuitpython-manual/busio/uart_echo.py6
-rw-r--r--tests/circuitpython-manual/socketpool/client/cpy-client.py4
-rw-r--r--tests/circuitpython-manual/socketpool/client/host-server.py2
-rw-r--r--tests/circuitpython-manual/socketpool/datagram/ntp.py2
-rw-r--r--tests/circuitpython-manual/socketpool/server/cpy-server.py10
-rw-r--r--tests/circuitpython-manual/socketpool/server/host-client.py8
-rw-r--r--tests/circuitpython/nvm_not_present.py3
-rw-r--r--tests/circuitpython/nvm_present.py8
-rw-r--r--tests/cmdline/cmd_parsetree.py8
-rw-r--r--tests/cmdline/cmd_showbc.py1
-rw-r--r--tests/cpydiff/core_class_delnotimpl.py6
-rw-r--r--tests/cpydiff/core_class_mro.py4
-rw-r--r--tests/cpydiff/core_class_supermultiple.py7
-rw-r--r--tests/cpydiff/core_function_userattr.py3
-rw-r--r--tests/cpydiff/core_generator_noexit.py10
-rw-r--r--tests/cpydiff/core_import_prereg.py3
-rw-r--r--tests/cpydiff/core_import_split_ns_pkgs.py1
-rw-r--r--tests/cpydiff/core_locals.py3
-rw-r--r--tests/cpydiff/core_locals_eval.py2
-rw-r--r--tests/cpydiff/modules/foo.py2
-rw-r--r--tests/cpydiff/modules_array_containment.py3
-rw-r--r--tests/cpydiff/modules_array_deletion.py3
-rw-r--r--tests/cpydiff/modules_array_subscrstep.py3
-rw-r--r--tests/cpydiff/modules_deque.py1
-rw-r--r--tests/cpydiff/modules_json_nonserializable.py5
-rw-r--r--tests/cpydiff/modules_struct_fewargs.py7
-rw-r--r--tests/cpydiff/modules_struct_manyargs.py7
-rw-r--r--tests/cpydiff/modules_sys_stdassign.py1
-rw-r--r--tests/cpydiff/syntax_spaces.py12
-rw-r--r--tests/cpydiff/types_bytes_keywords.py2
-rw-r--r--tests/cpydiff/types_bytes_subscrstep.py2
-rw-r--r--tests/cpydiff/types_exception_subclassinit.py3
-rw-r--r--tests/cpydiff/types_float_rounding.py2
-rw-r--r--tests/cpydiff/types_int_subclassconv.py5
-rw-r--r--tests/cpydiff/types_str_endswith.py2
-rw-r--r--tests/cpydiff/types_str_formatsubscr.py2
-rw-r--r--tests/cpydiff/types_str_keywords.py2
-rw-r--r--tests/cpydiff/types_str_ljust_rjust.py2
-rw-r--r--tests/cpydiff/types_str_rsplitnone.py2
-rw-r--r--tests/cpydiff/types_str_subclassequality.py7
-rw-r--r--tests/cpydiff/types_str_subscrstep.py2
-rw-r--r--tests/extmod/btree1.py2
-rw-r--r--tests/extmod/framebuf1.py26
-rw-r--r--tests/extmod/framebuf16.py26
-rw-r--r--tests/extmod/framebuf2.py4
-rw-r--r--tests/extmod/framebuf4.py38
-rw-r--r--tests/extmod/framebuf8.py6
-rw-r--r--tests/extmod/framebuf_subclass.py4
-rw-r--r--tests/extmod/machine_pinbase.py2
-rw-r--r--tests/extmod/machine_pulse.py2
-rw-r--r--tests/extmod/machine_signal.py1
-rw-r--r--tests/extmod/time_ms_us.py1
-rw-r--r--tests/extmod/ubinascii_a2b_base64.py44
-rw-r--r--tests/extmod/ubinascii_b2a_base64.py26
-rw-r--r--tests/extmod/ubinascii_crc32.py14
-rw-r--r--tests/extmod/ubinascii_hexlify.py10
-rw-r--r--tests/extmod/ubinascii_micropython.py4
-rw-r--r--tests/extmod/ubinascii_unhexlify.py18
-rw-r--r--tests/extmod/uctypes_32bit_intbig.py12
-rw-r--r--tests/extmod/uctypes_array_assign_le.py6
-rw-r--r--tests/extmod/uctypes_array_assign_native_le.py5
-rw-r--r--tests/extmod/uctypes_array_assign_native_le_intbig.py5
-rw-r--r--tests/extmod/uctypes_byteat.py2
-rw-r--r--tests/extmod/uctypes_error.py12
-rw-r--r--tests/extmod/uctypes_le.py19
-rw-r--r--tests/extmod/uctypes_le_float.py8
-rw-r--r--tests/extmod/uctypes_native_float.py9
-rw-r--r--tests/extmod/uctypes_native_le.py20
-rw-r--r--tests/extmod/uctypes_print.py4
-rw-r--r--tests/extmod/uctypes_ptr_le.py3
-rw-r--r--tests/extmod/uctypes_ptr_native_le.py3
-rw-r--r--tests/extmod/uctypes_sizeof.py11
-rw-r--r--tests/extmod/uctypes_sizeof_float.py4
-rw-r--r--tests/extmod/uctypes_sizeof_native.py28
-rw-r--r--tests/extmod/uhashlib_sha1.py8
-rw-r--r--tests/extmod/uhashlib_sha256.py18
-rw-r--r--tests/extmod/uheapq1.py4
-rw-r--r--tests/extmod/ujson_dump.py8
-rw-r--r--tests/extmod/ujson_dump_iobase.py11
-rw-r--r--tests/extmod/ujson_dumps.py10
-rw-r--r--tests/extmod/ujson_dumps_extra.py2
-rw-r--r--tests/extmod/ujson_load.py4
-rw-r--r--tests/extmod/ujson_load_readinto.py8
-rw-r--r--tests/extmod/ujson_loads.py44
-rw-r--r--tests/extmod/ujson_loads_float.py14
-rw-r--r--tests/extmod/umsgpack_pack.py8
-rw-r--r--tests/extmod/urandom_basic.py2
-rw-r--r--tests/extmod/urandom_extra.py24
-rw-r--r--tests/extmod/ure1.py18
-rw-r--r--tests/extmod/ure_debug.py2
-rw-r--r--tests/extmod/ure_error.py18
-rw-r--r--tests/extmod/ure_group.py12
-rw-r--r--tests/extmod/ure_groups.py12
-rw-r--r--tests/extmod/ure_namedclass.py12
-rw-r--r--tests/extmod/ure_span.py13
-rw-r--r--tests/extmod/ure_split_notimpl.py4
-rw-r--r--tests/extmod/ure_sub.py35
-rw-r--r--tests/extmod/ure_sub_unmatched.py6
-rw-r--r--tests/extmod/ussl_basic.py16
-rw-r--r--tests/extmod/utimeq1.py14
-rw-r--r--tests/extmod/uzlib_decompio.py6
-rw-r--r--tests/extmod/uzlib_decompio_gz.py26
-rw-r--r--tests/extmod/uzlib_decompress.py37
-rw-r--r--tests/extmod/vfs_basic.py127
-rw-r--r--tests/extmod/vfs_fat_fileio1.py44
-rw-r--r--tests/extmod/vfs_fat_fileio2.py12
-rw-r--r--tests/extmod/vfs_fat_more.py74
-rw-r--r--tests/extmod/vfs_fat_oldproto.py5
-rw-r--r--tests/extmod/vfs_fat_ramdisk.py12
-rw-r--r--tests/extmod/vfs_userfs.py28
-rw-r--r--tests/extmod/websocket_basic.py16
-rw-r--r--tests/feature_check/byteorder.py1
-rw-r--r--tests/feature_check/coverage.py4
-rw-r--r--tests/feature_check/float.py4
-rw-r--r--tests/feature_check/reverse_ops.py2
-rw-r--r--tests/float/array_construct.py4
-rw-r--r--tests/float/builtin_float_hash.py20
-rw-r--r--tests/float/builtin_float_pow.py6
-rw-r--r--tests/float/builtin_float_round.py16
-rw-r--r--tests/float/builtin_float_round_intbig.py2
-rw-r--r--tests/float/bytearray_construct.py2
-rw-r--r--tests/float/bytes_construct.py2
-rw-r--r--tests/float/cmath_fun.py34
-rw-r--r--tests/float/cmath_fun_special.py15
-rw-r--r--tests/float/complex1.py37
-rw-r--r--tests/float/complex1_intbig.py3
-rw-r--r--tests/float/float1.py10
-rw-r--r--tests/float/float2int_doubleprec_intbig.py81
-rw-r--r--tests/float/float2int_fp30_intbig.py75
-rw-r--r--tests/float/float2int_intbig.py74
-rw-r--r--tests/float/float_array.py14
-rw-r--r--tests/float/float_compare.py2
-rw-r--r--tests/float/float_divmod.py4
-rw-r--r--tests/float/float_divmod_relaxed.py4
-rw-r--r--tests/float/float_format.py14
-rw-r--r--tests/float/float_parse.py36
-rw-r--r--tests/float/float_parse_doubleprec.py24
-rw-r--r--tests/float/float_struct.py6
-rw-r--r--tests/float/int_power.py2
-rw-r--r--tests/float/math_domain.py56
-rw-r--r--tests/float/math_domain_special.py39
-rw-r--r--tests/float/math_fun.py73
-rw-r--r--tests/float/math_fun_bool.py3
-rw-r--r--tests/float/math_fun_int.py2
-rw-r--r--tests/float/math_fun_intbig.py2
-rw-r--r--tests/float/math_fun_special.py31
-rw-r--r--tests/float/python36.py8
-rw-r--r--tests/float/string_format.py15
-rw-r--r--tests/float/string_format2.py168
-rw-r--r--tests/float/string_format_fp30.py23
-rw-r--r--tests/float/string_format_modulo.py40
-rw-r--r--tests/float/string_format_modulo2.py14
-rw-r--r--tests/float/string_format_modulo2_intbig.py12
-rw-r--r--tests/float/string_format_modulo3.py4
-rw-r--r--tests/float/true_value.py2
-rw-r--r--tests/import/builtin_import.py8
-rw-r--r--tests/import/gen_context.py2
-rw-r--r--tests/import/import1a.py1
-rw-r--r--tests/import/import1b.py1
-rw-r--r--tests/import/import2a.py2
-rw-r--r--tests/import/import3a.py1
-rw-r--r--tests/import/import_file.py1
-rw-r--r--tests/import/import_pkg1.py1
-rw-r--r--tests/import/import_pkg3.py1
-rw-r--r--tests/import/mpy_invalid.py22
-rw-r--r--tests/import/pkg3/mod2.py1
-rw-r--r--tests/import/pkg6/__init__.py3
-rw-r--r--tests/import/pkg6/x/__init__.py3
-rw-r--r--tests/import/pkg6/x/y.py2
-rw-r--r--tests/import/pkg7/mod1.py4
-rw-r--r--tests/import/pkg7/mod2.py4
-rw-r--r--tests/import/pkg7/subpkg1/subpkg2/mod3.py3
-rw-r--r--tests/import/pkg8/mod.py2
-rw-r--r--tests/import/try_module.py5
-rw-r--r--tests/inlineasm/asmargs.py15
-rw-r--r--tests/inlineasm/asmbcc.py2
-rw-r--r--tests/inlineasm/asmbitops.py7
-rw-r--r--tests/inlineasm/asmblbx.py2
-rw-r--r--tests/inlineasm/asmconst.py7
-rw-r--r--tests/inlineasm/asmdiv.py6
-rw-r--r--tests/inlineasm/asmfpaddsub.py3
-rw-r--r--tests/inlineasm/asmfpcmp.py9
-rw-r--r--tests/inlineasm/asmfpldrstr.py5
-rw-r--r--tests/inlineasm/asmfpmuldiv.py3
-rw-r--r--tests/inlineasm/asmfpsqrt.py3
-rw-r--r--tests/inlineasm/asmit.py6
-rw-r--r--tests/inlineasm/asmpushpop.py1
-rw-r--r--tests/inlineasm/asmrettype.py12
-rw-r--r--tests/inlineasm/asmshift.py17
-rw-r--r--tests/inlineasm/asmspecialregs.py2
-rw-r--r--tests/inlineasm/asmsum.py6
-rw-r--r--tests/io/argv.py1
-rw-r--r--tests/io/buffered_writer.py2
-rw-r--r--tests/io/builtin_print_file.py8
-rw-r--r--tests/io/file1.py26
-rw-r--r--tests/io/file_readinto.py4
-rw-r--r--tests/io/file_readline.py4
-rw-r--r--tests/io/file_seek.py4
-rw-r--r--tests/io/file_with.py2
-rw-r--r--tests/io/iobase.py7
-rw-r--r--tests/io/resource_stream.py2
-rw-r--r--tests/io/stringio1.py4
-rw-r--r--tests/io/write_ext.py2
-rw-r--r--tests/jni/list.py1
-rw-r--r--tests/jni/object.py1
-rw-r--r--tests/jni/system_out.py1
-rw-r--r--tests/micropython/const.py6
-rw-r--r--tests/micropython/const2.py22
-rw-r--r--tests/micropython/const_error.py2
-rw-r--r--tests/micropython/const_intbig.py4
-rw-r--r--tests/micropython/decorator.py4
-rw-r--r--tests/micropython/decorator_error.py2
-rw-r--r--tests/micropython/emg_exc.py3
-rw-r--r--tests/micropython/extreme_exc.py93
-rw-r--r--tests/micropython/heap_lock.py4
-rw-r--r--tests/micropython/heapalloc.py27
-rw-r--r--tests/micropython/heapalloc_bytesio2.py1
-rw-r--r--tests/micropython/heapalloc_exc_raise.py2
-rw-r--r--tests/micropython/heapalloc_inst_call.py5
-rw-r--r--tests/micropython/heapalloc_iter.py17
-rw-r--r--tests/micropython/heapalloc_super.py17
-rw-r--r--tests/micropython/heapalloc_traceback.py5
-rw-r--r--tests/micropython/kbd_intr.py2
-rw-r--r--tests/micropython/meminfo.py4
-rw-r--r--tests/micropython/memstats.py4
-rw-r--r--tests/micropython/native_closure.py11
-rw-r--r--tests/micropython/native_const_intbig.py2
-rw-r--r--tests/micropython/native_misc.py9
-rw-r--r--tests/micropython/opt_level.py8
-rw-r--r--tests/micropython/schedule.py17
-rw-r--r--tests/micropython/stack_use.py6
-rw-r--r--tests/micropython/viper_addr.py15
-rw-r--r--tests/micropython/viper_args.py25
-rw-r--r--tests/micropython/viper_binop_arith.py42
-rw-r--r--tests/micropython/viper_binop_comp.py3
-rw-r--r--tests/micropython/viper_binop_comp_imm.py1
-rw-r--r--tests/micropython/viper_binop_divmod.py8
-rw-r--r--tests/micropython/viper_binop_multi_comp.py3
-rw-r--r--tests/micropython/viper_cond.py6
-rw-r--r--tests/micropython/viper_error.py20
-rw-r--r--tests/micropython/viper_import.py5
-rw-r--r--tests/micropython/viper_misc.py59
-rw-r--r--tests/micropython/viper_misc_intbig.py3
-rw-r--r--tests/micropython/viper_ptr16_load.py13
-rw-r--r--tests/micropython/viper_ptr16_store.py13
-rw-r--r--tests/micropython/viper_ptr32_load.py13
-rw-r--r--tests/micropython/viper_ptr32_store.py13
-rw-r--r--tests/micropython/viper_ptr8_load.py13
-rw-r--r--tests/micropython/viper_ptr8_store.py13
-rw-r--r--tests/micropython/viper_subscr.py7
-rw-r--r--tests/misc/features.py232
-rw-r--r--tests/misc/non_compliant.py76
-rw-r--r--tests/misc/non_compliant_lexer.py24
-rw-r--r--tests/misc/print_exception.py24
-rw-r--r--tests/misc/rge_sm.py71
-rw-r--r--tests/misc/sys_exc_info.py5
-rw-r--r--tests/net_hosted/accept_nonblock.py4
-rw-r--r--tests/net_hosted/accept_timeout.py6
-rw-r--r--tests/net_hosted/connect_nonblock.py4
-rw-r--r--tests/net_hosted/connect_poll.py2
-rw-r--r--tests/net_hosted/ssl_getpeercert.py2
-rw-r--r--tests/net_inet/test_tls_sites.py7
-rw-r--r--tests/pyb/adc.py23
-rw-r--r--tests/pyb/can.py161
-rw-r--r--tests/pyb/dac.py4
-rw-r--r--tests/pyb/extint.py2
-rw-r--r--tests/pyb/irq.py4
-rw-r--r--tests/pyb/modtime.py53
-rw-r--r--tests/pyb/pin.py8
-rw-r--r--tests/pyb/pyb1.py4
-rw-r--r--tests/pyb/pyb_f405.py4
-rw-r--r--tests/pyb/pyb_f411.py4
-rw-r--r--tests/pyb/rtc.py17
-rw-r--r--tests/pyb/timer_callback.py5
-rw-r--r--tests/pyb/uart.py8
-rw-r--r--tests/pybnative/for.py4
-rw-r--r--tests/pybnative/while.py2
-rw-r--r--tests/run-tests-exp.py16
-rw-r--r--tests/skip_if.py18
-rw-r--r--tests/stress/dict_copy.py2
-rw-r--r--tests/stress/gc_trace.py4
-rw-r--r--tests/stress/recursion.py1
-rw-r--r--tests/stress/recursive_gen.py8
-rw-r--r--tests/thread/mutate_bytearray.py3
-rw-r--r--tests/thread/mutate_dict.py3
-rw-r--r--tests/thread/mutate_instance.py17
-rw-r--r--tests/thread/mutate_list.py1
-rw-r--r--tests/thread/mutate_set.py1
-rw-r--r--tests/thread/stress_aes.py309
-rw-r--r--tests/thread/stress_create.py4
-rw-r--r--tests/thread/stress_heap.py3
-rw-r--r--tests/thread/stress_recurse.py7
-rw-r--r--tests/thread/thread_exc1.py5
-rw-r--r--tests/thread/thread_exc2.py4
-rw-r--r--tests/thread/thread_exit1.py4
-rw-r--r--tests/thread/thread_exit2.py4
-rw-r--r--tests/thread/thread_gc1.py2
-rw-r--r--tests/thread/thread_ident1.py8
-rw-r--r--tests/thread/thread_lock1.py4
-rw-r--r--tests/thread/thread_lock2.py6
-rw-r--r--tests/thread/thread_lock3.py4
-rw-r--r--tests/thread/thread_lock4.py3
-rw-r--r--tests/thread/thread_qstr1.py6
-rw-r--r--tests/thread/thread_shared1.py3
-rw-r--r--tests/thread/thread_shared2.py3
-rw-r--r--tests/thread/thread_sleep1.py6
-rw-r--r--tests/thread/thread_stacksize1.py7
-rw-r--r--tests/thread/thread_start1.py5
-rw-r--r--tests/thread/thread_start2.py10
-rw-r--r--tests/unicode/file2.py16
-rw-r--r--tests/unicode/unicode.py32
-rw-r--r--tests/unicode/unicode_id.py5
-rw-r--r--tests/unicode/unicode_ord.py2
-rw-r--r--tests/unicode/unicode_str_format.py4
-rw-r--r--tests/unicode/unicode_str_modulo.py2
-rw-r--r--tests/unicode/unicode_subscr.py2
-rw-r--r--tests/unix/extra_coverage.py51
-rw-r--r--tests/unix/ffi_callback.py7
-rw-r--r--tests/unix/ffi_float.py13
-rw-r--r--tests/unix/ffi_float2.py7
-rw-r--r--tests/wipy/adc.py38
-rw-r--r--tests/wipy/modwipy.py10
-rw-r--r--tests/wipy/os.py158
-rw-r--r--tests/wipy/pin.py110
-rw-r--r--tests/wipy/pin_irq.py38
-rw-r--r--tests/wipy/reset/reset.py8
-rw-r--r--tests/wipy/rtc.py28
-rw-r--r--tests/wipy/sd.py18
-rw-r--r--tests/wipy/skipped/rtc_irq.py18
-rw-r--r--tests/wipy/time.py58
-rw-r--r--tests/wipy/timer.py25
-rw-r--r--tests/wipy/uart.py100
-rw-r--r--tests/wipy/uart_irq.py67
-rw-r--r--tests/wipy/wdt.py4
-rw-r--r--tests/wipy/wlan/machine.py14
-rw-r--r--tests/wipy/wlan/server.py18
-rw-r--r--tests/wipy/wlan/wlan.py76
384 files changed, 3330 insertions, 2039 deletions
diff --git a/tests/bench/arrayop-1-list_inplace.py b/tests/bench/arrayop-1-list_inplace.py
index 0ee1ef2ec..b29593c1a 100644
--- a/tests/bench/arrayop-1-list_inplace.py
+++ b/tests/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/bench/arrayop-2-list_map.py b/tests/bench/arrayop-2-list_map.py
index 9d5095c53..5959d3f46 100644
--- a/tests/bench/arrayop-2-list_map.py
+++ b/tests/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/bench/arrayop-3-bytearray_inplace.py b/tests/bench/arrayop-3-bytearray_inplace.py
index a6d628070..fbbade2ca 100644
--- a/tests/bench/arrayop-3-bytearray_inplace.py
+++ b/tests/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/bench/arrayop-4-bytearray_map.py b/tests/bench/arrayop-4-bytearray_map.py
index 1b92a4096..8fa987970 100644
--- a/tests/bench/arrayop-4-bytearray_map.py
+++ b/tests/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/bench/bench.py b/tests/bench/bench.py
index 0cd40a93f..d7087e0e0 100644
--- a/tests/bench/bench.py
+++ b/tests/bench/bench.py
@@ -3,6 +3,7 @@ import time
ITERS = 20000000
+
def run(f):
t = time.time()
f(ITERS)
diff --git a/tests/bench/bytealloc-1-bytes_n.py b/tests/bench/bytealloc-1-bytes_n.py
index 4a4bbc6fa..8b8120a53 100644
--- a/tests/bench/bytealloc-1-bytes_n.py
+++ b/tests/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/bench/bytealloc-2-repeat.py b/tests/bench/bytealloc-2-repeat.py
index 786a80462..8d6b5d528 100644
--- a/tests/bench/bytealloc-2-repeat.py
+++ b/tests/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/bench/bytebuf-1-inplace.py b/tests/bench/bytebuf-1-inplace.py
index 7e7d9391c..e1b6016a5 100644
--- a/tests/bench/bytebuf-1-inplace.py
+++ b/tests/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/bench/bytebuf-2-join_map_bytes.py b/tests/bench/bytebuf-2-join_map_bytes.py
index daa622991..9ecee4797 100644
--- a/tests/bench/bytebuf-2-join_map_bytes.py
+++ b/tests/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/bench/bytebuf-3-bytarray_map.py b/tests/bench/bytebuf-3-bytarray_map.py
index 078d08e99..2752d4e78 100644
--- a/tests/bench/bytebuf-3-bytarray_map.py
+++ b/tests/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/bench/from_iter-1-list_bound.py b/tests/bench/from_iter-1-list_bound.py
index d209daecc..384d52903 100644
--- a/tests/bench/from_iter-1-list_bound.py
+++ b/tests/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/bench/from_iter-2-list_unbound.py b/tests/bench/from_iter-2-list_unbound.py
index be019c52f..98e22d681 100644
--- a/tests/bench/from_iter-2-list_unbound.py
+++ b/tests/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/bench/from_iter-3-tuple_bound.py b/tests/bench/from_iter-3-tuple_bound.py
index 7b7fa36c6..f052f6dee 100644
--- a/tests/bench/from_iter-3-tuple_bound.py
+++ b/tests/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/bench/from_iter-4-tuple_unbound.py b/tests/bench/from_iter-4-tuple_unbound.py
index 7c7f134c8..ff9d1b4df 100644
--- a/tests/bench/from_iter-4-tuple_unbound.py
+++ b/tests/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/bench/from_iter-5-bytes_bound.py b/tests/bench/from_iter-5-bytes_bound.py
index b793a3207..967cb99ee 100644
--- a/tests/bench/from_iter-5-bytes_bound.py
+++ b/tests/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/bench/from_iter-6-bytes_unbound.py b/tests/bench/from_iter-6-bytes_unbound.py
index 20aa55627..b85501916 100644
--- a/tests/bench/from_iter-6-bytes_unbound.py
+++ b/tests/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/bench/from_iter-7-bytearray_bound.py b/tests/bench/from_iter-7-bytearray_bound.py
index 72001a05c..d0c4c65a7 100644
--- a/tests/bench/from_iter-7-bytearray_bound.py
+++ b/tests/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/bench/from_iter-8-bytearray_unbound.py b/tests/bench/from_iter-8-bytearray_unbound.py
index e2263b8ef..aec2e65ad 100644
--- a/tests/bench/from_iter-8-bytearray_unbound.py
+++ b/tests/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/bench/func_args-1.1-pos_1.py b/tests/bench/func_args-1.1-pos_1.py
index eee0ea828..cadb17768 100644
--- a/tests/bench/func_args-1.1-pos_1.py
+++ b/tests/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/bench/func_args-1.2-pos_3.py b/tests/bench/func_args-1.2-pos_3.py
index 7e03ee2f8..12010d015 100644
--- a/tests/bench/func_args-1.2-pos_3.py
+++ b/tests/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/bench/func_args-2-pos_default_2_of_3.py b/tests/bench/func_args-2-pos_default_2_of_3.py
index 1fa0fbda5..4dc565090 100644
--- a/tests/bench/func_args-2-pos_default_2_of_3.py
+++ b/tests/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/bench/func_args-3.1-kw_1.py b/tests/bench/func_args-3.1-kw_1.py
index 7bc81e5be..18252570c 100644
--- a/tests/bench/func_args-3.1-kw_1.py
+++ b/tests/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/bench/func_args-3.2-kw_3.py b/tests/bench/func_args-3.2-kw_3.py
index 7f9510684..deac15cb4 100644
--- a/tests/bench/func_args-3.2-kw_3.py
+++ b/tests/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/bench/func_builtin-1-enum_pos.py b/tests/bench/func_builtin-1-enum_pos.py
index 20935164e..c7c148df1 100644
--- a/tests/bench/func_builtin-1-enum_pos.py
+++ b/tests/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/bench/func_builtin-2-enum_kw.py b/tests/bench/func_builtin-2-enum_kw.py
index 6c5e44419..a25ab241c 100644
--- a/tests/bench/func_builtin-2-enum_kw.py
+++ b/tests/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/bench/funcall-1-inline.py b/tests/bench/funcall-1-inline.py
index fbeb79630..8c3f0ccd5 100644
--- a/tests/bench/funcall-1-inline.py
+++ b/tests/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/bench/funcall-2-funcall.py b/tests/bench/funcall-2-funcall.py
index d5c36c60a..a24525804 100644
--- a/tests/bench/funcall-2-funcall.py
+++ b/tests/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/bench/funcall-3-funcall-local.py b/tests/bench/funcall-3-funcall-local.py
index 1a6d728c6..d92288868 100644
--- a/tests/bench/funcall-3-funcall-local.py
+++ b/tests/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/bench/loop_count-1-range.py b/tests/bench/loop_count-1-range.py
index e22adf6cb..fdb11eaac 100644
--- a/tests/bench/loop_count-1-range.py
+++ b/tests/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/bench/loop_count-2-range_iter.py b/tests/bench/loop_count-2-range_iter.py
index fe4a3857e..4189bf329 100644
--- a/tests/bench/loop_count-2-range_iter.py
+++ b/tests/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/bench/loop_count-3-while_up.py b/tests/bench/loop_count-3-while_up.py
index 1ab8054a0..22c64403b 100644
--- a/tests/bench/loop_count-3-while_up.py
+++ b/tests/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/bench/loop_count-4-while_down_gt.py b/tests/bench/loop_count-4-while_down_gt.py
index de8dee2ca..47b004c2b 100644
--- a/tests/bench/loop_count-4-while_down_gt.py
+++ b/tests/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/bench/loop_count-5-while_down_ne.py b/tests/bench/loop_count-5-while_down_ne.py
index b9a1af414..419c817c8 100644
--- a/tests/bench/loop_count-5-while_down_ne.py
+++ b/tests/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/bench/loop_count-5.1-while_down_ne_localvar.py b/tests/bench/loop_count-5.1-while_down_ne_localvar.py
index 96bdb9129..d25102a63 100644
--- a/tests/bench/loop_count-5.1-while_down_ne_localvar.py
+++ b/tests/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/bench/var-1-constant.py b/tests/bench/var-1-constant.py
index eec977909..4a2419472 100644
--- a/tests/bench/var-1-constant.py
+++ b/tests/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/bench/var-2-global.py b/tests/bench/var-2-global.py
index 5758ad61a..a47240d64 100644
--- a/tests/bench/var-2-global.py
+++ b/tests/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/bench/var-3-local.py b/tests/bench/var-3-local.py
index 124b48429..182bb95f6 100644
--- a/tests/bench/var-3-local.py
+++ b/tests/bench/var-3-local.py
@@ -7,4 +7,5 @@ def test(num):
while i < ITERS:
i += 1
+
bench.run(test)
diff --git a/tests/bench/var-4-arg.py b/tests/bench/var-4-arg.py
index cf050c58f..b9734357c 100644
--- a/tests/bench/var-4-arg.py
+++ b/tests/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/bench/var-5-class-attr.py b/tests/bench/var-5-class-attr.py
index 02ae874ac..e10770ee5 100644
--- a/tests/bench/var-5-class-attr.py
+++ b/tests/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/bench/var-6-instance-attr.py b/tests/bench/var-6-instance-attr.py
index 787ed870f..0124ef51b 100644
--- a/tests/bench/var-6-instance-attr.py
+++ b/tests/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/bench/var-6.1-instance-attr-5.py b/tests/bench/var-6.1-instance-attr-5.py
index e8d338360..692cef20d 100644
--- a/tests/bench/var-6.1-instance-attr-5.py
+++ b/tests/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/bench/var-7-instance-meth.py b/tests/bench/var-7-instance-meth.py
index f9d463f40..2ed7800be 100644
--- a/tests/bench/var-7-instance-meth.py
+++ b/tests/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/bench/var-8-namedtuple-1st.py b/tests/bench/var-8-namedtuple-1st.py
index 90ae7209d..e3a2fa19c 100644
--- a/tests/bench/var-8-namedtuple-1st.py
+++ b/tests/bench/var-8-namedtuple-1st.py
@@ -3,10 +3,12 @@ from collections 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/bench/var-8.1-namedtuple-5th.py b/tests/bench/var-8.1-namedtuple-5th.py
index 0d5789d2e..3e5212174 100644
--- a/tests/bench/var-8.1-namedtuple-5th.py
+++ b/tests/bench/var-8.1-namedtuple-5th.py
@@ -3,10 +3,12 @@ from collections 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/circuitpython-manual/audiobusio/i2s_sample_loop.py b/tests/circuitpython-manual/audiobusio/i2s_sample_loop.py
index c0ee5de31..8b40e916d 100644
--- a/tests/circuitpython-manual/audiobusio/i2s_sample_loop.py
+++ b/tests/circuitpython-manual/audiobusio/i2s_sample_loop.py
@@ -24,8 +24,7 @@ for i in range(length):
sample = audiocore.RawSample(s16, sample_rate=8000)
-dac = audiobusio.I2SOut(bit_clock=board.D10,
- word_select=board.D11, data=board.D12)
+dac = audiobusio.I2SOut(bit_clock=board.D10, word_select=board.D11, data=board.D12)
trigger.value = False
dac.play(sample, loop=True)
diff --git a/tests/circuitpython-manual/audiobusio/pdmin_rms.py b/tests/circuitpython-manual/audiobusio/pdmin_rms.py
index 8d1595752..53a6fea15 100644
--- a/tests/circuitpython-manual/audiobusio/pdmin_rms.py
+++ b/tests/circuitpython-manual/audiobusio/pdmin_rms.py
@@ -8,19 +8,18 @@ import math
trigger = digitalio.DigitalInOut(board.D4)
trigger.switch_to_output(True)
+
def mean(values):
return sum(values) / len(values)
def normalized_rms(values):
minbuf = int(mean(values))
- samples_sum = sum(
- float(sample - minbuf) * (sample - minbuf)
- for sample in values
- )
+ samples_sum = sum(float(sample - minbuf) * (sample - minbuf) for sample in values)
return math.sqrt(samples_sum / len(values))
+
# signed 16 bit
s16 = array.array("H", [0] * 10000)
diff --git a/tests/circuitpython-manual/audiopwmio/single_buffer_loop.py b/tests/circuitpython-manual/audiopwmio/single_buffer_loop.py
index dfac475b5..6013892a9 100644
--- a/tests/circuitpython-manual/audiopwmio/single_buffer_loop.py
+++ b/tests/circuitpython-manual/audiopwmio/single_buffer_loop.py
@@ -13,12 +13,7 @@ trigger.switch_to_output(True)
length = 8000 // 440
samples = []
-sample_names = [
-"unsigned 8 bit",
-"signed 8 bit",
-"unsigned 16 bit",
-"signed 16 bit"
-]
+sample_names = ["unsigned 8 bit", "signed 8 bit", "unsigned 16 bit", "signed 16 bit"]
# unsigned 8 bit
diff --git a/tests/circuitpython-manual/busio/uart_echo.py b/tests/circuitpython-manual/busio/uart_echo.py
index f55d4db9e..d429c7781 100644
--- a/tests/circuitpython-manual/busio/uart_echo.py
+++ b/tests/circuitpython-manual/busio/uart_echo.py
@@ -9,10 +9,10 @@ u = busio.UART(tx=board.TX, rx=board.RX)
while True:
u.write(str(i).encode("utf-8"))
time.sleep(0.1)
- print(i, u.in_waiting) # should be the number of digits
+ print(i, u.in_waiting) # should be the number of digits
time.sleep(0.1)
- print(i, u.in_waiting) # should be the number of digits
+ print(i, u.in_waiting) # should be the number of digits
r = u.read(64 + 10)
- print(i, u.in_waiting) # should be 0
+ print(i, u.in_waiting) # should be 0
print(len(r), r)
i += 1
diff --git a/tests/circuitpython-manual/socketpool/client/cpy-client.py b/tests/circuitpython-manual/socketpool/client/cpy-client.py
index dcc742c9f..a6e9e6b3e 100644
--- a/tests/circuitpython-manual/socketpool/client/cpy-client.py
+++ b/tests/circuitpython-manual/socketpool/client/cpy-client.py
@@ -4,7 +4,7 @@ import ssl
import time
TIMEOUT = None
-HOST = '192.168.10.179'
+HOST = "192.168.10.179"
PORT = 5000
# Connect to wifi
@@ -19,7 +19,7 @@ with pool.socket(pool.AF_INET, pool.SOCK_STREAM) as s:
print("Connecting")
s.connect((HOST, PORT))
print("Sending")
- sent = s.send(b'Hello, world')
+ sent = s.send(b"Hello, world")
print("Receiving")
buff = bytearray(128)
numbytes = s.recv_into(buff)
diff --git a/tests/circuitpython-manual/socketpool/client/host-server.py b/tests/circuitpython-manual/socketpool/client/host-server.py
index fd7ceb7f1..49da4055f 100644
--- a/tests/circuitpython-manual/socketpool/client/host-server.py
+++ b/tests/circuitpython-manual/socketpool/client/host-server.py
@@ -20,7 +20,7 @@ with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
with conn:
s.settimeout(TIMEOUT)
- print('Connected by', addr)
+ print("Connected by", addr)
data = conn.recv(128)
print("got: " + str(data))
conn.sendall(data)
diff --git a/tests/circuitpython-manual/socketpool/datagram/ntp.py b/tests/circuitpython-manual/socketpool/datagram/ntp.py
index 31d922858..df5fadb13 100644
--- a/tests/circuitpython-manual/socketpool/datagram/ntp.py
+++ b/tests/circuitpython-manual/socketpool/datagram/ntp.py
@@ -10,7 +10,7 @@ pool = socketpool.SocketPool(wifi.radio)
# make socket
print("Creating socket")
-sock = pool.socket(pool.AF_INET,pool.SOCK_DGRAM)
+sock = pool.socket(pool.AF_INET, pool.SOCK_DGRAM)
# Fill packet
packet = bytearray(48)
diff --git a/tests/circuitpython-manual/socketpool/server/cpy-server.py b/tests/circuitpython-manual/socketpool/server/cpy-server.py
index d865156bc..bce1f9d6a 100644
--- a/tests/circuitpython-manual/socketpool/server/cpy-server.py
+++ b/tests/circuitpython-manual/socketpool/server/cpy-server.py
@@ -11,21 +11,21 @@ pool = socketpool.SocketPool(wifi.radio)
print("Finding IP address")
print(wifi.radio.ipv4_address)
HOST = str(wifi.radio.ipv4_address)
-PORT = 80 # Port to listen on
+PORT = 80 # Port to listen on
print("Creating socket")
-sock = pool.socket(pool.AF_INET,pool.SOCK_STREAM)
+sock = pool.socket(pool.AF_INET, pool.SOCK_STREAM)
sock.bind((HOST, PORT))
sock.listen(1)
print("Accepting connections")
conn, addr = sock.accept()
with conn:
- print('Connected by', addr)
+ print("Connected by", addr)
buff = bytearray(128)
print("Receiving")
numbytes = conn.recvfrom_into(buff)
- print(buff[:numbytes[0]])
+ print(buff[: numbytes[0]])
if numbytes:
print("Sending")
- conn.send(buff[:numbytes[0]])
+ conn.send(buff[: numbytes[0]])
diff --git a/tests/circuitpython-manual/socketpool/server/host-client.py b/tests/circuitpython-manual/socketpool/server/host-client.py
index b482755d8..e2cc77c4e 100644
--- a/tests/circuitpython-manual/socketpool/server/host-client.py
+++ b/tests/circuitpython-manual/socketpool/server/host-client.py
@@ -1,7 +1,7 @@
import socket
-HOST = '192.168.10.128' # The server's hostname or IP address
-PORT = 80 # The port used by the server
+HOST = "192.168.10.128" # The server's hostname or IP address
+PORT = 80 # The port used by the server
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
s.settimeout(None)
@@ -10,8 +10,8 @@ with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
s.connect((HOST, PORT))
print("Sending")
- s.send(b'Hello, world')
+ s.send(b"Hello, world")
print("Receiving")
data = s.recv(1024)
- print('Received', repr(data))
+ print("Received", repr(data))
diff --git a/tests/circuitpython/nvm_not_present.py b/tests/circuitpython/nvm_not_present.py
index 141e60b01..53ad3ada5 100644
--- a/tests/circuitpython/nvm_not_present.py
+++ b/tests/circuitpython/nvm_not_present.py
@@ -1,6 +1,7 @@
import skip_if
+
skip_if.board_not_in("gemma_m0", "trinket_m0")
import microcontroller
-assert(microcontroller.nvm == None)
+assert microcontroller.nvm == None
diff --git a/tests/circuitpython/nvm_present.py b/tests/circuitpython/nvm_present.py
index bef80dcc6..ceaadc60b 100644
--- a/tests/circuitpython/nvm_present.py
+++ b/tests/circuitpython/nvm_present.py
@@ -1,24 +1,26 @@
import skip_if
+
# TODO(tannewt): Remove this when we add nvm support to 3.x
skip_if.always()
skip_if.board_not_in("metro_m0_express", "feather_m0_express", "circuitplayground_express")
import microcontroller
import random
+
nvm = microcontroller.nvm
len(nvm)
single = random.randint(0, 255)
nvm[1] = single
-assert(nvm[1] == single)
+assert nvm[1] == single
nvm[0] = single
-assert(nvm[0] == single)
+assert nvm[0] == single
b = bytearray()
for i in range(10):
b.append(random.randint(0, 255))
microcontroller.nvm[10:20] = b
-assert(microcontroller.nvm[10:20] == b)
+assert microcontroller.nvm[10:20] == b
diff --git a/tests/cmdline/cmd_parsetree.py b/tests/cmdline/cmd_parsetree.py
index da36c8070..50da36954 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 6e99fc418..58f8a7f70 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/cpydiff/core_class_delnotimpl.py b/tests/cpydiff/core_class_delnotimpl.py
index c51c3d536..18c176e9b 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 99713e790..bdd6dd5df 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 f0823ee11..9a87b85a8 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_function_userattr.py b/tests/cpydiff/core_function_userattr.py
index 297293908..a8380c690 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 c25fbe75a..149e9a0a9 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 4a7121782..3ce2340c6 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 700620c47..62bf337a2 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 0240e5a1a..af3280c6d 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 8416e3b06..025d22637 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 e6e33a7b4..51cd4b249 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 190a3c276..8f25b0d49 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 97f988da2..337652737 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 1103f1826..24308bd90 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 a503ea4f5..4d2746d1f 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 913b734e8..ffe523786 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_struct_fewargs.py b/tests/cpydiff/modules_struct_fewargs.py
index 08d32ca67..cb6b0fd87 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 cdbb5c672..03395baad 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 1bf2a598a..7d086078a 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 8578a51e2..c308240a7 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_keywords.py b/tests/cpydiff/types_bytes_keywords.py
index 4dc383f26..550ce12bb 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 paramter, 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 2871bda6c..51b94cb71 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_exception_subclassinit.py b/tests/cpydiff/types_exception_subclassinit.py
index 39cdaf45b..ade9ebc7a 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 c8d3cfbe8..a5b591966 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 260b060ed..5d337412c 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 ac2600bd2..f222ac1cd 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 dd1d8d33d..1b83cfff6 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 b336b1a73..77a4eac1c 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 fa3f594c1..72e5105e0 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 cadf86987..5d334fea2 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_subclassequality.py b/tests/cpydiff/types_str_subclassequality.py
index 8aec1ea78..e44198fcc 100644
--- a/tests/cpydiff/types_str_subclassequality.py
+++ b/tests/cpydiff/types_str_subclassequality.py
@@ -4,8 +4,11 @@ description: Instance of a subclass of str cannot be compared for equality with
cause: Unknown
workaround: Unknown
"""
+
+
class S(str):
pass
-s = S('hello')
-print(s == 'hello')
+
+s = S("hello")
+print(s == "hello")
diff --git a/tests/cpydiff/types_str_subscrstep.py b/tests/cpydiff/types_str_subscrstep.py
index 0c2fce1b1..2d3245e55 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 59638ef0a..4890d92b4 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 2c1366522..c8e013226 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 fe81f7f93..e658f1345 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 a313170eb..097057fe9 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 8358fa55b..56593ee15 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 b6899aae9..a3ca6fcd4 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 6363c224f..b429776bc 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()
diff --git a/tests/extmod/machine_pinbase.py b/tests/extmod/machine_pinbase.py
index e91775504..f6b27d1d1 100644
--- a/tests/extmod/machine_pinbase.py
+++ b/tests/extmod/machine_pinbase.py
@@ -10,7 +10,6 @@ except AttributeError:
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 d525974e0..7a8fe14d0 100644
--- a/tests/extmod/machine_pulse.py
+++ b/tests/extmod/machine_pulse.py
@@ -11,7 +11,6 @@ except AttributeError:
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 53f4f5890..c45309840 100644
--- a/tests/extmod/machine_signal.py
+++ b/tests/extmod/machine_signal.py
@@ -11,6 +11,7 @@ except AttributeError:
print("SKIP")
raise SystemExit
+
class Pin(machine.PinBase):
def __init__(self):
self.v = 0
diff --git a/tests/extmod/time_ms_us.py b/tests/extmod/time_ms_us.py
index 135cf1e09..0e4749b89 100644
--- a/tests/extmod/time_ms_us.py
+++ b/tests/extmod/time_ms_us.py
@@ -1,4 +1,5 @@
import utime
+
try:
utime.sleep_ms
except AttributeError:
diff --git a/tests/extmod/ubinascii_a2b_base64.py b/tests/extmod/ubinascii_a2b_base64.py
index 5e642ec51..39b85274b 100644
--- a/tests/extmod/ubinascii_a2b_base64.py
+++ b/tests/extmod/ubinascii_a2b_base64.py
@@ -7,43 +7,43 @@ 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"))
# Unicode strings can be decoded
-print(binascii.a2b_base64(u'Zm9v===YmFy'))
+print(binascii.a2b_base64(u"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 283c3936d..8c63b545a 100644
--- a/tests/extmod/ubinascii_b2a_base64.py
+++ b/tests/extmod/ubinascii_b2a_base64.py
@@ -7,20 +7,20 @@ 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 '+'
try:
- print(binascii.b2a_base64(''))
+ print(binascii.b2a_base64(""))
except TypeError:
print("TypeError")
diff --git a/tests/extmod/ubinascii_crc32.py b/tests/extmod/ubinascii_crc32.py
index a826662f1..186bd699a 100644
--- a/tests/extmod/ubinascii_crc32.py
+++ b/tests/extmod/ubinascii_crc32.py
@@ -13,16 +13,16 @@ 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))))))
try:
- binascii.crc32('')
+ binascii.crc32("")
except TypeError:
print("TypeError")
diff --git a/tests/extmod/ubinascii_hexlify.py b/tests/extmod/ubinascii_hexlify.py
index dabc3c7e4..3dcf0c427 100644
--- a/tests/extmod/ubinascii_hexlify.py
+++ b/tests/extmod/ubinascii_hexlify.py
@@ -7,11 +7,11 @@ 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"))
try:
- binascii.hexlify('')
+ binascii.hexlify("")
except TypeError:
print("TypeError")
diff --git a/tests/extmod/ubinascii_micropython.py b/tests/extmod/ubinascii_micropython.py
index 77084ec9e..94e8daa55 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 41a1bd1b8..f656bcd75 100644
--- a/tests/extmod/ubinascii_unhexlify.py
+++ b/tests/extmod/ubinascii_unhexlify.py
@@ -7,20 +7,20 @@ 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"))
# Unicode strings can be decoded
-print(binascii.unhexlify('313233344142434461626364'))
+print(binascii.unhexlify("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/uctypes_32bit_intbig.py b/tests/extmod/uctypes_32bit_intbig.py
index 6b4d3d76c..eed36e877 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 37c52388d..d822faf7e 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
diff --git a/tests/extmod/uctypes_array_assign_native_le.py b/tests/extmod/uctypes_array_assign_native_le.py
index a538bf9ad..d4c27fc4b 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 84dfba0e2..f33c63b4e 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 784209f80..0619d31dc 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))
diff --git a/tests/extmod/uctypes_error.py b/tests/extmod/uctypes_error.py
index 2500e2927..fb876de6d 100644
--- a/tests/extmod/uctypes_error.py
+++ b/tests/extmod/uctypes_error.py
@@ -13,25 +13,25 @@ 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), [])
try:
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
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
except TypeError:
- print('TypeError')
+ print("TypeError")
diff --git a/tests/extmod/uctypes_le.py b/tests/extmod/uctypes_le.py
index 7df5ac090..f69da30b6 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 84ff2b84c..89e9a9e0a 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 acef47036..1fdc65849 100644
--- a/tests/extmod/uctypes_native_float.py
+++ b/tests/extmod/uctypes_native_float.py
@@ -4,17 +4,14 @@ except ImportError:
print("SKIP")
raise SystemExit
-desc = {
- "f32": uctypes.FLOAT32 | 0,
- "f64": uctypes.FLOAT64 | 0,
-}
+desc = {"f32": uctypes.FLOAT32 | 0, "f64": uctypes.FLOAT64 | 0}
data = bytearray(8)
S = uctypes.struct(uctypes.addressof(data), desc, uctypes.NATIVE)
S.f32 = 12.34
-print('%.4f' % S.f32)
+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 8bba03b38..7958e5c22 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 c310238e5..6e0018abc 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 056e45650..a69467e62 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:
@@ -29,6 +30,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 24508b1cb..8ca4d2c55 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 e42e06c92..6e52232e3 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 1ba8871bd..351632d76 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 32c740e77..9aa5d84ec 100644
--- a/tests/extmod/uctypes_sizeof_native.py
+++ b/tests/extmod/uctypes_sizeof_native.py
@@ -10,17 +10,10 @@ assert uctypes.sizeof(S1) == 0
S2 = {"a": uctypes.UINT8 | 0}
assert uctypes.sizeof(S2) == 1
-S3 = {
- "a": uctypes.UINT8 | 0,
- "b": uctypes.UINT8 | 1,
-}
+S3 = {"a": uctypes.UINT8 | 0, "b": uctypes.UINT8 | 1}
assert uctypes.sizeof(S3) == 2
-S4 = {
- "a": uctypes.UINT8 | 0,
- "b": uctypes.UINT32 | 4,
- "c": uctypes.UINT8 | 8,
-}
+S4 = {"a": uctypes.UINT8 | 0, "b": uctypes.UINT32 | 4, "c": uctypes.UINT8 | 8}
assert uctypes.sizeof(S4) == 12
S5 = {
@@ -28,10 +21,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
@@ -40,18 +30,12 @@ s5 = uctypes.struct(0, S5)
assert uctypes.sizeof(s5) == 12
assert uctypes.sizeof(s5.sub) == 2
-S6 = {
- "ptr": (uctypes.PTR | 0, uctypes.UINT8),
-}
+S6 = {"ptr": (uctypes.PTR | 0, uctypes.UINT8)}
# As if there're no other arch bitnesses
assert uctypes.sizeof(S6) in (4, 8)
-S7 = {
- "arr": (uctypes.ARRAY | 0, uctypes.UINT8 | 5),
-}
+S7 = {"arr": (uctypes.ARRAY | 0, uctypes.UINT8 | 5)}
assert uctypes.sizeof(S7) == 5
-S8 = {
- "arr": (uctypes.ARRAY | 0, 3, {"a": uctypes.UINT32 | 0, "b": uctypes.UINT8 | 4}),
-}
+S8 = {"arr": (uctypes.ARRAY | 0, 3, {"a": uctypes.UINT32 | 0, "b": uctypes.UINT8 | 4})}
assert uctypes.sizeof(S8) == 24
diff --git a/tests/extmod/uhashlib_sha1.py b/tests/extmod/uhashlib_sha1.py
index 9d6427b33..a0ad8473a 100644
--- a/tests/extmod/uhashlib_sha1.py
+++ b/tests/extmod/uhashlib_sha1.py
@@ -16,13 +16,13 @@ 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())
-sha1 = hashlib.sha1(b'hello')
+sha1 = hashlib.sha1(b"hello")
try:
- sha1.update(u'world')
+ sha1.update(u"world")
except TypeError as e:
print("TypeError")
print(sha1.digest())
diff --git a/tests/extmod/uhashlib_sha256.py b/tests/extmod/uhashlib_sha256.py
index a793ea493..ad5aa124c 100644
--- a/tests/extmod/uhashlib_sha256.py
+++ b/tests/extmod/uhashlib_sha256.py
@@ -26,20 +26,20 @@ print(hashlib.sha256(b"\xff" * 64).digest())
# 56 bytes is a boundary case in the algorithm
print(hashlib.sha256(b"\xff" * 56).digest())
-sha256 = hashlib.sha256(b'hello')
+sha256 = hashlib.sha256(b"hello")
try:
- sha256.update(u'world')
+ sha256.update(u"world")
except TypeError as e:
print("TypeError")
print(sha256.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 7c1fe4e1e..a470bb6f7 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 b1cb4a9cb..feda8a47d 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 6280fb11b..c51994ef5 100644
--- a/tests/extmod/ujson_dump_iobase.py
+++ b/tests/extmod/ujson_dump_iobase.py
@@ -7,22 +7,23 @@ 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
diff --git a/tests/extmod/ujson_dumps.py b/tests/extmod/ujson_dumps.py
index d73271801..bfdae6264 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,7 +22,7 @@ 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"))
diff --git a/tests/extmod/ujson_dumps_extra.py b/tests/extmod/ujson_dumps_extra.py
index 21a388c32..f2aa7f249 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_load.py b/tests/extmod/ujson_load.py
index 9725ab2dd..7cec9246b 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_load_readinto.py b/tests/extmod/ujson_load_readinto.py
index a277f40ef..001aa4fb2 100644
--- a/tests/extmod/ujson_load_readinto.py
+++ b/tests/extmod/ujson_load_readinto.py
@@ -2,6 +2,7 @@ import ujson as json
# Test that json can load from any object with readinto
+
class Buffer:
def __init__(self, data):
self._data = data
@@ -12,11 +13,12 @@ class Buffer:
remaining = len(self._data) - self._i
end = min(end, len(self._data))
l = min(len(buf), remaining)
- buf[:l] = self._data[self._i:end]
+ buf[:l] = self._data[self._i : end]
self._i += l
return l
-print(json.load(Buffer(b'null')))
+
+print(json.load(Buffer(b"null")))
print(json.load(Buffer(b'"abc\\u0064e"')))
-print(json.load(Buffer(b'[false, true, 1, -2]')))
+print(json.load(Buffer(b"[false, true, 1, -2]")))
print(json.load(Buffer(b'{"a":true}')))
diff --git a/tests/extmod/ujson_loads.py b/tests/extmod/ujson_loads.py
index adba3c068..2de9cdcbc 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_float.py b/tests/extmod/ujson_loads_float.py
index f1b8cc364..e368ca42e 100644
--- a/tests/extmod/ujson_loads_float.py
+++ b/tests/extmod/ujson_loads_float.py
@@ -7,11 +7,13 @@ except ImportError:
print("SKIP")
raise SystemExit
+
def my_print(o):
- print('%.3f' % 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("1.2"))
+my_print(json.loads("1e2"))
+my_print(json.loads("-2.3"))
+my_print(json.loads("-2e3"))
+my_print(json.loads("-2e-3"))
diff --git a/tests/extmod/umsgpack_pack.py b/tests/extmod/umsgpack_pack.py
index d9f0005e1..7ea5ae8d6 100644
--- a/tests/extmod/umsgpack_pack.py
+++ b/tests/extmod/umsgpack_pack.py
@@ -20,11 +20,11 @@ print(b.getvalue())
# pack to a small-int not allowed
try:
msgpack.pack(123, 1)
-except (AttributeError, OSError): # CPython and uPy have different errors
- print('Exception')
+except (AttributeError, OSError): # CPython and uPy have different errors
+ print("Exception")
# pack to an object not allowed
try:
msgpack.pack(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/urandom_basic.py b/tests/extmod/urandom_basic.py
index 57e6b26cb..180197398 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 f5a34e168..636a22539 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,13 +66,13 @@ for i in range(50):
try:
random.choice([])
except IndexError:
- print('IndexError')
+ print("IndexError")
-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 710720c8b..d1cb9a05d 100644
--- a/tests/extmod/ure1.py
+++ b/tests/extmod/ure1.py
@@ -83,11 +83,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$")
@@ -100,4 +105,5 @@ 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))
diff --git a/tests/extmod/ure_debug.py b/tests/extmod/ure_debug.py
index cfb264bb6..4cef4c98a 100644
--- a/tests/extmod/ure_debug.py
+++ b/tests/extmod/ure_debug.py
@@ -5,4 +5,4 @@ except ImportError:
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 f52f735c7..a99a47f97 100644
--- a/tests/extmod/ure_error.py
+++ b/tests/extmod/ure_error.py
@@ -9,17 +9,19 @@ 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"?")
+test_re(r"*")
+test_re(r"+")
+test_re(r")")
+test_re(r"[")
+test_re(r"([")
+test_re(r"([)")
diff --git a/tests/extmod/ure_group.py b/tests/extmod/ure_group.py
index 4e39468c5..41425dd62 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 4fac896d7..7da072a92 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 215d09613..00d58ad98 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 50f44399c..03a3fef9f 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 da6e9652d..51bad791e 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 f5a19af8d..6bb332077 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 4795b3196..d6312bfc2 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/ussl_basic.py b/tests/extmod/ussl_basic.py
index e8710ed51..c8bdc81a4 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()
@@ -24,22 +24,22 @@ print(repr(ss)[:12])
try:
ss.setblocking(False)
except NotImplementedError:
- print('setblocking: NotImplementedError')
+ print("setblocking: NotImplementedError")
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()
@@ -50,10 +50,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/utimeq1.py b/tests/extmod/utimeq1.py
index dc7f3b660..234d7a31d 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 112a82597..6a0aae8bc 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 02087f763..1bc8ba885 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 dd6e4876f..8d4a9640b 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}<e\xb5g\x83\x0f\x89X\x07\xab'),
+ (
+ b"13371813150|13764518736|12345678901",
+ b"x\x9c\x05\xc1\x81\x01\x000\x04\x04\xb1\x95\\\x1f\xcfn\x86o\x82d\x06Qq\xc8\x9d\xc5X}<e\xb5g\x83\x0f\x89X\x07\xab",
+ ),
# dynamic Huffman tree with "case 17" (repeat code for 3-10 times)
- (b'>I}\x00\x951D>I}\x00\x951D>I}\x00\x951D>I}\x00\x951D', b'x\x9c\x05\xc11\x01\x00\x00\x00\x010\x95\x14py\x84\x12C_\x9bR\x8cV\x8a\xd1J1Z)F\x1fw`\x089'),
+ (
+ 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 fbcc92bad..c8e203b3d 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_fat_fileio1.py b/tests/extmod/vfs_fat_fileio1.py
index 4635ca84b..85a715870 100644
--- a/tests/extmod/vfs_fat_fileio1.py
+++ b/tests/extmod/vfs_fat_fileio1.py
@@ -20,19 +20,19 @@ 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]
return 0
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]
return 0
def ioctl(self, op, arg):
- #print("ioctl(%d, %r)" % (op, arg))
+ # print("ioctl(%d, %r)" % (op, arg))
if op == 4: # BP_IOCTL_SEC_COUNT
return len(self.data) // self.SEC_SIZE
if op == 5: # BP_IOCTL_SEC_SIZE
@@ -47,8 +47,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")
@@ -56,7 +56,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:
@@ -84,21 +84,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
@@ -107,7 +107,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()))
@@ -117,23 +117,25 @@ print(list(vfs.ilistdir()))
# 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_fileio2.py b/tests/extmod/vfs_fat_fileio2.py
index ab9623ddf..2b8c8155c 100644
--- a/tests/extmod/vfs_fat_fileio2.py
+++ b/tests/extmod/vfs_fat_fileio2.py
@@ -20,19 +20,19 @@ 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]
return 0
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]
return 0
def ioctl(self, op, arg):
- #print("ioctl(%d, %r)" % (op, arg))
+ # print("ioctl(%d, %r)" % (op, arg))
if op == 4: # BP_IOCTL_SEC_COUNT
return len(self.data) // self.SEC_SIZE
if op == 5: # BP_IOCTL_SEC_SIZE
@@ -47,8 +47,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")
@@ -113,4 +113,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_more.py b/tests/extmod/vfs_fat_more.py
index 8ddaf49fc..acae8c584 100644
--- a/tests/extmod/vfs_fat_more.py
+++ b/tests/extmod/vfs_fat_more.py
@@ -1,4 +1,5 @@
import uerrno
+
try:
import uos
except ImportError:
@@ -20,19 +21,19 @@ 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]
return 0
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]
return 0
def ioctl(self, op, arg):
- #print("ioctl(%d, %r)" % (op, arg))
+ # print("ioctl(%d, %r)" % (op, arg))
if op == 4: # BP_IOCTL_SEC_COUNT
return len(self.data) // self.SEC_SIZE
if op == 5: # BP_IOCTL_SEC_SIZE
@@ -48,75 +49,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 b671f3db2..e447ff4eb 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,13 +20,13 @@ 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]
return 0
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]
return 0
diff --git a/tests/extmod/vfs_fat_ramdisk.py b/tests/extmod/vfs_fat_ramdisk.py
index 30a94ec4e..c883d522c 100644
--- a/tests/extmod/vfs_fat_ramdisk.py
+++ b/tests/extmod/vfs_fat_ramdisk.py
@@ -20,19 +20,19 @@ 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]
return 0
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]
return 0
def ioctl(self, op, arg):
- #print("ioctl(%d, %r)" % (op, arg))
+ # print("ioctl(%d, %r)" % (op, arg))
if op == 4: # BP_IOCTL_SEC_COUNT
return len(self.data) // self.SEC_SIZE
if op == 5: # BP_IOCTL_SEC_SIZE
@@ -53,7 +53,7 @@ print(b"hello!" not in bdev.data)
vfs = uos.VfsFat(bdev)
uos.mount(vfs, "/ramdisk")
-vfs.label = 'label test'
+vfs.label = "label test"
print("label:", vfs.label)
print("statvfs:", vfs.statvfs("/ramdisk"))
print("getcwd:", vfs.getcwd())
@@ -68,7 +68,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)
@@ -98,4 +98,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_userfs.py b/tests/extmod/vfs_userfs.py
index e913f9748..60bf4d099 100644
--- a/tests/extmod/vfs_userfs.py
+++ b/tests/extmod/vfs_userfs.py
@@ -6,6 +6,7 @@ import sys, uio
try:
uio.IOBase
import uos
+
uos.mount
except (ImportError, AttributeError):
print("SKIP")
@@ -16,8 +17,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):
@@ -25,44 +28,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 9a80503a0..8c5cf5825 100644
--- a/tests/extmod/websocket_basic.py
+++ b/tests/extmod/websocket_basic.py
@@ -11,6 +11,7 @@ def ws_read(msg, sz):
ws = websocket.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 = websocket.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 = websocket.websocket(uio.BytesIO())
@@ -51,8 +53,8 @@ ws.close()
# ioctl
ws = websocket.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 d60f93956..c82a41a24 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/coverage.py b/tests/feature_check/coverage.py
index dcda53eae..82647ee31 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 af93f5976..d6d2a99d2 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 668748bc5..68eb91b44 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/float/array_construct.py b/tests/float/array_construct.py
index 938675835..6b5c99631 100644
--- a/tests/float/array_construct.py
+++ b/tests/float/array_construct.py
@@ -6,5 +6,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_hash.py b/tests/float/builtin_float_hash.py
index 7a7e37401..f77b1a183 100644
--- a/tests/float/builtin_float_hash.py
+++ b/tests/float/builtin_float_hash.py
@@ -1,25 +1,9 @@
# test builtin hash function with float args
# these should hash to an integer with a specific value
-for val in (
- '0.0',
- '-0.0',
- '1.0',
- '2.0',
- '-12.0',
- '12345.0',
- ):
+for val in ("0.0", "-0.0", "1.0", "2.0", "-12.0", "12345.0"):
print(val, hash(float(val)))
# just check that these values are hashable
-for val in (
- '0.1',
- '-0.1',
- '10.3',
- '0.4e3',
- '1e16',
- 'inf',
- '-inf',
- 'nan',
- ):
+for val in ("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_pow.py b/tests/float/builtin_float_pow.py
index 2de1b4817..98998bdc7 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 63cb39aa3..1153b8a2b 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 2083e3ea3..c8a338eef 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 e960d624e..f84fa7be5 100644
--- a/tests/float/bytearray_construct.py
+++ b/tests/float/bytearray_construct.py
@@ -6,4 +6,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 0e4482e43..c24263758 100644
--- a/tests/float/bytes_construct.py
+++ b/tests/float/bytes_construct.py
@@ -6,4 +6,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 ae5921c30..26f6c227c 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) < 1e15:
- 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 471fda8c0..1d9abac6b 100644
--- a/tests/float/cmath_fun_special.py
+++ b/tests/float/cmath_fun_special.py
@@ -2,27 +2,26 @@
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),
-]
+functions = [("log10", log10, test_values_non_zero)]
for f_name, f, test_vals in functions:
print(f_name)
diff --git a/tests/float/complex1.py b/tests/float/complex1.py
index 479b4b348..e6338551c 100644
--- a/tests/float/complex1.py
+++ b/tests/float/complex1.py
@@ -27,18 +27,23 @@ 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)
print(1j == 1j)
# comparison of nan is special
-nan = float('nan') * 1j
+nan = float("nan") * 1j
print(nan == 1j)
print(nan == nan)
@@ -54,20 +59,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:
@@ -93,11 +100,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 ed2390bba..864036b99 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 54807e5ac..e51e96fd9 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
@@ -66,7 +66,7 @@ print(1.2 >= 3.4)
print(1.2 >= -3.4)
# comparison of nan is special
-nan = float('nan')
+nan = float("nan")
print(nan == 1.2)
print(nan == nan)
@@ -106,7 +106,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 de2137d66..24d30fe69 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 fbb94a4cc..da3980040 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 3596d2f73..30522d44f 100644
--- a/tests/float/float2int_intbig.py
+++ b/tests/float/float2int_intbig.py
@@ -32,30 +32,31 @@ if ll_type is None:
# basic conversion
-print(int(14187745.))
-print("%d" % 14187745.)
+print(int(14187745.0))
+print("%d" % 14187745.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 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 +64,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 8c8edcff7..04212c44f 100644
--- a/tests/float/float_array.py
+++ b/tests/float/float_array.py
@@ -4,17 +4,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'))
+test(array("f"))
+test(array("d"))
-print('{:.4f}'.format(array('f', b'\xcc\xcc\xcc=')[0]))
+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 105923ac7..c177aa7e8 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 8e7cd435a..ec83ce2d1 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 a9450fa2c..ef5a6ad2e 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 d43535cf2..4c8a21756 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 4b026de1c..bef1122ac 100644
--- a/tests/float/float_parse.py
+++ b/tests/float/float_parse.py
@@ -1,32 +1,32 @@
# 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"))
diff --git a/tests/float/float_parse_doubleprec.py b/tests/float/float_parse_doubleprec.py
index dcc0dd592..81fcadcee 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 dd7a418ad..18893af0e 100644
--- a/tests/float/float_struct.py
+++ b/tests/float/float_struct.py
@@ -8,10 +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'):
-for fmt in ('f', 'd', '>f', '>d', '<f', '<d'):
+for fmt in ("f", "d", ">f", ">d", "<f", "<d"):
x = struct.pack(fmt, i)
v = struct.unpack(fmt, x)[0]
- print('%2s: %.17f - %s' % (fmt, v, (i == v) and 'passed' or 'failed'))
+ print("%2s: %.17f - %s" % (fmt, v, (i == v) and "passed" or "failed"))
diff --git a/tests/float/int_power.py b/tests/float/int_power.py
index 649d4d415..ba79247a5 100644
--- a/tests/float/int_power.py
+++ b/tests/float/int_power.py
@@ -5,4 +5,4 @@ print(x ** -2)
x = 3
x **= -2
-print('%.5f' % x)
+print("%.5f" % x)
diff --git a/tests/float/math_domain.py b/tests/float/math_domain.py
index 0cf10fb2a..2d4670f75 100644
--- a/tests/float/math_domain.py
+++ b/tests/float/math_domain.py
@@ -6,46 +6,46 @@ except ImportError:
print("SKIP")
raise SystemExit
-inf = float('inf')
-nan = float('nan')
+inf = float("inf")
+nan = float("nan")
# single argument functions
for name, f, args in (
- ('fabs', math.fabs, ()),
- ('ceil', math.ceil, ()),
- ('floor', math.floor, ()),
- ('trunc', math.trunc, ()),
- ('sqrt', math.sqrt, (-1, 0)),
- ('exp', math.exp, ()),
- ('sin', math.sin, ()),
- ('cos', math.cos, ()),
- ('tan', math.tan, ()),
- ('asin', math.asin, (-1.1, 1, 1.1)),
- ('acos', math.acos, (-1.1, 1, 1.1)),
- ('atan', math.atan, ()),
- ('ldexp', lambda x: math.ldexp(x, 0), ()),
- ('radians', math.radians, ()),
- ('degrees', math.degrees, ()),
- ):
+ ("fabs", math.fabs, ()),
+ ("ceil", math.ceil, ()),
+ ("floor", math.floor, ()),
+ ("trunc", math.trunc, ()),
+ ("sqrt", math.sqrt, (-1, 0)),
+ ("exp", math.exp, ()),
+ ("sin", math.sin, ()),
+ ("cos", math.cos, ()),
+ ("tan", math.tan, ()),
+ ("asin", math.asin, (-1.1, 1, 1.1)),
+ ("acos", math.acos, (-1.1, 1, 1.1)),
+ ("atan", math.atan, ()),
+ ("ldexp", lambda x: math.ldexp(x, 0), ()),
+ ("radians", math.radians, ()),
+ ("degrees", math.degrees, ()),
+):
for x in args + (inf, nan):
try:
ans = f(x)
- print('%.4f' % ans)
+ print("%.4f" % ans)
except ValueError:
- print(name, 'ValueError')
+ print(name, "ValueError")
except OverflowError:
- print(name, 'OverflowError')
+ print(name, "OverflowError")
# double argument functions
for name, f, args in (
- ('pow', math.pow, ((0, 2), (-1, 2), (0, -1), (-1, 2.3))),
- ('fmod', math.fmod, ((1.2, inf), (1.2, 0), (inf, 1.2))),
- ('atan2', math.atan2, ((0, 0),)),
- ('copysign', math.copysign, ()),
- ):
+ ("pow", math.pow, ((0, 2), (-1, 2), (0, -1), (-1, 2.3))),
+ ("fmod", math.fmod, ((1.2, inf), (1.2, 0), (inf, 1.2))),
+ ("atan2", math.atan2, ((0, 0),)),
+ ("copysign", math.copysign, ()),
+):
for x in args + ((0, inf), (inf, 0), (inf, inf), (inf, nan), (nan, inf), (nan, nan)):
try:
ans = f(*x)
- print('%.4f' % ans)
+ print("%.4f" % ans)
except ValueError:
- print(name, 'ValueError')
+ print(name, "ValueError")
diff --git a/tests/float/math_domain_special.py b/tests/float/math_domain_special.py
index 388920350..e5bfa9f03 100644
--- a/tests/float/math_domain_special.py
+++ b/tests/float/math_domain_special.py
@@ -2,35 +2,36 @@
try:
import math
+
math.erf
except (ImportError, AttributeError):
print("SKIP")
raise SystemExit
-inf = float('inf')
-nan = float('nan')
+inf = float("inf")
+nan = float("nan")
# single argument functions
for name, f, args in (
- ('expm1', math.exp, ()),
- ('log2', math.log2, (-1, 0)),
- ('log10', math.log10, (-1, 0)),
- ('sinh', math.sinh, ()),
- ('cosh', math.cosh, ()),
- ('tanh', math.tanh, ()),
- ('asinh', math.asinh, ()),
- ('acosh', math.acosh, (-1, 0.9, 1)),
- ('atanh', math.atanh, (-1, 1)),
- ('erf', math.erf, ()),
- ('erfc', math.erfc, ()),
- ('gamma', math.gamma, (-2, -1, 0, 1)),
- ('lgamma', math.lgamma, (-2, -1, 0, 1)),
- ):
+ ("expm1", math.exp, ()),
+ ("log2", math.log2, (-1, 0)),
+ ("log10", math.log10, (-1, 0)),
+ ("sinh", math.sinh, ()),
+ ("cosh", math.cosh, ()),
+ ("tanh", math.tanh, ()),
+ ("asinh", math.asinh, ()),
+ ("acosh", math.acosh, (-1, 0.9, 1)),
+ ("atanh", math.atanh, (-1, 1)),
+ ("erf", math.erf, ()),
+ ("erfc", math.erfc, ()),
+ ("gamma", math.gamma, (-2, -1, 0, 1)),
+ ("lgamma", math.lgamma, (-2, -1, 0, 1)),
+):
for x in args + (inf, nan):
try:
ans = f(x)
- print('%.4f' % ans)
+ print("%.4f" % ans)
except ValueError:
- print(name, 'ValueError')
+ print(name, "ValueError")
except OverflowError:
- print(name, 'OverflowError')
+ print(name, "OverflowError")
diff --git a/tests/float/math_fun.py b/tests/float/math_fun.py
index 2835b9bfb..dac57d782 100644
--- a/tests/float/math_fun.py
+++ b/tests/float/math_fun.py
@@ -6,26 +6,36 @@ except ImportError:
print("SKIP")
raise SystemExit
-test_values = [-100., -1.23456, -1, -0.5, 0.0, 0.5, 1.23456, 100.]
-test_values_small = [-10., -1.23456, -1, -0.5, 0.0, 0.5, 1.23456, 10.] # so we don't overflow 32-bit precision
-unit_range_test_values = [-1., -0.75, -0.5, -0.25, 0., 0.25, 0.5, 0.75, 1.]
-
-functions = [('sqrt', sqrt, test_values),
- ('exp', exp, test_values_small),
- ('log', log, test_values),
- ('cos', cos, test_values),
- ('sin', sin, test_values),
- ('tan', tan, test_values),
- ('acos', acos, unit_range_test_values),
- ('asin', asin, unit_range_test_values),
- ('atan', atan, test_values),
- ('ceil', ceil, test_values),
- ('fabs', fabs, test_values),
- ('floor', floor, test_values),
- ('trunc', trunc, test_values),
- ('radians', radians, test_values),
- ('degrees', degrees, test_values),
- ]
+test_values = [-100.0, -1.23456, -1, -0.5, 0.0, 0.5, 1.23456, 100.0]
+test_values_small = [
+ -10.0,
+ -1.23456,
+ -1,
+ -0.5,
+ 0.0,
+ 0.5,
+ 1.23456,
+ 10.0,
+] # so we don't overflow 32-bit precision
+unit_range_test_values = [-1.0, -0.75, -0.5, -0.25, 0.0, 0.25, 0.5, 0.75, 1.0]
+
+functions = [
+ ("sqrt", sqrt, test_values),
+ ("exp", exp, test_values_small),
+ ("log", log, test_values),
+ ("cos", cos, test_values),
+ ("sin", sin, test_values),
+ ("tan", tan, test_values),
+ ("acos", acos, unit_range_test_values),
+ ("asin", asin, unit_range_test_values),
+ ("atan", atan, test_values),
+ ("ceil", ceil, test_values),
+ ("fabs", fabs, test_values),
+ ("floor", floor, test_values),
+ ("trunc", trunc, test_values),
+ ("radians", radians, test_values),
+ ("degrees", degrees, test_values),
+]
for function_name, function, test_vals in functions:
print(function_name)
@@ -35,9 +45,7 @@ for function_name, function, test_vals in functions:
except ValueError as e:
print(str(e))
-tuple_functions = [('frexp', frexp, test_values),
- ('modf', modf, test_values),
- ]
+tuple_functions = [("frexp", frexp, test_values), ("modf", modf, test_values)]
for function_name, function, test_vals in tuple_functions:
print(function_name)
@@ -45,14 +53,17 @@ for function_name, function, test_vals in tuple_functions:
x, y = function(value)
print("{:.5g} {:.5g}".format(x, y))
-binary_functions = [('copysign', copysign, [(23., 42.), (-23., 42.), (23., -42.),
- (-23., -42.), (1., 0.0), (1., -0.0)]),
- ('pow', pow, ((1., 0.), (0., 1.), (2., 0.5), (-3., 5.), (-3., -4.),)),
- ('atan2', atan2, ((1., 0.), (0., 1.), (2., 0.5), (-3., 5.), (-3., -4.),)),
- ('fmod', fmod, ((1., 1.), (0., 1.), (2., 0.5), (-3., 5.), (-3., -4.),)),
- ('ldexp', ldexp, ((1., 0), (0., 1), (2., 2), (3., -2), (-3., -4),)),
- ('log', log, ((2., 2.), (3., 2.), (4., 5.), (0., 1.), (1., 0.), (-1., 1.), (1., -1.), (2., 1.))),
- ]
+binary_functions = [
+ (
+ "copysign",
+ copysign,
+ [(23.0, 42.0), (-23.0, 42.0), (23.0, -42.0), (-23.0, -42.0), (1.0, 0.0), (1.0, -0.0)],
+ ),
+ ("pow", pow, ((1.0, 0.0), (0.0, 1.0), (2.0, 0.5), (-3.0, 5.0), (-3.0, -4.0))),
+ ("atan2", atan2, ((1.0, 0.0), (0.0, 1.0), (2.0, 0.5), (-3.0, 5.0), (-3.0, -4.0))),
+ ("fmod", fmod, ((1.0, 1.0), (0.0, 1.0), (2.0, 0.5), (-3.0, 5.0), (-3.0, -4.0))),
+ ("ldexp", ldexp, ((1.0, 0), (0.0, 1), (2.0, 2), (3.0, -2), (-3.0, -4))),
+]
for function_name, function, test_vals in binary_functions:
print(function_name)
diff --git a/tests/float/math_fun_bool.py b/tests/float/math_fun_bool.py
index 761871b41..6e9af0dd3 100644
--- a/tests/float/math_fun_bool.py
+++ b/tests/float/math_fun_bool.py
@@ -6,8 +6,7 @@ except ImportError:
print("SKIP")
raise SystemExit
-test_values = [1, 0, -1, 1.0, 0.0, -1.0, float('NaN'), float('Inf'),
- -float('NaN'), -float('Inf')]
+test_values = [1, 0, -1, 1.0, 0.0, -1.0, float("NaN"), float("Inf"), -float("NaN"), -float("Inf")]
functions = [isfinite, isnan, isinf]
diff --git a/tests/float/math_fun_int.py b/tests/float/math_fun_int.py
index 5cadbb1e5..2cabad4e0 100644
--- a/tests/float/math_fun_int.py
+++ b/tests/float/math_fun_int.py
@@ -7,7 +7,7 @@ except ImportError:
raise SystemExit
for fun in (math.ceil, math.floor, math.trunc):
- for x in (-1.6, -0.2, 0, 0.6, 1.4, float('inf'), float('nan')):
+ for x in (-1.6, -0.2, 0, 0.6, 1.4, float("inf"), float("nan")):
try:
print(fun(x))
except (ValueError, OverflowError) as e:
diff --git a/tests/float/math_fun_intbig.py b/tests/float/math_fun_intbig.py
index 697ca7a6d..7169b8017 100644
--- a/tests/float/math_fun_intbig.py
+++ b/tests/float/math_fun_intbig.py
@@ -8,4 +8,4 @@ except ImportError:
for fun in (math.ceil, math.floor, math.trunc):
for x in (-1e25, 1e25):
- print('%.3g' % fun(x))
+ print("%.3g" % fun(x))
diff --git a/tests/float/math_fun_special.py b/tests/float/math_fun_special.py
index c3665a7cd..f4e53e891 100644
--- a/tests/float/math_fun_special.py
+++ b/tests/float/math_fun_special.py
@@ -2,28 +2,29 @@
try:
from math import *
+
erf
except (ImportError, NameError):
print("SKIP")
raise SystemExit
-test_values = [-8., -2.5, -1, -0.5, 0.0, 0.5, 2.5, 8.,]
-pos_test_values = [0.001, 0.1, 0.5, 1.0, 1.5, 10.,]
+test_values = [-8.0, -2.5, -1, -0.5, 0.0, 0.5, 2.5, 8.0]
+pos_test_values = [0.001, 0.1, 0.5, 1.0, 1.5, 10.0]
functions = [
- ('expm1', expm1, test_values),
- ('log2', log2, test_values),
- ('log10', log10, test_values),
- ('cosh', cosh, test_values),
- ('sinh', sinh, test_values),
- ('tanh', tanh, test_values),
- ('acosh', acosh, [1.0, 5.0, 1.0]),
- ('asinh', asinh, test_values),
- ('atanh', atanh, [-0.99, -0.5, 0.0, 0.5, 0.99]),
- ('erf', erf, test_values),
- ('erfc', erfc, test_values),
- ('gamma', gamma, pos_test_values),
- ('lgamma', lgamma, pos_test_values + [50., 100.,]),
+ ("expm1", expm1, test_values),
+ ("log2", log2, test_values),
+ ("log10", log10, test_values),
+ ("cosh", cosh, test_values),
+ ("sinh", sinh, test_values),
+ ("tanh", tanh, test_values),
+ ("acosh", acosh, [1.0, 5.0, 1.0]),
+ ("asinh", asinh, test_values),
+ ("atanh", atanh, [-0.99, -0.5, 0.0, 0.5, 0.99]),
+ ("erf", erf, test_values),
+ ("erfc", erfc, test_values),
+ ("gamma", gamma, pos_test_values),
+ ("lgamma", lgamma, pos_test_values + [50.0, 100.0]),
]
for function_name, function, test_vals in functions:
diff --git a/tests/float/python36.py b/tests/float/python36.py
index 6e8fb1f21..9e64e7a06 100644
--- a/tests/float/python36.py
+++ b/tests/float/python36.py
@@ -2,9 +2,9 @@
# underscores in numeric literals
print(1_000.1_8)
-print('%.2g' % 1e1_2)
+print("%.2g" % 1e1_2)
# underscore supported by int/float constructors
-print(float('1_2_3'))
-print(float('1_2_3.4'))
-print('%.2g' % float('1e1_3'))
+print(float("1_2_3"))
+print(float("1_2_3.4"))
+print("%.2g" % float("1e1_3"))
diff --git a/tests/float/string_format.py b/tests/float/string_format.py
index 6fb11c35a..92632fe5e 100644
--- a/tests/float/string_format.py
+++ b/tests/float/string_format.py
@@ -1,5 +1,6 @@
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)
@@ -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_format2.py b/tests/float/string_format2.py
index 269023e7f..7a36f4d2f 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 77b2a5288..5f0b213da 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 aea534247..094461538 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 f6b1ae537..b22021c5d 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 9992ba65d..8110bc7f6 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 5d26f2575..f9d9c43cd 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 df415f003..4c8d2e5c8 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 088f631fc..5258da891 100644
--- a/tests/import/builtin_import.py
+++ b/tests/import/builtin_import.py
@@ -1,16 +1,16 @@
# 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")
# 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 02f153146..b7567cf02 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 16b2d4d30..9d7d72ff7 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 be74eca09..8c9d15a71 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 def6aeb6a..8fb490525 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 2e9d41f71..2fadd8a52 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 cb9a88a70..90ec4e41e 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_pkg1.py b/tests/import/import_pkg1.py
index fe6e4473e..5c1b2ef4c 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 0ee885b22..ec4697906 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/mpy_invalid.py b/tests/import/mpy_invalid.py
index b9dd99a44..188fb1612 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,37 +35,41 @@ 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
+ "/mod0.mpy": b"", # empty file
+ "/mod1.mpy": b"M", # too short header
+ "/mod2.mpy": b"M\x00\x00\x00", # bad version
}
# 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 Exception as e:
print(mod, type(e).__name__, e)
# 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 67f43bad5..37721faaf 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 923531c1b..5215da2ec 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 6b8b84d0e..80817917d 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 e8d863c6c..0abc82404 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 6b574114d..0a5eb1505 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 039a5d174..657a6fb52 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 c73e2081f..0aa916d20 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 b98f02ce6..3d3d53a16 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 03a9db15b..7c97df28b 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 047d9ed42..3b03f1510 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 540fa6591..08967d48c 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 8cf92b301..d1c8a9823 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 d08c0ed6b..43585dddc 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 299a25093..8412dd2c7 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 b97d566eb..c27846384 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 2bdfccf0e..f69c89cdc 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,4 +11,5 @@ def add_sub(r0, r1, r2):
vcvt_s32_f32(s31, s0)
vmov(r0, s31)
+
print(add_sub(100, 20, 30))
diff --git a/tests/inlineasm/asmfpcmp.py b/tests/inlineasm/asmfpcmp.py
index d4fa1f241..47fd99a34 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 4c480671f..c65f8a798 100644
--- a/tests/inlineasm/asmfpldrstr.py
+++ b/tests/inlineasm/asmfpldrstr.py
@@ -1,11 +1,14 @@
import 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 043a28e22..930ddd053 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,4 +11,5 @@ def muldiv(r0, r1, r2):
vcvt_s32_f32(s31, s8)
vmov(r0, s31)
+
print(muldiv(100, 10, 50))
diff --git a/tests/inlineasm/asmfpsqrt.py b/tests/inlineasm/asmfpsqrt.py
index 7b7d52e23..519fde4fc 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,4 +11,5 @@ def sqrt_test(r0, r1):
vcvt_s32_f32(s31, s7)
vmov(r0, s31)
+
print(sqrt_test(256, 10))
diff --git a/tests/inlineasm/asmit.py b/tests/inlineasm/asmit.py
index 57bfcc7f9..640258e7c 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 c9005434b..74e729dfa 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 f1918696e..95068795d 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 0df218734..ba4c21b3f 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 2d3b0e396..053ae29a4 100644
--- a/tests/inlineasm/asmspecialregs.py
+++ b/tests/inlineasm/asmspecialregs.py
@@ -2,9 +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 07e71c738..f465b25af 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,12 +47,13 @@ def asm_sum_bytes(r0, r1):
mov(r0, r2)
+
import 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)
diff --git a/tests/io/argv.py b/tests/io/argv.py
index a13f2cad2..53254da11 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/buffered_writer.py b/tests/io/buffered_writer.py
index c2cedb991..64e5fa1ee 100644
--- a/tests/io/buffered_writer.py
+++ b/tests/io/buffered_writer.py
@@ -4,7 +4,7 @@ try:
io.BytesIO
io.BufferedWriter
except AttributeError:
- print('SKIP')
+ print("SKIP")
raise SystemExit
bts = io.BytesIO()
diff --git a/tests/io/builtin_print_file.py b/tests/io/builtin_print_file.py
index d9b8e2a96..822356a6c 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 af4176b64..2a46c9c63 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 cbefc6e04..1f3702a21 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 25e76597b..86d010eaf 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 10fb1fd06..2fe57692c 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 ee1e70242..899c0f928 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/iobase.py b/tests/io/iobase.py
index 6f554b00f..667e62985 100644
--- a/tests/io/iobase.py
+++ b/tests/io/iobase.py
@@ -6,14 +6,15 @@ except:
try:
io.IOBase
except AttributeError:
- print('SKIP')
+ print("SKIP")
raise SystemExit
class MyIO(io.IOBase):
def write(self, buf):
# CPython and uPy pass in different types for buf (str vs bytearray)
- print('write', len(buf))
+ print("write", len(buf))
return len(buf)
-print('test', file=MyIO())
+
+print("test", file=MyIO())
diff --git a/tests/io/resource_stream.py b/tests/io/resource_stream.py
index 37d985bf1..5656205b6 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/io/stringio1.py b/tests/io/stringio1.py
index 9f7c1e44e..6d8491754 100644
--- a/tests/io/stringio1.py
+++ b/tests/io/stringio1.py
@@ -4,7 +4,7 @@ except ImportError:
import io
a = io.StringIO()
-print('io.StringIO' in repr(a))
+print("io.StringIO" in repr(a))
print(a.getvalue())
print(a.read())
@@ -35,7 +35,7 @@ print(a.read())
a = io.StringIO()
a.close()
-for f in [a.read, a.getvalue, lambda:a.write("")]:
+for f in [a.read, a.getvalue, lambda: a.write("")]:
# CPython throws for operations on closed I/O, MicroPython makes
# the underlying string empty unless MICROPY_CPYTHON_COMPAT defined
try:
diff --git a/tests/io/write_ext.py b/tests/io/write_ext.py
index 5a6eaa35c..18cd75ddb 100644
--- a/tests/io/write_ext.py
+++ b/tests/io/write_ext.py
@@ -5,7 +5,7 @@ import uio
try:
uio.BytesIO
except AttributeError:
- print('SKIP')
+ print("SKIP")
raise SystemExit
buf = uio.BytesIO()
diff --git a/tests/jni/list.py b/tests/jni/list.py
index d58181d0b..7630a48e8 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 aa67615ec..8fbdb39d3 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 86c4b9e11..c34d7011f 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 660a095f2..1faf22be9 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 60085a1e0..ed4720122 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 6d3d135b5..311cfb4d5 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 e74902652..27990c8c2 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 bf688968a..2e7cf1777 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 c7da3119f..94772ac1e 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 4a9fa18bc..bca4d2d9f 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/extreme_exc.py b/tests/micropython/extreme_exc.py
index b9db96406..dae5b1518 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 ca3f5806a..855893537 100644
--- a/tests/micropython/heap_lock.py
+++ b/tests/micropython/heap_lock.py
@@ -11,13 +11,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")
micropython.heap_unlock()
diff --git a/tests/micropython/heapalloc.py b/tests/micropython/heapalloc.py
index f74bb92c8..99f157105 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 cd76f5807..3b9f14127 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 fb63a84bf..99810e007 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_inst_call.py b/tests/micropython/heapalloc_inst_call.py
index 3cc497b73..14d8826bf 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 163e17211..f80a099e9 100644
--- a/tests/micropython/heapalloc_iter.py
+++ b/tests/micropython/heapalloc_iter.py
@@ -9,7 +9,8 @@ except (NameError, 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()
@@ -17,16 +18,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))
@@ -34,7 +37,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)
@@ -42,7 +45,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)
@@ -58,7 +61,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 a8c23393e..51afae3d8 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 813dea4b2..eabd09388 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/kbd_intr.py b/tests/micropython/kbd_intr.py
index 879c9a229..81977aaa5 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 698bbbd21..9df341fbb 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 78e4d2473..dee3a4ce2 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 6c0592e52..07014e90d 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_intbig.py b/tests/micropython/native_const_intbig.py
index 611b39d8f..69bc1d216 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_misc.py b/tests/micropython/native_misc.py
index 0cd521de6..7c5415375 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/opt_level.py b/tests/micropython/opt_level.py
index 5a10047f0..3213dc003 100644
--- a/tests/micropython/opt_level.py
+++ b/tests/micropython/opt_level.py
@@ -8,12 +8,12 @@ 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")
# 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 74f90cb2d..6a91459ea 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 bc714755a..266885d9d 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 cd953ce07..a696b0662 100644
--- a/tests/micropython/viper_addr.py
+++ b/tests/micropython/viper_addr.py
@@ -1,29 +1,32 @@
# test passing addresses to viper
+
@micropython.viper
-def get_addr(x:ptr) -> ptr:
+def get_addr(x: ptr) -> ptr:
return x
+
@micropython.viper
-def memset(dest:ptr8, c:int, n:int):
+def memset(dest: ptr8, c: int, n: int):
for i in range(n):
dest[i] = c
+
# 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)
diff --git a/tests/micropython/viper_args.py b/tests/micropython/viper_args.py
index 2aebe1b04..223026b96 100644
--- a/tests/micropython/viper_args.py
+++ b/tests/micropython/viper_args.py
@@ -1,28 +1,43 @@
# 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)
# only up to 4 arguments currently supported
@@ -31,6 +46,8 @@ f4(1, 2, 3, 4)
@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 4d711f1a9..2691404b7 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):
+def and_(x: int, y: int):
print(x & y, y & x)
+
+
and_(1, 0)
and_(1, 3)
-and_(0xf0, 0x3f)
+and_(0xF0, 0x3F)
and_(-42, 6)
+
@micropython.viper
-def or_(x:int, y:int):
+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 dcf91ed89..a4c0809c8 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 c7c040895..daab8fcfb 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 822424982..4b74b527d 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:
+def div(x: int, y: int) -> int:
return x // y
+
@micropython.viper
-def mod(x:int, y:int) -> int:
+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 8065db291..997c397d4 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 a168afce9..d31a5f3cf 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,4 +26,6 @@ def g():
y = 1
if y:
print("y", y)
+
+
g()
diff --git a/tests/micropython/viper_error.py b/tests/micropython/viper_error.py
index 847257285..fa136197d 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")
@@ -17,30 +19,36 @@ test("@micropython.viper\ndef f(x:unknown_type): pass")
test("@micropython.viper\ndef f(a, b, c, d, e): 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_import.py b/tests/micropython/viper_import.py
index 987800744..3df23e17a 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 021e03f2c..41389c751 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 e036435c7..055c08d8e 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 0b865eb9e..30c85d066 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:
+def get1(src: ptr16) -> int:
return src[1]
+
@micropython.viper
-def memadd(src:ptr16, n:int) -> int:
+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 5a5f25d17..3ca5a027c 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):
+def set1(dest: ptr16, val: int):
dest[1] = val
+
@micropython.viper
-def memset(dest:ptr16, val:int, n:int):
+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 4d8b3846d..b0b90bcaf 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:
+def get1(src: ptr32) -> int:
return src[1]
+
@micropython.viper
-def memadd(src:ptr32, n:int) -> int:
+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 973086e4a..ff0c371ab 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):
+def set1(dest: ptr32, val: int):
dest[1] = val
+
@micropython.viper
-def memset(dest:ptr32, val:int, n:int):
+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 0ccf8a1d7..d871bfb68 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:
+def get1(src: ptr8) -> int:
return src[1]
+
@micropython.viper
-def memadd(src:ptr8, n:int) -> int:
+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 5a8622eb1..baa9e2c6d 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):
+def set1(dest: ptr8, val: int):
dest[1] = val
+
@micropython.viper
-def memset(dest:ptr8, val:int, n:int):
+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 2198ed731..bcaabd3fb 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/misc/features.py b/tests/misc/features.py
index de75cb46d..419d8795f 100644
--- a/tests/misc/features.py
+++ b/tests/misc/features.py
@@ -1,159 +1,199 @@
# 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)
+ 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 9a746a8b0..f745c30e8 100644
--- a/tests/misc/non_compliant.py
+++ b/tests/misc/non_compliant.py
@@ -9,137 +9,147 @@ 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")
# 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 7e50d2836..e1c21f3d7 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 f120fe1e1..11ed320f6 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,36 +32,43 @@ def print_exc(e):
elif not l.startswith(" "):
print(l)
+
# basic exception message
try:
- 1/0
+ 1 / 0
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():
- 2/0
+ 2 / 0
+
+
try:
f()
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:X})
+ f([1, 2], [1, 2], [1, 2], {1: 1, 1: 1, 1: 1, 1: 1, 1: 1, 1: 1, 1: 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 5bbf9d48b..f3bb4189f 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_exc_info.py b/tests/misc/sys_exc_info.py
index bf9438e46..d7e8a2d94 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/net_hosted/accept_nonblock.py b/tests/net_hosted/accept_nonblock.py
index 56f3288e2..941965e17 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 44b3b8c7c..ff989110a 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 6479978be..3a3eaa2ba 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 ece6aa0da..90f9b7138 100644
--- a/tests/net_hosted/connect_poll.py
+++ b/tests/net_hosted/connect_poll.py
@@ -29,4 +29,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 e265c830d..dee5fcfd8 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 bf8071d08..7fdafab99 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/pyb/adc.py b/tests/pyb/adc.py
index 0bd9b9d53..fff5a3019 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(adct)
-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/can.py b/tests/pyb/can.py
index 8a08ea9a6..7d27318d8 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):
@@ -273,7 +278,7 @@ while can.any(0):
# Testing rtr messages
bus1 = CAN(1, CAN.LOOPBACK)
-bus2 = CAN(2, CAN.LOOPBACK, extframe = True)
+bus2 = CAN(2, CAN.LOOPBACK, extframe=True)
while bus1.any(0):
bus1.recv(0)
while bus2.any(0):
@@ -286,24 +291,24 @@ 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,))
-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))
-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 ca68ec709..506cf272b 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 ae98ccd5a..927b2bceb 100644
--- a/tests/pyb/extint.py
+++ b/tests/pyb/extint.py
@@ -1,7 +1,7 @@
import pyb
# test basic functionality
-ext = pyb.ExtInt('Y1', pyb.ExtInt.IRQ_RISING, pyb.Pin.PULL_DOWN, lambda l:print('line:', l))
+ext = pyb.ExtInt("Y1", 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/irq.py b/tests/pyb/irq.py
index 42d276568..04e70a7b7 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/modtime.py b/tests/pyb/modtime.py
index d45440a63..1f5b5f32f 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,41 +21,56 @@ 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()
-spot_test( 0, (2000, 1, 1, 0, 0, 0, 5, 1))
-spot_test( 1, (2000, 1, 1, 0, 0, 1, 5, 1))
-spot_test( 59, (2000, 1, 1, 0, 0, 59, 5, 1))
-spot_test( 60, (2000, 1, 1, 0, 1, 0, 5, 1))
-spot_test( 3599, (2000, 1, 1, 0, 59, 59, 5, 1))
-spot_test( 3600, (2000, 1, 1, 1, 0, 0, 5, 1))
-spot_test( -1, (1999, 12, 31, 23, 59, 59, 4, 365))
-spot_test( 447549467, (2014, 3, 7, 23, 17, 47, 4, 66))
-spot_test( -940984933, (1970, 3, 7, 23, 17, 47, 5, 66))
-spot_test(-1072915199, (1966, 1, 1, 0, 0, 1, 5, 1))
-spot_test(-1072915200, (1966, 1, 1, 0, 0, 0, 5, 1))
-spot_test(-1072915201, (1965, 12, 31, 23, 59, 59, 4, 365))
+spot_test(0, (2000, 1, 1, 0, 0, 0, 5, 1))
+spot_test(1, (2000, 1, 1, 0, 0, 1, 5, 1))
+spot_test(59, (2000, 1, 1, 0, 0, 59, 5, 1))
+spot_test(60, (2000, 1, 1, 0, 1, 0, 5, 1))
+spot_test(3599, (2000, 1, 1, 0, 59, 59, 5, 1))
+spot_test(3600, (2000, 1, 1, 1, 0, 0, 5, 1))
+spot_test(-1, (1999, 12, 31, 23, 59, 59, 4, 365))
+spot_test(447549467, (2014, 3, 7, 23, 17, 47, 4, 66))
+spot_test(-940984933, (1970, 3, 7, 23, 17, 47, 5, 66))
+spot_test(-1072915199, (1966, 1, 1, 0, 0, 1, 5, 1))
+spot_test(-1072915200, (1966, 1, 1, 0, 0, 0, 5, 1))
+spot_test(-1072915201, (1965, 12, 31, 23, 59, 59, 4, 365))
diff --git a/tests/pyb/pin.py b/tests/pyb/pin.py
index 9b3788343..c5a444332 100644
--- a/tests/pyb/pin.py
+++ b/tests/pyb/pin.py
@@ -1,14 +1,14 @@
from pyb import Pin
-p = Pin('Y1', Pin.IN)
+p = Pin("Y1", Pin.IN)
print(p)
print(p.name())
print(p.pin())
print(p.port())
-p = Pin('Y1', Pin.IN, Pin.PULL_UP)
-p = Pin('Y1', Pin.IN, pull=Pin.PULL_UP)
-p = Pin('Y1', mode=Pin.IN, pull=Pin.PULL_UP)
+p = Pin("Y1", Pin.IN, Pin.PULL_UP)
+p = Pin("Y1", Pin.IN, pull=Pin.PULL_UP)
+p = Pin("Y1", 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 443722ca8..e9626ecf4 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 2f161ae09..6ca943dce 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())
diff --git a/tests/pyb/pyb_f411.py b/tests/pyb/pyb_f411.py
index 50de30282..58d5fa2d4 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 844526b4b..41b52f260 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/timer_callback.py b/tests/pyb/timer_callback.py
index 864dd479e..51242fba4 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 838dd9cfc..afa7b8b34 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,7 +26,7 @@ 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 309c6c14f..50177a9ba 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 3ea7221ea..0f397dd37 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-tests-exp.py b/tests/run-tests-exp.py
index 3af8feae7..34c6f650f 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/skip_if.py b/tests/skip_if.py
index a8f50c465..1ca1794ed 100644
--- a/tests/skip_if.py
+++ b/tests/skip_if.py
@@ -6,18 +6,23 @@
# This must be on one line so its skipped when built into tests.
"""This file provides helpers to detect particular running conditions and skip the test when appropriate."""
+
def skip():
print("SKIP")
raise SystemExit
+
def always():
skip()
+
def no_reversed():
import builtins
+
if "reversed" not in dir(builtins):
skip()
+
def no_bigint():
try:
# We have to use variables because 1 << 40 causes an exception on parse and
@@ -27,28 +32,35 @@ def no_bigint():
except OverflowError:
skip()
+
def board_in(*board):
try:
import test_env
except ImportError:
+
class Env:
def __init__(self, board):
self.board = board
+
test_env = Env("unknown")
if test_env.board in board:
skip()
+
def board_not_in(*board):
try:
import test_env
except ImportError:
+
class Env:
def __init__(self, board):
self.board = board
+
test_env = Env("unknown")
if test_env.board not in board:
skip()
+
def no_cpython_compat():
try:
from collections import namedtuple
@@ -59,13 +71,14 @@ def no_cpython_compat():
except TypeError:
skip()
+
def no_slice_assign():
try:
memoryview
except:
skip()
- b1 = bytearray(b'1234')
- b2 = bytearray(b'5678')
+ b1 = bytearray(b"1234")
+ b2 = bytearray(b"5678")
m1 = memoryview(b1)
m2 = memoryview(b2)
try:
@@ -78,6 +91,7 @@ def no_reverse_ops():
class Foo:
def __radd__(self, other):
pass
+
try:
5 + Foo()
except TypeError:
diff --git a/tests/stress/dict_copy.py b/tests/stress/dict_copy.py
index 36db9bb7e..73d3a5b51 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 72dc7b627..f952ad36a 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/recursion.py b/tests/stress/recursion.py
index 227f48396..c2d831bb8 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 0e0d3914e..8c2139765 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 5015c3f9c..9b52e0c01 100644
--- a/tests/thread/mutate_bytearray.py
+++ b/tests/thread/mutate_bytearray.py
@@ -25,10 +25,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):
diff --git a/tests/thread/mutate_dict.py b/tests/thread/mutate_dict.py
index 563fce39d..0840dcafb 100644
--- a/tests/thread/mutate_dict.py
+++ b/tests/thread/mutate_dict.py
@@ -7,7 +7,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):
@@ -28,6 +28,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 2ecfbe109..8ba91cbde 100644
--- a/tests/thread/mutate_instance.py
+++ b/tests/thread/mutate_instance.py
@@ -9,25 +9,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
@@ -42,4 +45,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 d70e8a8a3..8ce15c085 100644
--- a/tests/thread/mutate_list.py
+++ b/tests/thread/mutate_list.py
@@ -29,6 +29,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 c4529f356..61169b8aa 100644
--- a/tests/thread/mutate_set.py
+++ b/tests/thread/mutate_set.py
@@ -23,6 +23,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 ebf7af371..3191192a4 100644
--- a/tests/thread/stress_aes.py
+++ b/tests/thread/stress_aes.py
@@ -19,49 +19,295 @@
# discrete arithmetic routines, mostly from a precomputed table
# non-linear, invertible, substitution box
-aes_s_box_table = bytes((
- 0x63,0x7c,0x77,0x7b,0xf2,0x6b,0x6f,0xc5,0x30,0x01,0x67,0x2b,0xfe,0xd7,0xab,0x76,
- 0xca,0x82,0xc9,0x7d,0xfa,0x59,0x47,0xf0,0xad,0xd4,0xa2,0xaf,0x9c,0xa4,0x72,0xc0,
- 0xb7,0xfd,0x93,0x26,0x36,0x3f,0xf7,0xcc,0x34,0xa5,0xe5,0xf1,0x71,0xd8,0x31,0x15,
- 0x04,0xc7,0x23,0xc3,0x18,0x96,0x05,0x9a,0x07,0x12,0x80,0xe2,0xeb,0x27,0xb2,0x75,
- 0x09,0x83,0x2c,0x1a,0x1b,0x6e,0x5a,0xa0,0x52,0x3b,0xd6,0xb3,0x29,0xe3,0x2f,0x84,
- 0x53,0xd1,0x00,0xed,0x20,0xfc,0xb1,0x5b,0x6a,0xcb,0xbe,0x39,0x4a,0x4c,0x58,0xcf,
- 0xd0,0xef,0xaa,0xfb,0x43,0x4d,0x33,0x85,0x45,0xf9,0x02,0x7f,0x50,0x3c,0x9f,0xa8,
- 0x51,0xa3,0x40,0x8f,0x92,0x9d,0x38,0xf5,0xbc,0xb6,0xda,0x21,0x10,0xff,0xf3,0xd2,
- 0xcd,0x0c,0x13,0xec,0x5f,0x97,0x44,0x17,0xc4,0xa7,0x7e,0x3d,0x64,0x5d,0x19,0x73,
- 0x60,0x81,0x4f,0xdc,0x22,0x2a,0x90,0x88,0x46,0xee,0xb8,0x14,0xde,0x5e,0x0b,0xdb,
- 0xe0,0x32,0x3a,0x0a,0x49,0x06,0x24,0x5c,0xc2,0xd3,0xac,0x62,0x91,0x95,0xe4,0x79,
- 0xe7,0xc8,0x37,0x6d,0x8d,0xd5,0x4e,0xa9,0x6c,0x56,0xf4,0xea,0x65,0x7a,0xae,0x08,
- 0xba,0x78,0x25,0x2e,0x1c,0xa6,0xb4,0xc6,0xe8,0xdd,0x74,0x1f,0x4b,0xbd,0x8b,0x8a,
- 0x70,0x3e,0xb5,0x66,0x48,0x03,0xf6,0x0e,0x61,0x35,0x57,0xb9,0x86,0xc1,0x1d,0x9e,
- 0xe1,0xf8,0x98,0x11,0x69,0xd9,0x8e,0x94,0x9b,0x1e,0x87,0xe9,0xce,0x55,0x28,0xdf,
- 0x8c,0xa1,0x89,0x0d,0xbf,0xe6,0x42,0x68,0x41,0x99,0x2d,0x0f,0xb0,0x54,0xbb,0x16,
-))
+aes_s_box_table = bytes(
+ (
+ 0x63,
+ 0x7C,
+ 0x77,
+ 0x7B,
+ 0xF2,
+ 0x6B,
+ 0x6F,
+ 0xC5,
+ 0x30,
+ 0x01,
+ 0x67,
+ 0x2B,
+ 0xFE,
+ 0xD7,
+ 0xAB,
+ 0x76,
+ 0xCA,
+ 0x82,
+ 0xC9,
+ 0x7D,
+ 0xFA,
+ 0x59,
+ 0x47,
+ 0xF0,
+ 0xAD,
+ 0xD4,
+ 0xA2,
+ 0xAF,
+ 0x9C,
+ 0xA4,
+ 0x72,
+ 0xC0,
+ 0xB7,
+ 0xFD,
+ 0x93,
+ 0x26,
+ 0x36,
+ 0x3F,
+ 0xF7,
+ 0xCC,
+ 0x34,
+ 0xA5,
+ 0xE5,
+ 0xF1,
+ 0x71,
+ 0xD8,
+ 0x31,
+ 0x15,
+ 0x04,
+ 0xC7,
+ 0x23,
+ 0xC3,
+ 0x18,
+ 0x96,
+ 0x05,
+ 0x9A,
+ 0x07,
+ 0x12,
+ 0x80,
+ 0xE2,
+ 0xEB,
+ 0x27,
+ 0xB2,
+ 0x75,
+ 0x09,
+ 0x83,
+ 0x2C,
+ 0x1A,
+ 0x1B,
+ 0x6E,
+ 0x5A,
+ 0xA0,
+ 0x52,
+ 0x3B,
+ 0xD6,
+ 0xB3,
+ 0x29,
+ 0xE3,
+ 0x2F,
+ 0x84,
+ 0x53,
+ 0xD1,
+ 0x00,
+ 0xED,
+ 0x20,
+ 0xFC,
+ 0xB1,
+ 0x5B,
+ 0x6A,
+ 0xCB,
+ 0xBE,
+ 0x39,
+ 0x4A,
+ 0x4C,
+ 0x58,
+ 0xCF,
+ 0xD0,
+ 0xEF,
+ 0xAA,
+ 0xFB,
+ 0x43,
+ 0x4D,
+ 0x33,
+ 0x85,
+ 0x45,
+ 0xF9,
+ 0x02,
+ 0x7F,
+ 0x50,
+ 0x3C,
+ 0x9F,
+ 0xA8,
+ 0x51,
+ 0xA3,
+ 0x40,
+ 0x8F,
+ 0x92,
+ 0x9D,
+ 0x38,
+ 0xF5,
+ 0xBC,
+ 0xB6,
+ 0xDA,
+ 0x21,
+ 0x10,
+ 0xFF,
+ 0xF3,
+ 0xD2,
+ 0xCD,
+ 0x0C,
+ 0x13,
+ 0xEC,
+ 0x5F,
+ 0x97,
+ 0x44,
+ 0x17,
+ 0xC4,
+ 0xA7,
+ 0x7E,
+ 0x3D,
+ 0x64,
+ 0x5D,
+ 0x19,
+ 0x73,
+ 0x60,
+ 0x81,
+ 0x4F,
+ 0xDC,
+ 0x22,
+ 0x2A,
+ 0x90,
+ 0x88,
+ 0x46,
+ 0xEE,
+ 0xB8,
+ 0x14,
+ 0xDE,
+ 0x5E,
+ 0x0B,
+ 0xDB,
+ 0xE0,
+ 0x32,
+ 0x3A,
+ 0x0A,
+ 0x49,
+ 0x06,
+ 0x24,
+ 0x5C,
+ 0xC2,
+ 0xD3,
+ 0xAC,
+ 0x62,
+ 0x91,
+ 0x95,
+ 0xE4,
+ 0x79,
+ 0xE7,
+ 0xC8,
+ 0x37,
+ 0x6D,
+ 0x8D,
+ 0xD5,
+ 0x4E,
+ 0xA9,
+ 0x6C,
+ 0x56,
+ 0xF4,
+ 0xEA,
+ 0x65,
+ 0x7A,
+ 0xAE,
+ 0x08,
+ 0xBA,
+ 0x78,
+ 0x25,
+ 0x2E,
+ 0x1C,
+ 0xA6,
+ 0xB4,
+ 0xC6,
+ 0xE8,
+ 0xDD,
+ 0x74,
+ 0x1F,
+ 0x4B,
+ 0xBD,
+ 0x8B,
+ 0x8A,
+ 0x70,
+ 0x3E,
+ 0xB5,
+ 0x66,
+ 0x48,
+ 0x03,
+ 0xF6,
+ 0x0E,
+ 0x61,
+ 0x35,
+ 0x57,
+ 0xB9,
+ 0x86,
+ 0xC1,
+ 0x1D,
+ 0x9E,
+ 0xE1,
+ 0xF8,
+ 0x98,
+ 0x11,
+ 0x69,
+ 0xD9,
+ 0x8E,
+ 0x94,
+ 0x9B,
+ 0x1E,
+ 0x87,
+ 0xE9,
+ 0xCE,
+ 0x55,
+ 0x28,
+ 0xDF,
+ 0x8C,
+ 0xA1,
+ 0x89,
+ 0x0D,
+ 0xBF,
+ 0xE6,
+ 0x42,
+ 0x68,
+ 0x41,
+ 0x99,
+ 0x2D,
+ 0x0F,
+ 0xB0,
+ 0x54,
+ 0xBB,
+ 0x16,
+ )
+)
# 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
#
@@ -81,6 +327,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):
@@ -90,7 +337,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]
@@ -99,6 +346,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):
@@ -108,7 +356,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]
@@ -117,6 +365,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):
@@ -127,6 +376,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):
@@ -150,9 +400,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:
@@ -178,7 +430,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:
@@ -200,6 +452,7 @@ class AES:
idx += ln
self.state_pos += n
+
##################################################################
# test code
@@ -209,6 +462,7 @@ except ImportError:
import time
import _thread
+
class LockedCounter:
def __init__(self):
self.lock = _thread.allocate_lock()
@@ -219,8 +473,10 @@ class LockedCounter:
self.value += val
self.lock.release()
+
count = LockedCounter()
+
def thread_entry():
global count
@@ -249,7 +505,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 2399746cc..eda768fa7 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 206cf1a86..41dfa5f37 100644
--- a/tests/thread/stress_heap.py
+++ b/tests/thread/stress_heap.py
@@ -11,9 +11,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))
@@ -35,6 +37,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 8edee246a..b7a128821 100644
--- a/tests/thread/stress_recurse.py
+++ b/tests/thread/stress_recurse.py
@@ -6,17 +6,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, ())
@@ -24,4 +27,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 e00a16bd2..3c3a1e8be 100644
--- a/tests/thread/thread_exc1.py
+++ b/tests/thread/thread_exc1.py
@@ -6,9 +6,11 @@
import _thread
+
def foo():
raise ValueError
+
def thread_entry():
try:
foo()
@@ -18,6 +20,7 @@ def thread_entry():
global n_finished
n_finished += 1
+
lock = _thread.allocate_lock()
n_thread = 4
n_finished = 0
@@ -29,4 +32,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 35cb32441..2863e1dec 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_exit1.py b/tests/thread/thread_exit1.py
index ad7b01d89..6179716d1 100644
--- a/tests/thread/thread_exit1.py
+++ b/tests/thread/thread_exit1.py
@@ -10,12 +10,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 6bff8a173..ba9852b5c 100644
--- a/tests/thread/thread_exit2.py
+++ b/tests/thread/thread_exit2.py
@@ -10,12 +10,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 2ea189161..4e4faeaf8 100644
--- a/tests/thread/thread_gc1.py
+++ b/tests/thread/thread_gc1.py
@@ -7,6 +7,7 @@
import gc
import _thread
+
def thread_entry(n):
# allocate a bytearray and fill it
data = bytearray(i for i in range(256))
@@ -23,6 +24,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 9a6f89ff5..1ba342e2b 100644
--- a/tests/thread/thread_ident1.py
+++ b/tests/thread/thread_ident1.py
@@ -6,18 +6,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 c2d7c9d1e..e7066402c 100644
--- a/tests/thread/thread_lock1.py
+++ b/tests/thread/thread_lock1.py
@@ -38,11 +38,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 4ef912dff..c43b4b18d 100644
--- a/tests/thread/thread_lock2.py
+++ b/tests/thread/thread_lock2.py
@@ -12,15 +12,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 35808d99c..32d0c54b5 100644
--- a/tests/thread/thread_lock3.py
+++ b/tests/thread/thread_lock3.py
@@ -10,16 +10,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 440f3e90c..7637d10b9 100644
--- a/tests/thread/thread_lock4.py
+++ b/tests/thread/thread_lock4.py
@@ -10,12 +10,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:
@@ -27,6 +29,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 dccfb7f51..2099f94bd 100644
--- a/tests/thread/thread_qstr1.py
+++ b/tests/thread/thread_qstr1.py
@@ -15,6 +15,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):
@@ -25,10 +26,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):
@@ -38,4 +40,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 de339ad7f..87f8b51e2 100644
--- a/tests/thread/thread_shared1.py
+++ b/tests/thread/thread_shared1.py
@@ -6,9 +6,11 @@
import _thread
+
def foo(i):
pass
+
def thread_entry(n, tup):
for i in tup:
foo(i)
@@ -16,6 +18,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 2c749e688..dbe18f987 100644
--- a/tests/thread/thread_shared2.py
+++ b/tests/thread/thread_shared2.py
@@ -7,9 +7,11 @@
import _thread
+
def foo(lst, i):
lst[i] += 1
+
def thread_entry(n, lst, idx):
for i in range(n):
foo(lst, idx)
@@ -17,6 +19,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 d5aa99f97..d81d53739 100644
--- a/tests/thread/thread_sleep1.py
+++ b/tests/thread/thread_sleep1.py
@@ -6,9 +6,11 @@
try:
import utime
+
sleep_ms = utime.sleep_ms
except ImportError:
import time
+
sleep_ms = lambda t: time.sleep(t / 1000)
import _thread
@@ -17,6 +19,7 @@ lock = _thread.allocate_lock()
n_thread = 4
n_finished = 0
+
def thread_entry(t):
global n_finished
sleep_ms(t)
@@ -24,10 +27,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 e7189fafb..0c6e7a92c 100644
--- a/tests/thread/thread_stacksize1.py
+++ b/tests/thread/thread_stacksize1.py
@@ -8,20 +8,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()
@@ -46,4 +49,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 94df6dc62..f08ff05a8 100644
--- a/tests/thread/thread_start1.py
+++ b/tests/thread/thread_start1.py
@@ -10,16 +10,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 9412bb618..40f8a0522 100644
--- a/tests/thread/thread_start2.py
+++ b/tests/thread/thread_start2.py
@@ -10,11 +10,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)
@@ -23,6 +25,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 8c45f91fa..1a5b933c8 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 3a35ce894..f5af9cfff 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,31 +19,31 @@ 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")
diff --git a/tests/unicode/unicode_id.py b/tests/unicode/unicode_id.py
index 10f540c50..3a58e3f72 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 47cfa1c2d..73577050b 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 bf8505a31..1a60e7be4 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 e9b152473..42211d0b0 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 a2f434de5..502891007 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 13721f1f4..e31eece77 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)
@@ -52,23 +52,28 @@ import frzmpy1
# test import of frozen packages with __init__.py
import frzstr_pkg1
+
print(frzstr_pkg1.x)
import frzmpy_pkg1
+
print(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))
diff --git a/tests/unix/ffi_callback.py b/tests/unix/ffi_callback.py
index 23b058bce..21bfccf25 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 c92a39bcd..b12bce968 100644
--- a/tests/unix/ffi_float.py
+++ b/tests/unix/ffi_float.py
@@ -16,17 +16,18 @@ 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"))
strtof = libc.func("f", "strtof", "sp")
-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 721eb4d19..bbed69666 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/wipy/adc.py b/tests/wipy/adc.py
index 6fd4373db..73264113f 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/modwipy.py b/tests/wipy/modwipy.py
index 7571af075..59df3ae90 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 0596a16b5..1f4debcad 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 666ecb66b..43537bba5 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,66 +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 875f1f939..be5e1f426 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 35a970c67..8d314f3b4 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 2737ebe73..c62e400fe 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 c946e0c9f..381d46f30 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,11 +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 ec3baa552..99712f8d1 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/time.py b/tests/wipy/time.py
index e6237de35..c1d105d64 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,53 +21,69 @@ 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()
-spot_test( 0, (2000, 1, 1, 0, 0, 0, 5, 1))
-spot_test( 1, (2000, 1, 1, 0, 0, 1, 5, 1))
-spot_test( 59, (2000, 1, 1, 0, 0, 59, 5, 1))
-spot_test( 60, (2000, 1, 1, 0, 1, 0, 5, 1))
-spot_test( 3599, (2000, 1, 1, 0, 59, 59, 5, 1))
-spot_test( 3600, (2000, 1, 1, 1, 0, 0, 5, 1))
-spot_test( -1, (1999, 12, 31, 23, 59, 59, 4, 365))
-spot_test( 447549467, (2014, 3, 7, 23, 17, 47, 4, 66))
-spot_test( -940984933, (1970, 3, 7, 23, 17, 47, 5, 66))
-spot_test(-1072915199, (1966, 1, 1, 0, 0, 1, 5, 1))
-spot_test(-1072915200, (1966, 1, 1, 0, 0, 0, 5, 1))
-spot_test(-1072915201, (1965, 12, 31, 23, 59, 59, 4, 365))
+spot_test(0, (2000, 1, 1, 0, 0, 0, 5, 1))
+spot_test(1, (2000, 1, 1, 0, 0, 1, 5, 1))
+spot_test(59, (2000, 1, 1, 0, 0, 59, 5, 1))
+spot_test(60, (2000, 1, 1, 0, 1, 0, 5, 1))
+spot_test(3599, (2000, 1, 1, 0, 59, 59, 5, 1))
+spot_test(3600, (2000, 1, 1, 1, 0, 0, 5, 1))
+spot_test(-1, (1999, 12, 31, 23, 59, 59, 4, 365))
+spot_test(447549467, (2014, 3, 7, 23, 17, 47, 4, 66))
+spot_test(-940984933, (1970, 3, 7, 23, 17, 47, 5, 66))
+spot_test(-1072915199, (1966, 1, 1, 0, 0, 1, 5, 1))
+spot_test(-1072915200, (1966, 1, 1, 0, 0, 0, 5, 1))
+spot_test(-1072915201, (1965, 12, 31, 23, 59, 59, 4, 365))
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 f62899b47..db25870db 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 d8b405f77..0b1744d4f 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,15 +54,15 @@ 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(buf)
@@ -65,87 +71,87 @@ 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 d4cd90058..e631e46a9 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 a894b88fd..56f6ea8d9 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 2ee529965..f69b117b7 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 05847e376..40f56745c 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 96121325c..dd85c8696 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,64 +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")