dinemic-cli 0.0.19__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.
- dinemic_cli/__init__.py +1 -0
- dinemic_cli/__main__.py +16 -0
- dinemic_cli/client.py +75 -0
- dinemic_cli/commands/__init__.py +0 -0
- dinemic_cli/commands/auth.py +31 -0
- dinemic_cli/commands/caa.py +11 -0
- dinemic_cli/commands/cert.py +29 -0
- dinemic_cli/commands/cert_peer.py +37 -0
- dinemic_cli/commands/dns_entry.py +57 -0
- dinemic_cli/commands/dns_value.py +43 -0
- dinemic_cli/commands/dns_zone.py +98 -0
- dinemic_cli/commands/endpoint.py +39 -0
- dinemic_cli/commands/healthcheck.py +40 -0
- dinemic_cli/commands/loadbalancer.py +39 -0
- dinemic_cli/commands/loadbalancer_backend.py +44 -0
- dinemic_cli/commands/loadbalancer_host.py +37 -0
- dinemic_cli/commands/loadbalancer_route.py +42 -0
- dinemic_cli/commands/network.py +34 -0
- dinemic_cli/commands/node.py +29 -0
- dinemic_cli/commands/peer.py +33 -0
- dinemic_cli/commands/peer_config.py +33 -0
- dinemic_cli/commands/project.py +58 -0
- dinemic_cli/commands/quota.py +22 -0
- dinemic_cli/main.py +68 -0
- dinemic_cli/output.py +25 -0
- dinemic_cli-0.0.19.dist-info/METADATA +13 -0
- dinemic_cli-0.0.19.dist-info/RECORD +63 -0
- dinemic_cli-0.0.19.dist-info/WHEEL +5 -0
- dinemic_cli-0.0.19.dist-info/entry_points.txt +2 -0
- dinemic_cli-0.0.19.dist-info/licenses/LICENSE +696 -0
- dinemic_cli-0.0.19.dist-info/top_level.txt +2 -0
- tests/01-cli-fixes.patch +418 -0
- tests/02-tests-after-fixes.patch +208 -0
- tests/api_samples.py +214 -0
- tests/cert_peer.py +37 -0
- tests/cli_runner.py +113 -0
- tests/command_matrix.py +612 -0
- tests/conftest.py +235 -0
- tests/dns_entry.py +41 -0
- tests/dns_value.py +43 -0
- tests/dns_zone.py +38 -0
- tests/endpoint.py +39 -0
- tests/healthcheck.py +40 -0
- tests/loadbalancer.py +36 -0
- tests/loadbalancer_backend.py +44 -0
- tests/loadbalancer_host.py +37 -0
- tests/loadbalancer_route.py +42 -0
- tests/network.py +34 -0
- tests/network_node.py +74 -0
- tests/node.py +23 -0
- tests/peer.py +33 -0
- tests/project.py +58 -0
- tests/support.py +246 -0
- tests/test_auth.py +114 -0
- tests/test_columns.py +58 -0
- tests/test_commands.py +98 -0
- tests/test_confirmations.py +71 -0
- tests/test_envvars.py +119 -0
- tests/test_error_handling.py +83 -0
- tests/test_lifecycle.py +188 -0
- tests/test_network_node.py +116 -0
- tests/test_option_contract.py +335 -0
- tests/test_smoke.py +83 -0
tests/network_node.py
ADDED
|
@@ -0,0 +1,74 @@
|
|
|
1
|
+
"""Komendy dla modelu NetworkNode.
|
|
2
|
+
|
|
3
|
+
SZKIC — ścieżki API (`/network-node/`) i nazwy pól są odtworzone z opisu modelu,
|
|
4
|
+
nie z serializera. Zweryfikuj je przed scaleniem:
|
|
5
|
+
|
|
6
|
+
curl -H "Authorization: Token $DINEMIC_API_TOKEN" $DINEMIC_API_URL/schema/ \
|
|
7
|
+
| grep -i network-node
|
|
8
|
+
|
|
9
|
+
NetworkNode to wpięcie węzła do sieci: jeden interfejs WireGuard na parę
|
|
10
|
+
(network, node), współdzielony przez wszystkie peery tej sieci na tym węźle.
|
|
11
|
+
Wcześniej każdy peer stawiał własny interfejs — stąd problemy sieciowe.
|
|
12
|
+
|
|
13
|
+
Rejestracja w ``main.py``::
|
|
14
|
+
|
|
15
|
+
from dinemic_cli.commands import network_node
|
|
16
|
+
app.add_typer(network_node.app, name="network-node")
|
|
17
|
+
|
|
18
|
+
Po scaleniu: dopisz "network_node" do COMMAND_MODULES w ``tests/support.py``,
|
|
19
|
+
dodaj wiersze do ``tests/command_matrix.py`` i zdejmij ``skip`` z testów
|
|
20
|
+
w ``tests/test_network_node.py``.
|
|
21
|
+
"""
|
|
22
|
+
|
|
23
|
+
import typer
|
|
24
|
+
|
|
25
|
+
from dinemic_cli.output import render
|
|
26
|
+
|
|
27
|
+
app = typer.Typer(no_args_is_help=True, help="Node attachments to networks (WireGuard interfaces)")
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
@app.command("list")
|
|
31
|
+
def list_network_nodes(
|
|
32
|
+
ctx: typer.Context,
|
|
33
|
+
network: str = typer.Option(None, "--network", "-n", help="Network ID", envvar="DINEMIC_NETWORK"),
|
|
34
|
+
node: str = typer.Option(None, "--node", "-N", help="Node ID"),
|
|
35
|
+
):
|
|
36
|
+
"""Show which nodes are attached to which networks."""
|
|
37
|
+
data = ctx.obj["client"].get("/network-node/", network=network, node=node)
|
|
38
|
+
render(
|
|
39
|
+
data,
|
|
40
|
+
ctx.obj["output"],
|
|
41
|
+
columns=["id", "network", "node", "ipv4_address", "wg_public_key", "wg_port", "state"],
|
|
42
|
+
)
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
@app.command("create")
|
|
46
|
+
def create_network_node(
|
|
47
|
+
ctx: typer.Context,
|
|
48
|
+
network: str = typer.Option(..., "--network", "-n", help="Network ID", envvar="DINEMIC_NETWORK"),
|
|
49
|
+
node: str = typer.Option(..., "--node", "-N", help="Node ID"),
|
|
50
|
+
):
|
|
51
|
+
"""Attach a node to a network.
|
|
52
|
+
|
|
53
|
+
Normally not needed: the attachment is created automatically with the first
|
|
54
|
+
peer of that network on that node. Use it to pre-allocate an address and key.
|
|
55
|
+
"""
|
|
56
|
+
data = ctx.obj["client"].post("/network-node/", {"network": network, "node": node})
|
|
57
|
+
typer.secho(f"Attached node {node} to network {network} ({data['id']})", fg="green")
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
@app.command("delete")
|
|
61
|
+
def delete_network_node(
|
|
62
|
+
ctx: typer.Context,
|
|
63
|
+
network_node_id: str = typer.Option(..., "--network-node", "-a", help="Network node (attachment) ID"),
|
|
64
|
+
yes: bool = typer.Option(False, "--yes", "-y", help="Don't ask for confirmation"),
|
|
65
|
+
):
|
|
66
|
+
"""Detach a node from a network and tear down its WireGuard interface."""
|
|
67
|
+
if not yes:
|
|
68
|
+
typer.confirm(
|
|
69
|
+
f"Remove attachment {network_node_id}? Every peer of this network on that "
|
|
70
|
+
f"node will lose connectivity",
|
|
71
|
+
abort=True,
|
|
72
|
+
)
|
|
73
|
+
ctx.obj["client"].delete(f"/network-node/{network_node_id}/")
|
|
74
|
+
typer.secho("Removed.", fg="green")
|
tests/node.py
ADDED
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
import typer
|
|
2
|
+
|
|
3
|
+
from dinemic_cli.output import render
|
|
4
|
+
|
|
5
|
+
app = typer.Typer(no_args_is_help=True)
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
@app.command("list")
|
|
9
|
+
def list_nodes(
|
|
10
|
+
ctx: typer.Context,
|
|
11
|
+
project: str = typer.Option(None, "--project", "-p", help="Project ID", envvar="DINEMIC_PROJECT")):
|
|
12
|
+
data = ctx.obj["client"].get("/node/", project=project)
|
|
13
|
+
render(data, ctx.obj["output"], columns=["id", "project", "public_key", "project", "description", "created", "sync_time", "state", "ipv4_address", "ipv6_address", "continent_code", "country_code", "city_name"])
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
@app.command("delete")
|
|
17
|
+
def delete_node(ctx: typer.Context,
|
|
18
|
+
node_id: str = typer.Option(..., "--node", "-n", help="Node ID"),
|
|
19
|
+
yes: bool = typer.Option(False, "--yes", "-y", help="Don't ask for confirmation"),):
|
|
20
|
+
if not yes:
|
|
21
|
+
typer.confirm(f"Remove node {node_id} and all peers assigned to it?", abort=True)
|
|
22
|
+
ctx.obj["client"].delete(f"/node/{node_id}/")
|
|
23
|
+
typer.secho("Removed.", fg="green")
|
tests/peer.py
ADDED
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
import typer
|
|
2
|
+
|
|
3
|
+
from dinemic_cli.output import render
|
|
4
|
+
|
|
5
|
+
app = typer.Typer(no_args_is_help=True)
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
@app.command("list")
|
|
9
|
+
def list_peers(ctx: typer.Context,
|
|
10
|
+
project: str = typer.Option(None, "--project", "-p", help="Project ID", envvar="DINEMIC_PROJECT")):
|
|
11
|
+
data = ctx.obj["client"].get("/peer/", project=project)
|
|
12
|
+
render(data, ctx.obj["output"], columns=["id", "node", "network", "network_node", "ipv4_address", "service_port", "role"])
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
@app.command("create")
|
|
16
|
+
def create_peer(
|
|
17
|
+
ctx: typer.Context,
|
|
18
|
+
node: str = typer.Option(..., "--node", "-N", help="Node ID"),
|
|
19
|
+
network: str = typer.Option(..., "--network", "-n", help="Network ID", envvar="DINEMIC_NETWORK"),
|
|
20
|
+
config: str = typer.Option(..., "--config", "-c", help="Config ID (endpoint, load balancer or dns zone)"),
|
|
21
|
+
):
|
|
22
|
+
data = ctx.obj["client"].post("/peer/", {"network": network, "node": node, "config": config})
|
|
23
|
+
typer.secho(f"Created peer {data['id']}", fg="green")
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
@app.command("delete")
|
|
27
|
+
def delete_peer(ctx: typer.Context,
|
|
28
|
+
peer_id: str = typer.Option(..., "--peer", "-p", help="Peer ID"),
|
|
29
|
+
yes: bool = typer.Option(False, "--yes", "-y", help="Don't ask for confirmation"),):
|
|
30
|
+
if not yes:
|
|
31
|
+
typer.confirm(f"Remove peer {peer_id}", abort=True)
|
|
32
|
+
ctx.obj["client"].delete(f"/peer/{peer_id}/")
|
|
33
|
+
typer.secho("Removed.", fg="green")
|
tests/project.py
ADDED
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
import typer
|
|
2
|
+
|
|
3
|
+
from dinemic_cli.output import render
|
|
4
|
+
|
|
5
|
+
app = typer.Typer(no_args_is_help=True)
|
|
6
|
+
|
|
7
|
+
member_app = typer.Typer(no_args_is_help=True, help="Members of project")
|
|
8
|
+
app.add_typer(member_app, name="member")
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
@app.command("list")
|
|
12
|
+
def list_projects(ctx: typer.Context):
|
|
13
|
+
data = ctx.obj["client"].get("/project/")
|
|
14
|
+
render(data, ctx.obj["output"], columns=["id", "name", "public_key", "auto_accept_nodes"])
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
@app.command("create")
|
|
18
|
+
def create_project(ctx: typer.Context,
|
|
19
|
+
name: str = typer.Option(..., "--name", "-n", help="Project name")):
|
|
20
|
+
data = ctx.obj["client"].post("/project/", {"name": name})
|
|
21
|
+
typer.secho(f"Created project {data['name']} ({data['id']})", fg="green")
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
@app.command("delete")
|
|
25
|
+
def delete_project(ctx: typer.Context,
|
|
26
|
+
project_id: str = typer.Option(..., "--project", "-p", help="Project ID"),
|
|
27
|
+
yes: bool = typer.Option(False, "--yes", "-y", help="Don't ask for confirmation"),):
|
|
28
|
+
if not yes:
|
|
29
|
+
typer.confirm(f"Remove project {project_id} and all its resources?", abort=True)
|
|
30
|
+
ctx.obj["client"].delete(f"/project/{project_id}/")
|
|
31
|
+
typer.secho("Removed.", fg="green")
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
@app.command("configure")
|
|
35
|
+
def configure_node(ctx: typer.Context,
|
|
36
|
+
project_id: str = typer.Option(..., "--project", "-p", help="Project ID", envvar="DINEMIC_PROJECT"),
|
|
37
|
+
log_level: str = typer.Option("info", "--log-level", "-L", help="Agent log level (error, warn, info, debug, trace)"),
|
|
38
|
+
debug: bool = typer.Option(False, "--debug", "-D", help="Enable agent debug mode"),
|
|
39
|
+
):
|
|
40
|
+
"""Print the command that registers an agent in this project."""
|
|
41
|
+
data = ctx.obj["client"].get(f"/project/{project_id}/")
|
|
42
|
+
env = [f"RUST_LOG={log_level}"]
|
|
43
|
+
if debug:
|
|
44
|
+
env.append("RUST_DEBUG=True")
|
|
45
|
+
typer.secho(
|
|
46
|
+
f"sudo {' '.join(env)} ./dinemic-agent -p '{data['public_key']}'",
|
|
47
|
+
fg="green",
|
|
48
|
+
)
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
###########
|
|
52
|
+
# Members #
|
|
53
|
+
###########
|
|
54
|
+
|
|
55
|
+
# @member_app.command("list")
|
|
56
|
+
# def list_members(ctx: typer.Context, project_id: str = typer.Argument()):
|
|
57
|
+
# data = ctx.obj["client"].get(f"/project/{project_id}/members/")
|
|
58
|
+
# render(data, ctx.obj["output"], columns=["project_id", "record", "type", "ttl"])
|
tests/support.py
ADDED
|
@@ -0,0 +1,246 @@
|
|
|
1
|
+
"""Shared test infrastructure (helpers only — fixtures live in conftest.py).
|
|
2
|
+
|
|
3
|
+
Unit tests never touch the network. Every command receives a stubbed
|
|
4
|
+
``FakeClient`` in ``ctx.obj``, exactly the way ``@app.callback()`` injects the
|
|
5
|
+
real one in ``main.py``. That lets us test what these modules actually contain:
|
|
6
|
+
the URL path, the HTTP method, the payload shape and the column list — without
|
|
7
|
+
depending on ``client.py``.
|
|
8
|
+
"""
|
|
9
|
+
|
|
10
|
+
from __future__ import annotations
|
|
11
|
+
|
|
12
|
+
import functools
|
|
13
|
+
import importlib
|
|
14
|
+
from dataclasses import dataclass, field
|
|
15
|
+
from typing import Any
|
|
16
|
+
|
|
17
|
+
import typer
|
|
18
|
+
from typer.testing import CliRunner
|
|
19
|
+
|
|
20
|
+
# ---------------------------------------------------------------------------
|
|
21
|
+
# Loading command modules
|
|
22
|
+
# ---------------------------------------------------------------------------
|
|
23
|
+
|
|
24
|
+
#: Every command module. Add a new file under ``commands/`` -> list it here,
|
|
25
|
+
#: otherwise the contract tests (test_option_contract.py) will not see it.
|
|
26
|
+
COMMAND_MODULES = [
|
|
27
|
+
"auth",
|
|
28
|
+
"caa",
|
|
29
|
+
"cert",
|
|
30
|
+
"cert_peer",
|
|
31
|
+
"dns_entry",
|
|
32
|
+
"dns_value",
|
|
33
|
+
"dns_zone",
|
|
34
|
+
"endpoint",
|
|
35
|
+
"healthcheck",
|
|
36
|
+
"loadbalancer",
|
|
37
|
+
"loadbalancer_backend",
|
|
38
|
+
"loadbalancer_host",
|
|
39
|
+
"loadbalancer_route",
|
|
40
|
+
"network",
|
|
41
|
+
"node",
|
|
42
|
+
"peer",
|
|
43
|
+
"project",
|
|
44
|
+
]
|
|
45
|
+
|
|
46
|
+
_IMPORT_PREFIXES = ("dinemic_cli.commands.", "dinemic_cli.")
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
@functools.lru_cache(maxsize=None)
|
|
50
|
+
def load_command_module(name: str):
|
|
51
|
+
"""Import a command module regardless of whether it sits in ``commands/``."""
|
|
52
|
+
last_error: Exception | None = None
|
|
53
|
+
for prefix in _IMPORT_PREFIXES:
|
|
54
|
+
try:
|
|
55
|
+
return importlib.import_module(prefix + name)
|
|
56
|
+
except ImportError as exc: # pragma: no cover - depends on repo layout
|
|
57
|
+
last_error = exc
|
|
58
|
+
raise ImportError(
|
|
59
|
+
f"Cannot import command module {name!r}. "
|
|
60
|
+
f"Tried prefixes: {_IMPORT_PREFIXES}. Last error: {last_error}"
|
|
61
|
+
)
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
def typer_app_for(name: str) -> typer.Typer:
|
|
65
|
+
"""The module's Typer app — the object ``main.py`` mounts with add_typer."""
|
|
66
|
+
return load_command_module(name).app
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
def mount(module_name: str, obj: dict) -> typer.Typer:
|
|
70
|
+
"""Mount a sub-app under a root app, the same way ``main.py`` does.
|
|
71
|
+
|
|
72
|
+
Mounting (rather than invoking ``module.app`` directly) matters: Typer
|
|
73
|
+
collapses an app that has a SINGLE command and no callback down to that one
|
|
74
|
+
command. Invoked standalone, ``caa.app`` therefore has no ``list``
|
|
75
|
+
subcommand. Mounted under a root, it does. We test what the user sees.
|
|
76
|
+
"""
|
|
77
|
+
root = typer.Typer(no_args_is_help=True)
|
|
78
|
+
|
|
79
|
+
@root.callback()
|
|
80
|
+
def _callback(ctx: typer.Context) -> None: # mirrors @app.callback() in main.py
|
|
81
|
+
ctx.obj = obj
|
|
82
|
+
|
|
83
|
+
root.add_typer(typer_app_for(module_name), name=module_name)
|
|
84
|
+
return root
|
|
85
|
+
|
|
86
|
+
|
|
87
|
+
def module_source(name: str) -> str:
|
|
88
|
+
module = load_command_module(name)
|
|
89
|
+
with open(module.__file__, encoding="utf-8") as handle:
|
|
90
|
+
return handle.read()
|
|
91
|
+
|
|
92
|
+
|
|
93
|
+
# ---------------------------------------------------------------------------
|
|
94
|
+
# Fake client
|
|
95
|
+
# ---------------------------------------------------------------------------
|
|
96
|
+
|
|
97
|
+
|
|
98
|
+
@dataclass
|
|
99
|
+
class Call:
|
|
100
|
+
"""A single API call recorded by FakeClient."""
|
|
101
|
+
|
|
102
|
+
method: str
|
|
103
|
+
path: str
|
|
104
|
+
payload: dict[str, Any] | None = None
|
|
105
|
+
params: dict[str, Any] = field(default_factory=dict)
|
|
106
|
+
|
|
107
|
+
def __repr__(self) -> str: # nicer assertion output
|
|
108
|
+
return f"<{self.method} {self.path} payload={self.payload} params={self.params}>"
|
|
109
|
+
|
|
110
|
+
|
|
111
|
+
class ApiError(RuntimeError):
|
|
112
|
+
"""Stands in for the error ``client.py`` maps from a DRF response."""
|
|
113
|
+
|
|
114
|
+
def __init__(self, status_code: int, detail: Any = None):
|
|
115
|
+
super().__init__(f"HTTP {status_code}: {detail}")
|
|
116
|
+
self.status_code = status_code
|
|
117
|
+
self.detail = detail
|
|
118
|
+
|
|
119
|
+
|
|
120
|
+
class FakeClient:
|
|
121
|
+
"""Stub for ``dinemic_cli.client.Client``.
|
|
122
|
+
|
|
123
|
+
Records calls and answers with data from ``api_samples.py``. A specific
|
|
124
|
+
response can be forced with ``set_response`` and an error with ``set_error``.
|
|
125
|
+
"""
|
|
126
|
+
|
|
127
|
+
def __init__(self) -> None:
|
|
128
|
+
self.calls: list[Call] = []
|
|
129
|
+
self._responses: dict[tuple[str, str], Any] = {}
|
|
130
|
+
self._errors: dict[tuple[str, str], Exception] = {}
|
|
131
|
+
|
|
132
|
+
# -- setup -------------------------------------------------------------
|
|
133
|
+
def set_response(self, method: str, path: str, value: Any) -> None:
|
|
134
|
+
self._responses[(method.upper(), path)] = value
|
|
135
|
+
|
|
136
|
+
def set_error(self, method: str, path: str, error: Exception) -> None:
|
|
137
|
+
self._errors[(method.upper(), path)] = error
|
|
138
|
+
|
|
139
|
+
# -- interface used by the commands ------------------------------------
|
|
140
|
+
def get(self, path: str, **params: Any) -> Any:
|
|
141
|
+
# commands call get("/zone/", project=None); whether None ends up in the
|
|
142
|
+
# query string is client.py's decision, here we only record it
|
|
143
|
+
self._record("GET", path, None, params)
|
|
144
|
+
self._maybe_raise("GET", path)
|
|
145
|
+
if ("GET", path) in self._responses:
|
|
146
|
+
return self._responses[("GET", path)]
|
|
147
|
+
from api_samples import sample_for # local import: see conftest rootdir
|
|
148
|
+
|
|
149
|
+
return sample_for(path)
|
|
150
|
+
|
|
151
|
+
def post(self, path: str, payload: dict[str, Any]) -> Any:
|
|
152
|
+
self._record("POST", path, payload, {})
|
|
153
|
+
self._maybe_raise("POST", path)
|
|
154
|
+
if ("POST", path) in self._responses:
|
|
155
|
+
return self._responses[("POST", path)]
|
|
156
|
+
# the backend answers with the read serializer: id plus what we sent
|
|
157
|
+
return {"id": "new-id", **payload}
|
|
158
|
+
|
|
159
|
+
def post_login(self, path: str, payload: dict[str, Any]) -> Any:
|
|
160
|
+
self._record("POST_LOGIN", path, payload, {})
|
|
161
|
+
self._maybe_raise("POST_LOGIN", path)
|
|
162
|
+
if ("POST_LOGIN", path) in self._responses:
|
|
163
|
+
return self._responses[("POST_LOGIN", path)]
|
|
164
|
+
return {"token": "tok-from-api"}
|
|
165
|
+
|
|
166
|
+
def delete(self, path: str) -> Any:
|
|
167
|
+
self._record("DELETE", path, None, {})
|
|
168
|
+
self._maybe_raise("DELETE", path)
|
|
169
|
+
return None
|
|
170
|
+
|
|
171
|
+
# -- assertion helpers -------------------------------------------------
|
|
172
|
+
def _record(self, method: str, path: str, payload, params) -> None:
|
|
173
|
+
self.calls.append(Call(method, path, payload, {k: v for k, v in params.items()}))
|
|
174
|
+
|
|
175
|
+
def _maybe_raise(self, method: str, path: str) -> None:
|
|
176
|
+
error = self._errors.get((method, path))
|
|
177
|
+
if error is not None:
|
|
178
|
+
raise error
|
|
179
|
+
|
|
180
|
+
@property
|
|
181
|
+
def last(self) -> Call:
|
|
182
|
+
assert self.calls, "The command made no API call at all"
|
|
183
|
+
return self.calls[-1]
|
|
184
|
+
|
|
185
|
+
def calls_of(self, method: str) -> list[Call]:
|
|
186
|
+
return [c for c in self.calls if c.method == method.upper()]
|
|
187
|
+
|
|
188
|
+
|
|
189
|
+
# ---------------------------------------------------------------------------
|
|
190
|
+
# Render recorder
|
|
191
|
+
# ---------------------------------------------------------------------------
|
|
192
|
+
|
|
193
|
+
|
|
194
|
+
@dataclass
|
|
195
|
+
class RenderCall:
|
|
196
|
+
data: Any
|
|
197
|
+
output: str
|
|
198
|
+
columns: list[str]
|
|
199
|
+
|
|
200
|
+
|
|
201
|
+
class RenderRecorder:
|
|
202
|
+
"""Replaces ``render`` in a command module but calls the original.
|
|
203
|
+
|
|
204
|
+
We get to see which columns the command renders with, while the real
|
|
205
|
+
``output.render`` still runs against realistic data — so it blows up if it
|
|
206
|
+
cannot cope with, say, a missing key.
|
|
207
|
+
"""
|
|
208
|
+
|
|
209
|
+
def __init__(self, original) -> None:
|
|
210
|
+
self._original = original
|
|
211
|
+
self.calls: list[RenderCall] = []
|
|
212
|
+
|
|
213
|
+
def __call__(self, data, output, columns=None, **kwargs):
|
|
214
|
+
self.calls.append(RenderCall(data=data, output=output, columns=list(columns or [])))
|
|
215
|
+
# positional: we do not assume what the third parameter of the real
|
|
216
|
+
# output.render is called
|
|
217
|
+
return self._original(data, output, columns, **kwargs)
|
|
218
|
+
|
|
219
|
+
@property
|
|
220
|
+
def last(self) -> RenderCall:
|
|
221
|
+
assert self.calls, "The command rendered nothing"
|
|
222
|
+
return self.calls[-1]
|
|
223
|
+
|
|
224
|
+
@property
|
|
225
|
+
def columns(self) -> list[str]:
|
|
226
|
+
return self.last.columns
|
|
227
|
+
|
|
228
|
+
|
|
229
|
+
def all_output(result) -> str:
|
|
230
|
+
"""stdout + stderr — click 8.2+ splits the streams and usage errors go to stderr."""
|
|
231
|
+
out = result.stdout or ""
|
|
232
|
+
try:
|
|
233
|
+
err = result.stderr or ""
|
|
234
|
+
except ValueError: # stderr was not captured
|
|
235
|
+
err = ""
|
|
236
|
+
return out + err
|
|
237
|
+
|
|
238
|
+
|
|
239
|
+
def assert_ok(result) -> None:
|
|
240
|
+
"""Readable assertion on a CliRunner result (surfaces the command's traceback)."""
|
|
241
|
+
if result.exit_code != 0:
|
|
242
|
+
raise AssertionError(
|
|
243
|
+
f"Command exited with code {result.exit_code}\n"
|
|
244
|
+
f"--- output ---\n{all_output(result)}\n"
|
|
245
|
+
f"--- exception ---\n{result.exception!r}"
|
|
246
|
+
)
|
tests/test_auth.py
ADDED
|
@@ -0,0 +1,114 @@
|
|
|
1
|
+
"""The ``auth`` commands — the only ones that touch the keyring.
|
|
2
|
+
|
|
3
|
+
A token must never end up in the repo or in CI logs, so these tests also watch
|
|
4
|
+
what the commands print to stdout.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
import pytest
|
|
10
|
+
from support import assert_ok, load_command_module
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
@pytest.fixture
|
|
14
|
+
def keyring_stub(monkeypatch):
|
|
15
|
+
"""Patch set_token/get_token in the auth module's namespace.
|
|
16
|
+
|
|
17
|
+
The module does ``from dinemic_cli.client import set_token``, so the patch has
|
|
18
|
+
to land on ``auth.set_token``, not on ``client.set_token``.
|
|
19
|
+
"""
|
|
20
|
+
module = load_command_module("auth")
|
|
21
|
+
stored: dict[str, str | None] = {"token": None}
|
|
22
|
+
|
|
23
|
+
def fake_set_token(token):
|
|
24
|
+
stored["token"] = token
|
|
25
|
+
|
|
26
|
+
def fake_get_token():
|
|
27
|
+
return stored["token"]
|
|
28
|
+
|
|
29
|
+
monkeypatch.setattr(module, "set_token", fake_set_token, raising=True)
|
|
30
|
+
monkeypatch.setattr(module, "get_token", fake_get_token, raising=True)
|
|
31
|
+
return stored
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
def test_login_posts_credentials_and_stores_token(invoke, client, keyring_stub):
|
|
35
|
+
client.set_response("POST_LOGIN", "/auth/token/", {"token": "tok-abc123"})
|
|
36
|
+
|
|
37
|
+
result, _ = invoke("auth", ["login", "--username", "ola", "--password", "s3cret"])
|
|
38
|
+
|
|
39
|
+
assert_ok(result)
|
|
40
|
+
call = client.last
|
|
41
|
+
assert call.path == "/auth/token/"
|
|
42
|
+
assert call.payload == {"username": "ola", "password": "s3cret"}
|
|
43
|
+
assert keyring_stub["token"] == "tok-abc123"
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
def test_login_uses_unauthenticated_channel(invoke, client, keyring_stub):
|
|
47
|
+
"""Login goes through ``post_login`` (a separate ``_http_unauth``, see 7.5).
|
|
48
|
+
|
|
49
|
+
Sending a stale, invalid token while logging in ends in a 401 and a very
|
|
50
|
+
confusing error message.
|
|
51
|
+
"""
|
|
52
|
+
result, _ = invoke("auth", ["login", "--username", "ola", "--password", "s3cret"])
|
|
53
|
+
|
|
54
|
+
assert_ok(result)
|
|
55
|
+
assert client.last.method == "POST_LOGIN"
|
|
56
|
+
assert client.calls_of("POST") == []
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
def test_login_does_not_echo_password(invoke, client, keyring_stub):
|
|
60
|
+
result, _ = invoke("auth", ["login", "--username", "ola", "--password", "s3cret"])
|
|
61
|
+
|
|
62
|
+
assert_ok(result)
|
|
63
|
+
assert "s3cret" not in result.stdout
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
def test_login_does_not_print_the_token(invoke, client, keyring_stub):
|
|
67
|
+
"""A token on stdout is a token in the CI log."""
|
|
68
|
+
client.set_response("POST_LOGIN", "/auth/token/", {"token": "tok-abc123"})
|
|
69
|
+
|
|
70
|
+
result, _ = invoke("auth", ["login", "--username", "ola", "--password", "s3cret"])
|
|
71
|
+
|
|
72
|
+
assert_ok(result)
|
|
73
|
+
assert "tok-abc123" not in result.stdout
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
def test_login_prompts_when_options_missing(invoke, client, keyring_stub):
|
|
77
|
+
result, _ = invoke("auth", ["login"], input="ola\ns3cret\n")
|
|
78
|
+
|
|
79
|
+
assert_ok(result)
|
|
80
|
+
assert client.last.payload == {"username": "ola", "password": "s3cret"}
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
def test_set_token_stores_value_without_calling_api(invoke, client, keyring_stub):
|
|
84
|
+
result, _ = invoke("auth", ["set-token", "--token", "tok-from-web"])
|
|
85
|
+
|
|
86
|
+
assert_ok(result)
|
|
87
|
+
assert keyring_stub["token"] == "tok-from-web"
|
|
88
|
+
assert client.calls == []
|
|
89
|
+
|
|
90
|
+
|
|
91
|
+
def test_set_token_reads_from_prompt(invoke, keyring_stub):
|
|
92
|
+
result, _ = invoke("auth", ["set-token"], input="tok-prompt\n")
|
|
93
|
+
|
|
94
|
+
assert_ok(result)
|
|
95
|
+
assert keyring_stub["token"] == "tok-prompt"
|
|
96
|
+
|
|
97
|
+
|
|
98
|
+
def test_get_token_renders_stored_token(invoke, keyring_stub):
|
|
99
|
+
keyring_stub["token"] = "tok-stored"
|
|
100
|
+
|
|
101
|
+
result, render = invoke("auth", ["get-token"])
|
|
102
|
+
|
|
103
|
+
assert_ok(result)
|
|
104
|
+
assert render.columns == ["token"]
|
|
105
|
+
assert render.last.data == [{"token": "tok-stored"}]
|
|
106
|
+
|
|
107
|
+
|
|
108
|
+
def test_get_token_without_login_is_not_a_crash(invoke, keyring_stub):
|
|
109
|
+
"""No token should give a readable message, not a keyring traceback."""
|
|
110
|
+
keyring_stub["token"] = None
|
|
111
|
+
|
|
112
|
+
result, _ = invoke("auth", ["get-token"])
|
|
113
|
+
|
|
114
|
+
assert result.exit_code == 0, result.exception
|
tests/test_columns.py
ADDED
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
"""Do the columns the CLI renders exist in the API response at all?
|
|
2
|
+
|
|
3
|
+
This is the class of bug a backend refactor leaves behind: a field is renamed or
|
|
4
|
+
dropped, and the CLI keeps asking ``render`` for it. In a table it shows up as an
|
|
5
|
+
empty column, so nobody notices until someone relies on it.
|
|
6
|
+
|
|
7
|
+
The tests here check the contract against ``api_samples.py``. The authoritative
|
|
8
|
+
version — against the live API — is ``test_smoke.py::test_declared_columns_exist_on_live_api``.
|
|
9
|
+
"""
|
|
10
|
+
|
|
11
|
+
from __future__ import annotations
|
|
12
|
+
|
|
13
|
+
import api_samples
|
|
14
|
+
import pytest
|
|
15
|
+
from command_matrix import LIST_CASES
|
|
16
|
+
|
|
17
|
+
#: Columns we know do not match the backend model.
|
|
18
|
+
COLUMN_BUGS: dict[str, str] = {}
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
def _param(case):
|
|
22
|
+
bug = COLUMN_BUGS.get(case.id)
|
|
23
|
+
marks = [pytest.mark.xfail(reason=bug, strict=True)] if bug else []
|
|
24
|
+
return pytest.param(case, id=case.id, marks=marks)
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
LIST_PARAMS = [_param(c) for c in LIST_CASES]
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
@pytest.mark.parametrize("case", LIST_PARAMS)
|
|
31
|
+
def test_declared_columns_exist_in_api_response(case):
|
|
32
|
+
available = api_samples.sample_keys(case.path)
|
|
33
|
+
missing = [column for column in case.columns if column not in available]
|
|
34
|
+
|
|
35
|
+
assert not missing, (
|
|
36
|
+
f"{case.id}: the CLI renders columns absent from the API response: {missing}\n"
|
|
37
|
+
f"Available fields: {sorted(available)}"
|
|
38
|
+
)
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
@pytest.mark.parametrize("case", [pytest.param(c, id=c.id) for c in LIST_CASES])
|
|
42
|
+
def test_list_always_shows_id(case):
|
|
43
|
+
"""Without an ID the next command in the workflow has nothing to work with."""
|
|
44
|
+
assert "id" in case.columns, f"{case.id}: no 'id' column"
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
@pytest.mark.parametrize("case", [pytest.param(c, id=c.id) for c in LIST_CASES])
|
|
48
|
+
def test_no_secrets_in_columns(case):
|
|
49
|
+
"""Private keys and tokens never belong in a table."""
|
|
50
|
+
forbidden = {"wg_private_key", "private_key", "acc_key", "token", "password", "key"}
|
|
51
|
+
leaked = [column for column in case.columns if column in forbidden]
|
|
52
|
+
assert not leaked, f"{case.id}: column holding a secret: {leaked}"
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
def test_samples_cover_every_listed_endpoint():
|
|
56
|
+
"""Every path in the matrix has a sample response (otherwise the tests are blind)."""
|
|
57
|
+
for case in LIST_CASES:
|
|
58
|
+
api_samples.sample_list(case.path)
|