summaryrefslogtreecommitdiff
path: root/tests/basics
AgeCommit message (Collapse)Author
11 daystests/basics: Add tests for PEP487 __set_name__.Anson Mansfield
Including the stochastic tests needed to guarantee sensitivity to the potential iterate-while-modifying hazard a naive implementation might have. Signed-off-by: Anson Mansfield <amansfield@mantaro.com>
11 dayspy/objint_longlong: Fix overflow check in mp_obj_int_get_checked.Yoctopuce dev
This is to fix an outstanding TODO. The test cases is using a range as this will exist in all builds, but `mp_obj_get_int` is used in many different parts of code where an overflow is more likely to occur. Signed-off-by: Yoctopuce dev <dev@yoctopuce.com>
11 dayspy/objint_mpz: Fix pow3 where third argument is zero.Jeff Epler
This finding is based on fuzzing MicroPython. I manually minimized the test case it provided. Signed-off-by: Jeff Epler <jepler@gmail.com>
2025-07-24py/obj: Add new type flag to indicate subscr accepts slice-on-stack.Damien George
The recently merged 5e9189d6d1c00c92694888bf9c74276779c40716 now allows temporary slices to be allocated on the C stack, which is much better than allocating them on the GC heap. Unfortunately there are cases where the C-allocated slice can escape and be retained as an object, which leads to crashes (because that object points to the C stack which now has other values on it). The fix here is to add a new `MP_TYPE_FLAG_SUBSCR_ALLOWS_STACK_SLICE`. Native types should set this flag if their subscr method is guaranteed not to hold on to a reference of the slice object. Fixes issue #17733 (see also #17723). Signed-off-by: Damien George <damien@micropython.org>
2025-07-22py/modsys: Add sys.implementation._thread attribute.Damien George
This is useful to distinguish between GIL and non-GIL builds. Signed-off-by: Damien George <damien@micropython.org>
2025-07-18tests/basics/fun_code_lnotab: Test removal of co_lnotab from v2.Anson Mansfield
Signed-off-by: Anson Mansfield <amansfield@mantaro.com>
2025-07-18py/objint_longlong: Add arithmetic overflow checks.Angus Gratton
Long long big integer support now raises an exception on overflow rather than returning an undefined result. Also adds an error when shifting by a negative value. The new arithmetic checks are added in the misc.h header. This work was funded through GitHub Sponsors. Signed-off-by: Angus Gratton <angus@redyak.com.au>
2025-07-18tests: Add specific tests for "long long" 64-bit bigints.Angus Gratton
These will run on all ports which support them, but importantly they'll also run on ports that don't support arbitrary precision but do support 64-bit long ints. Includes some test workarounds to account for things which will overflow once "long long" big integers overflow (added in follow-up commit): - uctypes_array_load_store test was failing already, now won't parse. - all the ffi_int tests contain 64-bit unsigned values, that won't parse as long long. This work was funded through GitHub Sponsors. Signed-off-by: Angus Gratton <angus@redyak.com.au>
2025-07-16py/vm: Avoid heap-allocating slices when subscripting built-ins.Jim Mussared
This commit adds a fast-path optimisation for when a BUILD_SLICE is immediately followed by a LOAD/STORE_SUBSCR for a native type, to avoid needing to allocate the slice on the heap. In some cases (e.g. `a[1:3] = x`) this can result in no allocations at all. We can't do this for instance types because the get/set/delattr implementation may keep a reference to the slice. Adds more tests to the basic slice tests to ensure that a stack-allocated slice never makes it to Python, and also a heapalloc test that verifies (when using bytecode) that assigning to a slice is no-alloc. This work was funded through GitHub Sponsors. Signed-off-by: Jim Mussared <jim.mussared@gmail.com> Signed-off-by: Damien George <damien@micropython.org>
2025-07-08tests/basics/fun_code_colines: Test decoded co_lines values.Anson Mansfield
Signed-off-by: Anson Mansfield <amansfield@mantaro.com>
2025-07-08tests/basics/fun_code_full: Test code objects with full feature set.Anson Mansfield
Signed-off-by: Anson Mansfield <amansfield@mantaro.com>
2025-06-17py/modio: Fix the case where write fails in BufferedWriter.flush.Jeff Epler
Previously, there was no test coverage of the "write failed" path. In fact, the assertion would fire instead of gracefully raising a Python exception. Slightly re-organize the code to place the assertion later. Add a test case which exercises all paths, and update the expected output. Signed-off-by: Jeff Epler <jepler@gmail.com>
2025-06-10py/objarray: Allow extending array with any iterable.Jeff Epler
As suggested by @dpgeorge, factor out part of array_construct to allow it to be used for construction & extension. Note that extending with a known-length list (or tuple) goes through the slow path of calling array_extend once per element. Fixes issue #7408. Signed-off-by: Jeff Epler <jepler@gmail.com>
2025-05-13py/objstr: Add support for the :_b/o/x specifier in str.format.Jeff Epler
This groups non-decimal values by fours, such as bbb_bbbb_bbbb. It also supports `{:_d}` to use underscore for decimal numbers (grouped in threes). Use of incorrect ":,b" is not diagnosed. Thanks to @dpgeorge for the suggestion to reduce code size. Signed-off-by: Jeff Epler <jepler@gmail.com>
2025-04-21py/objstr: Fix handling of OP_MODULO with namedtuple.Yoctopuce dev
This fix handles attrtuple as well, eg. os.uname(). A test case has been added in basics/attrtuple2.py. Fixes issue #16969. Signed-off-by: Yoctopuce dev <dev@yoctopuce.com>
2025-04-21tests/basics/builtin_range.py: Add more tests for range slicing.Jeff Epler
Signed-off-by: Jeff Epler <jepler@gmail.com>
2025-03-05py/modsys: Add sys.implementation._build entry.Damien George
For a given MicroPython firmware/executable it can be sometimes important to know how it was built, which variant/board configuration it came from. This commit adds a new field `sys.implementation._build` that can help identify the configuration that MicroPython was built with. For now it's either: * <VARIANT> for unix, webassembly and windows ports * <BOARD>-<VARIANT> for microcontroller ports (the variant is optional) In the future additional elements may be added to this string, separated by a hyphen. Resolves issue #16498. Signed-off-by: Damien George <damien@micropython.org>
2025-03-02py/objstr: Support tuples and start/end args in startswith and endswith.Glenn Moloney
This change allows tuples to be passed as the prefix/suffix argument to the `str.startswith()` and `str.endswith()` methods. The methods will return `True` if the string starts/ends with any of the prefixes/suffixes in the tuple. Also adds full support for the `start` and `end` arguments to both methods for compatibility with CPython. Tests have been updated for the new behaviour. Signed-off-by: Glenn Moloney <glenn.moloney@gmail.com>
2025-02-11py/objfun: Implement function.__code__ and function constructor.Damien George
This allows retrieving the code object of a function using `function.__code__`, and then reconstructing a function from a code object using `FunctionType(code_object)`. This feature is controlled by `MICROPY_PY_FUNCTION_ATTRS_CODE` and is enabled at the full-features level. Signed-off-by: Damien George <damien@micropython.org>
2025-01-26py/parsenum: Throw an exception for invalid int literals like "01".Jeff Epler
This includes making int("01") parse in base 10 like standard Python. When a base of 0 is specified it means auto-detect based on the prefix, and literals begining with 0 (except when the literal is all 0's) like "01" are then invalid and now throw an exception. The new error message is different from CPython. It says e.g., `SyntaxError: invalid syntax for integer with base 0: '09'` Additional test cases were added to cover the changed & added code. Co-authored-by: Damien George <damien@micropython.org> Signed-off-by: Jeff Epler <jepler@gmail.com>
2025-01-26tests/basics/nanbox_smallint.py: Fix incorrect use of int() in test.Jeff Epler
The literal is in base 16 but int()'s default radix in CPython is 10, not 0. Signed-off-by: Jeff Epler <jepler@gmail.com>
2024-11-04tests/basics/deque2.py: Add tests for deque subscript-from-end.Damien George
Signed-off-by: Damien George <damien@micropython.org>
2024-10-16py/objtype: Don't delegate lookup of descriptor methods to __getattr__.Damien George
When descriptors are enabled, lookup of the `__get__`, `__set__` and `__delete__` descriptor methods should not be delegated to `__getattr__`. That follows CPython behaviour. Signed-off-by: Damien George <damien@micropython.org>
2024-10-07py/objtype: Allow passing keyword arguments to native base __init__.stijn
Allowing passing keyword arguments to a native base's __init__, i.e. `make_new` in the C code. Previously only positional arguments were allowed. The main trade-off in this commit is that every call to the native base's `make_new` is now going to be preceded by a call to `mp_map_init_fixed_table` even though most of what that does is unused and instead it merely serves as a way to pass the number of keyword arguments. Fixes issue #15465. Signed-off-by: stijn <stijn@ignitron.net>
2024-09-26py/mpz: Skip separators when running out of digits to print.Alessandro Gatti
This commit fixes the addition of a stray separator before the number when printing an MPZ-backed integer and the first group is three digits long. This fixes #8984. Signed-off-by: Alessandro Gatti <a.gatti@frob.it>
2024-09-06shared/runtime/sys_stdio_mphal: Fix printed type for stdio streams.timdechant
The printed type for stdio streams indicates "FileIO", which is a binary IO stream. Stdio is not binary by design, and its printed type should indicate a text stream. "TextIOWrapper" suits that purpose, and is used by VfsPosix files. Signed-off-by: timdechant <timdechant.git@gmail.com>
2024-09-02tests/basics: Add tests for optional args to int.to_bytes/from_bytes.Amirreza Hamzavi
Signed-off-by: Amirreza Hamzavi <amirrezahamzavi2000@gmail.com>
2024-08-19py/objstr: Skip whitespace in bytes.fromhex().Glenn Moloney
Skip whitespace characters between pairs of hex numbers. This makes `bytes.fromhex()` compatible with cpython. Includes simple test in `tests/basic/builtin_str_hex.py`. Signed-off-by: Glenn Moloney <glenn.moloney@gmail.com>
2024-07-25py/runtime: Fix self arg passed to classmethod when accessed via super.Damien George
Thanks to @AJMansfield for the original test case. Signed-off-by: Damien George <damien@micropython.org>
2024-07-25py/objtype: Validate super() arguments.stijn
This fixes various null dereferencing and out-of-bounds access because super_attr assumes the held obj is effectively an object of the held type, which is now verified. Fixes issue #12830. Signed-off-by: stijn <stijn@ignitron.net>
2024-07-01py/objint: Try to convert big-int back to small-int after binary op.Jim Mussared
Before this change, long/mpz ints propagated into all future calculations, even if their value could fit in a small-int object. With this change, the result of a big-int binary op will now be converted to a small-int object if the value fits in a small-int. For example, a relatively common operation like `x = a * b // c` where a,b,c all small ints would always result in a long/mpz int, even if it didn't need to, and then this would impact all future calculations with x. This adds +24 bytes on PYBV11 but avoids heap allocations and potential surprises (e.g. `big-big` is now a small `0`, and can safely be accessed with MP_OBJ_SMALL_INT_VALUE). Performance tests are unchanged on PYBV10, except for `bm_pidigits.py` which makes heavy use of big-ints and gains about 8% in speed. Unix coverage tests have been updated to cover mpz code that is now unreachable by normal Python code (removing the unreachable code would lead to some surprising gaps in the internal C functions and the functionality may be needed in the future, so it is kept because it has minimal overhead). This work was funded through GitHub Sponsors. Signed-off-by: Jim Mussared <jim.mussared@gmail.com>
2024-06-24py/objint: Fix int.to_bytes() buffer size checks.Angus Gratton
Fixes and improvements to `int.to_bytes()` are: - No longer overflows if byte size is 0 (closes #13041). - Raises OverflowError in any case where number won't fit into byte length (now matches CPython, previously MicroPython would return a truncated bytes object). - Document that `micropython int.to_bytes()` doesn't implement the optional signed kwarg, but will behave as if `signed=True` when the integer is negative (this is the current behaviour). Add tests for this also. Requires changes for small ints, MPZ large ints, and "long long" large ints. Adds a new set of unit tests for ints between 32 and 64 bits to increase coverage of "long long" large ints, which are otherwise untested. Tested on unix port (64 bit small ints, MPZ long ints) and Zephyr STM32WB board (32 bit small ints, long long large ints). This work was funded through GitHub Sponsors. Signed-off-by: Angus Gratton <angus@redyak.com.au>
2024-06-21tests/basics: Add tests to test repeated throw into the same generator.Damien George
Signed-off-by: Damien George <damien@micropython.org>
2024-06-06py/lexer: Support raw f-strings.Damien George
Support for raw str/bytes already exists, and extending that to raw f-strings is easy. It also reduces code size because it eliminates an error message. Signed-off-by: Damien George <damien@micropython.org>
2024-06-06py/lexer: Support concatenation of adjacent f-strings.Damien George
This is quite a simple and small change to support concatenation of adjacent f-strings, and improve compatibility with CPython. Signed-off-by: Damien George <damien@micropython.org>
2024-05-28tests/basics: Move str/bytes tests that give SyntaxWarning to sep file.Damien George
In CPython 3.12 these invalid str/bytes/fstring escapes will issue a SyntaxWarning, and so differ to MicroPython. Signed-off-by: Damien George <damien@micropython.org>
2024-05-28tests/basics: Add .exp file for slice_op test.Damien George
CPython 3.12 implemented hashing for slices, so now differs to MicroPython. Signed-off-by: Damien George <damien@micropython.org>
2024-05-27tests/basics: Split out generator.throw tests that pass multiple args.Damien George
The three-argument form of `.throw()` is deprecated since CPython 3.12. So split out into separate tests (with .exp files) the parts of the generator tests that test more than one argument. Signed-off-by: Damien George <damien@micropython.org>
2024-04-22py/objarray: Fix use-after-free if extending a bytearray from itself.Angus Gratton
Two cases, one assigning to a slice. Closes https://github.com/micropython/micropython/issues/13283 Second is extending a slice from itself, similar logic. In both cases the problem occurs when m_renew causes realloc to move the buffer, leaving a dangling pointer behind. There are more complex and hard to fix cases when either argument is a memoryview into the buffer, currently resizing to a new address breaks memoryviews into that object. Reproducing this bug and confirming the fix was done by running the unix port under valgrind with GC-aware extensions. Note in default configurations with GIL this bug exists but has no impact (the free buffer won't be reused while the function is still executing, and is no longer referenced after it returns). Signed-off-by: Angus Gratton <angus@redyak.com.au>
2024-03-19tests/basics: Split MicroPython-specific deque tests to separate file.Damien George
So that the MicroPython-specific behaviour can be isolated, and the CPython compatible test don't need a .exp file. Signed-off-by: Damien George <damien@micropython.org>
2024-03-18py/objdeque: Expand implementation to be doubly-ended and support iter.Dash Peters
Add `pop()`, `appendleft()`, and `extend()` methods, support iteration and indexing, and initializing from an existing sequence. Iteration and indexing (subscription) have independent configuration flags to enable them. They are enabled by default at the same level that collections.deque is enabled (the extra features level). Also add tests for checking new behavior. Signed-off-by: Damien George <damien@micropython.org>
2024-03-07all: Prune trailing whitespace.Phil Howard
Prune trailing whitespace across the whole project (almost), done automatically with: grep -IUrl --color "[[:blank:]]$" --exclude-dir=.git --exclude=*.exp |\ xargs sed -i 's/[[:space:]]*$//' Exceptions: - Skip third-party code in lib/ and drivers/cc3100/ - Skip generated code in bluetooth_init_cc2564C_1.5.c - Preserve command output whitespace in docs, eg: docs/esp8266/tutorial/repl.rst Signed-off-by: Phil Howard <phil@gadgetoid.com>
2024-02-20py/builtinevex: Fix setting globals for native functions in compile().Damien George
Signed-off-by: Damien George <damien@micropython.org>
2024-01-31py/compile: Fix potential Py-stack overflow in try-finally with return.Damien George
If a return is executed within the try block of a try-finally then the return value is stored on the top of the Python stack during the execution of the finally block. In this case the Python stack is one larger than it normally would be in the finally block. Prior to this commit, the compiler was not taking this case into account and could have a Python stack overflow if the Python stack used by the finally block was more than that used elsewhere in the function. In such a scenario the last argument of the function would be clobbered by the top-most temporary value used in the deepest Python expression/statement. This commit fixes that case by making sure enough Python stack is allocated to the function. Fixes issue #13562. Signed-off-by: Damien George <damien@micropython.org>
2024-01-05all: Fix "reuse" and "overridden" spelling mistakes.Damien George
Codespell doesn't pick up "re-used" or "re-uses", and ignores the tests/ directory, so fix these manually. Signed-off-by: Damien George <damien@micropython.org>
2023-12-15py/modsys: Implement optional sys.intern.stijn
Signed-off-by: stijn <stijn@ignitron.net>
2023-11-21py/objslice: Validate that the argument to indices() is an integer.Damien George
Otherwise passing in a non-integer can lead to an invalid memory access. Thanks to Junwha Hong and Wonil Jang @S2Lab, UNIST for finding the issue. Fixes issue #13007. Signed-off-by: Damien George <damien@micropython.org>
2023-10-13py/objboundmeth: Optimise check for types in binary_op.Damien George
Signed-off-by: Damien George <damien@micropython.org>
2023-10-13tests/basics/boundmeth1.py: Add tests for bound method equality/hash.Ned Konz
This commit adds tests for bound method comparison and hashing to support the changes in the previous commit. Signed-off-by: Ned Konz <ned@productcreationstudio.com>
2023-10-09py/vm: Don't emit warning when using "raise ... from None".Matthias Urlichs
"Raise SomeException() from None" is a common Python idiom to suppress chained exceptions and thus shouldn't trigger a warning on a version of Python that doesn't support them in the first place.