Debian Codegraph @

tests/test_parser.py

raw symbols SCIP
1 # Test the parser, feeding it with tricky sed scripts.
2 # coding: utf-8
3
4 import unittest
5
6 from utils import parse_string
7
8
9 # The global holder for all the test data
10 TEST_DATA = {}
11
12 # Aligning test cases makes them way more readable
13 # pylint: disable=bad-whitespace
14
15 # -----------------------------------------------------------------------------
16 # Test data for ADDRESSES
17
18 TEST_DATA["address"] = [
19 # Test cases for addresses: numeric, $, /regex/
20 # Source: compile_address(), match_slash()
21 # fmt: off
22
23 # sed script ! addr1 addr2
24 # --------------------------------------------
25
26 # no address
27 ("p", False, None, None),
28 ("!p", True, None, None),
29 ("{}", False, None, None),
30 ("!{}", True, None, None),
31
32 # last line
33 ("$p", False, "$", None),
34 ("${}", False, "$", None),
35 ("$!p", True, "$", None),
36 (" $ p", False, "$", None),
37 (" $ {}", False, "$", None),
38 (" $ ! p", True, "$", None),
39
40 # numeric
41 ("5p", False, "5", None),
42 ("5{}", False, "5", None),
43 ("5!p", True, "5", None),
44 (" 5 p", False, "5", None),
45 (" 5 {}", False, "5", None),
46 (" 5 ! p", True, "5", None),
47
48 # numeric range
49 ("1,5p", False, "1", "5"),
50 ("1,5{}", False, "1", "5"),
51 ("1,5!p", True, "1", "5"),
52 (" 1 , 5 p", False, "1", "5"),
53 (" 1 , 5 {}", False, "1", "5"),
54 (" 1 , 5 ! p", True, "1", "5"),
55
56 # inverted range
57 ("5,1p", False, "5", "1"),
58 ("$,1p", False, "$", "1"),
59
60 # zero is allowed if second address is a regex
61 ("0,/x/p", False, "0", "/x/"),
62
63 # steps ~ and +
64 ("1~2p", False, "1~2", None),
65 ("0~2p", False, "0~2", None),
66 ("5~0p", False, "5", None), # source change
67 ("1,~2p", False, "1", "~2"),
68 ("1,+2p", False, "1", "+2"),
69 ("1,~0p", False, "1", "~0"),
70 ("1,+0p", False, "1", "+0"),
71
72 # regex with /
73 ("/x/p", False, "/x/", None),
74 ("/x/{}", False, "/x/", None),
75 ("/x/!p", True, "/x/", None),
76 (" /x/ p", False, "/x/", None),
77 (" /x/ {}", False, "/x/", None),
78 (" /x/ ! p", True, "/x/", None),
79
80 ("/x/,/y/p", False, "/x/", "/y/"),
81 ("/x/,/y/{}", False, "/x/", "/y/"),
82 ("/x/,/y/!p", True, "/x/", "/y/"),
83 (" /x/ , /y/ p", False, "/x/", "/y/"),
84 (" /x/ , /y/ {}", False, "/x/", "/y/"),
85 (" /x/ , /y/ ! p", True, "/x/", "/y/"),
86
87 # flags (GNU extension)
88 ("/x/Ip", False, "/x/I", None),
89 ("/x/I{}", False, "/x/I", None),
90 ("/x/I!p", True, "/x/I", None),
91 (" /x/ I p", False, "/x/I", None),
92 (" /x/ I {}", False, "/x/I", None),
93 (" /x/ I ! p", True, "/x/I", None),
94
95 # combining flags
96 ("/x/IMp", False, "/x/IM", None),
97 ("/x/MIp", False, "/x/MI", None),
98 ("/x/ M I p", False, "/x/MI", None),
99
100 # repeated flags are not removed
101 ("/x/MMIIMIp", False, "/x/MMIIMI", None),
102
103 # escaped / delimiter will loose the escape
104 (r"\/x/p", False, r"/x/", None), # source change
105
106 # regex with other delimiter (\n and non-ASCII not allowed)
107 (r"\;x;p", False, r"\;x;", None),
108 (r"\,x,p", False, r"\,x,", None),
109 (r"\(x(p", False, r"\(x(", None),
110 (r"\[x[p", False, r"\[x[", None),
111 (r"\ x p", False, r"\ x ", None),
112 ( "\\\tx\tp", False, "\\\tx\t", None), # tab
113 (r"\\x\p", False, "\\\\x\\", None), # \
114 #(r"\★x★p", False, "\\★x★", None), # ★
115
116 # regex: command as delimiter
117 (r"\pxpp", False, r"\pxp", None),
118 (r"\=x==", False, r"\=x=", None),
119 (r"\{x{{}", False, r"\{x{", None),
120
121 # regex: bang as delimiter
122 (r"\!x!p", False, r"\!x!", None),
123 (r"\!x!!p", True, r"\!x!", None),
124
125 # regex: flag letter as delimiter
126 (r"\IxIp", False, r"\IxI", None),
127 (r"\IxIIp", False, r"\IxII", None),
128
129 # empty regex
130 (r"//p", False, r"//", None),
131 (r"\ppp", False, r"\pp", None),
132 (r"//,//p", False, r"//", r"//"),
133 (r"\,,,\ppp", False, r"\,,", r"\pp"),
134 (r"\III,\MMMp", False, r"\III", r"\MMM"),
135
136 # same address repeated
137 ("5,5p", False, "5", "5"),
138 ("$,$p", False, "$", "$"),
139 ("/x/,/x/p", False, "/x/", "/x/"),
140 ("//,//p", False, "//", "//"),
141
142 # Non-ASCII chars are allowed
143 ("/★/,/★/p", False, "/★/", "/★/"),
144
145 # regex that looks numeric or last line
146 ("/0/p", False, "/0/", None),
147 ("/5/p", False, "/5/", None),
148 ("/1,5/p", False, "/1,5/", None),
149 ("/$/p", False, "/$/", None),
150
151 # mixed extra tabs and spaces
152 (" 1\t ,\t 5\t p", False, "1", "5"),
153 ("\t /x/\t !\t p", True, "/x/", None),
154 ("\t /x/\t I\t p", False, "/x/I", None),
155
156 # regex: escaped delimiter (start, middle, end)
157 (r"/\/\/\//p", False, r"/\/\/\//", None),
158 (r"\|\|\|\||p", False, r"\|\|\|\||", None),
159
160 # Delimiter inside a regex character class
161 ("/[/]/p", False, "/[/]/", None),
162 ]
163
164
165 # -----------------------------------------------------------------------------
166 # Test data for FILENAME commands
167
168 TEST_DATA["r"] = [
169 # Test cases for command: r, R, w, W
170 # Note that "s///w filename" is tested in the "s" tests.
171 # Note: all scripts end in EOF. At run time the \n ending is also tested.
172 # Source: read_filename()
173 # Format: (sed script, expected filename)
174 # fmt: off
175
176 ("rname", "name"),
177
178 # Leading spaces are ignored
179 ("r space", "space"),
180 ("r\ttab", "tab"),
181 ("r \t \t mixed", "mixed"),
182
183 # Every char is valid (it reads until \n), so ;}# are not special
184 ("r;", ";"),
185 ("r}", "}"),
186 ("r#", "#"),
187 ("r\\", "\\"),
188 ("r foo}; \t#\\", "foo}; \t#\\"),
189
190 # Non-ASCII chars are allowed
191 ("r★", "★"),
192 ]
193
194 # Copy all "r" tests to: R, w, W
195 TEST_DATA["R"] = [("R" + script[1:], filename) for script, filename in TEST_DATA["r"]]
196 TEST_DATA["w"] = [("w" + script[1:], filename) for script, filename in TEST_DATA["r"]]
197 TEST_DATA["W"] = [("W" + script[1:], filename) for script, filename in TEST_DATA["r"]]
198
199 # Filename is the command name
200 TEST_DATA["r"].append(("rr", "r"))
201 TEST_DATA["R"].append(("RR", "R"))
202 TEST_DATA["w"].append(("ww", "w"))
203 TEST_DATA["W"].append(("WW", "W"))
204
205
206 # -----------------------------------------------------------------------------
207 # Test data for LABEL commands
208
209 TEST_DATA[":"] = [
210 # Test cases for commands: :, b, t, T, v
211 # Note: all scripts end in EOF. At run time the \n ending is also tested.
212 # Source: read_label()
213 # Format: (sed script, expected label name)
214 # fmt: off
215
216 (":name", "name"),
217
218 # Leading spaces are ignored
219 (": space", "space"),
220 (":\ttab", "tab"),
221 (": \t \t mixed", "mixed"),
222
223 # Those chars end a label: tab space ; #
224 # Note that } also ends a label, but it will be tested later
225 (":label\t", "label"),
226 (":label ", "label"),
227 (":label;", "label"),
228 (":label#", "label"),
229
230 # All other chars are valid as labels
231 (":!", "!"),
232 (":{", "{"),
233 (":\\", "\\"),
234
235 # Non-ASCII chars are allowed
236 (":★", "★"),
237 ]
238
239 # Copy all ":" tests to: b, t, T, v
240 TEST_DATA["b"] = [("b" + script[1:], label) for script, label in TEST_DATA[":"]]
241 TEST_DATA["t"] = [("t" + script[1:], label) for script, label in TEST_DATA[":"]]
242 TEST_DATA["T"] = [("T" + script[1:], label) for script, label in TEST_DATA[":"]]
243 TEST_DATA["v"] = [("v" + script[1:], label) for script, label in TEST_DATA[":"]]
244
245 # Label name is the command name
246 TEST_DATA[":"].append(("::", ":"))
247 TEST_DATA["b"].append(("bb", "b"))
248 TEST_DATA["t"].append(("tt", "t"))
249 TEST_DATA["T"].append(("TT", "T"))
250 TEST_DATA["v"].append(("vv", "v"))
251
252 # Labels are ended by the } command
253 TEST_DATA[":"].append(("{:label}", "label"))
254 TEST_DATA["b"].append(("{blabel}", "label"))
255 TEST_DATA["t"].append(("{tlabel}", "label"))
256 TEST_DATA["T"].append(("{Tlabel}", "label"))
257 TEST_DATA["v"].append(("{vlabel}", "label"))
258
259 # Empty labels are allowed when jumping
260 TEST_DATA["b"].append(("b", ""))
261 TEST_DATA["t"].append(("t", ""))
262 TEST_DATA["T"].append(("T", ""))
263
264 # The v command can also be empty
265 TEST_DATA["v"].append(("v", ""))
266
267 # Those chars end an empty label: tab space ; } #
268 TEST_DATA["b"].append(("b\t", ""))
269 TEST_DATA["b"].append(("b ", ""))
270 TEST_DATA["b"].append(("b;", ""))
271 TEST_DATA["b"].append(("{b}", ""))
272 TEST_DATA["b"].append(("b#", ""))
273
274
275 # -----------------------------------------------------------------------------
276 # Test data for TEXT commands
277
278 TEST_DATA["a"] = [
279 # Test cases for commands: a, i, c, e
280 # Source: read_text()
281 # Format: (sed script, expected text)
282 # fmt: off
283
284 # Traditional sed requires a line break after \
285 ("a\\\ntext", "text"),
286
287 # GNU sed allows no line break
288 ("a\\text", "text"),
289
290 # GNU sed allows no \ either
291 ("atext", "text"),
292
293 # Multiline texts with leading a\\n, a\, a should produce the same output
294 ("a\\\n1\\\n2\\\n3", "1\\\n2\\\n3"),
295 ( "a\\1\\\n2\\\n3", "1\\\n2\\\n3"),
296 ( "a1\\\n2\\\n3", "1\\\n2\\\n3"),
297
298 # Empty text at EOF is allowed (when having \ and/or \n)
299 ("a\\\n", ""),
300 ("a\\", ""),
301 ("a\n", ""),
302 #("a", ""), # Error: expected \ after `a', `c' or `i'
303
304 # Leading spaces before \ are ignored
305 ("a \\space", "space"),
306 ("a\t\\tab", "tab"),
307 ("a \t \t \\mixed", "mixed"),
308
309 # Leading spaces after \ are preserved
310 ("a\\ text", " text"),
311 ("a\\\ttext", "\ttext"),
312 ("a\\ \t \t text", " \t \t text"),
313
314 # Leading spaces are ignored when no \ is used
315 ("a space", "space"),
316 ("a\ttab", "tab"),
317 ("a \t \t mixed", "mixed"),
318
319 # Trailing spaces are always preserved
320 ("atext ", "text "),
321 ("atext\t", "text\t"),
322 ("atext \t \t ", "text \t \t "),
323
324 # From second line on, leading and trailing spaces are always preserved
325 ("a\\\n1\\\n 2 \\\n\t3\t", "1\\\n 2 \\\n\t3\t"),
326 ( "a\\1\\\n 2 \\\n\t3\t", "1\\\n 2 \\\n\t3\t"),
327 ( "a1\\\n 2 \\\n\t3\t", "1\\\n 2 \\\n\t3\t"),
328
329 # Literal escape at beginning and middle of the line
330 ("a\\\n\\text\\text", "\\text\\text"),
331 ( "a\\\\text\\text", "\\text\\text"),
332 ( "atext\\text", "text\\text"),
333
334 # Literal escape at EOL is allowed except in the last line
335 #XXX why only odd numbers work?
336 ("a\\\n1" + "\\"*1 + "\n2", "1" + "\\"*1 + "\n2"),
337 # ("a\\\n1" + "\\"*2 + "\n2p", "1" + "\\"*2 + "\n2p"),
338 ("a\\\n1" + "\\"*3 + "\n2", "1" + "\\"*3 + "\n2"),
339 # ("a\\\n1" + "\\"*4 + "\n2", "1" + "\\"*4 + "\n2"),
340 ("a\\\n1" + "\\"*5 + "\n2", "1" + "\\"*5 + "\n2"),
341
342 # Every char is valid (it reads until \n), so ;}# are not special
343 ("a;", ";"),
344 ("a}", "}"),
345 ("a#", "#"),
346 ("a\\ foo}; \t#", " foo}; \t#"),
347
348 # Non-ASCII chars are allowed
349 ("a★", "★"),
350 ]
351
352 # Copy all "a" tests to: i, c, e
353 TEST_DATA["i"] = [("i" + script[1:], text) for script, text in TEST_DATA["a"]]
354 TEST_DATA["c"] = [("c" + script[1:], text) for script, text in TEST_DATA["a"]]
355 TEST_DATA["e"] = [("e" + script[1:], text) for script, text in TEST_DATA["a"]]
356
357 # Empty bare "e" is allowed (but forbidden for a, i, c)
358 TEST_DATA["e"].append(("e", ""))
359
360
361 # -----------------------------------------------------------------------------
362 # Test data for "y" and "s" commands
363
364 TEST_DATA["y"] = [
365 # Test cases for commands: y, s
366 # Source: match_slash()
367 # Format: (sed script, delimiter, source, dest)
368 # fmt: off
369
370 # Simple usage
371 ("y/a/A/", "/", "a", "A"),
372
373 # Empty source and dest
374 ("y///", "/", "", ""),
375
376 # Source and dest are equal
377 ("y/a/a/", "/", "a", "a"),
378
379 # Space and tab in source and dest
380 ("y/ /\t/", "/", " ", "\t"),
381 ("y/\t/ /", "/", "\t", " "),
382
383 # Otherwise special chars as delimiter
384 ("y;a;A;", ";", "a", "A"),
385 ("y[a[A[", "[", "a", "A"),
386 ("y{a{A{", "{", "a", "A"),
387 ("y}a}A}", "}", "a", "A"),
388 ("y#a#A#", "#", "a", "A"),
389 ("y a A ", " ", "a", "A"),
390 ("y\ta\tA\t", "\t", "a", "A"),
391 ("y\\a\\A\\", "\\", "a", "A"),
392
393 # Literal / must be escaped as \/ in source and dest
394 ("y/\\/a/\\/A/", "/", "\\/a", "\\/A"),
395
396 # Literal x must be escaped as \x in source and dest when delim=x
397 ("y#\\#a#\\#A#", "#", "\\#a", "\\#A"),
398
399 # Literal \ must be escaped as \\ in source and dest
400 ("y/\\\\/\\\\/", "/", "\\\\", "\\\\"),
401
402 # Literal \n must be escaped as \\n in source and dest
403 ("y/\\\n/\\\n/", "/", "\\\n", "\\\n"),
404
405 # Literal \ is not allowed when \ is the delimiter
406 #("y\\\\\\a\\\\\\A\\", "\\", "\\\\a", "\\\\A"),
407
408 # Non-ASCII chars are NOT allowed as delimiter
409 #("y★a★A★", "★", "a", "A"),
410
411 # Non-ASCII chars are allowed as source and dest
412 ("y/★/★/", "/", "★", "★"),
413 ]
414
415 # Copy all "y" tests to: s
416 TEST_DATA["s"] = [
417 ("s" + script[1:], delimiter, source, dest)
418 for script, delimiter, source, dest in TEST_DATA["y"]
419 ]
420
421 # y: source and dest are allowed to have different lengths
422 # Note: This differs from the GNU sed parser. Since we do not perform the
423 # de-escaping of \/, \\ and \\n, the length check is turned off.
424 TEST_DATA["y"].append(("y/a/aa/", "/", "a", "aa"))
425
426 # Command name as delimiter
427 TEST_DATA["y"].append(("yyayAy", "y", "a", "A"))
428 TEST_DATA["s"].append(("ssasAs", "s", "a", "A"))
429
430 # Delimiter inside a regex character class
431 TEST_DATA["s"].append(("s/[/]//", "/", "[/]", ""))
432
433
434 # -----------------------------------------------------------------------------
435 # Test data for using flags in the "s" command
436
437 TEST_DATA["s-flags"] = [
438 # Source: match_slash(), mark_subst_opts()
439 # Format: (sed script, delimiter, pattern, replacement, flags, flag_arg)
440 # fmt: off
441
442 # Flags: traditional sed
443 ("s/a/A/g", "/", "a", "A", "g", ""),
444 ("s/a/A/p", "/", "a", "A", "p", ""),
445 ("s/a/A/1", "/", "a", "A", "1", ""),
446 ("s/a/A/99", "/", "a", "A", "99", ""),
447 ("s/a/A/999", "/", "a", "A", "999", ""),
448 ("s/a/A/wfile", "/", "a", "A", "w", "file"),
449
450 # Flags: GNU sed extensions
451 ("s/a/A/e", "/", "a", "A", "e", ""),
452 ("s/a/A/m", "/", "a", "A", "m", ""),
453 ("s/a/A/i", "/", "a", "A", "i", ""),
454 ("s/a/A/M", "/", "a", "A", "M", ""),
455 ("s/a/A/I", "/", "a", "A", "I", ""),
456
457 # Flags: trailing \r\n is allowed
458 ("s/a/A/g\r\n", "/", "a", "A", "g", ""),
459
460 # Flags mixed (note that the order is preserved)
461 ("s/a/A/gpemiMIwfile", "/", "a", "A", "gpemiMIw", "file"),
462
463 # Flags: GNU sed extensions can be repeated
464 ("s/a/A/eemmiiMMII", "/", "a", "A", "eemmiiMMII", ""),
465 ("s/a/A/emiMIemiMI", "/", "a", "A", "emiMIemiMI", ""),
466
467 # Flag w: must be the last flag (everything is a filename after it)
468 ("s/a/A/wfile gp", "/", "a", "A", "w", "file gp"),
469
470 # Flag w: leading spaces are ignored
471 ("s/a/A/w space", "/", "a", "A", "w", "space"),
472 ("s/a/A/w\ttab", "/", "a", "A", "w", "tab"),
473 ("s/a/A/w \t \t mixed", "/", "a", "A", "w", "mixed"),
474
475 # Flag w: every char is valid (it reads until \n), so ;}# are not special
476 ("s/a/A/w;", "/", "a", "A", "w", ";"),
477 ("s/a/A/w}", "/", "a", "A", "w", "}"),
478 ("s/a/A/w#", "/", "a", "A", "w", "#"),
479 ("s/a/A/w\\", "/", "a", "A", "w", "\\"),
480 ("s/a/A/w foo}; \t#\\", "/", "a", "A", "w", "foo}; \t#\\"),
481
482 # Flag w: non-ASCII chars are allowed
483 ("s/a/A/w★", "/", "a", "A", "w", "★"),
484 ]
485
486
487 # -----------------------------------------------------------------------------
488
489 TEST_DATA["#"] = [
490 # Test cases for comments
491 # Preserving comments is a sedparse extension. GNU sed discards them.
492 # Note: all scripts end in EOF. At run time the \n ending is also tested.
493 # Note: result_index identifies # command index in the parsing results list.
494 # Source: read_comment()
495 # Format: (result_index, sed script, comment)
496 # fmt: off
497
498 # Empty comment
499 (0, "#", ""),
500 (1, "p#", ""),
501 (1, "p;#", ""),
502
503 # No spaces around #
504 (0, "#foo", "foo"),
505 (1, "p#foo", "foo"),
506 (1, "p;#foo", "foo"),
507
508 # Leading spaces before # are ignored
509 (0, " \t#foo", "foo"),
510 (1, "p \t#foo", "foo"),
511 (1, "p; \t#foo", "foo"),
512
513 # Leading and trailing spaces in the comment contents are preserved
514 (0, "# foo ", " foo "),
515 (0, "#\t\tfoo\t\t", "\t\tfoo\t\t"),
516
517 # Extra leading # are treated as comment content
518 (0, "##foo", "#foo"),
519 (0, "####foo", "###foo"),
520
521 # An escape at line end is not special inside comments
522 (0, "#foo\\", "foo\\"),
523
524 # Command-ending characters are not special inside comments
525 (0, "#foo;", "foo;"),
526 (0, "#foo}", "foo}"),
527
528 # Comment right after a label command
529 (1, ":a#foo", "foo"),
530 (1, "ba#foo", "foo"),
531 (1, "b #foo", "foo"),
532 (1, "b#foo", "foo"),
533
534 # Comment right after y and s
535 (1, "y/a/A/#foo", "foo"),
536 (1, "s/a/A/g#foo", "foo"),
537
538 # Comment right after blocks
539 # Note: "{#foo" is the only allowed partial comment in BSD sed (no ; before)
540 (1, "{#foo\n}", "foo"),
541 (2, "{}#foo", "foo"),
542
543 # The special #n at first line is treated as a normal comment by the parser.
544 # After parsing, the calling code can make it special if desired.
545 (0, "#n", "n"),
546 ]
547
548
549 # -----------------------------------------------------------------------------
550
551 TEST_DATA["\n"] = [
552 # Test cases for blank lines
553 # Preserving blank lines is a sedparse extension. GNU sed discards them.
554 # Source: ignore_trailing_fluff() and also search for "sedparse" comments.
555 # Format: (sed script, *expected_parsed_commands)
556 # fmt: off
557
558 # 100% blank lines script
559 ("\n", "\n"),
560 ("\n\n", "\n", "\n"),
561 ("\n\n\n", "\n", "\n", "\n"),
562
563 # blank lines at the top and bottom should be preserved
564 ("\n\np", "\n", "\n", "p"),
565 ("p\n\n\n", "p", "\n", "\n"),
566
567 # blank lines between solo commands should be preserved
568 ("p\nq", "p", "q"),
569 ("p\n\nq", "p", "\n", "q"),
570 ("p\n\n\nq", "p", "\n", "\n", "q"),
571
572 # blank lines between label commands should be preserved
573 ("b\nq", "b", "q"),
574 ("b\n\nq", "b", "\n", "q"),
575 ("b\n\n\nq", "b", "\n", "\n", "q"),
576
577 # blank lines between filename commands should be preserved
578 ("rfoo\nq", "r", "q"),
579 ("rfoo\n\nq", "r", "\n", "q"),
580 ("rfoo\n\n\nq", "r", "\n", "\n", "q"),
581
582 # blank lines between text commands should be preserved
583 ("a\\\nfoo\nq", "a", "q"),
584 ("a\\\nfoo\n\nq", "a", "\n", "q"),
585 ("a\\\nfoo\n\n\nq", "a", "\n", "\n", "q"),
586
587 # blank lines between consecutive blocks should be preserved
588 ("{\n}\n{}", "{", "}", "{", "}"),
589 ("{\n\n}\n\n{}", "{", "\n", "}", "\n", "{", "}"),
590 ("{\n\n\n}\n\n\n{}", "{", "\n", "\n", "}", "\n", "\n", "{", "}"),
591
592 # blank lines between nested blocks should be preserved
593 ("{\n{}\n}", "{", "{", "}", "}"),
594 ("{\n\n{}\n\n}", "{", "\n", "{", "}", "\n", "}"),
595 ("{\n\n\n{}\n\n\n}", "{", "\n", "\n", "{", "}", "\n", "\n", "}"),
596
597 # blank lines between comments should be preserved
598 ("#foo\n#bar", "#", "#"),
599 ("#foo\n\n#bar", "#", "\n", "#"),
600 ("#foo\n\n\n#bar", "#", "\n", "\n", "#"),
601 ]
602
603
604 # -----------------------------------------------------------------------------
605
606 TEST_DATA["block"] = [
607 # Test cases for blocks
608 # Note: all scripts end in EOF. At run time the \n ending is also tested.
609 # Format: (sed script, *expected_parsed_commands)
610 # fmt: off
611
612 # Empty blocks are allowed
613 ("{}", "{", "}"),
614
615 # Nested empty blocks are allowed
616 ("{{}}", "{", "{", "}", "}"),
617
618 # Using ; is optional around { and }
619 ("{p}", "{", "p", "}"),
620 ("{p;}", "{", "p", "}"),
621 ("{;p}", "{", "p", "}"),
622 ("{;p;}", "{", "p", "}"),
623 ("{p;};", "{", "p", "}"),
624 ]
625
626
627 # -----------------------------------------------------------------------------
628
629 TEST_DATA["gotcha"] = [
630 # Test cases for some gotchas
631 # Note: all scripts end in EOF. At run time the \n ending is also tested.
632 # Format: (sed script, *expected_parsed_commands)
633 # fmt: off
634
635 # Test read_label() detection for the next command
636 ("blabel\t", "b"),
637 ("blabel ", "b"),
638 ("blabel;", "b"),
639 ("{blabel}", "{", "b", "}"),
640 ("blabel#", "b", "#"),
641 ("blabel;;; #", "b", "#"),
642
643 # Same tests repeated, now with an empty label
644 ("b\t", "b"),
645 ("b ", "b"),
646 ("b;", "b"),
647 ("{b}", "{", "b", "}"),
648 ("b#", "b", "#"),
649 ("b;;; #", "b", "#"),
650 ]
651
652
653 # -----------------------------------------------------------------------------
654
655 TEST_DATA["trailing_fluff"] = [
656 # Test cases for ignore_trailing_fluff()
657 # Note: all scripts end in EOF. At run time the \n ending is also tested.
658 # Format: (sed script, *expected_parsed_commands)
659 # fmt: off
660
661 # Ignore trailing spaces and tabs
662 ("p ", "p"),
663 ("p\t\t\t", "p"),
664 ("p\t \t ", "p"),
665
666 # Ignore trailing semicolons
667 ("p;", "p"),
668 ("p;;;;;", "p"),
669 ("p;;;;;x", "p", "x"),
670
671 # Mixing spaces and semicolons
672 ("p ;\t; ", "p"),
673 ("p ;;\tx", "p", "x"),
674 ]
675
676
677 class TestSedparseParser(unittest.TestCase): # pylint: disable=unused-variable
678 def _assert_defaults(self, data, skip=None, msg=""):
679 """Assert that all command attributes are set to their default values.
680 Use `skip=["foo"]` to skip checking the `foo` attribute.
681 """
682 # pylint: disable=too-many-branches
683 if skip is None:
684 skip = []
685 if "a1" not in skip:
686 self.assertEqual(None, data.a1, msg=msg)
687 if "a2" not in skip:
688 self.assertEqual(None, data.a2, msg=msg)
689 if "addr_bang" not in skip:
690 self.assertEqual(False, data.addr_bang, msg=msg)
691 if "int_arg" not in skip:
692 self.assertEqual(-1, data.x.int_arg, msg=msg)
693 if "fname" not in skip:
694 self.assertEqual("", data.x.fname, msg=msg)
695 if "label_name" not in skip:
696 self.assertEqual("", data.x.label_name, msg=msg)
697 if "cmd_txt" not in skip:
698 self.assertEqual("", str(data.x.cmd_txt), msg=msg)
699 if "comment" not in skip:
700 self.assertEqual("", data.x.comment, msg=msg)
701 if "slash" not in skip:
702 self.assertEqual("", data.x.cmd_subst.regx.slash, msg=msg)
703 if "pattern" not in skip:
704 self.assertEqual("", data.x.cmd_subst.regx.pattern, msg=msg)
705 if "replacement" not in skip:
706 self.assertEqual("", data.x.cmd_subst.replacement.text, msg=msg)
707 if "flags" not in skip:
708 self.assertEqual("", data.x.cmd_subst.regx.flags, msg=msg)
709 if "outf" not in skip:
710 self.assertEqual("", data.x.cmd_subst.outf.name, msg=msg)
711
712 def test_address(self):
713 for script, bang, addr1, addr2 in TEST_DATA["address"]:
714 expected = [bang, addr1, addr2]
715
716 # only the first command matters, i.e., { when {}
717 parsed = parse_string(script)[0]
718 self.assertListEqual(
719 expected,
720 [
721 parsed.addr_bang,
722 str(parsed.a1) if parsed.a1 else None,
723 str(parsed.a2) if parsed.a2 else None,
724 ],
725 msg=script,
726 )
727
728 def test_commands_with_no_args(self):
729 commands = (
730 "=",
731 "d",
732 "D",
733 "F",
734 "g",
735 "G",
736 "h",
737 "H",
738 "l",
739 "L",
740 "n",
741 "N",
742 "p",
743 "P",
744 "q",
745 "Q",
746 "x",
747 "z",
748 )
749 for command in commands:
750 for template in ("%s", "%s;", "{%s}", "%s#foo", "{ \t%s \t}"):
751 script = template % command
752 parsed = parse_string(script)
753 parsed = parsed[1] if "{" in script else parsed[0]
754 self.assertEqual(command, parsed.cmd, msg=script)
755 self._assert_defaults(parsed, skip=None, msg=script)
756
757 def test_commands_with_numeric_arg(self):
758 # Note that those commands "solo", with no numeric arguments,
759 # are already tested in test_commands_with_no_args().
760 for command in ("l", "L", "q", "Q"):
761 for arg in (0, 5, 99):
762 for template in (
763 "%s%d",
764 "%s%d;",
765 "{%s%d}",
766 "%s%d#foo",
767 "{ \t%s \t%d \t}",
768 ):
769 script = template % (command, arg)
770 parsed = parse_string(script)
771 parsed = parsed[1] if "{" in script else parsed[0]
772 self.assertEqual(command, parsed.cmd, msg=script)
773 self.assertEqual(arg, parsed.x.int_arg, msg=script)
774 self._assert_defaults(parsed, skip=["int_arg"], msg=script)
775
776 def test_commands_with_filename(self):
777 for command in ("r", "R", "w", "W"):
778 for script_end in ("", "\n"): # empty=EOF
779 for script, filename in TEST_DATA[command]:
780 script = script + script_end
781 parsed = parse_string(script)[0]
782 self.assertEqual(command, parsed.cmd, msg=script)
783 self.assertEqual(filename, parsed.x.fname, msg=script)
784 self._assert_defaults(parsed, skip=["fname"], msg=script)
785
786 def test_commands_with_label(self):
787 for command in (":", "b", "t", "T", "v"):
788 for script_end in ("", "\n"): # empty=EOF
789 for script, label in TEST_DATA[command]:
790 script = script + script_end
791 parsed = parse_string(script)
792 if parsed[0].cmd == "{":
793 parsed = parsed[1]
794 else:
795 parsed = parsed[0]
796 self.assertEqual(command, parsed.cmd, msg=script)
797 self.assertEqual(label, parsed.x.label_name, msg=script)
798 self._assert_defaults(parsed, skip=["label_name"], msg=script)
799
800 def test_commands_with_text(self):
801 for command in ("a", "i", "c", "e"):
802 for script, text in TEST_DATA[command]:
803 parsed = parse_string(script)[0]
804 self.assertEqual(command, parsed.cmd, msg=script)
805 self.assertEqual(text, str(parsed.x.cmd_txt), msg=script)
806 self._assert_defaults(parsed, skip=["cmd_txt"], msg=script)
807
808 def test_commands_y_and_s(self):
809 for command in ("y", "s"):
810 for script, delimiter, arg1, arg2 in TEST_DATA[command]:
811 parsed = parse_string(script)[0]
812 self.assertEqual(command, parsed.cmd, msg=script)
813 self.assertEqual(delimiter, parsed.x.cmd_subst.regx.slash, msg=script)
814 self.assertEqual(arg1, parsed.x.cmd_subst.regx.pattern, msg=script)
815 self.assertEqual(arg2, parsed.x.cmd_subst.replacement.text, msg=script)
816 self._assert_defaults(
817 parsed, skip=["slash", "pattern", "replacement"], msg=script
818 )
819
820 def test_command_s_flags(self):
821 command = "s"
822 for script, delimiter, pattern, replacement, flags, flag_arg in TEST_DATA[
823 "s-flags"
824 ]:
825 parsed = parse_string(script)[0]
826 self.assertEqual(command, parsed.cmd, msg=script)
827 self.assertEqual(delimiter, parsed.x.cmd_subst.regx.slash, msg=script)
828 self.assertEqual(pattern, parsed.x.cmd_subst.regx.pattern, msg=script)
829 self.assertEqual(
830 replacement, parsed.x.cmd_subst.replacement.text, msg=script
831 )
832 self.assertEqual(flags, parsed.x.cmd_subst.regx.flags, msg=script)
833 self.assertEqual(flag_arg, parsed.x.cmd_subst.outf.name, msg=script)
834 self._assert_defaults(
835 parsed,
836 skip=["slash", "pattern", "replacement", "flags", "outf"],
837 msg=script,
838 )
839
840 def test_comments(self): # sedparse extension
841 command = "#"
842 for script_end in ("", "\n"): # empty=EOF
843 for index, script, comment in TEST_DATA[command]:
844 script = script + script_end
845 parsed = parse_string(script)[index]
846 self.assertEqual(command, parsed.cmd, msg=script)
847 self.assertEqual(comment, parsed.x.comment, msg=script)
848 self._assert_defaults(parsed, skip=["comment"], msg=script)
849
850 def test_blank_lines(self): # sedparse extension
851 for data in TEST_DATA["\n"]:
852 script = data[0]
853 expected_commands = list(data[1:])
854 self.assertEqual(
855 expected_commands, [x.cmd for x in parse_string(script)], msg=script
856 )
857
858 def test_blocks(self):
859 for script_end in ("", "\n"): # empty=EOF
860 for data in TEST_DATA["block"]:
861 script = data[0] + script_end
862 expected_commands = list(data[1:])
863 self.assertEqual(
864 expected_commands, [x.cmd for x in parse_string(script)], msg=script
865 )
866
867 def test_gotchas(self):
868 for script_end in ("", "\n"): # empty=EOF
869 for data in TEST_DATA["gotcha"]:
870 script = data[0] + script_end
871 expected_commands = list(data[1:])
872 self.assertEqual(
873 expected_commands, [x.cmd for x in parse_string(script)], msg=script
874 )
875
876 def test_ignore_trailing_fluff(self):
877 for script_end in ("", "\n"): # empty=EOF
878 for data in TEST_DATA["trailing_fluff"]:
879 script = data[0] + script_end
880 expected_commands = list(data[1:])
881 self.assertEqual(
882 expected_commands, [x.cmd for x in parse_string(script)], msg=script
883 )
884
885 def test_command_data_cleanup(self):
886 """
887 All data from the previous command must be cleared when reading
888 the next one. Those tests check that the last bare "p" command
889 should be using the default values for all the data fields.
890 """
891 # a1, a2, bang, slash, pattern, replacement, flags, outf
892 script = ["/a1/I, /a2/M ! s/foo/bar/igw file", "p"]
893 p_data = parse_string("\n".join(script))[-1]
894 self._assert_defaults(p_data, skip=None, msg=script)
895
896 # int_arg
897 script = ["q99", "p"]
898 p_data = parse_string("\n".join(script))[-1]
899 self._assert_defaults(p_data, skip=None, msg=script)
900
901 # fname
902 script = ["r file", "p"]
903 p_data = parse_string("\n".join(script))[-1]
904 self._assert_defaults(p_data, skip=None, msg=script)
905
906 # label_name
907 script = [":label", "p"]
908 p_data = parse_string("\n".join(script))[-1]
909 self._assert_defaults(p_data, skip=None, msg=script)
910
911 # cmd_txt
912 script = ["a", "text", "p"]
913 p_data = parse_string("\n".join(script))[-1]
914 self._assert_defaults(p_data, skip=None, msg=script)
915
916
917 if __name__ == "__main__":
918 unittest.main()