Debian Codegraph @

tests/test_misc.py

raw symbols SCIP
1 # Misc tests.
2 # coding: utf-8
3
4 import json
5 import os
6 import tempfile
7 import unittest
8
9 from context import sedparse
10 from utils import parse_string
11
12
13 class TestSedparseMisc(unittest.TestCase): # pylint: disable=unused-variable
14 def test_string_expr_count(self):
15 """Calling compile_string() should increase by one the expression count."""
16 before = sedparse.cur_input.string_expr_count
17 _ = parse_string("p")
18 _ = parse_string("p")
19 _ = parse_string("p")
20 after = sedparse.cur_input.string_expr_count
21 self.assertEqual(before + 3, after)
22
23 def test_global_data_cleanup(self):
24 """
25 Global variables should be reset after an error and after the end of
26 normal execution, to avoid leaking and affecting the next run.
27 """
28
29 # After compile_string(), prog.* should be NULL
30 script = ["p", "x", "s/foo/bar/g"]
31 sedparse.compile_string([], "\n".join(script))
32 self.assertIsNone(sedparse.prog.base)
33 self.assertIsNone(sedparse.prog.cur)
34 self.assertIsNone(sedparse.prog.end)
35 self.assertIsNone(sedparse.prog.text)
36
37 # After compile_file(), prog.file should be NULL
38 script = ["p", "x", "s/foo/bar/g"]
39 with tempfile.NamedTemporaryFile(mode="w", delete=False) as file:
40 file.write("\n".join(script))
41 filename = file.name
42 sedparse.compile_file([], filename)
43 self.assertIsNone(sedparse.prog.file)
44 os.remove(filename)
45
46 # After normal execution, blocks is back to zero and old_text_buf will
47 # still hold some contents.
48 script = ["{", "i\\", "foo", "}"]
49 _ = parse_string("\n".join(script))
50 self.assertEqual(0, sedparse.blocks)
51 self.assertIsNone(sedparse.pending_text)
52
53 # After an error, every global should be reset
54 script = ["{", "i\\", "foo", "XXX"]
55 try:
56 _ = parse_string("\n".join(script))
57 except sedparse.ParseError:
58 pass
59 self.assertEqual(0, sedparse.blocks)
60 self.assertIsNone(sedparse.old_text_buf)
61 self.assertIsNone(sedparse.pending_text)
62 self.assertIsNone(sedparse.prog.base)
63 self.assertIsNone(sedparse.prog.cur)
64 self.assertIsNone(sedparse.prog.end)
65 self.assertIsNone(sedparse.prog.text)
66 self.assertIsNone(sedparse.prog.file)
67
68 def test_expressions_and_files(self):
69 """
70 In the commmand line, the sed script to be parsed can be informed using
71 a string `-e` and/or a file `-f`. Both options can be used multiple
72 times to compose a larger script in smaller chunks. The original option
73 order is respected. This mimics how GNU sed itself works.
74
75 Option `-e` is mapped to `compile_string()` and option `-f` is mapped to
76 `compile_file()`. Both are called here in different combinations to make
77 sure they work as expected.
78 """
79
80 # Create a script file
81 with tempfile.NamedTemporaryFile(mode="w", delete=False) as file:
82 file.write("x\n")
83 filename = file.name
84
85 data = [
86 # @ means the file must be loaded (-f file)
87 (["@"], ["x"]),
88 (["p"], ["p"]),
89 (["p", "d", "q"], ["p", "d", "q"]),
90 (["@", "p"], ["x", "p"]),
91 (["p", "@"], ["p", "x"]),
92 (["p", "@", "d", "@", "q"], ["p", "x", "d", "x", "q"]),
93 ]
94 for scripts, expected_commands in data:
95 args = []
96 for script in scripts:
97 if script == "@":
98 args.extend(["-f", filename])
99 else:
100 args.extend(["-e", script])
101 the_json = sedparse.main(args)
102 the_program = json.loads(the_json)
103 self.assertEqual(
104 expected_commands, [x["cmd"] for x in the_program], msg=scripts
105 )
106 os.remove(filename)
107
108 def test_savchar_with_unicode(self):
109 """
110 savchar() should handle Unicode characters correctly. That means going
111 back N bytes when the input is a file, where N is the lenght in bytes of
112 the current Unicode character (i.e., ★ is composed of 3 bytes).
113
114 In this test, while reading the numeric argument for the "q" command in
115 `in_integer()`, it will detect the "9" and then a non-number "★". At
116 this point `savchar()` will be called to go back before the "★". Then
117 the parser will read "★" again and complain about "extra characters
118 after command". If Unicode backtracking is not supported, the parser
119 error would be different.
120 """
121 script = "q9★\n"
122
123 # Create a script file
124 with tempfile.NamedTemporaryFile(mode="w", delete=False) as file:
125 file.write(script)
126 filename = file.name
127
128 # Test reading from a file (-f)
129 with self.assertRaises(sedparse.ParseError) as manager:
130 sedparse.compile_file([], filename)
131 self.assertTrue(
132 manager.exception.message.endswith("extra characters after command")
133 )
134 os.remove(filename)
135
136 # Test reading from a string (-e)
137 with self.assertRaises(sedparse.ParseError) as manager:
138 sedparse.compile_string([], script)
139 self.assertTrue(
140 manager.exception.message.endswith("extra characters after command")
141 )
142
143
144 if __name__ == "__main__":
145 unittest.main()