tests/import/builtin_ext.py: Add test for built-in module override.

This verifies the behavior:
 - Exact matches of built-ins bypass filesystem.
 - u-prefix modules can be overridden from the filesystem.
 - Builtin import can be forced using either u-prefix or sys.path=[].

This work was funded through GitHub Sponsors.

Signed-off-by: Jim Mussared <jim.mussared@gmail.com>
This commit is contained in:
Jim Mussared 2023-05-12 17:10:07 +10:00 committed by Damien George
parent 5e04521251
commit dfa7677e2f
7 changed files with 72 additions and 0 deletions

View File

@ -0,0 +1,36 @@
import sys
print(sys, hasattr(sys, "__file__"))
sys.path.clear()
sys.path.append("ext")
# All three should only get builtins, despite sys.py, usys.py, and
# micropython.py being in the path.
import micropython
print(micropython, hasattr(micropython, "__file__"))
import sys
print(sys, hasattr(sys, "__file__"))
import usys
print(usys, hasattr(usys, "__file__"))
# This should get os.py, which uses uos to get the builtin.
import os
print(os, hasattr(os, "__file__"), os.sep, os.extra)
# This should get time.py, which uses empty sys.path to get the builtin.
import time
print(time, hasattr(time, "__file__"), time.sleep, time.extra)
# These should get the builtins.
import uos
print(uos, hasattr(uos, "__file__"), hasattr(uos, "extra"))
import utime
print(utime, hasattr(utime, "__file__"), hasattr(utime, "extra"))

View File

@ -0,0 +1,10 @@
<module 'sys'> False
<module 'micropython'> False
<module 'sys'> False
<module 'sys'> False
os from filesystem
<module 'os' from 'ext/os.py'> True / 1
time from filesystem
<module 'time' from 'ext/time.py'> True <function> 1
<module 'uos'> False False
<module 'utime'> False False

View File

@ -0,0 +1,2 @@
# micropython is always builtin and cannot be overriden by the filesystem.
print("ERROR: micropython from filesystem")

5
tests/import/ext/os.py Normal file
View File

@ -0,0 +1,5 @@
print("os from filesystem")
from uos import *
extra = 1

2
tests/import/ext/sys.py Normal file
View File

@ -0,0 +1,2 @@
# sys is always builtin and cannot be overriden by the filesystem.
print("ERROR: sys from filesystem")

14
tests/import/ext/time.py Normal file
View File

@ -0,0 +1,14 @@
print("time from filesystem")
# Tests the CPython-compatible / non-u-prefix way of forcing a builtin
# import.
import sys
_path = sys.path[:]
sys.path.clear()
from time import *
sys.path.extend(_path)
del _path
extra = 1

3
tests/import/ext/usys.py Normal file
View File

@ -0,0 +1,3 @@
# usys (and any u-prefix) is always builtin and cannot be overriden by the
# filesystem.
print("ERROR: usys from filesystem")