circuitpython/tests/extmod/vfs_userfs.py

79 lines
1.6 KiB
Python
Raw Normal View History

# test VFS functionality with a user-defined filesystem
# also tests parts of uio.IOBase implementation
import sys
try:
import uio
2021-04-20 01:22:44 -04:00
uio.IOBase
import uos
2021-04-20 01:22:44 -04:00
uos.mount
except (ImportError, AttributeError):
print("SKIP")
raise SystemExit
class UserFile(uio.IOBase):
def __init__(self, data):
self.data = data
self.pos = 0
2021-04-20 01:22:44 -04:00
def read(self):
return self.data
2021-04-20 01:22:44 -04:00
def readinto(self, buf):
n = 0
while n < len(buf) and self.pos < len(self.data):
buf[n] = self.data[self.pos]
n += 1
self.pos += 1
return n
2021-04-20 01:22:44 -04:00
def ioctl(self, req, arg):
2021-04-20 01:22:44 -04:00
print("ioctl", req, arg)
return 0
class UserFS:
def __init__(self, files):
self.files = files
2021-04-20 01:22:44 -04:00
def mount(self, readonly, mksfs):
pass
2021-04-20 01:22:44 -04:00
def umount(self):
pass
2021-04-20 01:22:44 -04:00
def stat(self, path):
2021-04-20 01:22:44 -04:00
print("stat", path)
if path in self.files:
return (32768, 0, 0, 0, 0, 0, 0, 0, 0, 0)
raise OSError
2021-04-20 01:22:44 -04:00
def open(self, path, mode):
2021-04-20 01:22:44 -04:00
print("open", path, mode)
return UserFile(self.files[path])
# create and mount a user filesystem
user_files = {
2021-04-20 01:22:44 -04:00
"/data.txt": b"some data in a text file\n",
"/usermod1.py": b"print('in usermod1')\nimport usermod2",
"/usermod2.py": b"print('in usermod2')",
}
2021-04-20 01:22:44 -04:00
uos.mount(UserFS(user_files), "/userfs")
# open and read a file
2021-04-20 01:22:44 -04:00
f = open("/userfs/data.txt")
print(f.read())
# import files from the user filesystem
2021-04-20 01:22:44 -04:00
sys.path.append("/userfs")
import usermod1
# unmount and undo path addition
2021-04-20 01:22:44 -04:00
uos.umount("/userfs")
sys.path.pop()