-
-
Notifications
You must be signed in to change notification settings - Fork 276
/
test_unit.py
9680 lines (8352 loc) · 332 KB
/
test_unit.py
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
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#
# test_unit.py
#
# Unit tests for pyparsing module
#
# Copyright 2002-2021, Paul McGuire
#
#
import contextlib
import datetime
import random
import re
import sys
import warnings
from types import SimpleNamespace
from io import StringIO
from textwrap import dedent
from typing import Any
import unittest
import pyparsing as pp
from examples.jsonParser import jsonObject
from pyparsing import ParserElement, ParseException, ParseFatalException
from tests.json_parser_tests import test1, test2, test3, test4, test5
import platform
ppc = pp.pyparsing_common
ppt = pp.pyparsing_test
# see which Python implementation we are running
python_impl = platform.python_implementation()
CPYTHON_ENV = python_impl == "CPython"
IRON_PYTHON_ENV = python_impl == "IronPython"
JYTHON_ENV = python_impl == "Jython"
PYPY_ENV = python_impl == "PyPy"
# get full stack traces during testing
pp.ParserElement.verbose_stacktrace = True
# simple utility for flattening nested lists
def flatten(nested_list):
if not isinstance(nested_list, list):
return [nested_list]
if not nested_list:
return nested_list
return flatten(nested_list[0]) + flatten(nested_list[1:])
class resetting:
def __init__(self, *args):
ob = args[0]
attrnames = args[1:]
self.ob = ob
self.save_attrs = attrnames
self.save_values = [getattr(ob, attrname) for attrname in attrnames]
def __enter__(self):
pass
def __exit__(self, *args):
for attr, value in zip(self.save_attrs, self.save_values):
setattr(self.ob, attr, value)
def find_all_re_matches(patt, s):
ret = []
start = 0
if isinstance(patt, str):
patt = re.compile(patt)
while True:
found = patt.search(s, pos=start)
if found:
ret.append(found)
start = found.end()
else:
break
return ret
def current_method_name(level=2):
import traceback
stack = traceback.extract_stack(limit=level)
return stack[0].name
def __():
return current_method_name(3) + ": "
class TestCase(unittest.TestCase):
@contextlib.contextmanager
def assertRaises(self, expected_exception_type: Any, msg: Any = None):
"""
Simple wrapper to print out the exceptions raised after assertRaises
"""
with super().assertRaises(expected_exception_type, msg=msg) as ar:
yield
if getattr(ar, "exception", None) is not None:
print(
f"Raised expected exception: {type(ar.exception).__name__}: {str(ar.exception)}"
)
else:
print(f"Expected {expected_exception_type.__name__} exception not raised")
return ar
@contextlib.contextmanager
def assertDoesNotWarn(self, warning_type: type = UserWarning, msg: str = None):
with warnings.catch_warnings(record=True) as w:
warnings.simplefilter("error")
try:
yield
except Exception as e:
if msg is None:
msg = f"unexpected warning {e} raised"
if isinstance(e, warning_type):
self.fail(f"{msg}: {e}")
else:
raise
class Test01_PyparsingTestInit(TestCase):
def runTest(self):
print(
"Beginning test of pyparsing, version",
pp.__version__,
pp.__version_time__,
)
print("Python version", sys.version)
print("__version_info__ :", pp.__version_info__)
print("__version_info__ repr:", repr(pp.__version_info__))
class Test01a_PyparsingEnvironmentTests(TestCase):
def runTest(self):
# test warnings enable detection
# fmt: off
tests = [
(([], "",), False),
((["d", ], "",), True),
((["d", "i:::pyparsing", ], "",), False),
((["d:::pyparsing", ], "",), True),
((["d:::pyparsing", "i", ], "",), False),
((["d:::blah", ], "",), False),
((["i", ], "",), False),
(([], "1",), True),
((["d", ], "1",), True),
((["d", "i:::pyparsing", ], "1",), False),
((["d:::pyparsing", ], "1",), True),
((["d:::pyparsing", "i", ], "1",), False),
((["d:::blah", ], "1",), True),
((["i", ], "1",), False),
]
# fmt: on
all_success = True
for args, expected in tests:
message = f"{args} should be {expected}"
print(message, end=" -> ")
actual = pp.core._should_enable_warnings(*args)
print("PASS" if actual == expected else "FAIL")
if actual != expected:
all_success = False
self.assertTrue(all_success, "failed warnings enable test")
class Test01b_PyparsingUnitTestUtilitiesTests(TestCase):
def runTest(self):
with ppt.reset_pyparsing_context():
pp.enable_diag(pp.Diagnostics.warn_on_parse_using_empty_Forward)
# test assertDoesNotWarn raises an AssertionError
with self.assertRaises(AssertionError):
with self.assertDoesNotWarn(
msg="warned when parsing with an empty Forward expression warning was suppressed",
):
base = pp.Forward()
try:
print(base.parseString("x"))
except ParseException as pe:
pass
class Test02_WithoutPackrat(ppt.TestParseResultsAsserts, TestCase):
suite_context = None
save_suite_context = None
def setUp(self):
self.suite_context.restore()
def test000_assert_packrat_status(self):
print("Packrat enabled:", ParserElement._packratEnabled)
self.assertFalse(ParserElement._packratEnabled, "packrat enabled")
def testScanStringWithOverlap(self):
parser = pp.Word(pp.alphas, exact=3)
without_overlaps = sum(t for t, s, e in parser.scanString("ABCDEFGHI")).asList()
self.assertEqual(
["ABC", "DEF", "GHI"],
without_overlaps,
msg="scanString without overlaps failed",
)
with_overlaps = sum(
t for t, s, e in parser.scanString("ABCDEFGHI", overlap=True)
).asList()
self.assertEqual(
["ABC", "BCD", "CDE", "DEF", "EFG", "FGH", "GHI"],
with_overlaps,
msg="scanString with overlaps failed",
)
def testCombineWithResultsNames(self):
# test case reproducing Issue #350
from pyparsing import White, alphas, Word
parser = White(" \t").set_results_name("indent") + Word(
alphas
).set_results_name("word")
result = parser.parse_string(" test")
print(result.dump())
self.assertParseResultsEquals(
result, [" ", "test"], {"indent": " ", "word": "test"}
)
parser = White(" \t") + Word(alphas).set_results_name("word")
result = parser.parse_string(" test")
print(result.dump())
self.assertParseResultsEquals(result, [" ", "test"], {"word": "test"})
def testTransformString(self):
make_int_with_commas = ppc.integer().addParseAction(lambda t: f"{t[0]:,}")
lower_case_words = pp.Word(pp.alphas.lower(), asKeyword=True) + pp.Optional(
pp.White()
)
nested_list = pp.nestedExpr().addParseAction(pp.ParseResults.asList)
transformer = make_int_with_commas | nested_list | lower_case_words.suppress()
in_string = (
"I wish to buy 12345 shares of Acme Industries (as a gift to my (ex)wife)"
)
print(in_string)
out_string = transformer.transformString(in_string)
print(out_string)
self.assertEqual(
"I 12,345 Acme Industries asagifttomyexwife",
out_string,
msg="failure in transformString",
)
def testTransformStringWithLeadingWhitespace(self):
sample = "\n\ncheck"
sample = " check"
keywords = pp.oneOf("aaa bbb", asKeyword=True)
ident = ~keywords + pp.Word(pp.alphas)
ident = pp.Combine(~keywords + pp.Word(pp.alphas))
# ident.add_parse_action(lambda t: t[0].upper())
ident.add_parse_action(ppc.upcaseTokens)
transformed = ident.transformString(sample)
print(ppt.with_line_numbers(sample))
print(ppt.with_line_numbers(transformed))
self.assertEqual(sample.replace("check", "CHECK"), transformed)
def testTransformStringWithLeadingNotAny(self):
sample = "print a100"
keywords = set("print read".split())
ident = pp.Word(pp.alphas, pp.alphanums).add_condition(
lambda t: t[0] not in keywords
)
print(ident.searchString(sample))
def testTransformStringWithExpectedLeadingWhitespace(self):
sample1 = "\n\ncheck aaa"
sample2 = " check aaa"
keywords = pp.oneOf("aaa bbb", asKeyword=True)
# This construct only works with parse_string, not with scan_string or its siblings
# ident = ~keywords + pp.Word(pp.alphas)
ident = pp.Word(pp.alphas)
ident.add_parse_action(ppc.upcaseTokens)
for sample in sample1, sample2:
transformed = (keywords | ident).transformString(sample)
print(ppt.with_line_numbers(sample))
print(ppt.with_line_numbers(transformed))
self.assertEqual(sample.replace("check", "CHECK"), transformed)
print()
def testTransformStringWithLeadingWhitespaceFromTranslateProject(self):
from pyparsing import Keyword, Word, alphas, alphanums, Combine
block_start = (Keyword("{") | Keyword("BEGIN")).set_name("block_start")
block_end = (Keyword("}") | Keyword("END")).set_name("block_end")
reserved_words = block_start | block_end
# this is the first critical part of this test, an And with a leading NotAny
# This construct only works with parse_string, not with scan_string or its siblings
# name_id = ~reserved_words + Word(alphas, alphanums + "_").set_name("name_id")
name_id = Word(alphas, alphanums + "_").set_name("name_id")
dialog = name_id("block_id") + (Keyword("DIALOGEX") | Keyword("DIALOG"))(
"block_type"
)
string_table = Keyword("STRINGTABLE")("block_type")
test_string = (
"""\r\nSTRINGTABLE\r\nBEGIN\r\n// Comment\r\nIDS_1 "Copied"\r\nEND\r\n"""
)
print("Original:")
print(repr(test_string))
print("Should match:")
# this is the second critical part of this test, an Or or MatchFirst including dialog
for parser in (dialog ^ string_table, dialog | string_table):
result = (reserved_words | parser).transformString(test_string)
print(repr(result))
self.assertEqual(
test_string,
result,
"Failed whitespace skipping with NotAny and MatchFirst/Or",
)
def testUpdateDefaultWhitespace(self):
prev_default_whitespace_chars = pp.ParserElement.DEFAULT_WHITE_CHARS
try:
pp.dblQuotedString.copyDefaultWhiteChars = False
pp.ParserElement.setDefaultWhitespaceChars(" \t")
self.assertEqual(
set(" \t"),
set(pp.sglQuotedString.whiteChars),
"setDefaultWhitespaceChars did not update sglQuotedString",
)
self.assertEqual(
set(prev_default_whitespace_chars),
set(pp.dblQuotedString.whiteChars),
"setDefaultWhitespaceChars updated dblQuotedString but should not",
)
finally:
pp.dblQuotedString.copyDefaultWhiteChars = True
pp.ParserElement.setDefaultWhitespaceChars(prev_default_whitespace_chars)
self.assertEqual(
set(prev_default_whitespace_chars),
set(pp.dblQuotedString.whiteChars),
"setDefaultWhitespaceChars updated dblQuotedString",
)
with ppt.reset_pyparsing_context():
pp.ParserElement.setDefaultWhitespaceChars(" \t")
self.assertNotEqual(
set(prev_default_whitespace_chars),
set(pp.dblQuotedString.whiteChars),
"setDefaultWhitespaceChars updated dblQuotedString but should not",
)
EOL = pp.LineEnd().suppress().setName("EOL")
# Identifiers is a string + optional $
identifier = pp.Combine(pp.Word(pp.alphas) + pp.Optional("$"))
# Literals (number or double quoted string)
literal = ppc.number | pp.dblQuotedString
expression = literal | identifier
# expression.setName("expression").setDebug()
# ppc.number.setDebug()
# ppc.integer.setDebug()
line_number = ppc.integer
# Keywords
PRINT = pp.CaselessKeyword("print")
print_stmt = PRINT - pp.ZeroOrMore(expression | ";")
statement = print_stmt
code_line = pp.Group(line_number + statement + EOL)
program = pp.ZeroOrMore(code_line)
test = """\
10 print 123;
20 print 234; 567;
30 print 890
"""
parsed_program = program.parseString(test, parseAll=True)
print(parsed_program.dump())
self.assertEqual(
3,
len(parsed_program),
"failed to apply new whitespace chars to existing builtins",
)
def testUpdateDefaultWhitespace2(self):
with ppt.reset_pyparsing_context():
expr_tests = [
(pp.dblQuotedString, '"abc"'),
(pp.sglQuotedString, "'def'"),
(ppc.integer, "123"),
(ppc.number, "4.56"),
(ppc.identifier, "a_bc"),
]
NL = pp.LineEnd()
for expr, test_str in expr_tests:
parser = pp.Group(expr[1, ...] + pp.Optional(NL))[1, ...]
test_string = "\n".join([test_str] * 3)
result = parser.parseString(test_string, parseAll=True)
print(result.dump())
self.assertEqual(1, len(result), f"failed {test_string!r}")
pp.ParserElement.setDefaultWhitespaceChars(" \t")
for expr, test_str in expr_tests:
parser = pp.Group(expr[1, ...] + pp.Optional(NL))[1, ...]
test_string = "\n".join([test_str] * 3)
result = parser.parseString(test_string, parseAll=True)
print(result.dump())
self.assertEqual(3, len(result), f"failed {test_string!r}")
pp.ParserElement.setDefaultWhitespaceChars(" \n\t")
for expr, test_str in expr_tests:
parser = pp.Group(expr[1, ...] + pp.Optional(NL))[1, ...]
test_string = "\n".join([test_str] * 3)
result = parser.parseString(test_string, parseAll=True)
print(result.dump())
self.assertEqual(1, len(result), f"failed {test_string!r}")
def testParseFourFn(self):
import examples.fourFn as fourFn
import math
def test(s, ans):
fourFn.exprStack[:] = []
results = fourFn.BNF().parseString(s, parseAll=True)
try:
resultValue = fourFn.evaluate_stack(fourFn.exprStack)
except Exception:
self.assertIsNone(ans, f"exception raised for expression {s!r}")
else:
self.assertEqual(
ans,
resultValue,
f"failed to evaluate {s}, got {resultValue:f}",
)
print(s, "->", resultValue)
test("9", 9)
test("-9", -9)
test("--9", 9)
test("-E", -math.e)
test("9 + 3 + 5", 9 + 3 + 5)
test("9 + 3 / 11", 9 + 3.0 / 11)
test("(9 + 3)", (9 + 3))
test("(9+3) / 11", (9 + 3.0) / 11)
test("9 - 12 - 6", 9 - 12 - 6)
test("9 - (12 - 6)", 9 - (12 - 6))
test("2*3.14159", 2 * 3.14159)
test("3.1415926535*3.1415926535 / 10", 3.1415926535 * 3.1415926535 / 10)
test("PI * PI / 10", math.pi * math.pi / 10)
test("PI*PI/10", math.pi * math.pi / 10)
test("PI^2", math.pi**2)
test("round(PI^2)", round(math.pi**2))
test("6.02E23 * 8.048", 6.02e23 * 8.048)
test("e / 3", math.e / 3)
test("sin(PI/2)", math.sin(math.pi / 2))
test("10+sin(PI/4)^2", 10 + math.sin(math.pi / 4) ** 2)
test("trunc(E)", int(math.e))
test("trunc(-E)", int(-math.e))
test("round(E)", round(math.e))
test("round(-E)", round(-math.e))
test("E^PI", math.e**math.pi)
test("exp(0)", 1)
test("exp(1)", math.e)
test("2^3^2", 2**3**2)
test("(2^3)^2", (2**3) ** 2)
test("2^3+2", 2**3 + 2)
test("2^3+5", 2**3 + 5)
test("2^9", 2**9)
test("sgn(-2)", -1)
test("sgn(0)", 0)
test("sgn(0.1)", 1)
test("foo(0.1)", None)
test("round(E, 3)", round(math.e, 3))
test("round(PI^2, 3)", round(math.pi**2, 3))
test("sgn(cos(PI/4))", 1)
test("sgn(cos(PI/2))", 0)
test("sgn(cos(PI*3/4))", -1)
test("+(sgn(cos(PI/4)))", 1)
test("-(sgn(cos(PI/4)))", -1)
def testParseSQL(self):
# SQL parser uses packrat parsing, not compatible with LR
if ParserElement._left_recursion_enabled:
return
import examples.simpleSQL as simpleSQL
def test(s, num_expected_toks, expected_errloc=-1):
try:
sqlToks = flatten(
simpleSQL.simpleSQL.parseString(s, parseAll=True).asList()
)
print(s, sqlToks, len(sqlToks))
self.assertEqual(
num_expected_toks,
len(sqlToks),
f"invalid parsed tokens, expected {num_expected_toks}, found {len(sqlToks)} ({sqlToks})",
)
except ParseException as e:
if expected_errloc >= 0:
self.assertEqual(
expected_errloc,
e.loc,
f"expected error at {expected_errloc}, found at {e.loc}",
)
test("SELECT * from XYZZY, ABC", 6)
test("select * from SYS.XYZZY", 5)
test("Select A from Sys.dual", 5)
test("Select A,B,C from Sys.dual", 7)
test("Select A, B, C from Sys.dual", 7)
test("Select A, B, C from Sys.dual, Table2 ", 8)
test("Xelect A, B, C from Sys.dual", 0, 0)
test("Select A, B, C frox Sys.dual", 0, 15)
test("Select", 0, 6)
test("Select &&& frox Sys.dual", 0, 7)
test("Select A from Sys.dual where a in ('RED','GREEN','BLUE')", 12)
test(
"Select A from Sys.dual where a in ('RED','GREEN','BLUE') and b in (10,20,30)",
20,
)
test(
"Select A,b from table1,table2 where table1.id eq table2.id -- test out comparison operators",
10,
)
def testParseConfigFile(self):
from examples import configParse
def test(fnam, num_expected_toks, resCheckList):
print("Parsing", fnam, "...", end=" ")
with open(fnam) as infile:
iniFileLines = "\n".join(infile.read().splitlines())
iniData = configParse.inifile_BNF().parseString(iniFileLines, parseAll=True)
print(len(flatten(iniData.asList())))
print(list(iniData.keys()))
self.assertEqual(
num_expected_toks,
len(flatten(iniData.asList())),
"file %s not parsed correctly" % fnam,
)
for chkkey, chkexpect in resCheckList:
var = iniData
for attr in chkkey.split("."):
var = getattr(var, attr)
print(chkkey, var, chkexpect)
self.assertEqual(
chkexpect,
var,
f"ParseConfigFileTest: failed to parse ini {chkkey!r} as expected {chkexpect!r}, found {var}",
)
print("OK")
test(
"tests/karthik.ini",
23,
[("users.K", "8"), ("users.mod_scheme", "'QPSK'"), ("users.Na", "K+2")],
)
test(
"examples/Setup.ini",
125,
[
("Startup.audioinf", "M3i"),
("Languages.key1", "0x0003"),
("test.foo", "bar"),
],
)
def testParseJSONData(self):
expected = [
{
"glossary": {
"GlossDiv": {
"GlossList": [
{
"Abbrev": "ISO 8879:1986",
"Acronym": "SGML",
"AvogadroNumber": 6.02e23,
"EmptyDict": {},
"EmptyList": [],
"EvenPrimesGreaterThan2": [],
"FermatTheoremInMargin": False,
"GlossDef": "A meta-markup language, "
"used to create markup "
"languages such as "
"DocBook.",
"GlossSeeAlso": ["GML", "XML", "markup"],
"GlossTerm": "Standard Generalized " "Markup Language",
"ID": "SGML",
"LargestPrimeLessThan100": 97,
"MapRequiringFiveColors": None,
"PrimesLessThan10": [2, 3, 5, 7],
"SortAs": "SGML",
}
],
"title": "S",
},
"title": "example glossary",
}
},
{
"menu": {
"id": "file",
"popup": {
"menuitem": [
{"onclick": "CreateNewDoc()", "value": "New"},
{"onclick": "OpenDoc()", "value": "Open"},
{"onclick": "CloseDoc()", "value": "Close"},
]
},
"value": "File:",
}
},
{
"widget": {
"debug": "on",
"image": {
"alignment": "center",
"hOffset": 250,
"name": "sun1",
"src": "Images/Sun.png",
"vOffset": 250,
},
"text": {
"alignment": "center",
"data": "Click Here",
"hOffset": 250,
"name": "text1",
"onMouseUp": "sun1.opacity = (sun1.opacity / 100) * 90;",
"size": 36,
"style": "bold",
"vOffset": 100,
},
"window": {
"height": 500,
"name": "main_window",
"title": "Sample Konfabulator Widget",
"width": 500,
},
}
},
{
"web-app": {
"servlet": [
{
"init-param": {
"cachePackageTagsRefresh": 60,
"cachePackageTagsStore": 200,
"cachePackageTagsTrack": 200,
"cachePagesDirtyRead": 10,
"cachePagesRefresh": 10,
"cachePagesStore": 100,
"cachePagesTrack": 200,
"cacheTemplatesRefresh": 15,
"cacheTemplatesStore": 50,
"cacheTemplatesTrack": 100,
"configGlossary:adminEmail": "ksm@pobox.com",
"configGlossary:installationAt": "Philadelphia, " "PA",
"configGlossary:poweredBy": "Cofax",
"configGlossary:poweredByIcon": "/images/cofax.gif",
"configGlossary:staticPath": "/content/static",
"dataStoreClass": "org.cofax.SqlDataStore",
"dataStoreConnUsageLimit": 100,
"dataStoreDriver": "com.microsoft.jdbc.sqlserver.SQLServerDriver",
"dataStoreInitConns": 10,
"dataStoreLogFile": "/usr/local/tomcat/logs/datastore.log",
"dataStoreLogLevel": "debug",
"dataStoreMaxConns": 100,
"dataStoreName": "cofax",
"dataStorePassword": "dataStoreTestQuery",
"dataStoreTestQuery": "SET NOCOUNT "
"ON;select "
"test='test';",
"dataStoreUrl": "jdbc:microsoft:sqlserver://LOCALHOST:1433;DatabaseName=goon",
"dataStoreUser": "sa",
"defaultFileTemplate": "articleTemplate.htm",
"defaultListTemplate": "listTemplate.htm",
"jspFileTemplate": "articleTemplate.jsp",
"jspListTemplate": "listTemplate.jsp",
"maxUrlLength": 500,
"redirectionClass": "org.cofax.SqlRedirection",
"searchEngineFileTemplate": "forSearchEngines.htm",
"searchEngineListTemplate": "forSearchEnginesList.htm",
"searchEngineRobotsDb": "WEB-INF/robots.db",
"templateLoaderClass": "org.cofax.FilesTemplateLoader",
"templateOverridePath": "",
"templatePath": "templates",
"templateProcessorClass": "org.cofax.WysiwygTemplate",
"useDataStore": True,
"useJSP": False,
},
"servlet-class": "org.cofax.cds.CDSServlet",
"servlet-name": "cofaxCDS",
},
{
"init-param": {
"mailHost": "mail1",
"mailHostOverride": "mail2",
},
"servlet-class": "org.cofax.cds.EmailServlet",
"servlet-name": "cofaxEmail",
},
{
"servlet-class": "org.cofax.cds.AdminServlet",
"servlet-name": "cofaxAdmin",
},
{
"servlet-class": "org.cofax.cds.FileServlet",
"servlet-name": "fileServlet",
},
{
"init-param": {
"adminGroupID": 4,
"betaServer": True,
"dataLog": 1,
"dataLogLocation": "/usr/local/tomcat/logs/dataLog.log",
"dataLogMaxSize": "",
"fileTransferFolder": "/usr/local/tomcat/webapps/content/fileTransferFolder",
"log": 1,
"logLocation": "/usr/local/tomcat/logs/CofaxTools.log",
"logMaxSize": "",
"lookInContext": 1,
"removePageCache": "/content/admin/remove?cache=pages&id=",
"removeTemplateCache": "/content/admin/remove?cache=templates&id=",
"templatePath": "toolstemplates/",
},
"servlet-class": "org.cofax.cms.CofaxToolsServlet",
"servlet-name": "cofaxTools",
},
],
"servlet-mapping": {
"cofaxAdmin": "/admin/*",
"cofaxCDS": "/",
"cofaxEmail": "/cofaxutil/aemail/*",
"cofaxTools": "/tools/*",
"fileServlet": "/static/*",
},
"taglib": {
"taglib-location": "/WEB-INF/tlds/cofax.tld",
"taglib-uri": "cofax.tld",
},
}
},
{
"menu": {
"header": "SVG Viewer",
"items": [
{"id": "Open"},
{"id": "OpenNew", "label": "Open New"},
None,
{"id": "ZoomIn", "label": "Zoom In"},
{"id": "ZoomOut", "label": "Zoom Out"},
{"id": "OriginalView", "label": "Original View"},
None,
{"id": "Quality"},
{"id": "Pause"},
{"id": "Mute"},
None,
{"id": "Find", "label": "Find..."},
{"id": "FindAgain", "label": "Find Again"},
{"id": "Copy"},
{"id": "CopyAgain", "label": "Copy Again"},
{"id": "CopySVG", "label": "Copy SVG"},
{"id": "ViewSVG", "label": "View SVG"},
{"id": "ViewSource", "label": "View Source"},
{"id": "SaveAs", "label": "Save As"},
None,
{"id": "Help"},
{"id": "About", "label": "About Adobe CVG Viewer..."},
],
}
},
]
for t, exp_result in zip((test1, test2, test3, test4, test5), expected):
result = jsonObject.parseString(t, parseAll=True)
self.assertEqual(exp_result, result[0])
def testParseCommaSeparatedValues(self):
testData = [
"a,b,c,100.2,,3",
"d, e, j k , m ",
"'Hello, World', f, g , , 5.1,x",
"John Doe, 123 Main St., Cleveland, Ohio",
"Jane Doe, 456 St. James St., Los Angeles , California ",
"",
]
testVals = [
[(3, "100.2"), (4, ""), (5, "3")],
[(2, "j k"), (3, "m")],
[(0, "'Hello, World'"), (2, "g"), (3, "")],
[(0, "John Doe"), (1, "123 Main St."), (2, "Cleveland"), (3, "Ohio")],
[
(0, "Jane Doe"),
(1, "456 St. James St."),
(2, "Los Angeles"),
(3, "California"),
],
]
for line, tests in zip(testData, testVals):
print("Parsing: %r ->" % line, end=" ")
results = ppc.comma_separated_list.parseString(line, parseAll=True)
print(results)
for t in tests:
if not (len(results) > t[0] and results[t[0]] == t[1]):
print("$$$", results.dump())
print("$$$", results[0])
self.assertTrue(
len(results) > t[0] and results[t[0]] == t[1],
"failed on %s, item %d s/b '%s', got '%s'"
% (line, t[0], t[1], str(results.asList())),
)
def testParseEBNF(self):
from examples import ebnf
print("Constructing EBNF parser with pyparsing...")
grammar = """
syntax = (syntax_rule), {(syntax_rule)};
syntax_rule = meta_identifier, '=', definitions_list, ';';
definitions_list = single_definition, {'|', single_definition};
single_definition = syntactic_term, {',', syntactic_term};
syntactic_term = syntactic_factor,['-', syntactic_factor];
syntactic_factor = [integer, '*'], syntactic_primary;
syntactic_primary = optional_sequence | repeated_sequence |
grouped_sequence | meta_identifier | terminal_string;
optional_sequence = '[', definitions_list, ']';
repeated_sequence = '{', definitions_list, '}';
grouped_sequence = '(', definitions_list, ')';
(*
terminal_string = "'", character - "'", {character - "'"}, "'" |
'"', character - '"', {character - '"'}, '"';
meta_identifier = letter, {letter | digit};
integer = digit, {digit};
*)
"""
table = {}
table["terminal_string"] = pp.quotedString
table["meta_identifier"] = pp.Word(pp.alphas + "_", pp.alphas + "_" + pp.nums)
table["integer"] = pp.Word(pp.nums)
print("Parsing EBNF grammar with EBNF parser...")
parsers = ebnf.parse(grammar, table)
ebnf_parser = parsers["syntax"]
ebnf_comment = pp.Literal("(*") + ... + "*)"
ebnf_parser.ignore(ebnf_comment)
print("-", "\n- ".join(parsers.keys()))
self.assertEqual(
13, len(list(parsers.keys())), "failed to construct syntax grammar"
)
print("Parsing EBNF grammar with generated EBNF parser...")
parsed_chars = ebnf_parser.parseString(grammar, parseAll=True)
parsed_char_len = len(parsed_chars)
print("],\n".join(str(parsed_chars.asList()).split("],")))
self.assertEqual(
98,
len(flatten(parsed_chars.asList())),
"failed to tokenize grammar correctly",
)
def testParseIDL(self):
from examples import idlParse
def test(strng, numToks, expectedErrloc=0):
print(strng)
try:
bnf = idlParse.CORBA_IDL_BNF()
tokens = bnf.parseString(strng, parseAll=True)
print("tokens = ")
tokens.pprint()
tokens = flatten(tokens.asList())
print(len(tokens))
self.assertEqual(
numToks,
len(tokens),
f"error matching IDL string, {strng} -> {str(tokens)}",
)
except ParseException as err:
print(err.line)
print(" " * (err.column - 1) + "^")
print(err)
self.assertEqual(
0,
numToks,
f"unexpected ParseException while parsing {strng}, {str(err)}",
)
self.assertEqual(
expectedErrloc,
err.loc,
"expected ParseException at %d, found exception at %d"
% (expectedErrloc, err.loc),
)
test(
"""
/*
* a block comment *
*/
typedef string[10] tenStrings;
typedef sequence<string> stringSeq;
typedef sequence< sequence<string> > stringSeqSeq;
interface QoSAdmin {
stringSeq method1(in string arg1, inout long arg2);
stringSeqSeq method2(in string arg1, inout long arg2, inout long arg3);
string method3();
};
""",
59,
)
test(
"""
/*
* a block comment *
*/
typedef string[10] tenStrings;
typedef
/** ** *** **** *
* a block comment *
*/
sequence<string> /*comment inside an And */ stringSeq;
/* */ /**/ /***/ /****/
typedef sequence< sequence<string> > stringSeqSeq;
interface QoSAdmin {
stringSeq method1(in string arg1, inout long arg2);
stringSeqSeq method2(in string arg1, inout long arg2, inout long arg3);
string method3();
};
""",
59,
)
test(
r"""
const string test="Test String\n";
const long a = 0;
const long b = -100;
const float c = 3.14159;
const long d = 0x007f7f7f;
exception TestException
{
string msg;
sequence<string> dataStrings;
};
interface TestInterface
{
void method1(in string arg1, inout long arg2);
};
""",
60,
)
test(
"""
module Test1
{
exception TestException
{
string msg;
];
interface TestInterface
{
void method1(in string arg1, inout long arg2)
raises (TestException);
};
};
""",
0,
56,
)
test(
"""
module Test1
{
exception TestException
{
string msg;
};
};
""",
13,
)
def testParseVerilog(self):