test_micropython.py 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  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_ROOTFS_OVERLAY="{infra.filepath("tests/package/test_micropython/rootfs-overlay")}"
  8. BR2_TARGET_ROOTFS_CPIO=y
  9. # BR2_TARGET_ROOTFS_TAR is not set
  10. """
  11. def run_upy_code(self, python_code, opts=""):
  12. cmd = f'micropython {opts} -c "{python_code}"'
  13. output, ret = self.emulator.run(cmd)
  14. self.assertEqual(ret, 0, f"could not run '{cmd}', returnd {ret}: '{output}'")
  15. return output
  16. def test_run(self):
  17. cpio_file = os.path.join(self.builddir, "images", "rootfs.cpio")
  18. self.emulator.boot(arch="armv5",
  19. kernel="builtin",
  20. options=["-initrd", cpio_file])
  21. self.emulator.login()
  22. # The micropython binary can execute.
  23. self.assertRunOk("micropython -h")
  24. # Query interpreter version and implementation.
  25. py_code = "import sys ; "
  26. py_code += "print('Version:', sys.version) ; "
  27. py_code += "print('Implementation:', sys.implementation)"
  28. self.run_upy_code(py_code)
  29. # Check implementation is 'micropython'.
  30. py_code = "import sys ; print(sys.implementation.name)"
  31. output = self.run_upy_code(py_code)
  32. self.assertEqual(output[0], "micropython")
  33. # Check micropython optimization are correctly reported.
  34. py_code = "import micropython ; print(micropython.opt_level())"
  35. for opt_level in range(4):
  36. output = self.run_upy_code(py_code, f"-O{opt_level}")
  37. self.assertEqual(
  38. int(output[0]),
  39. opt_level,
  40. f"Running '{py_code}' at -O{opt_level} returned '{output}'"
  41. )
  42. # Check micropython can return a non-zero exit code.
  43. expected_code = 123
  44. py_code = "import sys ; "
  45. py_code += f"sys.exit({expected_code})"
  46. cmd = f'micropython -c "{py_code}"'
  47. _, exit_code = self.emulator.run(cmd)
  48. self.assertEqual(exit_code, expected_code)
  49. # Check micropython computes correctly.
  50. input_value = 1234
  51. expected_output = str(sum(range(input_value)))
  52. py_code = f"print(sum(range(({input_value}))))"
  53. output = self.run_upy_code(py_code)
  54. self.assertEqual(output[0], expected_output)
  55. # Finally, Check a small script can execute.
  56. self.assertRunOk("/root/mandel.py", timeout=10)