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 +10 -0
- cli_test/__main__.py +4 -0
- cli_test/_sphinx_compare.py +9 -0
- cli_test/_version.py +24 -0
- cli_test/cli.py +275 -0
- cli_test/compare.py +23 -0
- cli_test/config.py +114 -0
- cli_test/parser.py +395 -0
- cli_test/runner.py +57 -0
- cli_test/sphinxext.py +281 -0
- doc_cli_test-0.2.3.dist-info/METADATA +333 -0
- doc_cli_test-0.2.3.dist-info/RECORD +15 -0
- doc_cli_test-0.2.3.dist-info/WHEEL +4 -0
- doc_cli_test-0.2.3.dist-info/entry_points.txt +2 -0
- doc_cli_test-0.2.3.dist-info/licenses/LICENSE +201 -0
cli_test/sphinxext.py
ADDED
|
@@ -0,0 +1,281 @@
|
|
|
1
|
+
"""Sphinx integration for cli-test.
|
|
2
|
+
|
|
3
|
+
Provides a ``cli-test`` directive and a ``cli-test`` builder.
|
|
4
|
+
|
|
5
|
+
The directive is the single source of truth for a documented command: it
|
|
6
|
+
renders a clean console block in the output documentation (no cli-test
|
|
7
|
+
markers are visible) and registers the example so it can be executed.
|
|
8
|
+
|
|
9
|
+
Enable it in ``conf.py``::
|
|
10
|
+
|
|
11
|
+
extensions = ["cli_test.sphinxext"]
|
|
12
|
+
|
|
13
|
+
Usage::
|
|
14
|
+
|
|
15
|
+
.. cli-test:: python -c "print(2 + 2)"
|
|
16
|
+
|
|
17
|
+
4
|
|
18
|
+
|
|
19
|
+
Directive options:
|
|
20
|
+
|
|
21
|
+
``stderr``
|
|
22
|
+
Expected output on ``stderr``. Tested but not rendered.
|
|
23
|
+
``ret``
|
|
24
|
+
Expected return code. Defaults to 0 when not given.
|
|
25
|
+
``cfg``
|
|
26
|
+
Per-example cli-test settings, one ``key=value`` per line. Lines are
|
|
27
|
+
continued by indenting them under the option::
|
|
28
|
+
|
|
29
|
+
.. cli-test:: some-command
|
|
30
|
+
:cfg: timeout=10s
|
|
31
|
+
seq=1
|
|
32
|
+
|
|
33
|
+
expected output
|
|
34
|
+
``hide-output``
|
|
35
|
+
Flag. Render only the command line, not the expected output.
|
|
36
|
+
|
|
37
|
+
Run the examples during the documentation build::
|
|
38
|
+
|
|
39
|
+
sphinx-build -b cli-test docs docs/_build/clitest
|
|
40
|
+
|
|
41
|
+
By default the examples are also checked on every build, including plain
|
|
42
|
+
``sphinx-build -M html``: failures are reported as build errors and the build
|
|
43
|
+
exits non-zero. Set ``cli_test_check_on_build = False`` in ``conf.py`` to
|
|
44
|
+
check them only with the dedicated ``cli-test`` builder. With
|
|
45
|
+
``sphinx-build -W -b cli-test`` a mismatch fails the build as a warning.
|
|
46
|
+
Examples run with the Sphinx project directory as working directory; a
|
|
47
|
+
relative ``run-dir`` in ``cfg`` is resolved against the Sphinx project
|
|
48
|
+
directory.
|
|
49
|
+
|
|
50
|
+
Comparison is byte-for-byte like the cli-test CLI, except that trailing
|
|
51
|
+
newlines are ignored on both sides (directive content cannot express a
|
|
52
|
+
trailing newline). Provide your own ``cmp=...`` in ``cfg`` for full control.
|
|
53
|
+
"""
|
|
54
|
+
|
|
55
|
+
from __future__ import annotations
|
|
56
|
+
|
|
57
|
+
import os
|
|
58
|
+
from pathlib import Path
|
|
59
|
+
from typing import Any, Dict, List
|
|
60
|
+
|
|
61
|
+
from docutils import nodes
|
|
62
|
+
from docutils.parsers.rst import directives
|
|
63
|
+
|
|
64
|
+
from sphinx.application import Sphinx
|
|
65
|
+
from sphinx.builders import Builder
|
|
66
|
+
from sphinx.util import logging
|
|
67
|
+
from sphinx.util.docutils import SphinxDirective
|
|
68
|
+
|
|
69
|
+
from .cli import run_example
|
|
70
|
+
from .config import default_config, merge_config
|
|
71
|
+
from .parser import Example, _parse_cfg_block
|
|
72
|
+
|
|
73
|
+
logger = logging.getLogger(__name__)
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
def _env_data(env: Any) -> Dict[str, List[Dict[str, Any]]]:
|
|
77
|
+
if not hasattr(env, "cli_test_examples"):
|
|
78
|
+
env.cli_test_examples = {}
|
|
79
|
+
return env.cli_test_examples
|
|
80
|
+
|
|
81
|
+
|
|
82
|
+
def _execute(env: Any, record: Dict[str, Any], index: int) -> Dict[str, Any]:
|
|
83
|
+
example = Example(
|
|
84
|
+
cmd=record["cmd"],
|
|
85
|
+
stdout=record["stdout"],
|
|
86
|
+
stderr=record["stderr"],
|
|
87
|
+
code=record.get("code", ""),
|
|
88
|
+
config=record["config"],
|
|
89
|
+
path=Path(record["source"]),
|
|
90
|
+
index=index,
|
|
91
|
+
)
|
|
92
|
+
cfg = default_config()
|
|
93
|
+
if cfg.run_dir is None:
|
|
94
|
+
cfg.run_dir = env.srcdir
|
|
95
|
+
if "cmp" not in example.config:
|
|
96
|
+
cfg.cmp = str(Path(__file__).with_name("_sphinx_compare.py"))
|
|
97
|
+
cfg = merge_config(cfg, example.config)
|
|
98
|
+
if cfg.run_dir and not os.path.isabs(cfg.run_dir):
|
|
99
|
+
cfg.run_dir = str(Path(env.srcdir) / cfg.run_dir)
|
|
100
|
+
try:
|
|
101
|
+
return run_example(example, cfg)
|
|
102
|
+
except FileNotFoundError as err:
|
|
103
|
+
# a missing command (or setup command) is an example failure,
|
|
104
|
+
# not a build crash
|
|
105
|
+
return {
|
|
106
|
+
"ok": False,
|
|
107
|
+
"stdout": b"",
|
|
108
|
+
"stderr": b"",
|
|
109
|
+
"failed": ("command-not-found", b"", b"", {"line": 1, "column": 1}),
|
|
110
|
+
"error": str(err),
|
|
111
|
+
"example": example,
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
|
|
115
|
+
def _report_failure(
|
|
116
|
+
docname: str, record: Dict[str, Any], index: int, result: Dict[str, Any]
|
|
117
|
+
) -> None:
|
|
118
|
+
if "error" in result:
|
|
119
|
+
logger.error(
|
|
120
|
+
"%s:%s: cli-test example %d: command not found: %s",
|
|
121
|
+
docname,
|
|
122
|
+
record["line"],
|
|
123
|
+
index,
|
|
124
|
+
result["error"],
|
|
125
|
+
)
|
|
126
|
+
return
|
|
127
|
+
stream, expected, actual, location = result["failed"]
|
|
128
|
+
if stream == "timeout":
|
|
129
|
+
logger.error(
|
|
130
|
+
"%s:%s: cli-test example %d timed out",
|
|
131
|
+
docname,
|
|
132
|
+
record["line"],
|
|
133
|
+
index,
|
|
134
|
+
)
|
|
135
|
+
else:
|
|
136
|
+
logger.error(
|
|
137
|
+
"%s:%s: cli-test example %d mismatch on %s at line %d, column %d; "
|
|
138
|
+
"expected %r, got %r",
|
|
139
|
+
docname,
|
|
140
|
+
record["line"],
|
|
141
|
+
index,
|
|
142
|
+
stream,
|
|
143
|
+
location["line"],
|
|
144
|
+
location["column"],
|
|
145
|
+
expected,
|
|
146
|
+
actual,
|
|
147
|
+
)
|
|
148
|
+
|
|
149
|
+
|
|
150
|
+
class CliTestDirective(SphinxDirective):
|
|
151
|
+
"""Document a command once: rendered in the docs, tested by the builder."""
|
|
152
|
+
|
|
153
|
+
has_content = True
|
|
154
|
+
required_arguments = 1
|
|
155
|
+
optional_arguments = 0
|
|
156
|
+
final_argument_whitespace = True
|
|
157
|
+
option_spec = {
|
|
158
|
+
"stderr": directives.unchanged_required,
|
|
159
|
+
"cfg": directives.unchanged_required,
|
|
160
|
+
"ret": directives.unchanged_required,
|
|
161
|
+
"hide-output": directives.flag,
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
def run(self) -> List[nodes.Node]:
|
|
165
|
+
cmd = self.arguments[0].strip()
|
|
166
|
+
stdout = "\n".join(self.content)
|
|
167
|
+
stderr = self.options.get("stderr", "")
|
|
168
|
+
code_text = self.options.get("ret", "")
|
|
169
|
+
if code_text:
|
|
170
|
+
try:
|
|
171
|
+
int(code_text)
|
|
172
|
+
except ValueError:
|
|
173
|
+
raise ValueError(f"invalid ret option: {code_text!r} (expected an integer)")
|
|
174
|
+
cfg_lines = self.options.get("cfg", "").splitlines()
|
|
175
|
+
config = _parse_cfg_block(cfg_lines) if cfg_lines else {}
|
|
176
|
+
source, line = self.state_machine.get_source_and_line(self.lineno)
|
|
177
|
+
|
|
178
|
+
_env_data(self.env).setdefault(self.env.docname, []).append(
|
|
179
|
+
{
|
|
180
|
+
"cmd": cmd,
|
|
181
|
+
"stdout": stdout,
|
|
182
|
+
"stderr": stderr,
|
|
183
|
+
"code": code_text,
|
|
184
|
+
"config": config,
|
|
185
|
+
"source": source,
|
|
186
|
+
"line": line,
|
|
187
|
+
}
|
|
188
|
+
)
|
|
189
|
+
|
|
190
|
+
text = "$ " + cmd
|
|
191
|
+
if "hide-output" not in self.options and stdout:
|
|
192
|
+
text += "\n" + stdout
|
|
193
|
+
block = nodes.literal_block(text, text)
|
|
194
|
+
block["language"] = "console"
|
|
195
|
+
block["classes"].append("cli-test")
|
|
196
|
+
return [block]
|
|
197
|
+
|
|
198
|
+
|
|
199
|
+
class CliTestBuilder(Builder):
|
|
200
|
+
"""Run every cli-test example registered by the directive."""
|
|
201
|
+
|
|
202
|
+
name = "cli-test"
|
|
203
|
+
|
|
204
|
+
def init(self) -> None:
|
|
205
|
+
self.passed = 0
|
|
206
|
+
self.failed = 0
|
|
207
|
+
|
|
208
|
+
def get_outdated_docs(self) -> List[str]:
|
|
209
|
+
return list(self.env.all_docs.keys())
|
|
210
|
+
|
|
211
|
+
def get_target_uri(self, docname: str, typ: str | None = None) -> str:
|
|
212
|
+
return docname
|
|
213
|
+
|
|
214
|
+
def prepare_writing(self, docnames: Any) -> None:
|
|
215
|
+
pass
|
|
216
|
+
|
|
217
|
+
def write_doc(self, docname: str, doctree: nodes.document) -> None:
|
|
218
|
+
for index, record in enumerate(_env_data(self.env).get(docname, []), start=1):
|
|
219
|
+
result = _execute(self.env, record, index)
|
|
220
|
+
if result["ok"]:
|
|
221
|
+
self.passed += 1
|
|
222
|
+
else:
|
|
223
|
+
self.failed += 1
|
|
224
|
+
_report_failure(docname, record, index, result)
|
|
225
|
+
|
|
226
|
+
def finish(self) -> None:
|
|
227
|
+
logger.info(
|
|
228
|
+
"cli-test: %d example(s), %d passed, %d failed",
|
|
229
|
+
self.passed + self.failed,
|
|
230
|
+
self.passed,
|
|
231
|
+
self.failed,
|
|
232
|
+
)
|
|
233
|
+
|
|
234
|
+
|
|
235
|
+
def _purge_doc(app: Sphinx, env: Any, docname: str) -> None:
|
|
236
|
+
_env_data(env).pop(docname, None)
|
|
237
|
+
|
|
238
|
+
|
|
239
|
+
def _check_on_build(app: Sphinx, exception: Exception | None) -> None:
|
|
240
|
+
"""Run every registered example unless the dedicated builder did already.
|
|
241
|
+
|
|
242
|
+
Makes plain builds such as ``sphinx-build -M html`` check the documented
|
|
243
|
+
examples. Failures are reported as build errors and make the build exit
|
|
244
|
+
non-zero.
|
|
245
|
+
"""
|
|
246
|
+
if exception is not None:
|
|
247
|
+
return
|
|
248
|
+
if app.builder.name == "cli-test":
|
|
249
|
+
return
|
|
250
|
+
if not app.config.cli_test_check_on_build:
|
|
251
|
+
return
|
|
252
|
+
passed = failed = 0
|
|
253
|
+
for docname, records in _env_data(app.env).items():
|
|
254
|
+
for index, record in enumerate(records, start=1):
|
|
255
|
+
result = _execute(app.env, record, index)
|
|
256
|
+
if result["ok"]:
|
|
257
|
+
passed += 1
|
|
258
|
+
else:
|
|
259
|
+
failed += 1
|
|
260
|
+
_report_failure(docname, record, index, result)
|
|
261
|
+
logger.info(
|
|
262
|
+
"cli-test: %d example(s), %d passed, %d failed",
|
|
263
|
+
passed + failed,
|
|
264
|
+
passed,
|
|
265
|
+
failed,
|
|
266
|
+
)
|
|
267
|
+
if failed:
|
|
268
|
+
app.statuscode = 1
|
|
269
|
+
|
|
270
|
+
|
|
271
|
+
def setup(app: Sphinx) -> Dict[str, Any]:
|
|
272
|
+
app.add_directive("cli-test", CliTestDirective, override=True)
|
|
273
|
+
app.add_builder(CliTestBuilder)
|
|
274
|
+
app.add_config_value("cli_test_check_on_build", True, "env", bool)
|
|
275
|
+
app.connect("env-purge-doc", _purge_doc)
|
|
276
|
+
app.connect("build-finished", _check_on_build)
|
|
277
|
+
return {
|
|
278
|
+
"version": "0.2",
|
|
279
|
+
"parallel_read_safe": False,
|
|
280
|
+
"parallel_write_safe": False,
|
|
281
|
+
}
|
|
@@ -0,0 +1,333 @@
|
|
|
1
|
+
Metadata-Version: 2.5
|
|
2
|
+
Name: doc-cli-test
|
|
3
|
+
Version: 0.2.3
|
|
4
|
+
Summary: Test CLI programs as you document them (doctest for CLI)
|
|
5
|
+
License: Apache-2.0
|
|
6
|
+
License-File: LICENSE
|
|
7
|
+
Requires-Python: >=3.9
|
|
8
|
+
Description-Content-Type: text/markdown
|
|
9
|
+
|
|
10
|
+
# cli-test
|
|
11
|
+
Test CLI programs as you document them (doctest for CLI)
|
|
12
|
+
|
|
13
|
+
## Installation
|
|
14
|
+
|
|
15
|
+
Install the `cli-test` command globally with [pipx](https://pipx.pypa.io/):
|
|
16
|
+
|
|
17
|
+
````
|
|
18
|
+
pipx install git+https://github.com/sebastien-riou/cli-test.git
|
|
19
|
+
````
|
|
20
|
+
|
|
21
|
+
Or from a local checkout of this repository:
|
|
22
|
+
|
|
23
|
+
````
|
|
24
|
+
pipx install .
|
|
25
|
+
````
|
|
26
|
+
|
|
27
|
+
This installs an isolated virtual environment and exposes the `cli-test`
|
|
28
|
+
command on your `PATH`. Python 3.9+ is required; no other dependencies.
|
|
29
|
+
The `cli_test` module can also be used as a library or run with
|
|
30
|
+
`python -m cli_test`.
|
|
31
|
+
|
|
32
|
+
## Concept
|
|
33
|
+
cli-test is a CLI tool which checks examples embedded within text files (source files, documentation files...).
|
|
34
|
+
It is loosely inspired by [doctest](https://docs.python.org/3/library/doctest.html) and [Sphinx doctest extension](https://github.com/sphinx-doc/sphinx/blob/master/sphinx/ext/doctest.py).
|
|
35
|
+
|
|
36
|
+
It looks for the following markers:
|
|
37
|
+
|
|
38
|
+
- `cli-test-cmd`: that marker should be followed by a new line and the command line to run.
|
|
39
|
+
- `cli-test-cfg`: that marker should be followed by a new line and some options ovverrides. It is optional.
|
|
40
|
+
- `cli-test-out`:
|
|
41
|
+
- that marker should be followed by a new line and the expected output on `stdout`.
|
|
42
|
+
- alternatively that marker can be followed by the name of a file containing the expected content.
|
|
43
|
+
- `cli-test-err`: It is optional.
|
|
44
|
+
- that marker should be followed by a new line and the expected output on `stderr`.
|
|
45
|
+
- alternatively that marker can be followed by the name of a file containing the expected content.
|
|
46
|
+
- `cli-test-ret`: It is optional.
|
|
47
|
+
- that marker should be followed by a new line and the expected return code (an integer).
|
|
48
|
+
- when it is not provided, the return code must be 0, otherwise the example fails.
|
|
49
|
+
- `cli-test-end`: that marker marks the end of the previous section.
|
|
50
|
+
|
|
51
|
+
By default, the following applies:
|
|
52
|
+
|
|
53
|
+
- Each example is independant and runs in a temporary directory.
|
|
54
|
+
- Examples may run concurrently.
|
|
55
|
+
- The environment variables are the same as for `cli-test`.
|
|
56
|
+
- The program runs with the same user that invoked `cli-test`.
|
|
57
|
+
- The program runs within the same python environment (but any program can be run).
|
|
58
|
+
- The program is killed after 30s of execution. Such timeout is considered as a fatal error and is reported as such.
|
|
59
|
+
|
|
60
|
+
`cli-test` is a python module, it can be used as a library or as a CLI program. In both cases,
|
|
61
|
+
the following optional arguments allows to change the default behavior:
|
|
62
|
+
|
|
63
|
+
- `run-dir`: path to a directory.
|
|
64
|
+
- `path`: list of path to search the program.
|
|
65
|
+
- `env`: list of environment variables.
|
|
66
|
+
- `timeout`: custom value for timeout (human friendly notation, '10m' means 10 minutes for example).
|
|
67
|
+
- `setup`: execute a script before running each example.
|
|
68
|
+
- `global-setup`: execute a script before running the first example.
|
|
69
|
+
- `cleanup`: execute a script after running each example.
|
|
70
|
+
- `global-cleanup`: execute a script after running the last example.
|
|
71
|
+
- `cmp`: specifiy a python script which implement a custom comparison function (for example if you want to ignor timestamps in the output). that function should be called `compare` and take just two positional arguments `expected` and `actual`. `expected` comes from the `cli-test-out` or `cli-test-err` section and `actual` comes from the execution of the program under test, from `stdout` or `stderre` respectively.
|
|
72
|
+
- `seq`: should be 0 or 1. default is 0. run each example sequentially.
|
|
73
|
+
- `reuse`: should be 0 or 1. default is 0. run each example within the same common environment.
|
|
74
|
+
- `prefix`: change prefix for markers. default is 'cli-test-'. It should be something like 'my-prefix-' to have the marker 'my-prefix-cmd'.
|
|
75
|
+
- `hexdump`: should be 0 or 1. default is 0. output in `cli-test-out` is represented as an hexdump rather than the actual value.
|
|
76
|
+
|
|
77
|
+
Each example can override the settings by using the `cli-test-cfg` marker.
|
|
78
|
+
Each override must be on a separate line and follow the exact form `key=value`.
|
|
79
|
+
For example:
|
|
80
|
+
````
|
|
81
|
+
cli-test-cfg
|
|
82
|
+
timeout=10s
|
|
83
|
+
seq=1
|
|
84
|
+
reuse=0
|
|
85
|
+
````
|
|
86
|
+
|
|
87
|
+
## Exact behavior
|
|
88
|
+
|
|
89
|
+
The following rules make the tool behavior precise and implementation-ready.
|
|
90
|
+
|
|
91
|
+
### Marker syntax
|
|
92
|
+
|
|
93
|
+
A source file is scanned for examples defined by markers:
|
|
94
|
+
|
|
95
|
+
- `cli-test-cmd`: starts a command block. The block continues until the next marker or end of file.
|
|
96
|
+
- `cli-test-cfg`: optional; configures the current example. It contains one override per line.
|
|
97
|
+
- `cli-test-out`: expected output on `stdout`.
|
|
98
|
+
- `cli-test-err`: optional; expected output on `stderr`.
|
|
99
|
+
- `cli-test-ret`: optional; expected return code (an integer). When absent, the return code must be 0.
|
|
100
|
+
- `cli-test-end`: closes the current example.
|
|
101
|
+
|
|
102
|
+
The scanner is line-based. A marker is recognized only when its exact text is found in the current section with the configured prefix, and it is case-sensitive.
|
|
103
|
+
|
|
104
|
+
### Config syntax
|
|
105
|
+
|
|
106
|
+
`cli-test-cfg` supports one setting per line using the format `name=value`.
|
|
107
|
+
Unknown keys are invalid and should stop parsing with an error.
|
|
108
|
+
Duplicate keys in the same block are invalid.
|
|
109
|
+
|
|
110
|
+
Supported keys include:
|
|
111
|
+
|
|
112
|
+
- `timeout`: duration string such as `10s`, `2m`, `500ms`
|
|
113
|
+
- `run-dir`: path to the working directory for the example
|
|
114
|
+
- `path`: list of directories to search for executables
|
|
115
|
+
- `env`: list of `NAME=value` pairs
|
|
116
|
+
- `setup`: script or command executed before the example
|
|
117
|
+
- `cleanup`: script or command executed after the example
|
|
118
|
+
- `seq`: `0` or `1`
|
|
119
|
+
- `reuse`: `0` or `1`
|
|
120
|
+
- `hexdump`: `0` or `1`
|
|
121
|
+
- `cmp`: Python script path containing a `compare(expected, actual)` function
|
|
122
|
+
|
|
123
|
+
Per-example values override the global defaults for that specific example only.
|
|
124
|
+
|
|
125
|
+
### Command execution
|
|
126
|
+
|
|
127
|
+
The command in a `cli-test-cmd` block is parsed into an argument list and executed with `shell=False`.
|
|
128
|
+
The command string is tokenized using the platform's standard shell-splitting rules:
|
|
129
|
+
|
|
130
|
+
- on POSIX systems, use `shlex.split(command, posix=True)`
|
|
131
|
+
- on Windows, use the equivalent Windows-aware splitting rules
|
|
132
|
+
|
|
133
|
+
The resulting argument vector is passed to `subprocess.run` without invoking a shell, so shell features such as pipes, redirections, `&&`, and `||` are not interpreted by `cli-test` itself.
|
|
134
|
+
|
|
135
|
+
The program is run in the example's working directory, inherits the environment unless overridden, and is killed after the configured timeout expires.
|
|
136
|
+
|
|
137
|
+
The return code is checked after execution: it must be 0 unless a `cli-test-ret` marker says otherwise.
|
|
138
|
+
|
|
139
|
+
A timeout is treated as a fatal error and counted separately from normal mismatches.
|
|
140
|
+
|
|
141
|
+
### Global setup and cleanup
|
|
142
|
+
|
|
143
|
+
The global hooks are executed once per file, not once per example:
|
|
144
|
+
|
|
145
|
+
- `global-setup`: runs before the first example in the file
|
|
146
|
+
- `global-cleanup`: runs after the last example in the file
|
|
147
|
+
|
|
148
|
+
The per-example hooks keep their usual meaning:
|
|
149
|
+
|
|
150
|
+
- `setup`: runs before each example
|
|
151
|
+
- `cleanup`: runs after each example
|
|
152
|
+
|
|
153
|
+
### Output blocks
|
|
154
|
+
|
|
155
|
+
`cli-test-out` and `cli-test-err` accept either:
|
|
156
|
+
|
|
157
|
+
- inline text, or
|
|
158
|
+
- a path to a file containing the expected output.
|
|
159
|
+
|
|
160
|
+
When inline text is used, indentation rules applies, see [indentation.md](indentation.md)
|
|
161
|
+
|
|
162
|
+
When a file path is used, it is resolved relative to the source file containing the example. The file content is read as bytes and used as the expected output.
|
|
163
|
+
|
|
164
|
+
When `hexdump=1`, the expected output is interpreted as a hex dump rather than literal text. The hex dump is converted to the equivalent bytes before comparison.
|
|
165
|
+
|
|
166
|
+
### Comparison semantics
|
|
167
|
+
|
|
168
|
+
By default, comparison is byte-for-byte and exact.
|
|
169
|
+
|
|
170
|
+
If a custom comparison function is supplied via `cmp`, it must be named `compare` and accept exactly two positional arguments: `expected` and `actual`. Both values are bytes. The function must return a boolean value indicating whether the outputs match.
|
|
171
|
+
|
|
172
|
+
### Failure reporting
|
|
173
|
+
|
|
174
|
+
After executing all examples of a file, `cli-test` reports:
|
|
175
|
+
|
|
176
|
+
- the absolute path of the file
|
|
177
|
+
- how many examples were found
|
|
178
|
+
- how many passed
|
|
179
|
+
- how many timed out
|
|
180
|
+
- how many failed
|
|
181
|
+
- for each failure, a detailed diagnostic including:
|
|
182
|
+
- the example index and file location (line number and column of the first mismatch byte position)
|
|
183
|
+
- whether the mismatch was on `stdout` or `stderr`, a return code mismatch, or a timeout
|
|
184
|
+
- the first mismatching byte position and both expected/actual byte values
|
|
185
|
+
- the full actual output
|
|
186
|
+
|
|
187
|
+
The first differing byte is reported. If one output is shorter than the other, the mismatch is reported at the first missing byte.
|
|
188
|
+
|
|
189
|
+
### Temporary directories and reuse
|
|
190
|
+
|
|
191
|
+
By default, each example runs in a separate temporary directory. The example is independent from others. If `reuse=1`, all examples in the same file share the same working directory and environment state.
|
|
192
|
+
|
|
193
|
+
If `seq=1`, examples run sequentially. If `seq=0`, they may run concurrently.
|
|
194
|
+
|
|
195
|
+
## Quick start
|
|
196
|
+
|
|
197
|
+
A minimal demo file is available at [examples/demo.txt](examples/demo.txt).
|
|
198
|
+
Examples embedded in documentation are shown in the Markdown variant
|
|
199
|
+
([examples/demo.md](examples/demo.md), with markers both visible in fenced
|
|
200
|
+
blocks and hidden in HTML comments) and in the AsciiDoc variant
|
|
201
|
+
([examples/demo.adoc](examples/demo.adoc), with markers hidden in `//`
|
|
202
|
+
line comments).
|
|
203
|
+
|
|
204
|
+
Run it directly with:
|
|
205
|
+
|
|
206
|
+
```bash
|
|
207
|
+
pipenv run python -m cli_test examples/demo.txt
|
|
208
|
+
```
|
|
209
|
+
|
|
210
|
+
This parses the file, executes the command, compares the output against the expected result, and prints a pass/fail summary.
|
|
211
|
+
|
|
212
|
+
## Markdown and AsciiDoc transcripts
|
|
213
|
+
|
|
214
|
+
In `.md` and `.adoc`/`.asciidoc` files, a comment line anchors the next code
|
|
215
|
+
or listing block as a checked transcript: lines starting with `$ ` are
|
|
216
|
+
commands, and the lines after each command are its expected output. No
|
|
217
|
+
`cli-test-` markers are needed, and the block renders as a normal console
|
|
218
|
+
transcript:
|
|
219
|
+
|
|
220
|
+
````markdown
|
|
221
|
+
<!-- cli-test -->
|
|
222
|
+
```console
|
|
223
|
+
$ mytool --version
|
|
224
|
+
mytool 1.2.3
|
|
225
|
+
```
|
|
226
|
+
````
|
|
227
|
+
|
|
228
|
+
````asciidoc
|
|
229
|
+
// cli-test
|
|
230
|
+
[source,console]
|
|
231
|
+
----
|
|
232
|
+
$ mytool --version
|
|
233
|
+
mytool 1.2.3
|
|
234
|
+
----
|
|
235
|
+
````
|
|
236
|
+
|
|
237
|
+
Options are attached to the anchor comment as `key=value` pairs; `ret` sets
|
|
238
|
+
the expected return code (default 0), any other key is a `cli-test-cfg`
|
|
239
|
+
override (`timeout=10s`, `seq=1`, ...):
|
|
240
|
+
|
|
241
|
+
````markdown
|
|
242
|
+
<!-- cli-test ret=2 timeout=10s -->
|
|
243
|
+
````
|
|
244
|
+
|
|
245
|
+
Comparison ignores trailing newlines, since blocks cannot express them;
|
|
246
|
+
blank lines inside the expected output are preserved. Provide a custom
|
|
247
|
+
`cmp=...` option for full control. See
|
|
248
|
+
[examples/demo.md](examples/demo.md) and [examples/demo.adoc](examples/demo.adoc).
|
|
249
|
+
|
|
250
|
+
Expected output that itself starts with `$ ` would be mistaken for a new
|
|
251
|
+
command. The anchor options `out=N` and `err=N` handle this: from the line
|
|
252
|
+
N lines below the anchor (counting every line between the anchor and the
|
|
253
|
+
block) to the end of the block, every line is expected stdout (resp.
|
|
254
|
+
stderr) of the last command, including lines starting with `$ `:
|
|
255
|
+
|
|
256
|
+
````markdown
|
|
257
|
+
<!-- cli-test out=3 -->
|
|
258
|
+
```console
|
|
259
|
+
$ mytool gen
|
|
260
|
+
$ this line is output, not a command
|
|
261
|
+
```
|
|
262
|
+
````
|
|
263
|
+
|
|
264
|
+
## Sphinx integration
|
|
265
|
+
|
|
266
|
+
The `cli-test` Sphinx extension (`cli_test.sphinxext`) lets you document a
|
|
267
|
+
command once: a directive renders a clean console block in the documentation
|
|
268
|
+
(no `cli-test-` markers are visible) and registers the example so it is
|
|
269
|
+
executed when the docs are built.
|
|
270
|
+
|
|
271
|
+
Enable it in `docs/conf.py`:
|
|
272
|
+
|
|
273
|
+
````python
|
|
274
|
+
extensions = ["cli_test.sphinxext"]
|
|
275
|
+
````
|
|
276
|
+
|
|
277
|
+
Then write examples like this:
|
|
278
|
+
|
|
279
|
+
````rst
|
|
280
|
+
.. cli-test:: python -c "print(2 + 2)"
|
|
281
|
+
|
|
282
|
+
4
|
|
283
|
+
````
|
|
284
|
+
|
|
285
|
+
Options:
|
|
286
|
+
|
|
287
|
+
- `stderr`: expected output on `stderr` (tested but not rendered)
|
|
288
|
+
- `ret`: expected return code (default 0)
|
|
289
|
+
- `cfg`: per-example overrides, one `key=value` per line, continuation lines indented
|
|
290
|
+
- `hide-output`: render only the command line
|
|
291
|
+
|
|
292
|
+
The examples are checked on every build, including a plain `make html`:
|
|
293
|
+
failures are reported as build errors and the build exits non-zero.
|
|
294
|
+
Set `cli_test_check_on_build = False` in `conf.py` to check them only with
|
|
295
|
+
the dedicated `cli-test` builder:
|
|
296
|
+
|
|
297
|
+
````
|
|
298
|
+
sphinx-build -b cli-test docs docs/_build/clitest
|
|
299
|
+
````
|
|
300
|
+
|
|
301
|
+
(Note: this differs from `sphinx.ext.doctest`, whose doctests only run with
|
|
302
|
+
`-b doctest`.) Examples run with the Sphinx project directory as working
|
|
303
|
+
directory (a relative `run-dir` in `cfg` is resolved against it). Comparison
|
|
304
|
+
is byte-for-byte like the CLI, except that trailing newlines are ignored on
|
|
305
|
+
both sides, since directive content cannot express them.
|
|
306
|
+
|
|
307
|
+
See [docs/index.rst](docs/index.rst) for a working example page which is
|
|
308
|
+
itself tested by the suite.
|
|
309
|
+
|
|
310
|
+
## Versioning
|
|
311
|
+
|
|
312
|
+
The package version is derived from git tags (via
|
|
313
|
+
[hatch-vcs](https://github.com/ofek/hatch-vcs)). To release a version, commit
|
|
314
|
+
your changes, tag the commit, and push the tag:
|
|
315
|
+
|
|
316
|
+
````
|
|
317
|
+
git tag v0.1.0
|
|
318
|
+
git push origin v0.1.0
|
|
319
|
+
````
|
|
320
|
+
|
|
321
|
+
Pushing a `v*` tag triggers the GitHub Actions workflow
|
|
322
|
+
[.github/workflows/workflow.yml](.github/workflows/workflow.yml), which runs
|
|
323
|
+
the test suite, builds the sdist and wheel, and publishes them to PyPI
|
|
324
|
+
(project `doc-cli-test`) via Trusted Publishing — no API token is stored in
|
|
325
|
+
the repository.
|
|
326
|
+
|
|
327
|
+
Builds from a tagged, clean checkout use the tag as the version; builds from
|
|
328
|
+
untagged commits get a `dev` version instead.
|
|
329
|
+
|
|
330
|
+
## How to launch tests
|
|
331
|
+
````
|
|
332
|
+
PYTHONPATH=. pipenv run pytest
|
|
333
|
+
````
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
cli_test/__init__.py,sha256=MF_oXTwT5RBrRO74TZezd5YtupsjeohqQd9vFq8EqYI,360
|
|
2
|
+
cli_test/__main__.py,sha256=MHKZ_ae3fSLGTLUUMOx15fWdeOnJSHhq-zslRP5F5Lc,79
|
|
3
|
+
cli_test/_sphinx_compare.py,sha256=UC2lH9lXIqWqvrPSrA8oDYSKxtFNX2R94SfTyVG12VU,300
|
|
4
|
+
cli_test/_version.py,sha256=yBpRAzc1O-fFxRL6MELR93JAnRVchbETxkSjTfqgm_w,520
|
|
5
|
+
cli_test/cli.py,sha256=xRy8qC-BHGDx00zgLjol8GscRmBcmF52czILhoDhr3Y,9620
|
|
6
|
+
cli_test/compare.py,sha256=b_rtE6ncer1oCOqPc760OuD5tDYJfXX6uGAXx9CDq3Q,799
|
|
7
|
+
cli_test/config.py,sha256=jMvsZtvbsE59pdH9pDv4_IcBI_FGi1vINqsElpCr1Bs,3450
|
|
8
|
+
cli_test/parser.py,sha256=oglXHPuLJ8JPXwraK1IATsbUXSPVJmwfH8V1qlO-oPs,15257
|
|
9
|
+
cli_test/runner.py,sha256=gqUzbvDkZzqi4DaUQs1pMIZ3zyHKQMqvbCsIh6AZtIc,1587
|
|
10
|
+
cli_test/sphinxext.py,sha256=DwFy0bYhrwgcKnIa8N5DPVXHYyl-VsogxXe4FyPleGE,8789
|
|
11
|
+
doc_cli_test-0.2.3.dist-info/METADATA,sha256=sdOFshJKyaLl8UGhpslOVyuo7PgqChm8H0-6HNzzr6A,13190
|
|
12
|
+
doc_cli_test-0.2.3.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
|
|
13
|
+
doc_cli_test-0.2.3.dist-info/entry_points.txt,sha256=PabAiEZIrfpw8-FcwYN94RmCV25p1F_yr01aedioR2c,47
|
|
14
|
+
doc_cli_test-0.2.3.dist-info/licenses/LICENSE,sha256=xx0jnfkXJvxRnG63LTGOxlggYnIysveWIZ6H3PNdCrQ,11357
|
|
15
|
+
doc_cli_test-0.2.3.dist-info/RECORD,,
|