test_jq.py 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. import json
  2. import os
  3. import infra.basetest
  4. class TestJq(infra.basetest.BRTest):
  5. rootfs_overlay = \
  6. infra.filepath("tests/package/test_jq/rootfs-overlay")
  7. config = infra.basetest.BASIC_TOOLCHAIN_CONFIG + \
  8. f"""
  9. BR2_PACKAGE_JQ=y
  10. BR2_ROOTFS_OVERLAY="{rootfs_overlay}"
  11. BR2_TARGET_ROOTFS_CPIO=y
  12. # BR2_TARGET_ROOTFS_TAR is not set
  13. """
  14. def test_run(self):
  15. cpio_file = os.path.join(self.builddir, "images", "rootfs.cpio")
  16. self.emulator.boot(arch="armv5",
  17. kernel="builtin",
  18. options=["-initrd", cpio_file])
  19. self.emulator.login()
  20. # Check the program can execute.
  21. self.assertRunOk("jq --version")
  22. # Run jq on examples extracted from JSON RFC:
  23. # https://www.rfc-editor.org/rfc/rfc8259.txt
  24. for i in range(1, 6):
  25. fname = f"ex13-{i}.json"
  26. cmd = f"jq -M '.' {fname}"
  27. self.assertRunOk(cmd)
  28. # Check the execution fails on a non JSON file.
  29. cmd = "jq -M '.' broken.json"
  30. _, ret = self.emulator.run(cmd)
  31. self.assertNotEqual(ret, 0)
  32. # Check an execution of a simple query. Note that output is a
  33. # JSON (quoted) string.
  34. cmd = "jq -M '.[1].City' ex13-2.json"
  35. out, ret = self.emulator.run(cmd)
  36. self.assertEqual(ret, 0)
  37. self.assertEqual(out[0], '"SUNNYVALE"')
  38. # Run the same query with the -r option, to output raw text
  39. # (i.e. strings without quotes).
  40. cmd = "jq -r -M '.[1].City' ex13-2.json"
  41. out, ret = self.emulator.run(cmd)
  42. self.assertEqual(ret, 0)
  43. self.assertEqual(out[0], "SUNNYVALE")
  44. # Print the ex13-2.json file as compact JSON (with option -c).
  45. cmd = "jq -c -M '.' ex13-2.json"
  46. out, ret = self.emulator.run(cmd)
  47. self.assertEqual(ret, 0)
  48. # We reload this compact string using the Python json parser,
  49. # to test interoperability. We check the same element as in
  50. # previous queries in the Python object.
  51. json_data = json.loads(out[0])
  52. self.assertEqual(json_data[1]["City"], "SUNNYVALE")