doc-cli-test 0.2.3__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
cli_test/__init__.py ADDED
@@ -0,0 +1,10 @@
1
+ from .config import Config, default_config, merge_config
2
+ from .parser import parse_file
3
+ from .runner import run_example
4
+
5
+ try:
6
+ from ._version import __version__
7
+ except ImportError: # plain source checkout, no build has generated _version.py yet
8
+ __version__ = "0.0.0"
9
+
10
+ __all__ = ["Config", "default_config", "merge_config", "parse_file", "run_example"]
cli_test/__main__.py ADDED
@@ -0,0 +1,4 @@
1
+ from .cli import main
2
+
3
+ if __name__ == "__main__":
4
+ raise SystemExit(main())
@@ -0,0 +1,9 @@
1
+ """Compare function used by the Sphinx builder.
2
+
3
+ Directive content cannot express a trailing newline, so trailing newlines
4
+ are ignored on both sides when testing documented examples.
5
+ """
6
+
7
+
8
+ def compare(expected: bytes, actual: bytes) -> bool:
9
+ return expected.rstrip(b"\n") == actual.rstrip(b"\n")
cli_test/_version.py ADDED
@@ -0,0 +1,24 @@
1
+ # file generated by vcs-versioning
2
+ # don't change, don't track in version control
3
+ from __future__ import annotations
4
+
5
+ __all__ = [
6
+ "__version__",
7
+ "__version_tuple__",
8
+ "version",
9
+ "version_tuple",
10
+ "__commit_id__",
11
+ "commit_id",
12
+ ]
13
+
14
+ version: str
15
+ __version__: str
16
+ __version_tuple__: tuple[int | str, ...]
17
+ version_tuple: tuple[int | str, ...]
18
+ commit_id: str | None
19
+ __commit_id__: str | None
20
+
21
+ __version__ = version = '0.2.3'
22
+ __version_tuple__ = version_tuple = (0, 2, 3)
23
+
24
+ __commit_id__ = commit_id = None
cli_test/cli.py ADDED
@@ -0,0 +1,275 @@
1
+ from __future__ import annotations
2
+
3
+ import argparse
4
+ import os
5
+ import re
6
+ import shlex
7
+ import subprocess
8
+ import sys
9
+ from pathlib import Path
10
+ from typing import Any, Dict, List, Optional
11
+
12
+
13
+ from .compare import default_compare, load_compare
14
+ from .config import Config, default_config, merge_config
15
+ from .parser import parse_file
16
+
17
+
18
+ def _collect_files(paths: List[str]) -> List[Path]:
19
+ files: List[Path] = []
20
+ for raw in paths:
21
+ p = Path(raw)
22
+ if p.is_dir():
23
+ for child in sorted(p.rglob("*")):
24
+ if child.is_file():
25
+ files.append(child)
26
+ elif p.exists():
27
+ files.append(p)
28
+ return files
29
+
30
+
31
+ def _run_setup(cmd: Optional[str], cwd: Optional[str] = None, env: Optional[Dict[str, str]] = None) -> None:
32
+ if not cmd:
33
+ return
34
+ subprocess.run(shlex.split(cmd), cwd=cwd, env=env, check=False)
35
+
36
+
37
+ def _parse_hexdump(hexdump_str: str) -> bytes:
38
+ """Parse hexdump format and extract raw bytes.
39
+
40
+ Handles various hexdump formats:
41
+ - Simple hex: "48 65 6c 6c 6f"
42
+ - With offsets: "00000000 48 65 6c 6c 6f"
43
+ - With ASCII: "00000000 48 65 6c 6c 6f |hello|"
44
+ - Full format: "00000000 48 65 6c 6c 6f 0a 48 65 78 64 75 6d 70 0a |hello.hexdump.|"
45
+ """
46
+ hex_bytes = []
47
+
48
+ for line in hexdump_str.splitlines():
49
+ line = line.strip()
50
+ if not line:
51
+ continue
52
+
53
+ # Skip column header lines (contain non-hex formatting like "0 1 2 3")
54
+ if any(c in line for c in '[]{}'):
55
+ continue
56
+ if line.startswith((' ', '\t')):
57
+ continue
58
+ # Skip lines that are only offset numbers (like "00000015")
59
+ if len(line) == 8 and all(c in '0123456789ABCDEFabcdef' for c in line):
60
+ continue
61
+ # Skip column headers (lines starting with spaces and containing hex digits)
62
+ if re.match(r'^\s+[0-9A-Fa-f\s]+$', line) and '|' not in line:
63
+ # Check if this looks like a header line
64
+ parts = line.split()
65
+ if all(len(p) <= 2 for p in parts):
66
+ continue
67
+
68
+ # Remove ASCII representation part (everything after and including '|')
69
+ if '|' in line:
70
+ line = line.split('|')[0].rstrip()
71
+
72
+ # Remove leading offset (8 hex digits followed by spaces)
73
+ # Pattern: 8 hex digits, optional spaces, then hex bytes
74
+ line = re.sub(r'^[0-9a-fA-F]{8}\s+', '', line)
75
+
76
+ # Extract all hex byte sequences (pairs of hex digits, possibly with spaces)
77
+ # This regex finds all 2-character hex sequences separated by spaces
78
+ hex_pairs = re.findall(r'[0-9a-fA-F]{2}', line)
79
+ hex_bytes.extend(hex_pairs)
80
+
81
+ # Convert hex byte strings to actual bytes
82
+ if hex_bytes:
83
+ return bytes.fromhex(''.join(hex_bytes))
84
+ return b""
85
+
86
+
87
+ def _resolve_expected(raw: str, source_path: Path, hexdump: int) -> bytes:
88
+ if not raw:
89
+ return b""
90
+ if raw.startswith("@"):
91
+ file_path = (source_path.parent / raw[1:]).resolve()
92
+ return file_path.read_bytes()
93
+ value = raw.encode("utf-8")
94
+ if hexdump:
95
+ return _parse_hexdump(raw)
96
+ return value
97
+
98
+
99
+ def _first_mismatch(expected: bytes, actual: bytes) -> int:
100
+ limit = min(len(expected), len(actual))
101
+ for offset in range(limit):
102
+ if expected[offset] != actual[offset]:
103
+ return offset
104
+ if len(expected) != len(actual):
105
+ return limit
106
+ return -1
107
+
108
+
109
+ def _byte_position(data: bytes, offset: int, start_line: int = 1, start_column: int = 1) -> Dict[str, int]:
110
+ if offset < 0:
111
+ offset = 0
112
+ line = start_line
113
+ column = start_column
114
+ for index in range(offset):
115
+ if index >= len(data):
116
+ break
117
+ if data[index] == 10:
118
+ line += 1
119
+ column = 1
120
+ else:
121
+ column += 1
122
+ return {"line": line, "column": column}
123
+
124
+
125
+ def run_example(example, cfg: Config) -> Dict[str, Any]:
126
+ cwd = cfg.run_dir or os.getcwd()
127
+ env = os.environ.copy()
128
+ env.update(cfg.env)
129
+
130
+ if cfg.path:
131
+ env["PATH"] = os.pathsep.join(cfg.path + [env.get("PATH", "")]) if env.get("PATH") else os.pathsep.join(cfg.path)
132
+
133
+ _run_setup(cfg.setup, cwd=cwd, env=env)
134
+
135
+ try:
136
+ result = subprocess.run(
137
+ shlex.split(example.cmd),
138
+ cwd=cwd,
139
+ env=env,
140
+ capture_output=True,
141
+ timeout=cfg.timeout,
142
+ text=False,
143
+ )
144
+ stdout = result.stdout
145
+ stderr = result.stderr
146
+ ok = True
147
+ failed = None
148
+
149
+ if cfg.hexdump:
150
+ expected_stdout = _resolve_expected(example.stdout, example.path, 1)
151
+ expected_stderr = _resolve_expected(example.stderr, example.path, 1)
152
+ else:
153
+ expected_stdout = _resolve_expected(example.stdout, example.path, 0)
154
+ expected_stderr = _resolve_expected(example.stderr, example.path, 0)
155
+
156
+ compare_fn = default_compare
157
+ if cfg.cmp:
158
+ compare_fn = load_compare(cfg.cmp)
159
+
160
+ if example.stdout and not compare_fn(expected_stdout, stdout):
161
+ ok = False
162
+ offset = _first_mismatch(expected_stdout, stdout)
163
+ start_line = example.stdout_start_line or 1
164
+ failed = ("stdout", expected_stdout, stdout, _byte_position(expected_stdout, offset if offset >= 0 else 0, start_line=start_line))
165
+ if example.stderr and not compare_fn(expected_stderr, stderr):
166
+ ok = False
167
+ offset = _first_mismatch(expected_stderr, stderr)
168
+ start_line = example.stderr_start_line or 1
169
+ failed = ("stderr", expected_stderr, stderr, _byte_position(expected_stderr, offset if offset >= 0 else 0, start_line=start_line))
170
+
171
+ try:
172
+ expected_code = int(example.code.strip()) if example.code else 0
173
+ except ValueError:
174
+ raise ValueError(f"invalid expected return code: {example.code.strip()!r}")
175
+ if result.returncode != expected_code:
176
+ ok = False
177
+ failed = (
178
+ "returncode",
179
+ str(expected_code).encode("utf-8"),
180
+ str(result.returncode).encode("utf-8"),
181
+ {"line": example.code_start_line or 1, "column": 1},
182
+ )
183
+ return {
184
+ "ok": ok,
185
+ "stdout": stdout,
186
+ "stderr": stderr,
187
+ "failed": failed,
188
+ "returncode": result.returncode,
189
+ "example": example,
190
+ }
191
+ except subprocess.TimeoutExpired:
192
+ return {
193
+ "ok": False,
194
+ "stdout": b"",
195
+ "stderr": b"",
196
+ "failed": ("timeout", b"", b"", {"line": 1, "column": 1}),
197
+ "timeout": True,
198
+ "example": example,
199
+ }
200
+ finally:
201
+ _run_setup(cfg.cleanup, cwd=cwd, env=env)
202
+
203
+
204
+ def main(argv: Optional[List[str]] = None) -> int:
205
+ parser = argparse.ArgumentParser(prog="cli-test")
206
+ parser.add_argument("paths", nargs="+", help="files or directories to scan")
207
+ parser.add_argument("--timeout", type=int, default=30)
208
+ parser.add_argument("--run-dir")
209
+ parser.add_argument("--path", action="append", default=[])
210
+ parser.add_argument("--env", action="append", default=[])
211
+ parser.add_argument("--seq", type=int, default=0)
212
+ parser.add_argument("--reuse", type=int, default=0)
213
+ parser.add_argument("--prefix", default="cli-test-")
214
+ parser.add_argument("--hexdump", type=int, default=0)
215
+ parser.add_argument("--setup")
216
+ parser.add_argument("--cleanup")
217
+ parser.add_argument("--global-setup")
218
+ parser.add_argument("--global-cleanup")
219
+ parser.add_argument("--cmp")
220
+ args = parser.parse_args(argv)
221
+
222
+ base_cfg = default_config()
223
+ base_cfg.timeout = args.timeout
224
+ base_cfg.run_dir = args.run_dir
225
+ base_cfg.path = args.path
226
+ base_cfg.seq = args.seq
227
+ base_cfg.reuse = args.reuse
228
+ base_cfg.prefix = args.prefix
229
+ base_cfg.hexdump = args.hexdump
230
+ base_cfg.setup = args.setup
231
+ base_cfg.cleanup = args.cleanup
232
+ base_cfg.global_setup = args.global_setup
233
+ base_cfg.global_cleanup = args.global_cleanup
234
+ base_cfg.cmp = args.cmp
235
+
236
+ for item in args.env:
237
+ if "=" not in item:
238
+ raise ValueError(f"Invalid --env value: {item!r}")
239
+ key, value = item.split("=", 1)
240
+ base_cfg.env[key] = value
241
+
242
+ files = _collect_files(args.paths)
243
+ total_examples = 0
244
+ passed = 0
245
+ timed_out = 0
246
+ failed = 0
247
+
248
+ for path in files:
249
+ examples = parse_file(path)
250
+ for example in examples:
251
+ total_examples += 1
252
+ cfg = merge_config(base_cfg, example.config)
253
+ result = run_example(example, cfg)
254
+ if result["ok"]:
255
+ passed += 1
256
+ elif result.get("timeout"):
257
+ timed_out += 1
258
+ else:
259
+ failed += 1
260
+ stream, expected, actual, location = result["failed"]
261
+ print(f"FAIL: {path} example {example.index} {stream}")
262
+ if stream == "returncode":
263
+ print(f" expected return code: {expected.decode()}")
264
+ print(f" actual return code: {actual.decode()}")
265
+ else:
266
+ print(f" mismatch at line {location['line']}, column {location['column']}")
267
+ print(f" expected: {expected!r}")
268
+ print(f" actual: {actual!r}")
269
+
270
+ print(f"{len(files)} files, {total_examples} examples, {passed} passed, {timed_out} timeout, {failed} failed")
271
+ return 0 if failed == 0 and timed_out == 0 else 1
272
+
273
+
274
+ if __name__ == "__main__":
275
+ raise SystemExit(main())
cli_test/compare.py ADDED
@@ -0,0 +1,23 @@
1
+ from __future__ import annotations
2
+
3
+ import importlib.util
4
+ from pathlib import Path
5
+ from types import ModuleType
6
+ from typing import Callable
7
+
8
+
9
+ def default_compare(expected: bytes, actual: bytes) -> bool:
10
+ return expected == actual
11
+
12
+
13
+ def load_compare(path: str) -> Callable[[bytes, bytes], bool]:
14
+ module_path = Path(path)
15
+ spec = importlib.util.spec_from_file_location("cli_test_compare", module_path)
16
+ if spec is None or spec.loader is None:
17
+ raise ImportError(f"Cannot load comparison module: {path!r}")
18
+ module = importlib.util.module_from_spec(spec)
19
+ spec.loader.exec_module(module)
20
+ compare = getattr(module, "compare", None)
21
+ if compare is None:
22
+ raise ValueError(f"Comparison module {path!r} does not define compare(expected, actual)")
23
+ return compare
cli_test/config.py ADDED
@@ -0,0 +1,114 @@
1
+ from __future__ import annotations
2
+
3
+ import os
4
+ from dataclasses import dataclass, field
5
+ from typing import Dict, Iterable, List, Optional
6
+
7
+
8
+ @dataclass
9
+ class Config:
10
+ timeout: int = 30
11
+ run_dir: Optional[str] = None
12
+ path: List[str] = field(default_factory=list)
13
+ env: Dict[str, str] = field(default_factory=dict)
14
+ setup: Optional[str] = None
15
+ global_setup: Optional[str] = None
16
+ cleanup: Optional[str] = None
17
+ global_cleanup: Optional[str] = None
18
+ cmp: Optional[str] = None
19
+ seq: int = 0
20
+ reuse: int = 0
21
+ prefix: str = "cli-test-"
22
+ hexdump: int = 0
23
+
24
+ def apply_override(self, overrides: Dict[str, object]) -> "Config":
25
+ merged = Config(**self.__dict__)
26
+ for raw_key, value in overrides.items():
27
+ key = raw_key.replace("-", "_")
28
+ if key not in merged.__dict__:
29
+ raise ValueError(f"Unknown config key: {raw_key}")
30
+ if key in {"timeout", "seq", "reuse", "hexdump"}:
31
+ setattr(merged, key, _coerce_int(value))
32
+ elif key == "path":
33
+ setattr(merged, key, _coerce_path_list(value))
34
+ elif key == "env":
35
+ setattr(merged, key, _coerce_env(value))
36
+ elif key in {"run_dir", "setup", "global_setup", "cleanup", "global_cleanup", "cmp", "prefix"}:
37
+ setattr(merged, key, value)
38
+ else:
39
+ setattr(merged, key, value)
40
+ return merged
41
+
42
+
43
+ def _coerce_int(value: object) -> int:
44
+ if isinstance(value, bool):
45
+ return int(value)
46
+ if isinstance(value, int):
47
+ return value
48
+ if isinstance(value, str):
49
+ text = value.strip()
50
+ if not text:
51
+ return 0
52
+ if text.lower() in {"0", "1"}:
53
+ return int(text)
54
+ return parse_duration(text)
55
+ raise TypeError(f"Expected int-like value, got {value!r}")
56
+
57
+
58
+ def parse_duration(text: str) -> int:
59
+ text = text.strip()
60
+ if not text:
61
+ return 0
62
+
63
+ suffix_map = {
64
+ "ms": 0.001,
65
+ "s": 1.0,
66
+ "m": 60.0,
67
+ "h": 3600.0,
68
+ }
69
+ for suffix, factor in suffix_map.items():
70
+ if text.lower().endswith(suffix):
71
+ number = text[: -len(suffix)]
72
+ return int(float(number) * factor)
73
+ return int(float(text))
74
+
75
+
76
+ def _coerce_path_list(value: object) -> List[str]:
77
+ if value is None:
78
+ return []
79
+ if isinstance(value, str):
80
+ return [part for part in value.split(os.pathsep) if part]
81
+ if isinstance(value, Iterable):
82
+ return [str(item) for item in value]
83
+ return [str(value)]
84
+
85
+
86
+ def _coerce_env(value: object) -> Dict[str, str]:
87
+ env: Dict[str, str] = {}
88
+ if not value:
89
+ return env
90
+ if isinstance(value, dict):
91
+ return {str(k): str(v) for k, v in value.items()}
92
+ if isinstance(value, str):
93
+ for item in value.split(os.pathsep):
94
+ if not item:
95
+ continue
96
+ if "=" not in item:
97
+ raise ValueError(f"Invalid env entry: {item!r}")
98
+ key, val = item.split("=", 1)
99
+ env[key] = val
100
+ return env
101
+ for item in value:
102
+ if "=" not in str(item):
103
+ raise ValueError(f"Invalid env entry: {item!r}")
104
+ key, val = str(item).split("=", 1)
105
+ env[key] = val
106
+ return env
107
+
108
+
109
+ def merge_config(base: Config, override: Dict[str, object]) -> Config:
110
+ return base.apply_override(override)
111
+
112
+
113
+ def default_config() -> Config:
114
+ return Config()