This repo contains code to mirror other repos. It also contains the code that is getting mirrored.
Du kannst nicht mehr als 25 Themen auswählen Themen müssen entweder mit einem Buchstaben oder einer Ziffer beginnen. Sie können Bindestriche („-“) enthalten und bis zu 35 Zeichen lang sein.

111 Zeilen
2.5 KiB

  1. from __future__ import absolute_import
  2. import sys
  3. from unittest import TestCase, main
  4. from lark.tree import Tree
  5. from lark.tools import standalone
  6. try:
  7. from StringIO import StringIO
  8. except ImportError:
  9. from io import StringIO
  10. class TestStandalone(TestCase):
  11. def setUp(self):
  12. pass
  13. def _create_standalone(self, grammar):
  14. code_buf = StringIO()
  15. temp = sys.stdout
  16. sys.stdout = code_buf
  17. standalone.main(StringIO(grammar), 'start')
  18. sys.stdout = temp
  19. code = code_buf.getvalue()
  20. context = {}
  21. exec(code, context)
  22. return context
  23. def test_simple(self):
  24. grammar = """
  25. start: NUMBER WORD
  26. %import common.NUMBER
  27. %import common.WORD
  28. %import common.WS
  29. %ignore WS
  30. """
  31. context = self._create_standalone(grammar)
  32. _Lark = context['Lark_StandAlone']
  33. l = _Lark()
  34. x = l.parse('12 elephants')
  35. self.assertEqual(x.children, ['12', 'elephants'])
  36. x = l.parse('16 candles')
  37. self.assertEqual(x.children, ['16', 'candles'])
  38. def test_contextual(self):
  39. grammar = """
  40. start: a b
  41. a: "A" "B"
  42. b: "AB"
  43. """
  44. context = self._create_standalone(grammar)
  45. _Lark = context['Lark_StandAlone']
  46. l = _Lark()
  47. x = l.parse('ABAB')
  48. class T(context['Transformer']):
  49. def a(self, items):
  50. return 'a'
  51. def b(self, items):
  52. return 'b'
  53. start = list
  54. x = T().transform(x)
  55. self.assertEqual(x, ['a', 'b'])
  56. l2 = _Lark(transformer=T())
  57. x = l2.parse('ABAB')
  58. self.assertEqual(x, ['a', 'b'])
  59. def test_postlex(self):
  60. from lark.indenter import Indenter
  61. class MyIndenter(Indenter):
  62. NL_type = '_NEWLINE'
  63. OPEN_PAREN_types = ['LPAR', 'LSQB', 'LBRACE']
  64. CLOSE_PAREN_types = ['RPAR', 'RSQB', 'RBRACE']
  65. INDENT_type = '_INDENT'
  66. DEDENT_type = '_DEDENT'
  67. tab_len = 8
  68. grammar = r"""
  69. start: "(" ")" _NEWLINE
  70. _NEWLINE: /\n/
  71. """
  72. context = self._create_standalone(grammar)
  73. _Lark = context['Lark_StandAlone']
  74. l = _Lark(postlex=MyIndenter())
  75. x = l.parse('()\n')
  76. self.assertEqual(x, Tree('start', []))
  77. l = _Lark(postlex=MyIndenter())
  78. x = l.parse('(\n)\n')
  79. self.assertEqual(x, Tree('start', []))
  80. if __name__ == '__main__':
  81. main()