fork/mons

git clone https://git.julia.blue/fork/mons

coloursofnoiseRename global wait flag due to conflict, add test to cover164f254

misc-fixes
2.0 KiB75 linesraw
1"""Sanity checks for click commands."""
2import typing as t
3
4if t.TYPE_CHECKING:
5    import click
6import mons.clickExt as clickExt
7from inspect import signature, unwrap
8
9
10def unwrap_count(f):
11    depth = 0
12
13    def incr(_):
14        nonlocal depth
15        depth = depth + 1
16        return False
17
18    return unwrap(f, stop=incr), depth
19
20
21def test_command_arguments(command: "click.Command"):
22    assert command.callback
23
24    callback, depth = unwrap_count(command.callback)
25
26    callback_args = signature(callback).parameters.keys()
27    callback_args_unique = set(callback_args)
28    command_params = [
29        param.name
30        for param in command.params
31        if param.expose_value and not isinstance(param, clickExt.PlaceHolder)
32        if param.name
33    ]
34
35    for param in command_params:
36        assert (
37            param in callback_args
38        ), f"Callback for '{command.name}' has missing argument: '{param}'"
39        callback_args_unique.discard(param)
40
41    assert depth == len(
42        callback_args_unique
43    ), f"Callback for '{command.name}' has too many positional arguments: '{callback_args_unique}"
44
45
46def test_command_global_flags(command: "click.Command"):
47    command_params = [
48        param
49        for param in command.params
50        if param.expose_value
51        and not isinstance(param, clickExt.PlaceHolder)
52        and any(
53            opt in clickExt.loglevel_flags
54            for opt in (*param.opts, *param.secondary_opts)
55        )
56    ]
57
58    assert (
59        not command_params
60    ), "Log level flags are swallowed by logger. Use `logger.isEnabledFor` to check logging level."
61
62    command_params = [
63        param
64        for param in command.params
65        if param.expose_value
66        and not isinstance(param, clickExt.PlaceHolder)
67        and any(
68            opt in ["--pause", "--prompt-install"]
69            for opt in (*param.opts, *param.secondary_opts)
70        )
71    ]
72
73    assert (
74        not command_params
75    ), "The '--pause' and '--prompt-install' flags are swallowed by the command group."