1# Test for VfsLittle using a RAM device, file IO 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): 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): 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(bdev, vfs_class): 39 print("test", vfs_class) 40 41 # mkfs 42 vfs_class.mkfs(bdev) 43 44 # construction 45 vfs = vfs_class(bdev) 46 47 # create text, print, write, close 48 f = vfs.open("test.txt", "wt") 49 print(f) 50 f.write("littlefs") 51 f.close() 52 53 # close already-closed file 54 f.close() 55 56 # create binary, print, write, flush, close 57 f = vfs.open("test.bin", "wb") 58 print(f) 59 f.write("littlefs") 60 f.flush() 61 f.close() 62 63 # create for append 64 f = vfs.open("test.bin", "ab") 65 f.write("more") 66 f.close() 67 68 # create exclusive 69 f = vfs.open("test2.bin", "xb") 70 f.close() 71 72 # create exclusive with error 73 try: 74 vfs.open("test2.bin", "x") 75 except OSError: 76 print("open OSError") 77 78 # read default 79 with vfs.open("test.txt", "") as f: 80 print(f.read()) 81 82 # read text 83 with vfs.open("test.txt", "rt") as f: 84 print(f.read()) 85 86 # read binary 87 with vfs.open("test.bin", "rb") as f: 88 print(f.read()) 89 90 # create read and write 91 with vfs.open("test.bin", "r+b") as f: 92 print(f.read(8)) 93 f.write("MORE") 94 with vfs.open("test.bin", "rb") as f: 95 print(f.read()) 96 97 # seek and tell 98 f = vfs.open("test.txt", "r") 99 print(f.tell()) 100 f.seek(3, 0) 101 print(f.tell()) 102 f.close() 103 104 # open nonexistent 105 try: 106 vfs.open("noexist", "r") 107 except OSError: 108 print("open OSError") 109 110 # open multiple files at the same time 111 f1 = vfs.open("test.txt", "") 112 f2 = vfs.open("test.bin", "b") 113 print(f1.read()) 114 print(f2.read()) 115 f1.close() 116 f2.close() 117 118 119bdev = RAMBlockDevice(30) 120test(bdev, uos.VfsLfs1) 121test(bdev, uos.VfsLfs2) 122