1# Test for VfsLittle using a RAM device, with mount/umount
2
3try:
4    import uos
5
6    uos.VfsLfs1
7    uos.VfsLfs2
8except (ImportError, AttributeError):
9    print("SKIP")
10    raise SystemExit
11
12
13class RAMBlockDevice:
14    ERASE_BLOCK_SIZE = 1024
15
16    def __init__(self, blocks):
17        self.data = bytearray(blocks * self.ERASE_BLOCK_SIZE)
18
19    def readblocks(self, block, buf, off=0):
20        addr = block * self.ERASE_BLOCK_SIZE + off
21        for i in range(len(buf)):
22            buf[i] = self.data[addr + i]
23
24    def writeblocks(self, block, buf, off=0):
25        addr = block * self.ERASE_BLOCK_SIZE + off
26        for i in range(len(buf)):
27            self.data[addr + i] = buf[i]
28
29    def ioctl(self, op, arg):
30        if op == 4:  # block count
31            return len(self.data) // self.ERASE_BLOCK_SIZE
32        if op == 5:  # block size
33            return self.ERASE_BLOCK_SIZE
34        if op == 6:  # erase block
35            return 0
36
37
38def test(vfs_class):
39    print("test", vfs_class)
40
41    bdev = RAMBlockDevice(30)
42
43    # mount bdev unformatted
44    try:
45        uos.mount(bdev, "/lfs")
46    except Exception as er:
47        print(repr(er))
48
49    # mkfs
50    vfs_class.mkfs(bdev)
51
52    # construction
53    vfs = vfs_class(bdev)
54
55    # mount
56    uos.mount(vfs, "/lfs")
57
58    # import
59    with open("/lfs/lfsmod.py", "w") as f:
60        f.write('print("hello from lfs")\n')
61    import lfsmod
62
63    # import package
64    uos.mkdir("/lfs/lfspkg")
65    with open("/lfs/lfspkg/__init__.py", "w") as f:
66        f.write('print("package")\n')
67    import lfspkg
68
69    # chdir and import module from current directory (needs "" in sys.path)
70    uos.mkdir("/lfs/subdir")
71    uos.chdir("/lfs/subdir")
72    uos.rename("/lfs/lfsmod.py", "/lfs/subdir/lfsmod2.py")
73    import lfsmod2
74
75    # umount
76    uos.umount("/lfs")
77
78    # mount read-only
79    vfs = vfs_class(bdev)
80    uos.mount(vfs, "/lfs", readonly=True)
81
82    # test reading works
83    with open("/lfs/subdir/lfsmod2.py") as f:
84        print("lfsmod2.py:", f.read())
85
86    # test writing fails
87    try:
88        open("/lfs/test_write", "w")
89    except OSError as er:
90        print(repr(er))
91
92    # umount
93    uos.umount("/lfs")
94
95    # mount bdev again
96    uos.mount(bdev, "/lfs")
97
98    # umount
99    uos.umount("/lfs")
100
101    # clear imported modules
102    usys.modules.clear()
103
104
105# initialise path
106import usys
107
108usys.path.clear()
109usys.path.append("/lfs")
110usys.path.append("")
111
112# run tests
113test(uos.VfsLfs1)
114test(uos.VfsLfs2)
115