summaryrefslogtreecommitdiff
path: root/tests/micropython/builtin_execfile.py
blob: 75a867bb94023dcc737c7efa51df795c1cf3271a (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
# Test builtin execfile function using VFS.

try:
    import io, os, vfs

    execfile
    io.IOBase
except (ImportError, NameError, AttributeError):
    print("SKIP")
    raise SystemExit


class File(io.IOBase):
    def __init__(self, data):
        self.data = data
        self.off = 0

    def ioctl(self, request, arg):
        if request == 4:  # MP_STREAM_CLOSE
            return 0
        return -1

    def readinto(self, buf):
        buf[:] = memoryview(self.data)[self.off : self.off + len(buf)]
        self.off += len(buf)
        return len(buf)


class Filesystem:
    def __init__(self, files):
        self.files = files

    def mount(self, readonly, mkfs):
        print("mount", readonly, mkfs)

    def umount(self):
        print("umount")

    def open(self, file, mode):
        print("open", file, mode)
        if file not in self.files:
            raise OSError(2)  # ENOENT
        return File(self.files[file])


# First umount any existing mount points the target may have.
try:
    vfs.umount("/")
except OSError:
    pass
for path in os.listdir("/"):
    vfs.umount("/" + path)

# Create and mount the VFS object.
files = {
    "/test.py": "print(123)",
}
fs = Filesystem(files)
vfs.mount(fs, "/test_mnt")

# Test execfile with a file that doesn't exist.
try:
    execfile("/test_mnt/noexist.py")
except OSError:
    print("OSError")

# Test execfile with a file that does exist.
execfile("/test_mnt/test.py")

# Test that it only works with string arguments.
try:
    execfile(b"aaa")
except TypeError:
    print("TypeError")

# Unmount the VFS object.
vfs.umount(fs)