forked from pyparsing/pyparsing
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathunitTests.py
4285 lines (3611 loc) · 166 KB
/
unitTests.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
# -*- coding: utf-8 -*-
#
# unitTests.py
#
# Unit tests for pyparsing module
#
# Copyright 2002-2018, Paul McGuire
#
#
from __future__ import division
from unittest import TestCase, TestSuite, TextTestRunner
import datetime
from pyparsing import ParseException
import pyparsing as pp
import sys
PY_3 = sys.version.startswith('3')
if PY_3:
import builtins
print_ = getattr(builtins, "print")
# catch calls to builtin print(), should be print_
def printX(*args, **kwargs):
raise Exception("Test coding error: using print() directly, should use print_()")
globals()['print'] = printX
from io import StringIO
else:
def _print(*args, **kwargs):
if 'end' in kwargs:
sys.stdout.write(' '.join(map(str,args)) + kwargs['end'])
else:
sys.stdout.write(' '.join(map(str,args)) + '\n')
print_ = _print
from cStringIO import StringIO
# see which Python implementation we are running
CPYTHON_ENV = (sys.platform == "win32")
IRON_PYTHON_ENV = (sys.platform == "cli")
JYTHON_ENV = sys.platform.startswith("java")
TEST_USING_PACKRAT = True
#~ TEST_USING_PACKRAT = False
VERBOSE = True
# simple utility for flattening nested lists
def flatten(L):
if type(L) is not list: return [L]
if L == []: return L
return flatten(L[0]) + flatten(L[1:])
"""
class ParseTest(TestCase):
def setUp(self):
pass
def runTest(self):
self.assertTrue(1==1, "we've got bigger problems...")
def tearDown(self):
pass
"""
class AutoReset(object):
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)
BUFFER_OUTPUT = True
class ParseTestCase(TestCase):
def __init__(self):
super(ParseTestCase, self).__init__(methodName='_runTest')
def _runTest(self):
buffered_stdout = StringIO()
try:
with AutoReset(sys, 'stdout', 'stderr'):
try:
if BUFFER_OUTPUT:
sys.stdout = buffered_stdout
sys.stderr = buffered_stdout
print_(">>>> Starting test",str(self))
self.runTest()
finally:
print_("<<<< End of test",str(self))
print_()
except Exception as exc:
if BUFFER_OUTPUT:
print_()
print_(buffered_stdout.getvalue())
raise
def runTest(self):
pass
def __str__(self):
return self.__class__.__name__
class PyparsingTestInit(ParseTestCase):
def setUp(self):
from pyparsing import __version__ as pyparsingVersion
print_("Beginning test of pyparsing, version", pyparsingVersion)
print_("Python version", sys.version)
def tearDown(self):
pass
if 0:
class ParseASMLTest(ParseTestCase):
def runTest(self):
import parseASML
files = [ ("A52759.txt", 2150, True, True, 0.38, 25, "21:47:17", "22:07:32", 235),
("24141506_P5107RM59_399A1457N1_PHS04", 373,True, True, 0.5, 1, "11:35:25", "11:37:05", 183),
("24141506_P5107RM59_399A1457N1_PHS04B", 373, True, True, 0.5, 1, "01:02:54", "01:04:49", 186),
("24157800_P5107RM74_399A1828M1_PHS04", 1141, True, False, 0.5, 13, "00:00:54", "23:59:48", 154) ]
for testFile,numToks,trkInpUsed,trkOutpUsed,maxDelta,numWafers,minProcBeg,maxProcEnd,maxLevStatsIV in files:
print_("Parsing",testFile,"...", end=' ')
#~ text = "\n".join( [ line for line in file(testFile) ] )
#~ results = parseASML.BNF().parseString( text )
results = parseASML.BNF().parseFile( testFile )
#~ pprint.pprint( results.asList() )
#~ pprint.pprint( results.batchData.asList() )
#~ print results.batchData.keys()
allToks = flatten( results.asList() )
self.assertTrue(len(allToks) == numToks,
"wrong number of tokens parsed (%s), got %d, expected %d" % (testFile, len(allToks),numToks))
self.assertTrue(results.batchData.trackInputUsed == trkInpUsed, "error evaluating results.batchData.trackInputUsed")
self.assertTrue(results.batchData.trackOutputUsed == trkOutpUsed, "error evaluating results.batchData.trackOutputUsed")
self.assertTrue(results.batchData.maxDelta == maxDelta,"error evaluating results.batchData.maxDelta")
self.assertTrue(len(results.waferData) == numWafers, "did not read correct number of wafers")
self.assertTrue(min([wd.procBegin for wd in results.waferData]) == minProcBeg, "error reading waferData.procBegin")
self.assertTrue(max([results.waferData[k].procEnd for k in range(len(results.waferData))]) == maxProcEnd, "error reading waferData.procEnd")
self.assertTrue(sum(results.levelStatsIV['MAX']) == maxLevStatsIV, "error reading levelStatsIV")
self.assertTrue(sum(results.levelStatsIV.MAX) == maxLevStatsIV, "error reading levelStatsIV")
print_("OK")
print_(testFile,len(allToks))
#~ print "results.batchData.trackInputUsed =",results.batchData.trackInputUsed
#~ print "results.batchData.trackOutputUsed =",results.batchData.trackOutputUsed
#~ print "results.batchData.maxDelta =",results.batchData.maxDelta
#~ print len(results.waferData)," wafers"
#~ print min([wd.procBegin for wd in results.waferData])
#~ print max([results.waferData[k].procEnd for k in range(len(results.waferData))])
#~ print sum(results.levelStatsIV['MAX.'])
class ParseFourFnTest(ParseTestCase):
def runTest(self):
import examples.fourFn as fourFn
def test(s,ans):
fourFn.exprStack = []
results = fourFn.BNF().parseString( s )
resultValue = fourFn.evaluateStack( fourFn.exprStack )
self.assertTrue(resultValue == ans, "failed to evaluate %s, got %f" % ( s, resultValue ))
print_(s, "->", resultValue)
from math import pi,exp
e = exp(1)
test( "9", 9 )
test( "9 + 3 + 6", 18 )
test( "9 + 3 / 11", 9.0+3.0/11.0)
test( "(9 + 3)", 12 )
test( "(9+3) / 11", (9.0+3.0)/11.0 )
test( "9 - (12 - 6)", 3)
test( "2*3.14159", 6.28318)
test( "3.1415926535*3.1415926535 / 10", 3.1415926535*3.1415926535/10.0 )
test( "PI * PI / 10", pi*pi/10.0 )
test( "PI*PI/10", pi*pi/10.0 )
test( "6.02E23 * 8.048", 6.02E23 * 8.048 )
test( "e / 3", e/3.0 )
test( "sin(PI/2)", 1.0 )
test( "trunc(E)", 2.0 )
test( "E^PI", e**pi )
test( "2^3^2", 2**3**2)
test( "2^3+2", 2**3+2)
test( "2^9", 2**9 )
test( "sgn(-2)", -1 )
test( "sgn(0)", 0 )
test( "sgn(0.1)", 1 )
class ParseSQLTest(ParseTestCase):
def runTest(self):
import examples.simpleSQL as simpleSQL
def test(s, numToks, errloc=-1):
try:
sqlToks = flatten(simpleSQL.simpleSQL.parseString(s).asList())
print_(s,sqlToks,len(sqlToks))
self.assertEqual(len(sqlToks), numToks,
"invalid parsed tokens, expected {0}, found {1} ({2})".format(numToks,
len(sqlToks),
sqlToks))
except ParseException as e:
if errloc >= 0:
self.assertEqual(e.loc, errloc, "expected error at {0}, found at {1}".format(errloc, 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 )
class ParseConfigFileTest(ParseTestCase):
def runTest(self):
from examples import configParse
def test(fnam,numToks,resCheckList):
print_("Parsing",fnam,"...", end=' ')
with open(fnam) as infile:
iniFileLines = "\n".join(infile.read().splitlines())
iniData = configParse.inifile_BNF().parseString( iniFileLines )
print_(len(flatten(iniData.asList())))
#~ pprint.pprint( iniData.asList() )
#~ pprint.pprint( repr(iniData) )
#~ print len(iniData), len(flatten(iniData.asList()))
print_(list(iniData.keys()))
#~ print iniData.users.keys()
#~ print
self.assertEqual(len(flatten(iniData.asList())), numToks, "file %s not parsed correctly" % fnam)
for chk in resCheckList:
var = iniData
for attr in chk[0].split('.'):
var = getattr(var, attr)
print_(chk[0], var, chk[1])
self.assertEqual(var, chk[1],
"ParseConfigFileTest: failed to parse ini {0!r} as expected {1}, found {2}".format(chk[0],
chk[1],
var))
print_("OK")
test("test/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") ] )
class ParseJSONDataTest(ParseTestCase):
def runTest(self):
from examples.jsonParser import jsonObject
from test.jsonParserTests import test1,test2,test3,test4,test5
from test.jsonParserTests import test1,test2,test3,test4,test5
expected = [
[],
[],
[],
[],
[],
]
for t,exp in zip((test1,test2,test3,test4,test5),expected):
result = jsonObject.parseString(t)
## print result.dump()
result.pprint()
print_()
## if result.asList() != exp:
## print "Expected %s, parsed results as %s" % (exp, result.asList())
class ParseCommaSeparatedValuesTest(ParseTestCase):
def runTest(self):
from pyparsing import commaSeparatedList
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: \""+line+"\" ->", end=' ')
results = commaSeparatedList.parseString(line)
print_(results.asList())
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())))
class ParseEBNFTest(ParseTestCase):
def runTest(self):
from examples import ebnf
from pyparsing import Word, quotedString, alphas, nums
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'] = quotedString
table['meta_identifier'] = Word(alphas+"_", alphas+"_"+nums)
table['integer'] = Word(nums)
print_('Parsing EBNF grammar with EBNF parser...')
parsers = ebnf.parse(grammar, table)
ebnf_parser = parsers['syntax']
#~ print ",\n ".join( str(parsers.keys()).split(", ") )
print_("-","\n- ".join( list(parsers.keys()) ))
self.assertEqual(len(list(parsers.keys())), 13, "failed to construct syntax grammar")
print_('Parsing EBNF grammar with generated EBNF parser...')
parsed_chars = ebnf_parser.parseString(grammar)
parsed_char_len = len(parsed_chars)
print_("],\n".join(str( parsed_chars.asList() ).split("],")))
self.assertEqual(len(flatten(parsed_chars.asList())), 98, "failed to tokenize grammar correctly")
class ParseIDLTest(ParseTestCase):
def runTest(self):
from examples import idlParse
def test( strng, numToks, errloc=0 ):
print_(strng)
try:
bnf = idlParse.CORBA_IDL_BNF()
tokens = bnf.parseString( strng )
print_("tokens = ")
tokens.pprint()
tokens = flatten( tokens.asList() )
print_(len(tokens))
self.assertEqual(len(tokens), numToks, "error matching IDL string, %s -> %s" % (strng, str(tokens)))
except ParseException as err:
print_(err.line)
print_(" "*(err.column-1) + "^")
print_(err)
self.assertEqual(numToks, 0, "unexpected ParseException while parsing %s, %s" % (strng, str(err)))
self.assertEqual(err.loc, errloc,
"expected ParseException at %d, found exception at %d" % (errloc, 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
)
class ParseVerilogTest(ParseTestCase):
def runTest(self):
pass
class RunExamplesTest(ParseTestCase):
def runTest(self):
pass
class ScanStringTest(ParseTestCase):
def runTest(self):
from pyparsing import Word, Combine, Suppress, CharsNotIn, nums, StringEnd
testdata = """
<table border="0" cellpadding="3" cellspacing="3" frame="" width="90%">
<tr align="left" valign="top">
<td><b>Name</b></td>
<td><b>IP Address</b></td>
<td><b>Location</b></td>
</tr>
<tr align="left" valign="top" bgcolor="#c7efce">
<td>time-a.nist.gov</td>
<td>129.6.15.28</td>
<td>NIST, Gaithersburg, Maryland</td>
</tr>
<tr align="left" valign="top">
<td>time-b.nist.gov</td>
<td>129.6.15.29</td>
<td>NIST, Gaithersburg, Maryland</td>
</tr>
<tr align="left" valign="top" bgcolor="#c7efce">
<td>time-a.timefreq.bldrdoc.gov</td>
<td>132.163.4.101</td>
<td>NIST, Boulder, Colorado</td>
</tr>
<tr align="left" valign="top">
<td>time-b.timefreq.bldrdoc.gov</td>
<td>132.163.4.102</td>
<td>NIST, Boulder, Colorado</td>
</tr>
<tr align="left" valign="top" bgcolor="#c7efce">
<td>time-c.timefreq.bldrdoc.gov</td>
<td>132.163.4.103</td>
<td>NIST, Boulder, Colorado</td>
</tr>
</table>
"""
integer = Word(nums)
ipAddress = Combine( integer + "." + integer + "." + integer + "." + integer )
tdStart = Suppress("<td>")
tdEnd = Suppress("</td>")
timeServerPattern = (tdStart + ipAddress("ipAddr") + tdEnd
+ tdStart + CharsNotIn("<")("loc") + tdEnd)
servers = [srvr.ipAddr for srvr,startloc,endloc in timeServerPattern.scanString( testdata )]
print_(servers)
self.assertEqual(servers,
['129.6.15.28', '129.6.15.29', '132.163.4.101', '132.163.4.102', '132.163.4.103'],
"failed scanString()")
# test for stringEnd detection in scanString
foundStringEnds = [ r for r in StringEnd().scanString("xyzzy") ]
print_(foundStringEnds)
self.assertTrue(foundStringEnds, "Failed to find StringEnd in scanString")
class QuotedStringsTest(ParseTestCase):
def runTest(self):
from pyparsing import sglQuotedString,dblQuotedString,quotedString,QuotedString
testData = \
"""
'a valid single quoted string'
'an invalid single quoted string
because it spans lines'
"a valid double quoted string"
"an invalid double quoted string
because it spans lines"
"""
print_(testData)
sglStrings = [(t[0],b,e) for (t,b,e) in sglQuotedString.scanString(testData)]
print_(sglStrings)
self.assertTrue(len(sglStrings) == 1 and (sglStrings[0][1] == 17 and sglStrings[0][2] == 47),
"single quoted string failure")
dblStrings = [(t[0],b,e) for (t,b,e) in dblQuotedString.scanString(testData)]
print_(dblStrings)
self.assertTrue(len(dblStrings) == 1 and (dblStrings[0][1] == 154 and dblStrings[0][2] == 184),
"double quoted string failure")
allStrings = [(t[0],b,e) for (t,b,e) in quotedString.scanString(testData)]
print_(allStrings)
self.assertTrue(len(allStrings) == 2
and (allStrings[0][1] == 17
and allStrings[0][2] == 47)
and (allStrings[1][1] == 154
and allStrings[1][2] == 184),
"quoted string failure")
escapedQuoteTest = \
r"""
'This string has an escaped (\') quote character'
"This string has an escaped (\") quote character"
"""
sglStrings = [(t[0],b,e) for (t,b,e) in sglQuotedString.scanString(escapedQuoteTest)]
print_(sglStrings)
self.assertTrue(len(sglStrings) == 1 and (sglStrings[0][1]==17 and sglStrings[0][2]==66),
"single quoted string escaped quote failure (%s)" % str(sglStrings[0]))
dblStrings = [(t[0],b,e) for (t,b,e) in dblQuotedString.scanString(escapedQuoteTest)]
print_(dblStrings)
self.assertTrue(len(dblStrings) == 1 and (dblStrings[0][1]==83 and dblStrings[0][2]==132),
"double quoted string escaped quote failure (%s)" % str(dblStrings[0]))
allStrings = [(t[0],b,e) for (t,b,e) in quotedString.scanString(escapedQuoteTest)]
print_(allStrings)
self.assertTrue(len(allStrings) == 2
and (allStrings[0][1] == 17
and allStrings[0][2] == 66
and allStrings[1][1] == 83
and allStrings[1][2] == 132),
"quoted string escaped quote failure (%s)" % ([str(s[0]) for s in allStrings]))
dblQuoteTest = \
r"""
'This string has an doubled ('') quote character'
"This string has an doubled ("") quote character"
"""
sglStrings = [(t[0],b,e) for (t,b,e) in sglQuotedString.scanString(dblQuoteTest)]
print_(sglStrings)
self.assertTrue(len(sglStrings) == 1 and (sglStrings[0][1]==17 and sglStrings[0][2]==66),
"single quoted string escaped quote failure (%s)" % str(sglStrings[0]))
dblStrings = [(t[0],b,e) for (t,b,e) in dblQuotedString.scanString(dblQuoteTest)]
print_(dblStrings)
self.assertTrue(len(dblStrings) == 1 and (dblStrings[0][1]==83 and dblStrings[0][2]==132),
"double quoted string escaped quote failure (%s)" % str(dblStrings[0]))
allStrings = [(t[0],b,e) for (t,b,e) in quotedString.scanString(dblQuoteTest)]
print_(allStrings)
self.assertTrue(len(allStrings) == 2
and (allStrings[0][1] == 17
and allStrings[0][2] == 66
and allStrings[1][1] == 83
and allStrings[1][2] == 132),
"quoted string escaped quote failure (%s)" % ([str(s[0]) for s in allStrings]))
print_("testing catastrophic RE backtracking in implementation of dblQuotedString")
for expr, test_string in [
(dblQuotedString, '"' + '\\xff' * 500),
(sglQuotedString, "'" + '\\xff' * 500),
(quotedString, '"' + '\\xff' * 500),
(quotedString, "'" + '\\xff' * 500),
(QuotedString('"'), '"' + '\\xff' * 500),
(QuotedString("'"), "'" + '\\xff' * 500),
]:
expr.parseString(test_string+test_string[0])
try:
expr.parseString(test_string)
except Exception:
continue
class CaselessOneOfTest(ParseTestCase):
def runTest(self):
from pyparsing import oneOf,ZeroOrMore
caseless1 = oneOf("d a b c aA B A C", caseless=True)
caseless1str = str( caseless1 )
print_(caseless1str)
caseless2 = oneOf("d a b c Aa B A C", caseless=True)
caseless2str = str( caseless2 )
print_(caseless2str)
self.assertEqual(caseless1str.upper(), caseless2str.upper(), "oneOf not handling caseless option properly")
self.assertNotEqual(caseless1str, caseless2str, "Caseless option properly sorted")
res = ZeroOrMore(caseless1).parseString("AAaaAaaA")
print_(res)
self.assertEqual(len(res), 4, "caseless1 oneOf failed")
self.assertEqual("".join(res), "aA"*4,"caseless1 CaselessLiteral return failed")
res = ZeroOrMore(caseless2).parseString("AAaaAaaA")
print_(res)
self.assertEqual(len(res), 4, "caseless2 oneOf failed")
self.assertEqual("".join(res), "Aa"*4,"caseless1 CaselessLiteral return failed")
class AsXMLTest(ParseTestCase):
def runTest(self):
# test asXML()
aaa = pp.Word("a")("A")
bbb = pp.Group(pp.Word("b"))("B")
ccc = pp.Combine(":" + pp.Word("c"))("C")
g1 = "XXX>&<" + pp.ZeroOrMore( aaa | bbb | ccc )
teststring = "XXX>&< b b a b b a b :c b a"
#~ print teststring
print_("test including all items")
xml = g1.parseString(teststring).asXML("TEST",namedItemsOnly=False)
assert xml=="\n".join(["",
"<TEST>",
" <ITEM>XXX>&<</ITEM>",
" <B>",
" <ITEM>b</ITEM>",
" </B>",
" <B>",
" <ITEM>b</ITEM>",
" </B>",
" <A>a</A>",
" <B>",
" <ITEM>b</ITEM>",
" </B>",
" <B>",
" <ITEM>b</ITEM>",
" </B>",
" <A>a</A>",
" <B>",
" <ITEM>b</ITEM>",
" </B>",
" <C>:c</C>",
" <B>",
" <ITEM>b</ITEM>",
" </B>",
" <A>a</A>",
"</TEST>",
] ), \
"failed to generate XML correctly showing all items: \n[" + xml + "]"
print_("test filtering unnamed items")
xml = g1.parseString(teststring).asXML("TEST",namedItemsOnly=True)
assert xml=="\n".join(["",
"<TEST>",
" <B>",
" <ITEM>b</ITEM>",
" </B>",
" <B>",
" <ITEM>b</ITEM>",
" </B>",
" <A>a</A>",
" <B>",
" <ITEM>b</ITEM>",
" </B>",
" <B>",
" <ITEM>b</ITEM>",
" </B>",
" <A>a</A>",
" <B>",
" <ITEM>b</ITEM>",
" </B>",
" <C>:c</C>",
" <B>",
" <ITEM>b</ITEM>",
" </B>",
" <A>a</A>",
"</TEST>",
] ), \
"failed to generate XML correctly, filtering unnamed items: " + xml
class AsXMLTest2(ParseTestCase):
def runTest(self):
from pyparsing import Suppress,Optional,CharsNotIn,Combine,ZeroOrMore,Word,\
Group,Literal,alphas,alphanums,delimitedList,OneOrMore
EndOfLine = Word("\n").setParseAction(lambda s,l,t: [' '])
whiteSpace=Word('\t ')
Mexpr = Suppress(Optional(whiteSpace)) + CharsNotIn('\\"\t \n') + Optional(" ") + \
Suppress(Optional(whiteSpace))
reducedString = Combine(Mexpr + ZeroOrMore(EndOfLine + Mexpr))
_bslash = "\\"
_escapables = "tnrfbacdeghijklmopqsuvwxyz" + _bslash + "'" + '"'
_octDigits = "01234567"
_escapedChar = ( Word( _bslash, _escapables, exact=2 ) |
Word( _bslash, _octDigits, min=2, max=4 ) )
_sglQuote = Literal("'")
_dblQuote = Literal('"')
QuotedReducedString = Combine( Suppress(_dblQuote) + ZeroOrMore( reducedString |
_escapedChar ) + \
Suppress(_dblQuote )).streamline()
Manifest_string = QuotedReducedString('manifest_string')
Identifier = Word( alphas, alphanums+ '_$' )("identifier")
Index_string = CharsNotIn('\\";\n')
Index_string.setName('index_string')
Index_term_list = (
Group(delimitedList(Manifest_string, delim=',')) | \
Index_string
)('value')
IndexKey = Identifier('key')
IndexKey.setName('key')
Index_clause = Group(IndexKey + Suppress(':') + Optional(Index_term_list))
Index_clause.setName('index_clause')
Index_list = Index_clause('index')
Index_list.setName('index_list')
Index_block = Group('indexing' + Group(OneOrMore(Index_list + Suppress(';'))))('indexes')
class CommentParserTest(ParseTestCase):
def runTest(self):
print_("verify processing of C and HTML comments")
testdata = """
/* */
/** **/
/**/
/***/
/****/
/* /*/
/** /*/
/*** /*/
/*
ablsjdflj
*/
"""
foundLines = [ pp.lineno(s,testdata)
for t,s,e in pp.cStyleComment.scanString(testdata) ]
self.assertEqual(foundLines, list(range(11))[2:],"only found C comments on lines "+str(foundLines))
testdata = """
<!-- -->
<!--- --->
<!---->
<!----->
<!------>
<!-- /-->
<!--- /-->
<!---- /-->
<!---- /- ->
<!---- / -- >
<!--
ablsjdflj
-->
"""
foundLines = [ pp.lineno(s,testdata)
for t,s,e in pp.htmlComment.scanString(testdata) ]
self.assertEqual(foundLines, list(range(11))[2:],"only found HTML comments on lines "+str(foundLines))
# test C++ single line comments that have line terminated with '\' (should continue comment to following line)
testSource = r"""
// comment1
// comment2 \
still comment 2
// comment 3
"""
self.assertEqual(len(pp.cppStyleComment.searchString(testSource)[1][0]), 41,
r"failed to match single-line comment with '\' at EOL")
class ParseExpressionResultsTest(ParseTestCase):
def runTest(self):
from pyparsing import Word,alphas,OneOrMore,Optional,Group
a = Word("a",alphas).setName("A")
b = Word("b",alphas).setName("B")
c = Word("c",alphas).setName("C")
ab = (a + b).setName("AB")
abc = (ab + c).setName("ABC")
word = Word(alphas).setName("word")
#~ words = OneOrMore(word).setName("words")
words = Group(OneOrMore(~a + word)).setName("words")
#~ phrase = words.setResultsName("Head") + \
#~ ( abc ^ ab ^ a ).setResultsName("ABC") + \
#~ words.setResultsName("Tail")
#~ phrase = words.setResultsName("Head") + \
#~ ( abc | ab | a ).setResultsName("ABC") + \
#~ words.setResultsName("Tail")
phrase = words("Head") + \
Group( a + Optional(b + Optional(c)) )("ABC") + \
words("Tail")
results = phrase.parseString("xavier yeti alpha beta charlie will beaver")
print_(results,results.Head, results.ABC,results.Tail)
for key,ln in [("Head",2), ("ABC",3), ("Tail",2)]:
self.assertEqual(len(results[key]), ln,
"expected %d elements in %s, found %s" % (ln, key, str(results[key])))
class ParseKeywordTest(ParseTestCase):
def runTest(self):
from pyparsing import Literal,Keyword
kw = Keyword("if")
lit = Literal("if")
def test(s,litShouldPass,kwShouldPass):
print_("Test",s)
print_("Match Literal", end=' ')
try:
print_(lit.parseString(s))
except Exception:
print_("failed")
if litShouldPass:
self.assertTrue(False, "Literal failed to match %s, should have" % s)
else:
if not litShouldPass:
self.assertTrue(False, "Literal matched %s, should not have" % s)
print_("Match Keyword", end=' ')
try:
print_(kw.parseString(s))
except Exception:
print_("failed")
if kwShouldPass:
self.assertTrue(False, "Keyword failed to match %s, should have" % s)
else:
if not kwShouldPass:
self.assertTrue(False, "Keyword matched %s, should not have" % s)
test("ifOnlyIfOnly", True, False)
test("if(OnlyIfOnly)", True, True)
test("if (OnlyIf Only)", True, True)
kw = Keyword("if",caseless=True)
test("IFOnlyIfOnly", False, False)
test("If(OnlyIfOnly)", False, True)
test("iF (OnlyIf Only)", False, True)
class ParseExpressionResultsAccumulateTest(ParseTestCase):
def runTest(self):
from pyparsing import Word,delimitedList,Combine,alphas,nums
num=Word(nums).setName("num")("base10*")
hexnum=Combine("0x"+ Word(nums)).setName("hexnum")("hex*")
name = Word(alphas).setName("word")("word*")
list_of_num=delimitedList( hexnum | num | name, "," )
tokens = list_of_num.parseString('1, 0x2, 3, 0x4, aaa')
for k,llen,lst in ( ("base10",2,['1','3']),
("hex",2,['0x2','0x4']),
("word",1,['aaa']) ):
print_(k,tokens[k])
self.assertEqual(len(tokens[k]), llen, "Wrong length for key %s, %s" % (k,str(tokens[k].asList())))
self.assertEqual(lst, tokens[k].asList(),
"Incorrect list returned for key %s, %s" % (k,str(tokens[k].asList())))
self.assertEqual(tokens.base10.asList(), ['1','3'],
"Incorrect list for attribute base10, %s" % str(tokens.base10.asList()))
self.assertEqual(tokens.hex.asList(), ['0x2','0x4'],
"Incorrect list for attribute hex, %s" % str(tokens.hex.asList()))
self.assertEqual(tokens.word.asList(), ['aaa'],
"Incorrect list for attribute word, %s" % str(tokens.word.asList()))
from pyparsing import Literal, Word, nums, Group, Dict, alphas, \
quotedString, oneOf, delimitedList, removeQuotes, alphanums
lbrack = Literal("(").suppress()
rbrack = Literal(")").suppress()
integer = Word( nums ).setName("int")
variable = Word( alphas, max=1 ).setName("variable")
relation_body_item = variable | integer | quotedString.copy().setParseAction(removeQuotes)
relation_name = Word( alphas+"_", alphanums+"_" )
relation_body = lbrack + Group(delimitedList(relation_body_item)) + rbrack
Goal = Dict(Group( relation_name + relation_body ))
Comparison_Predicate = Group(variable + oneOf("< >") + integer)("pred*")
Query = Goal("head") + ":-" + delimitedList(Goal | Comparison_Predicate)
test="""Q(x,y,z):-Bloo(x,"Mitsis",y),Foo(y,z,1243),y>28,x<12,x>3"""
queryRes = Query.parseString(test)
print_("pred",queryRes.pred)
self.assertEqual(queryRes.pred.asList(), [['y', '>', '28'], ['x', '<', '12'], ['x', '>', '3']],
"Incorrect list for attribute pred, %s" % str(queryRes.pred.asList()))
print_(queryRes.dump())
class ReStringRangeTest(ParseTestCase):
def runTest(self):
testCases = (
(r"[A-Z]"),
(r"[A-A]"),
(r"[A-Za-z]"),
(r"[A-z]"),
(r"[\ -\~]"),
(r"[\0x20-0]"),
(r"[\0x21-\0x7E]"),
(r"[\0xa1-\0xfe]"),
(r"[\040-0]"),
(r"[A-Za-z0-9]"),
(r"[A-Za-z0-9_]"),
(r"[A-Za-z0-9_$]"),
(r"[A-Za-z0-9_$\-]"),
(r"[^0-9\\]"),
(r"[a-zA-Z]"),
(r"[/\^~]"),
(r"[=\+\-!]"),
(r"[A-]"),
(r"[-A]"),
(r"[\x21]"),
#(r"[а-яА-ЯёЁA-Z$_\041α-ω]".decode('utf-8')),
(u'[\u0430-\u044f\u0410-\u042f\u0451\u0401ABCDEFGHIJKLMNOPQRSTUVWXYZ$_\041\u03b1-\u03c9]'),
)
expectedResults = (
"ABCDEFGHIJKLMNOPQRSTUVWXYZ",
"A",
"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",
"ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz",
" !\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~",
" !\"#$%&'()*+,-./0",
"!\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~",
#~ "¡¢£¤¥¦§¨©ª«¬®¯°±²³´µ¶·¸¹º»¼½¾¿ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖ×ØÙÚÛÜÝÞßàáâãäåæçèéêëìíîïðñòóôõö÷øùúûüýþ",
u'\xa1\xa2\xa3\xa4\xa5\xa6\xa7\xa8\xa9\xaa\xab\xac\xad\xae\xaf\xb0\xb1\xb2\xb3\xb4\xb5\xb6\xb7\xb8\xb9\xba\xbb\xbc\xbd\xbe\xbf\xc0\xc1\xc2\xc3\xc4\xc5\xc6\xc7\xc8\xc9\xca\xcb\xcc\xcd\xce\xcf\xd0\xd1\xd2\xd3\xd4\xd5\xd6\xd7\xd8\xd9\xda\xdb\xdc\xdd\xde\xdf\xe0\xe1\xe2\xe3\xe4\xe5\xe6\xe7\xe8\xe9\xea\xeb\xec\xed\xee\xef\xf0\xf1\xf2\xf3\xf4\xf5\xf6\xf7\xf8\xf9\xfa\xfb\xfc\xfd\xfe',
" !\"#$%&'()*+,-./0",
"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789",
"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_",
"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_$",
"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_$-",
"0123456789\\",
"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ",
"/^~",
"=+-!",
"A-",
"-A",
"!",
u"абвгдежзийклмнопрстуфхцчшщъыьэюяАБВГДЕЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯёЁABCDEFGHIJKLMNOPQRSTUVWXYZ$_!αβγδεζηθικλμνξοπρςστυφχψω",
)
for test in zip( testCases, expectedResults ):
t,exp = test
res = pp.srange(t)
#print_(t,"->",res)
self.assertEqual(res, exp, "srange error, srange(%r)->'%r', expected '%r'" % (t, res, exp))
class SkipToParserTests(ParseTestCase):
def runTest(self):
from pyparsing import Literal, SkipTo, cStyleComment, ParseBaseException
thingToFind = Literal('working')
testExpr = SkipTo(Literal(';'), include=True, ignore=cStyleComment) + thingToFind