1# test importing of invalid .mpy files
2
3try:
4    import usys, uio, uos
5
6    uio.IOBase
7    uos.mount
8except (ImportError, AttributeError):
9    print("SKIP")
10    raise SystemExit
11
12
13class UserFile(uio.IOBase):
14    def __init__(self, data):
15        self.data = memoryview(data)
16        self.pos = 0
17
18    def readinto(self, buf):
19        n = min(len(buf), len(self.data) - self.pos)
20        buf[:n] = self.data[self.pos : self.pos + n]
21        self.pos += n
22        return n
23
24    def ioctl(self, req, arg):
25        return 0
26
27
28class UserFS:
29    def __init__(self, files):
30        self.files = files
31
32    def mount(self, readonly, mksfs):
33        pass
34
35    def umount(self):
36        pass
37
38    def stat(self, path):
39        if path in self.files:
40            return (32768, 0, 0, 0, 0, 0, 0, 0, 0, 0)
41        raise OSError
42
43    def open(self, path, mode):
44        return UserFile(self.files[path])
45
46
47# these are the test .mpy files
48user_files = {
49    "/mod0.mpy": b"",  # empty file
50    "/mod1.mpy": b"M",  # too short header
51    "/mod2.mpy": b"M\x00\x00\x00",  # bad version
52    "/mod3.mpy": b"M\x00\x00\x00\x7f",  # qstr window too large
53}
54
55# create and mount a user filesystem
56uos.mount(UserFS(user_files), "/userfs")
57usys.path.append("/userfs")
58
59# import .mpy files from the user filesystem
60for i in range(len(user_files)):
61    mod = "mod%u" % i
62    try:
63        __import__(mod)
64    except ValueError as er:
65        print(mod, "ValueError", er)
66
67# unmount and undo path addition
68uos.umount("/userfs")
69usys.path.pop()
70