Debian Codegraph @

python/unit_tests/data/test_defs.py

raw
1 # SPDX-FileCopyrightText: Peter Pentchev <[email protected]>
2 # SPDX-License-Identifier: BSD-2-Clause
3
4 """Class definitions for the confget test suite."""
5
6 import abc
7 import dataclasses
8 import os
9 import shlex
10 from typing import Any, Dict, Iterable, List, NamedTuple, Optional, Type
11
12 from confget import backend as cbackend
13 from confget import defs as cdefs
14 from confget import format as cformat
15
16
17 class CmdOpt(NamedTuple):
18 """Keep track of command-line options that require an argument."""
19
20 option: str
21 has_argument: bool
22
23
24 CMDLINE_OPTIONS = {
25 "check_only": CmdOpt("-c", has_argument=False),
26 "filename": CmdOpt("-f", has_argument=True),
27 "hide_var_name": CmdOpt("-n", has_argument=False),
28 "list_all": CmdOpt("-l", has_argument=False),
29 "match_var_names": CmdOpt("-L", has_argument=False),
30 "match_var_values": CmdOpt("-m", has_argument=True),
31 "section": CmdOpt("-s", has_argument=True),
32 "section_override": CmdOpt("-O", has_argument=False),
33 "section_specified": CmdOpt("", has_argument=False),
34 "show_var_name": CmdOpt("-N", has_argument=False),
35 }
36
37
38 def get_test_path(relpath: Optional[str]) -> str:
39 """Get the path to a test definition file."""
40 return os.environ.get("TESTDIR", "test_data") + ("/" + relpath if relpath is not None else "")
41
42
43 @dataclasses.dataclass(frozen=True)
44 class XFormType(metaclass=abc.ABCMeta):
45 """Transform something to something else with great prejudice."""
46
47 @property
48 @abc.abstractmethod
49 def command(self) -> str:
50 """Get the shell command to transform the confget output."""
51 raise NotImplementedError(f"{type(self).__name__}.command")
52
53 @abc.abstractmethod
54 def do_xform(self, res: Iterable[cformat.FormatOutput]) -> str:
55 """Transform the Python representation of the result."""
56 raise NotImplementedError(f"{type(self).__name__}.do_xform()")
57
58
59 @dataclasses.dataclass(frozen=True)
60 class XFormNone(XFormType):
61 """No transformation, newlines preserved."""
62
63 @property
64 def command(self) -> str:
65 """Return a no-op shell command, nothing at all."""
66 return ""
67
68 def do_xform(self, res: Iterable[cformat.FormatOutput]) -> str:
69 """Return the output exactly as it was produced."""
70 return "\n".join([line.output_full for line in res])
71
72
73 @dataclasses.dataclass(frozen=True)
74 class XFormNewlineToSpace(XFormType):
75 """Translate newlines to spaces."""
76
77 @property
78 def command(self) -> str:
79 """Get the shell command to merge all lines into one."""
80 return '| tr "\\n" " "'
81
82 def do_xform(self, res: Iterable[cformat.FormatOutput]) -> str:
83 """Merge the lines output by confget."""
84 return "".join(line.output_full + " " for line in res)
85
86
87 @dataclasses.dataclass(frozen=True)
88 class XFormCountLines(XFormType):
89 """Count the lines output by confget."""
90
91 sought: Optional[str] = None
92 sought_in: bool = True
93
94 @property
95 def command(self) -> str:
96 """Get the shell command to count lines, either the matching ones or all of them."""
97 prefix = (
98 "| fgrep -{inv}e {sought} ".format(
99 inv="" if self.sought_in else "v",
100 sought=shlex.quote(self.sought),
101 )
102 if self.sought is not None
103 else ""
104 )
105 return prefix + "| wc -l | tr -d ' '"
106
107 def do_xform(self, res: Iterable[cformat.FormatOutput]) -> str:
108 """Return the number of matching lines (all of them if "sought" not specified)."""
109 if self.sought is None:
110 return str(len(list(res)))
111
112 lines = [line for line in res if self.sought_in == (self.sought in line.output_full)]
113 return str(len(lines))
114
115
116 XFORM = {
117 "": XFormNone(),
118 "count-lines": XFormCountLines(),
119 "count-lines-eq": XFormCountLines(sought="="),
120 "count-lines-non-eq": XFormCountLines(sought="=", sought_in=False),
121 "newline-to-space": XFormNewlineToSpace(),
122 }
123
124
125 class OutputDef(metaclass=abc.ABCMeta):
126 """A definition for a single test's output."""
127
128 def __init__(self) -> None: # noqa: B027
129 """No initialization at all for the base class."""
130
131 @abc.abstractmethod
132 def get_check(self) -> str:
133 """Get the check string as a shell command."""
134 raise NotImplementedError(f"{type(self).__name__}.get_check()")
135
136 @property
137 @abc.abstractmethod
138 def var_name(self) -> str:
139 """Get the variable name to display."""
140 raise NotImplementedError(f"{type(self).__name__}.var_name")
141
142 @abc.abstractmethod
143 def check_result(self, _res: str) -> None:
144 """Check whether the processed confget result is correct."""
145 raise NotImplementedError(f"{type(self).__name__}.check_result()")
146
147
148 class ExactOutputDef(OutputDef):
149 """Check that the program output this exact string."""
150
151 def __init__(self, exact: str) -> None:
152 """Initialize an exact test output object."""
153 super().__init__()
154 self.exact = exact
155
156 def get_check(self) -> str:
157 """Get the "is this the correct string?" check as a shell command."""
158 return '[ "$v" = ' + shlex.quote(self.exact) + " ]"
159
160 @property
161 def var_name(self) -> str:
162 """Get the "v" variable name to display."""
163 return "v"
164
165 def check_result(self, res: str) -> None:
166 """Check whether the processed confget result is exactly as expected."""
167 assert res == self.exact
168
169
170 class ExitOKOutputDef(OutputDef):
171 """Check that the program succeeded or failed as expected."""
172
173 def __init__(self, *, success: bool) -> None:
174 """Initialize an "finished successfully" test output object."""
175 super().__init__()
176 self.success = success
177
178 def get_check(self) -> str:
179 """Get the "did the program succeed?" check as a shell command."""
180 return '[ "$res" {compare} 0 ]'.format(compare="=" if self.success else "!=")
181
182 @property
183 def var_name(self) -> str:
184 """Get the "res" variable name to display."""
185 return "res"
186
187 def check_result(self, res: str) -> None:
188 """Raise an error since this class merely tests the program's exit code."""
189 raise NotImplementedError(repr((self, res)))
190
191
192 @dataclasses.dataclass(frozen=True)
193 class SingleTestDef:
194 """A definition for a single test."""
195
196 args: Dict[str, str]
197 keys: List[str]
198 output: OutputDef
199 xform: str = ""
200 backend: str = cdefs.BackendType.INI
201 stdin: Optional[str] = None
202
203 def get_backend(self) -> Type[cbackend.abstract.Backend]:
204 """Get the appropriate confget backend type."""
205 return cbackend.BACKENDS[self.backend]
206
207 def get_config(self) -> cformat.FormatConfig:
208 """Convert the test's data to a config object."""
209 data: Dict[str, Any] = {}
210 for name, value in self.args.items():
211 if name == "hide_var_name":
212 continue
213
214 opt = CMDLINE_OPTIONS[name]
215 if opt.has_argument:
216 data[name] = value
217 else:
218 data[name] = True
219
220 if "filename" in data:
221 data["filename"] = get_test_path(data["filename"])
222 elif self.stdin:
223 data["filename"] = "-"
224
225 data["show_var_name"] = "show_var_name" in self.args or (
226 ("match_var_names" in self.args or "list_all" in self.args or len(self.keys) > 1)
227 and "hide_var_name" not in self.args
228 )
229
230 return cformat.FormatConfig(self.keys, **data)
231
232 def do_xform(self, res: Iterable[cformat.FormatOutput]) -> str:
233 """Return the output delimiter depending on the xform property."""
234 return XFORM[self.xform].do_xform(res)
235
236
237 @dataclasses.dataclass(frozen=True)
238 class FileDef:
239 """A definition for a file defining related tests."""
240
241 tests: List[SingleTestDef]