|
| 1 | +# test VFS functionality with a user-defined filesystem |
| 2 | +# also tests parts of uio.IOBase implementation |
| 3 | + |
| 4 | +import sys, uio |
| 5 | + |
| 6 | +try: |
| 7 | + uio.IOBase |
| 8 | + import uos |
| 9 | + uos.mount |
| 10 | +except (ImportError, AttributeError): |
| 11 | + print("SKIP") |
| 12 | + raise SystemExit |
| 13 | + |
| 14 | + |
| 15 | +class UserFile(uio.IOBase): |
| 16 | + def __init__(self, data): |
| 17 | + self.data = data |
| 18 | + self.pos = 0 |
| 19 | + def read(self): |
| 20 | + return self.data |
| 21 | + def readinto(self, buf): |
| 22 | + n = 0 |
| 23 | + while n < len(buf) and self.pos < len(self.data): |
| 24 | + buf[n] = self.data[self.pos] |
| 25 | + n += 1 |
| 26 | + self.pos += 1 |
| 27 | + return n |
| 28 | + def ioctl(self, req, arg): |
| 29 | + print('ioctl', req, arg) |
| 30 | + return 0 |
| 31 | + |
| 32 | + |
| 33 | +class UserFS: |
| 34 | + def __init__(self, files): |
| 35 | + self.files = files |
| 36 | + def mount(self, readonly, mksfs): |
| 37 | + pass |
| 38 | + def umount(self): |
| 39 | + pass |
| 40 | + def stat(self, path): |
| 41 | + print('stat', path) |
| 42 | + if path in self.files: |
| 43 | + return (32768, 0, 0, 0, 0, 0, 0, 0, 0, 0) |
| 44 | + raise OSError |
| 45 | + def open(self, path, mode): |
| 46 | + print('open', path, mode) |
| 47 | + return UserFile(self.files[path]) |
| 48 | + |
| 49 | + |
| 50 | +# create and mount a user filesystem |
| 51 | +user_files = { |
| 52 | + '/data.txt': b"some data in a text file\n", |
| 53 | + '/usermod1.py': b"print('in usermod1')\nimport usermod2", |
| 54 | + '/usermod2.py': b"print('in usermod2')", |
| 55 | +} |
| 56 | +uos.mount(UserFS(user_files), '/userfs') |
| 57 | + |
| 58 | +# open and read a file |
| 59 | +f = open('/userfs/data.txt') |
| 60 | +print(f.read()) |
| 61 | + |
| 62 | +# import files from the user filesystem |
| 63 | +sys.path.append('/userfs') |
| 64 | +import usermod1 |
| 65 | + |
| 66 | +# unmount and undo path addition |
| 67 | +uos.umount('/userfs') |
| 68 | +sys.path.pop() |
0 commit comments