mpy_invalid.py 1.5 KB

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