Skip to content

Commit 6d8816f

Browse files
committed
tests/import: Add test for importing invalid .mpy file.
1 parent e49cd10 commit 6d8816f

2 files changed

Lines changed: 70 additions & 0 deletions

File tree

tests/import/mpy_invalid.py

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

tests/import/mpy_invalid.py.exp

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
mod0 ValueError incompatible .mpy file
2+
mod1 ValueError incompatible .mpy file
3+
mod2 ValueError incompatible .mpy file

0 commit comments

Comments
 (0)