-
Notifications
You must be signed in to change notification settings - Fork 3
/
pent_base.py
1200 lines (910 loc) · 38.8 KB
/
pent_base.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
r"""*Core test objects for* ``pent`` *test suite*.
``pent`` Extracts Numerical Text.
**Author**
Brian Skinn (bskinn@alum.mit.edu)
**File Created**
3 Sep 2018
**Copyright**
\(c) Brian Skinn 2018
**Source Repository**
http://www.github.com/bskinn/pent
**Documentation**
http://pent.readthedocs.io
**License**
The MIT License; see |license_txt|_ for full license terms
**Members**
*(none documented)*
"""
import gzip
import itertools as itt
from pathlib import Path
import re
from textwrap import dedent
import unittest as ut
import pent
from pent import ParserField
from pent.errors import LineError
from pent.thrulist import ThruList
# HELPERS
testdir_path = Path() / "pent" / "test"
class SuperPent:
"""Superclass of various test classes, with common methods."""
import pent
prs = pent.Parser(body="")
@staticmethod
def does_parse_match(re_pat, s):
"""Run match-or-not test on `s` using regex pattern `re_pat`."""
m = re.search(re_pat, s)
return m is not None
@staticmethod
def make_testname(v, n, s):
"""Compose test name from a numerical value and pattern Number/Sign."""
return "{0}_{1}_{2}".format(v, n, s)
@staticmethod
def get_file(fname):
"""Return the contents of the given file."""
path = str(Path() / "pent" / "test" / fname)
if fname.endswith(".gz"):
with gzip.open(path, "rt") as f:
return f.read()
else:
with open(path) as f:
return f.read()
class TestPentTokens(ut.TestCase, SuperPent):
"""Direct tests on the Token class."""
def test_arbitrary_bad_token(self):
"""Confirm bad tokens raise errors."""
import pent
self.assertRaises(pent.TokenError, pent.Token, "abcd")
def test_group_enclosures(self):
"""Ensure 'ignore' flag is properly set."""
import pent
testname_fmt = "{0}_{1}"
token_fmt = {
pent.Content.Any: "~{0}",
pent.Content.String: "@{0}.thing",
pent.Content.Number: "#{0}..i",
pent.Content.Misc: "&{0}.",
}
for ct, cap in itt.product(pent.Content, (True, False)):
if ct is pent.Content.OptionalLine:
continue
t = pent.Token(token_fmt[ct].format("!" if cap else ""))
with self.subTest(testname_fmt.format(ct, cap)):
self.assertEqual(t.capture, cap)
def test_number_property(self):
"""Ensure t.number properties return correct values."""
import pent
from .testdata import number_patterns as npats
for p in npats.values():
pat = p.format("", "", pent.Quantity.Single)
with self.subTest(pat):
self.assertEqual(pent.Token(pat).number, pent.Number(p[-1]))
with self.subTest("string"):
self.assertEqual(pent.Token("@.abcd").number, None)
with self.subTest("any"):
self.assertEqual(pent.Token("~").number, None)
def test_sign_property(self):
"""Ensure t.sign properties return correct values."""
import pent
from .testdata import number_patterns as npats
for p in npats.values():
pat = p.format("", "", pent.Quantity.Single)
with self.subTest(pat):
self.assertEqual(pent.Token(pat).sign, pent.Sign(p[-2]))
with self.subTest("string"):
self.assertEqual(pent.Token("@.abcd").sign, None)
with self.subTest("any"):
self.assertEqual(pent.Token("~").sign, None)
def test_qty_property_on_any_and_optline(self):
"""Ensure t.match_quantity property returns correct value on 'any'."""
import pent
self.assertEqual(pent.Token("~").match_quantity, None)
self.assertEqual(pent.Token("?").match_quantity, None)
class TestPentThruList(ut.TestCase, SuperPent):
"""Direct tests of the custom pass-thru list."""
from pent import ThruListError
def test_list_value(self):
"""Confirm simple list behavior."""
work_l = ThruList(range(5))
self.assertEqual(work_l[2], 2)
with self.assertRaises(IndexError):
work_l[8]
with self.assertRaises(self.ThruListError):
work_l["foo"]
def test_list_pass_thru(self):
"""Confirm key pass-through behavior works."""
work_l = ThruList([{"foo": "bar", "baz": "quux"}])
self.assertEqual(work_l["foo"], "bar")
self.assertEqual(work_l["baz"], "quux")
def test_int_index_addresses_top_layer(self):
"""Confirm a numeric index doesn't dig into item 0."""
work_l = ThruList([[1, 2, 3], 4, 5, 6])
self.assertEqual(work_l[2], 5)
def test_fail_when_multiple_items(self):
"""Confirm the pass-through is not attempted when len > 1."""
work_l = ThruList([{"foo": "bar"}, {"baz": "quux"}])
with self.assertRaises(self.ThruListError):
work_l["foo"]
self.assertEqual(work_l[1], {"baz": "quux"})
def test_fail_when_no_items(self):
"""Confirm the pass-through is not attempted when len < 1."""
work_l = ThruList([])
with self.assertRaises(self.ThruListError):
work_l["foo"]
class TestPentCorePatterns(ut.TestCase, SuperPent):
"""Confirming basic pattern matching of the core regex patterns."""
def test_number_and_sign_matching(self):
"""Confirm number and sign patterns match the right string patterns."""
import pent
from .testdata import number_sign_vals as vals
for (v, n, s) in itt.product(vals, pent.Number, pent.Sign):
with self.subTest(self.make_testname(v, n, s)):
npat = pent.number_patterns[(n, s)]
npat = pent.std_wordify(npat)
res = self.does_parse_match(npat, v)
self.assertEqual(vals[v][(n, s)], res, msg=npat)
def test_raw_single_value_space_delimited(self):
"""Confirm single-value parsing from a line works with raw patterns."""
import pent
from .testdata import number_sign_vals as vals
test_line = "This line contains the value {} with space delimit."
for v in vals:
test_str = test_line.format(v)
for (n, s) in itt.product(pent.Number, pent.Sign):
with self.subTest(self.make_testname(v, n, s)):
npat = pent.number_patterns[(n, s)]
npat = pent.std_wordify(npat)
res = self.does_parse_match(npat, test_str)
self.assertEqual(vals[v][(n, s)], res, msg=test_str)
class TestPentParserPatterns(ut.TestCase, SuperPent):
"""Confirming pattern matching of patterns generated by the Parser."""
def test_empty_pattern_matches_blank_line(self):
"""Confirm an empty pattern matches only a blank line."""
self.assertIsNotNone(re.search(self.prs.pattern(), ""))
self.assertIsNone(re.search(self.prs.pattern(), "3"))
def test_token_error_raised_at_init(self):
"""Ensure TokenError raised at instantiation w/bad token."""
import pent
self.assertRaises(pent.TokenError, pent.Parser, body="abcd")
def test_group_tags_or_not(self):
"""Confirm group tags are added when needed; omitted when not."""
import pent
patterns = {
pent.Content.Any: "~{}",
pent.Content.String: "@{}.this",
pent.Content.Number: "#{}..g",
pent.Content.Misc: "&{}.",
}
for content, capture in itt.product(pent.Content, (True, False)):
if content is pent.Content.OptionalLine:
continue
test_name = "{0}_{1}".format(content, capture)
with self.subTest(test_name):
test_pat = patterns[content].format("!" if capture else "")
test_rx = self.prs.convert_line(test_pat)[0]
self.assertEqual(capture, "(?P<" in test_rx, msg=test_pat)
def test_parser_single_line_space_delim(self):
"""Confirm parser works on single lines with space-delimited values.
Also tests the 'suppress' number mode.
"""
import pent
from .testdata import number_sign_vals as vals
test_line = "This line contains the value {} with space delimit."
test_pat_template = "~ @!.contains ~! #!.{0}{1} ~"
for v in vals:
test_str = test_line.format(v)
for (n, s) in itt.product(pent.Number, pent.Sign):
test_pat = test_pat_template.format(s.value, n.value)
with self.subTest(self.make_testname(v, n, s)):
npat = self.prs.convert_line(test_pat)[0]
res = self.does_parse_match(npat, test_str)
self.assertEqual(vals[v][n, s], res, msg=test_str)
def test_string_capture(self):
"""Confirm string capture works when desired; is ignored when not."""
import pent
test_line = "This is a string with a word and [symbol] in it."
test_pat_capture = "~ @!.word ~"
test_pat_ignore = "~ @.word ~"
test_pat_symbol = "~ @!.[symbol] ~"
test_pat_with_space = "~ '@!.string with' ~"
with self.subTest("capture"):
pat = self.prs.convert_line(test_pat_capture)[0]
m = re.search(pat, test_line)
self.assertIsNotNone(m)
self.assertEqual(m.group(pent.Token.group_prefix + "0"), "word")
with self.subTest("ignore"):
pat = self.prs.convert_line(test_pat_ignore)[0]
m = re.search(pat, test_line)
self.assertIsNotNone(m)
self.assertRaises(
IndexError, m.group, pent.Token.group_prefix + "0"
)
with self.subTest("symbol"):
pat = self.prs.convert_line(test_pat_symbol)[0]
m = re.search(pat, test_line)
self.assertIsNotNone(m)
self.assertEqual(
m.group(pent.Token.group_prefix + "0"), "[symbol]"
)
with self.subTest("with_space"):
pat = self.prs.convert_line(test_pat_with_space)[0]
m = re.search(pat, test_line)
self.assertIsNotNone(m)
self.assertEqual(
m.group(pent.Token.group_prefix + "0"), "string with"
)
def test_misc_token_matches_various(self):
"""Confirm scope of misc token matching."""
import pent
vals = ["Cu", "43/yfd", "foo", "355.57"]
bads = ["foo bar", "baz 456", "quux\t2e5"]
test_pat = "~ @.has &!. ~"
test_str = "This line has {} in it."
for v in vals:
test_line = test_str.format(v)
with self.subTest("ok_" + v):
pat = self.prs.convert_line(test_pat)[0]
m = re.search(pat, test_line)
self.assertIsNotNone(m)
self.assertEqual(m.group(pent.Token.group_prefix + "0"), v)
for v in bads:
test_line = test_str.format(v)
with self.subTest("bad_" + v):
pat = self.prs.convert_line(test_pat)[0]
m = re.search(pat, test_line)
self.assertIsNotNone(m)
self.assertNotEqual(m.group(pent.Token.group_prefix + "0"), v)
def test_single_num_capture(self):
"""Confirm single-number capture works."""
import pent
from .testdata import number_sign_vals as vals
test_line = "This is a string with {} in it."
test_pat_template = "~ #!.{0}{1} ~"
for v in vals:
test_str = test_line.format(v)
for (n, s) in itt.product(pent.Number, pent.Sign):
test_pat = test_pat_template.format(s.value, n.value)
with self.subTest(self.make_testname(v, n, s)):
npat = self.prs.convert_line(test_pat)[0]
m = re.search(npat, test_str)
self.assertEqual(
vals[v][n, s], m is not None, msg=test_str
)
if m is not None:
self.assertEqual(
m.group(pent.Token.group_prefix + "0"), v
)
def test_single_nums_no_space(self):
"""Confirm two-number capture works, with no intervening space.
Not a particularly real-world test-case, but it probes the
no-space-before check.
"""
import pent
test_str = "This is a string with 123-456 in it."
test_pat = "~ #x!.+i #!.-i ~"
npat = self.prs.convert_line(test_pat)[0]
m = re.search(npat, test_str)
self.assertIsNotNone(m)
self.assertEqual(m.group(pent.Token.group_prefix + "0"), "123")
self.assertEqual(m.group(pent.Token.group_prefix + "1"), "-456")
def test_single_num_preceding_colon_capture(self):
"""Confirm single-number capture works, with preceding colon."""
import pent
from .testdata import number_sign_vals as vals
test_line = "This is a string with :{} in it, after a colon."
test_pat_template = "~ @x.: #!.{0}{1} ~"
for v in vals:
test_str = test_line.format(v)
for (n, s) in itt.product(pent.Number, pent.Sign):
test_pat = test_pat_template.format(s.value, n.value)
with self.subTest(self.make_testname(v, n, s)):
npat = self.prs.convert_line(test_pat)[0]
m = re.search(npat, test_str)
self.assertEqual(
vals[v][n, s], m is not None, msg=test_str
)
if m is not None:
self.assertEqual(
m.group(pent.Token.group_prefix + "0"), v
)
def test_string_and_single_num_capture(self):
"""Confirm multiple capture of string and single number."""
import pent
from .testdata import number_sign_vals as vals
test_line = "This is a string with {} in it."
test_pat_template = "~ @!.string ~ #!.{0}{1} ~"
for v in vals:
test_str = test_line.format(v)
for (n, s) in itt.product(pent.Number, pent.Sign):
test_pat = test_pat_template.format(s.value, n.value)
with self.subTest(self.make_testname(v, n, s)):
npat = self.prs.convert_line(test_pat)[0]
m = re.search(npat, test_str)
self.assertEqual(
vals[v][n, s], m is not None, msg=test_str
)
if m is not None:
self.assertEqual(
m.group(pent.Token.group_prefix + "0"), "string"
)
self.assertEqual(
m.group(pent.Token.group_prefix + "1"), v
)
def test_number_ending_sentence(self):
"""Check that a number at the end of a sentence matches correctly."""
import pent
from .testdata import number_patterns as npats
test_line = "This sentence ends with a number {}."
test_pat = "~ {} @.."
for n in npats:
token = npats[n].format(
pent.SpaceAfter.Prohibited,
pent.Token._s_capture,
pent.Quantity.Single,
)
with self.subTest(token):
pat = self.prs.convert_line(test_pat.format(token))[0]
m = re.search(pat, test_line.format(n))
self.assertIsNotNone(m, msg=test_line.format(n) + token)
self.assertEqual(n, m.group(pent.Token.group_prefix + "0"))
def test_match_entire_line(self):
"""Confirm the tilde works to match an entire line."""
import pent
test_line = "This is a line with whatever weird (*#$(*&23646{}}{#$"
with self.subTest("capture"):
pat = self.prs.convert_line("~!")[0]
self.assertTrue(self.does_parse_match(pat, test_line))
m = re.search(pat, test_line)
self.assertEqual(test_line, m.group(pent.Token.group_prefix + "0"))
with self.subTest("no_capture"):
pat = self.prs.convert_line("~")[0]
self.assertTrue(self.does_parse_match(pat, test_line))
m = re.search(pat, test_line)
self.assertRaises(
IndexError, m.group, pent.Token.group_prefix + "0"
)
def test_any_token_capture_ranges(self):
"""Confirm 'any' captures work as expected with other tokens."""
import pent
test_line_start = "This is a line "
test_line_end = " with a number in brackets in the middle."
test_num = "2e-4"
test_line = test_line_start + "[" + test_num + "]" + test_line_end
pat = self.prs.convert_line("~! @x.[ #x!..g @x.] ~!")[0]
m = re.search(pat, test_line)
self.assertEqual(
m.group(pent.Token.group_prefix + "0"), test_line_start
)
self.assertEqual(m.group(pent.Token.group_prefix + "1"), test_num)
self.assertEqual(m.group(pent.Token.group_prefix + "2"), test_line_end)
def test_one_or_more_str_nospace(self):
"""Confirm one-or-more str token works as expected w/no space."""
import pent
test_string = "This is a test {} string."
test_pat = "~ @{}+foo ~"
for qty, cap in itt.product((1, 2, 3), (True, False)):
with self.subTest("Qty: {0}, Cap: {1}".format(qty, cap)):
pat = test_pat.format(pent.Token._s_capture if cap else "")
pat = self.prs.convert_line(pat)[0]
work_str = test_string.format("foo" * qty)
m = re.search(pat, work_str)
self.assertIsNotNone(m)
if cap:
self.assertEqual(
"foo" * qty, m.group(pent.Token.group_prefix + "0")
)
else:
self.assertRaises(
IndexError, m.group, pent.Token.group_prefix + "0"
)
def test_one_or_more_str_with_space(self):
"""Confirm one-or-more str token works as expected w/space."""
import pent
test_string = "This is a test {}string."
test_pat = "~ '@x{}+foo ' ~"
for qty, cap in itt.product((1, 2, 3), (True, False)):
with self.subTest("Qty: {0}, Cap: {1}".format(qty, cap)):
pat = test_pat.format(pent.Token._s_capture if cap else "")
pat = self.prs.convert_line(pat)[0]
work_str = test_string.format("foo " * qty)
m = re.search(pat, work_str)
self.assertIsNotNone(m)
if cap:
self.assertEqual(
"foo " * qty, m.group(pent.Token.group_prefix + "0")
)
else:
self.assertRaises(
IndexError, m.group, pent.Token.group_prefix + "0"
)
@ut.skip("Not implementing optional/zero-or-more tokens")
def test_optional_str(self):
"""Confirm single optional str token works as expected."""
import pent
test_string = "This is a test {} string."
test_pat = "~ @.test @{}?foo @x.string ~"
for there, cap in itt.product(*itt.repeat((True, False), 2)):
with self.subTest("There: {0}, Cap: {1}".format(there, cap)):
pat = test_pat.format(pent.Token._s_capture if cap else "")
prs_pat = self.prs.convert_line(pat)[0]
work_str = test_string.format("foo" if there else "")
m = re.search(prs_pat, work_str)
self.assertIsNotNone(m)
if cap:
if there:
self.assertEqual(
"foo",
m.group(pent.Token.group_prefix + "0"),
msg=work_str + pat,
)
else:
self.assertEqual(
"", m.group(pent.Token.group_prefix + "0")
)
else:
self.assertRaises(
IndexError, m.group, pent.Token.group_prefix + "0"
)
@ut.skip("Not implementing optional/zero-or-more tokens")
def test_zero_or_more_str(self):
"""Confirm zero-or-more str token works as expected."""
import pent
test_string = "This is a test {}string."
test_pat = "~ @{}*foo ~"
for qty, cap in itt.product((0, 1, 2, 3), (True, False)):
with self.subTest("Qty: {0}, Cap: {1}".format(qty, cap)):
pat = test_pat.format(pent.Token._s_capture if cap else "")
pat = self.prs.convert_line(pat)[0]
work_str = test_string.format("foo " * qty)
m = re.search(pat, work_str)
self.assertIsNotNone(m)
if cap:
self.assertEqual(
"foo " * qty, m.group(pent.Token.group_prefix + "0")
)
else:
self.assertRaises(
IndexError, m.group, pent.Token.group_prefix + "0"
)
@ut.skip("Not implementing optional/zero-or-more tokens")
def test_one_or_more_doesnt_match_zero_reps(self):
"""Confirm one-or-more str doesn't match if string isn't there."""
import pent
test_string = "This is a test string."
test_pat = "~ @.is @!?absolutely @.a ~"
m = re.search(self.prs.convert_line(test_pat)[0], test_string)
self.assertEqual("", m.group(pent.Token.group_prefix + "0"))
def test_optional_pattern_syntax(self):
"""Confirm optional-line flag is only accepted as first token."""
with self.subTest("expect_good"):
try:
self.prs.convert_line("? #!..g")
except LineError:
self.fail("Optional-line token parsing failed unexpectedly.")
with self.subTest("expect_fail"):
with self.assertRaises(LineError):
self.prs.convert_line("#!..g ?")
def test_optional_single_line_tail(self):
"""Confirm optional-line parsing works."""
import pent
from .testdata import opt_1line_tail_data as data
from .testdata import opt_1line_tail_expect_block as expect_block
from .testdata import opt_1line_tail_expect_struct as expect_struct
prs = pent.Parser(
head="@.HEAD",
body=pent.Parser(head="#++i", body="#!+.f", tail="? @!.FOOT"),
)
for i, tup in enumerate(zip(data, expect_block)):
d, e = tup
with self.subTest("block_{}".format(i)):
result = prs.capture_body(d)
self.assertEqual(result, e)
for i, tup in enumerate(zip(data, expect_struct)):
d, e = tup
res_struct = []
with self.subTest("struct_{}".format(i)):
for bdict in prs.capture_struct(d)[ParserField.Body]:
res_struct.append(bdict[ParserField.Tail])
self.assertEqual(res_struct, e)
def test_body_cleared_after_init(self):
"""Confirm correct error raised if 'body' is reset to None."""
import pent
prs = pent.Parser(body="#..i")
prs.body = None
self.assertRaises(pent.SectionError, prs.pattern)
def test_manual_two_lines(self):
"""Run manual check on concatenating two single-line regexes."""
import pent
test_str = "This is line one: 12345 \nAnd this is line two: -3e-5"
test_pat_1 = "~ @!.one: #!.+i"
test_pat_2 = "~ @!.two: #!.-s"
cp_1 = self.prs.convert_line(test_pat_1)[0]
cp_2 = self.prs.convert_line(test_pat_2, group_id=2)[0]
m = re.search(cp_1 + r"\n" + cp_2, test_str)
self.assertIsNotNone(m)
self.assertEqual("one:", m.group(pent.Token.group_prefix + "0"))
self.assertEqual("12345", m.group(pent.Token.group_prefix + "1"))
self.assertEqual("two:", m.group(pent.Token.group_prefix + "2"))
self.assertEqual("-3e-5", m.group(pent.Token.group_prefix + "3"))
def test_quick_one_or_more_number(self):
"""Run quick check on capture of one-or-more number token."""
import pent
numbers = "2 5 -54 3.8 -1.e-12"
test_str = "This has numbers {} with end space.".format(numbers)
test_str_period = "This has numbers {}.".format(numbers)
test_pat = "~ #!+.g ~"
test_pat_period = "~ #x!+.g @.."
re_pat = self.prs.convert_line(test_pat)[0]
re_pat_period = self.prs.convert_line(test_pat_period)[0]
with self.subTest("end_space"):
m_pat = re.search(re_pat, test_str)
self.assertIsNotNone(m_pat)
self.assertEqual(
m_pat.group(pent.Token.group_prefix + "0"), numbers
)
with self.subTest("period"):
m_pat_period = re.search(re_pat_period, test_str_period)
self.assertIsNotNone(m_pat_period)
self.assertEqual(
m_pat_period.group(pent.Token.group_prefix + "0"), numbers
)
def test_multiline_body_parser(self):
"""Confirm parsing w/multi-line body works ok."""
import pent
result = [[["1", "2", "4"]]]
text = "\n1\n\n2\n\n\n4"
pat = ("", "#!.+i", "", "#!.+i", "", "", "#!.+i")
prs = pent.Parser(body=pat)
self.assertEqual(prs.capture_body(text), result)
def test_optional_space_after_literal(self):
"""Confirm the optional-space matching works."""
from textwrap import dedent
import pent
text = dedent(
"""\
1 2 3 4 5
VALUE= 1
VALUE= 2
VALUE=10"""
)
result = [[["1"], ["2"], ["10"]]]
fail_prs = pent.Parser(head="#++i", body="@.VALUE= #!..i")
good_prs = pent.Parser(head="#++i", body="@o.VALUE= #!..i")
self.assertNotEqual(result, fail_prs.capture_body(text))
self.assertEqual(result, good_prs.capture_body(text))
def test_optional_space_after_number(self):
"""Confirm optional-space works for after numbers."""
from textwrap import dedent
import pent
text = dedent(
"""
1 2 3 4 5
23 .
23.
-3e4 .
-3e4.
"""
)
result = [[["23"], ["23"], ["-3e4"], ["-3e4"]]]
good_prs = pent.Parser(head="#++i", body="#o!..g @..")
fail_prs = pent.Parser(head="#++i", body="#!..g @..")
self.assertNotEqual(result, fail_prs.capture_body(text))
self.assertEqual(result, good_prs.capture_body(text))
def test_simple_multiblock(self):
"""Confirm simple multiblock parser works correctly."""
from textwrap import dedent
import pent
from .testdata import mblock_result
data = dedent(
"""
test
more test
$data
1 2 3
1 2.5 -3.5 0.8
2 -1.2 8.1 -9.2
4 5 6
1 -0.1 3.5 8.1
2 1.4 2.2 -4.7
$next_data"""
)
prs_inner = pent.Parser(head="#++i", body="#.+i #!+.f", tail="")
prs_outer = pent.Parser(head="@.$data", body=prs_inner)
self.assertEqual(prs_outer.capture_body(data), mblock_result)
def test_repeated_multiblock(self):
"""Confirm repeated multiblock parser works correctly."""
from textwrap import dedent
import pent
from .testdata import mblock_repeated_result
data = dedent(
"""
$top
1 2 3
0.2 0.3 0.4
0.3 0.4 0.6
4 5 6
0.1 0.1 0.1
0.5 0.5 0.5
$top
7 8 9
0.2 0.2 0.2
0.6 0.6 0.6
1 2 3
0.4 0.4 0.4
0.8 0.8 0.8
"""
)
prs_inner = pent.Parser(head="#++i", body="#!+.f")
prs_outer = pent.Parser(head="@.$top", body=prs_inner)
self.assertEqual(prs_outer.capture_body(data), mblock_repeated_result)
def test_parsers_in_head_and_tail(self):
"""Confirm proper behavior of Parsers for head and tail."""
import pent
data = dedent(
"""\
HEAD 1 2
HEAD 3 4
1 2 3
.1 .2 .3
.2 .3 .4
4 5 6
.3 .4 .5
.4 .5 .6
.5 .6 .7
TAIL a b
TAIL c d
"""
)
prs_head = pent.Parser(body="@.HEAD #!++i")
prs_body = pent.Parser(head="#++i", body="#!++f")
prs_tail = pent.Parser(body="@.TAIL &!+")
prs = pent.Parser(head=prs_head, body=prs_body, tail=prs_tail)
result = prs.capture_struct(data)
expect = [
{
pent.ParserField.Head: [
{
pent.ParserField.Head: None,
pent.ParserField.Body: [["1", "2"], ["3", "4"]],
pent.ParserField.Tail: None,
}
],
pent.ParserField.Body: [
{
pent.ParserField.Head: [[]],
pent.ParserField.Body: [
[".1", ".2", ".3"],
[".2", ".3", ".4"],
],
pent.ParserField.Tail: None,
},
{
pent.ParserField.Head: [[]],
pent.ParserField.Body: [
[".3", ".4", ".5"],
[".4", ".5", ".6"],
[".5", ".6", ".7"],
],
pent.ParserField.Tail: None,
},
],
pent.ParserField.Tail: [
{
pent.ParserField.Head: None,
pent.ParserField.Body: [["a", "b"], ["c", "d"]],
pent.ParserField.Tail: None,
}
],
}
]
self.assertEqual(result, expect)
class TestPentParserOptlinePatterns(ut.TestCase, SuperPent):
"""Confirming matching of optional-line patterns."""
def test_optional_1line_head(self):
"""Confirm parsers with one optional line in head."""
prs = pent.Parser(head="? @!.foo", body="#!+.i")
# Many of these match because the "header" line is just
# ignored by the optional line of the head.
# NEED TO ROBUSTIFY WITH A CHECK ON THE HEAD CAPTURES!
good_texts = [
("1 2 3", []),
("1 2 3\n4 5 6", []),
("foo\n1 2 3", [["foo"]]),
("\n1 2 3", []),
("foo\n\n\n1 2 3", []),
("foobar\n1 2 3", []),
]
for i, tup in enumerate(good_texts):
with self.subTest("good_{}".format(i)):
s = prs.capture_struct(tup[0])
self.assertNotEqual([], s)
self.assertEqual(s[pent.ParserField.Head], tup[1])
def test_optional_2line_head(self):
"""Confirm parsers with two optional lines in head."""
prs = pent.Parser(head=("? @!.foo", "? @!.bar"), body="#!+.i")
# Again, a couple of these match because the whole header
# is just ignored.
good_texts = [
("1 2 3", []),
("1 2 3\n4 5", []),
("foo\n1 2 3", [["foo", None]]),
("bar\n1 2 3", [[None, "bar"]]),
("foobar\n1 2 3", [[None, None]]),
("foo\n\n\n1 2 3", [[None, None]]),
("foo\nbar\n1 2 3", [["foo", "bar"]]),
("foo\n\n1 2 3", [["foo", None]]),
]
for i, tup in enumerate(good_texts):
with self.subTest("good_{}".format(i)):
s = prs.capture_struct(tup[0])
self.assertNotEqual([], s)
self.assertEqual(s[pent.ParserField.Head], tup[1])