1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
|
import unittest
from io import StringIO
from pathlib import Path
from typing import List
from examples.jsonParser import jsonObject
from examples.simpleBool import boolExpr
from examples.simpleSQL import simpleSQL
from examples.mozillaCalendarParser import calendars
from pyparsing.diagram import to_railroad, railroad_to_html, NamedDiagram
import pyparsing as pp
import tempfile
import os
import sys
print(f"Running {__file__}")
print(sys.version_info)
curdir = Path(__file__).parent
def is_run_with_coverage():
"""Check whether test is run with coverage.
From https://stackoverflow.com/a/69812849/165216
"""
gettrace = getattr(sys, "gettrace", None)
if gettrace is None:
return False
else:
gettrace_result = gettrace()
try:
from coverage.pytracer import PyTracer
from coverage.tracer import CTracer
if isinstance(gettrace_result, (CTracer, PyTracer)):
return True
except ImportError:
pass
return False
def running_in_debug() -> bool:
"""
Returns True if we're in debug mode (determined by either setting
environment var, or running in a debugger which sets sys.settrace)
"""
return (
os.environ.get("RAILROAD_DEBUG", False)
or sys.gettrace()
and not is_run_with_coverage()
)
class TestRailroadDiagrams(unittest.TestCase):
def get_temp(self):
"""
Returns an appropriate temporary file for writing a railroad diagram
"""
delete_on_close = not running_in_debug()
return tempfile.NamedTemporaryFile(
dir=".",
delete=delete_on_close,
mode="w",
encoding="utf-8",
suffix=".html",
)
def generate_railroad(
self, expr: pp.ParserElement, label: str, show_results_names: bool = False
) -> List[NamedDiagram]:
"""
Generate an intermediate list of NamedDiagrams from a pyparsing expression.
"""
with self.get_temp() as temp:
railroad = to_railroad(expr, show_results_names=show_results_names)
temp.write(railroad_to_html(railroad))
if running_in_debug():
print(f"{label}: {temp.name}")
return railroad
def test_example_rr_diags(self):
subtests = [
(jsonObject, "jsonObject", 8),
(boolExpr, "boolExpr", 5),
(simpleSQL, "simpleSQL", 20),
(calendars, "calendars", 13),
]
for example_expr, label, expected_rr_len in subtests:
with self.subTest(f"{label}: test rr diag without results names"):
railroad = self.generate_railroad(example_expr, example_expr)
if len(railroad) != expected_rr_len:
diag_html = railroad_to_html(railroad)
for line in diag_html.splitlines():
if 'h1 class="railroad-heading"' in line:
print(line)
assert (
len(railroad) == expected_rr_len
), f"expected {expected_rr_len}, got {len(railroad)}"
with self.subTest(f"{label}: test rr diag with results names"):
railroad = self.generate_railroad(
example_expr, example_expr, show_results_names=True
)
if len(railroad) != expected_rr_len:
print(railroad_to_html(railroad))
assert (
len(railroad) == expected_rr_len
), f"expected {expected_rr_len}, got {len(railroad)}"
def test_nested_forward_with_inner_and_outer_names(self):
outer = pp.Forward().setName("outer")
inner = pp.Word(pp.alphas)[...].setName("inner")
outer <<= inner
railroad = self.generate_railroad(outer, "inner_outer_names")
assert len(railroad) == 2
railroad = self.generate_railroad(
outer, "inner_outer_names", show_results_names=True
)
assert len(railroad) == 2
def test_nested_forward_with_inner_name_only(self):
outer = pp.Forward()
inner = pp.Word(pp.alphas)[...].setName("inner")
outer <<= inner
railroad = self.generate_railroad(outer, "inner_only")
assert len(railroad) == 2
railroad = self.generate_railroad(outer, "inner_only", show_results_names=True)
assert len(railroad) == 2
def test_each_grammar(self):
grammar = pp.Each(
[
pp.Word(pp.nums),
pp.Word(pp.alphas),
pp.pyparsing_common.uuid,
]
).setName("int-word-uuid in any order")
railroad = self.generate_railroad(grammar, "each_expression")
assert len(railroad) == 2
railroad = self.generate_railroad(
grammar, "each_expression", show_results_names=True
)
assert len(railroad) == 2
def test_none_name(self):
grammar = pp.Or(["foo", "bar"])
railroad = to_railroad(grammar)
assert len(railroad) == 1
assert railroad[0].name is not None
def test_none_name2(self):
grammar = pp.Or(["foo", "bar"]) + pp.Word(pp.nums).setName("integer")
railroad = to_railroad(grammar)
assert len(railroad) == 2
assert railroad[0].name is not None
railroad = to_railroad(grammar, show_results_names=True)
assert len(railroad) == 2
def test_complete_combine_element(self):
ints = pp.Word(pp.nums)
grammar = pp.Combine(
ints("hours")
+ pp.Literal(":")
+ ints("minutes")
+ pp.Literal(":")
+ ints("seconds")
)
railroad = to_railroad(grammar)
assert len(railroad) == 1
railroad = to_railroad(grammar, show_results_names=True)
assert len(railroad) == 1
def test_create_diagram(self):
ints = pp.Word(pp.nums)
grammar = pp.Combine(
ints("hours")
+ pp.Literal(":")
+ ints("minutes")
+ pp.Literal(":")
+ ints("seconds")
)
diag_strio = StringIO()
grammar.create_diagram(output_html=diag_strio)
diag_str = diag_strio.getvalue().lower()
tags = "<html> </html> <head> </head> <body> </body>".split()
assert all(tag in diag_str for tag in tags)
def test_create_diagram_embed(self):
ints = pp.Word(pp.nums)
grammar = pp.Combine(
ints("hours")
+ pp.Literal(":")
+ ints("minutes")
+ pp.Literal(":")
+ ints("seconds")
)
diag_strio = StringIO()
grammar.create_diagram(output_html=diag_strio, embed=True)
diag_str = diag_strio.getvalue().lower()
tags = "<html> </html> <head> </head> <body> </body>".split()
assert not any(tag in diag_str for tag in tags)
if __name__ == "__main__":
unittest.main()
|