This repo contains code to mirror other repos. It also contains the code that is getting mirrored.
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

75 lines
2.1 KiB

  1. from __future__ import absolute_import
  2. import sys
  3. from unittest import TestCase, main
  4. from lark import Lark, Token, Tree
  5. from lark.load_grammar import GrammarLoader, GrammarError
  6. class TestGrammar(TestCase):
  7. def setUp(self):
  8. pass
  9. def test_errors(self):
  10. for msg, examples in GrammarLoader.ERRORS:
  11. for example in examples:
  12. try:
  13. p = Lark(example)
  14. except GrammarError as e:
  15. assert msg in str(e)
  16. else:
  17. assert False, "example did not raise an error"
  18. def test_override_rule(self):
  19. # Overrides the 'sep' template in existing grammar to add an optional terminating delimiter
  20. # Thus extending it beyond its original capacity
  21. p = Lark("""
  22. %import .test_templates_import (start, sep)
  23. %override sep{item, delim}: item (delim item)* delim?
  24. %ignore " "
  25. """, source_path=__file__)
  26. a = p.parse('[1, 2, 3]')
  27. b = p.parse('[1, 2, 3, ]')
  28. assert a == b
  29. def test_override_terminal(self):
  30. p = Lark("""
  31. %import .grammars.ab (startab, A, B)
  32. %override A: "c"
  33. %override B: "d"
  34. """, start='startab', source_path=__file__)
  35. a = p.parse('cd')
  36. self.assertEqual(a.children[0].children, [Token('A', 'c'), Token('B', 'd')])
  37. def test_extend_rule(self):
  38. p = Lark("""
  39. %import .grammars.ab (startab, A, B, expr)
  40. %extend expr: B A
  41. """, start='startab', source_path=__file__)
  42. a = p.parse('abab')
  43. self.assertEqual(a.children[0].children, ['a', Tree('expr', ['b', 'a']), 'b'])
  44. def test_extend_term(self):
  45. p = Lark("""
  46. %import .grammars.ab (startab, A, B, expr)
  47. %extend A: "c"
  48. """, start='startab', source_path=__file__)
  49. a = p.parse('acbb')
  50. self.assertEqual(a.children[0].children, ['a', Tree('expr', ['c', 'b']), 'b'])
  51. if __name__ == '__main__':
  52. main()