This repo contains code to mirror other repos. It also contains the code that is getting mirrored.
您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符
 
 

117 行
2.8 KiB

  1. import json
  2. import unittest
  3. from unittest import TestCase
  4. from lark import Lark
  5. from lark.reconstruct import Reconstructor
  6. common = """
  7. %import common (WS_INLINE, NUMBER, WORD)
  8. %ignore WS_INLINE
  9. """
  10. def _remove_ws(s):
  11. return s.replace(' ', '').replace('\n','')
  12. class TestReconstructor(TestCase):
  13. def assert_reconstruct(self, grammar, code):
  14. parser = Lark(grammar, parser='lalr', maybe_placeholders=False)
  15. tree = parser.parse(code)
  16. new = Reconstructor(parser).reconstruct(tree)
  17. self.assertEqual(_remove_ws(code), _remove_ws(new))
  18. def test_starred_rule(self):
  19. g = """
  20. start: item*
  21. item: NL
  22. | rule
  23. rule: WORD ":" NUMBER
  24. NL: /(\\r?\\n)+\\s*/
  25. """ + common
  26. code = """
  27. Elephants: 12
  28. """
  29. self.assert_reconstruct(g, code)
  30. def test_starred_group(self):
  31. g = """
  32. start: (rule | NL)*
  33. rule: WORD ":" NUMBER
  34. NL: /(\\r?\\n)+\\s*/
  35. """ + common
  36. code = """
  37. Elephants: 12
  38. """
  39. self.assert_reconstruct(g, code)
  40. def test_alias(self):
  41. g = """
  42. start: line*
  43. line: NL
  44. | rule
  45. | "hello" -> hi
  46. rule: WORD ":" NUMBER
  47. NL: /(\\r?\\n)+\\s*/
  48. """ + common
  49. code = """
  50. Elephants: 12
  51. hello
  52. """
  53. self.assert_reconstruct(g, code)
  54. def test_json_example(self):
  55. test_json = '''
  56. {
  57. "empty_object" : {},
  58. "empty_array" : [],
  59. "booleans" : { "YES" : true, "NO" : false },
  60. "numbers" : [ 0, 1, -2, 3.3, 4.4e5, 6.6e-7 ],
  61. "strings" : [ "This", [ "And" , "That", "And a \\"b" ] ],
  62. "nothing" : null
  63. }
  64. '''
  65. json_grammar = r"""
  66. ?start: value
  67. ?value: object
  68. | array
  69. | string
  70. | SIGNED_NUMBER -> number
  71. | "true" -> true
  72. | "false" -> false
  73. | "null" -> null
  74. array : "[" [value ("," value)*] "]"
  75. object : "{" [pair ("," pair)*] "}"
  76. pair : string ":" value
  77. string : ESCAPED_STRING
  78. %import common.ESCAPED_STRING
  79. %import common.SIGNED_NUMBER
  80. %import common.WS
  81. %ignore WS
  82. """
  83. json_parser = Lark(json_grammar, parser='lalr', maybe_placeholders=False)
  84. tree = json_parser.parse(test_json)
  85. new_json = Reconstructor(json_parser).reconstruct(tree)
  86. self.assertEqual(json.loads(new_json), json.loads(test_json))
  87. if __name__ == '__main__':
  88. unittest.main()