test_micropython.py 2.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. import os
  2. import infra.basetest
  3. class TestMicroPython(infra.basetest.BRTest):
  4. config = infra.basetest.BASIC_TOOLCHAIN_CONFIG + \
  5. f"""
  6. BR2_PACKAGE_MICROPYTHON=y
  7. BR2_PACKAGE_MICROPYTHON_LIB=y
  8. BR2_ROOTFS_OVERLAY="{infra.filepath("tests/package/test_micropython/rootfs-overlay")}"
  9. BR2_TARGET_ROOTFS_CPIO=y
  10. # BR2_TARGET_ROOTFS_TAR is not set
  11. """
  12. def run_upy_code(self, python_code, opts=""):
  13. cmd = f'micropython {opts} -c "{python_code}"'
  14. output, ret = self.emulator.run(cmd)
  15. self.assertEqual(ret, 0, f"could not run '{cmd}', returned {ret}: '{output}'")
  16. return output
  17. def test_run(self):
  18. cpio_file = os.path.join(self.builddir, "images", "rootfs.cpio")
  19. self.emulator.boot(arch="armv5",
  20. kernel="builtin",
  21. options=["-initrd", cpio_file])
  22. self.emulator.login()
  23. # The micropython binary can execute.
  24. self.assertRunOk("micropython -h")
  25. # Query interpreter version and implementation.
  26. py_code = "import sys ; "
  27. py_code += "print('Version:', sys.version) ; "
  28. py_code += "print('Implementation:', sys.implementation)"
  29. self.run_upy_code(py_code)
  30. # Check implementation is 'micropython'.
  31. py_code = "import sys ; print(sys.implementation.name)"
  32. output = self.run_upy_code(py_code)
  33. self.assertEqual(output[0], "micropython")
  34. # Check micropython optimization are correctly reported.
  35. py_code = "import micropython ; print(micropython.opt_level())"
  36. for opt_level in range(4):
  37. output = self.run_upy_code(py_code, f"-O{opt_level}")
  38. self.assertEqual(
  39. int(output[0]),
  40. opt_level,
  41. f"Running '{py_code}' at -O{opt_level} returned '{output}'"
  42. )
  43. # Check micropython can return a non-zero exit code.
  44. expected_code = 123
  45. py_code = "import sys ; "
  46. py_code += f"sys.exit({expected_code})"
  47. cmd = f'micropython -c "{py_code}"'
  48. _, exit_code = self.emulator.run(cmd)
  49. self.assertEqual(exit_code, expected_code)
  50. # Check micropython computes correctly.
  51. input_value = 1234
  52. expected_output = str(sum(range(input_value)))
  53. py_code = f"print(sum(range(({input_value}))))"
  54. output = self.run_upy_code(py_code)
  55. self.assertEqual(output[0], expected_output)
  56. # Check a small script can execute.
  57. self.assertRunOk("/root/mandel.py", timeout=10)
  58. # Check we can use a micropython-lib module.
  59. msg = "Hello Buildroot!"
  60. filename = "file.txt"
  61. gz_filename = f"{filename}.gz"
  62. self.assertRunOk(f"echo '{msg}' > {filename}")
  63. self.assertRunOk(f"gzip {filename}")
  64. out, ret = self.emulator.run(f"/root/zcat.py {gz_filename}")
  65. self.assertEqual(ret, 0)
  66. self.assertEqual(out[0], msg)