|
| 1 | +"""Tests for CLI commands.""" |
| 2 | +from __future__ import annotations |
| 3 | + |
| 4 | +import subprocess |
| 5 | + |
| 6 | +import click |
| 7 | +import pytest |
| 8 | +from aiida_common_workflows.cli import cmd_root |
| 9 | + |
| 10 | + |
| 11 | +def recurse_commands(command: click.Command, parents: list[str] | None = None): |
| 12 | + """Recursively return all subcommands that are part of ``command``. |
| 13 | +
|
| 14 | + :param command: The click command to start with. |
| 15 | + :param parents: A list of strings that represent the parent commands leading up to the current command. |
| 16 | + :returns: A list of strings denoting the full path to the current command. |
| 17 | + """ |
| 18 | + if isinstance(command, click.Group): |
| 19 | + for command_name in command.commands: |
| 20 | + subcommand = command.get_command(None, command_name) |
| 21 | + if parents is not None: |
| 22 | + subparents = [*parents, command.name] |
| 23 | + else: |
| 24 | + subparents = [command.name] |
| 25 | + yield from recurse_commands(subcommand, subparents) |
| 26 | + |
| 27 | + if parents is not None: |
| 28 | + yield [*parents, command.name] |
| 29 | + else: |
| 30 | + yield [command.name] |
| 31 | + |
| 32 | + |
| 33 | +@pytest.mark.parametrize('command', recurse_commands(cmd_root)) |
| 34 | +@pytest.mark.parametrize('help_option', ('--help', '-h')) |
| 35 | +def test_commands_help_option(command, help_option): |
| 36 | + """Test the help options for all subcommands of the CLI. |
| 37 | +
|
| 38 | + The usage of ``subprocess.run`` is on purpose because using :meth:`click.Context.invoke`, which is used by the |
| 39 | + ``run_cli_command`` fixture that should usually be used in testing CLI commands, does not behave exactly the same |
| 40 | + compared to a direct invocation on the command line. The invocation through ``invoke`` does not go through all the |
| 41 | + parent commands and so might not get all the necessary initializations. |
| 42 | + """ |
| 43 | + result = subprocess.run([*command, help_option], check=False, capture_output=True, text=True) |
| 44 | + assert result.returncode == 0, result.stderr |
| 45 | + assert 'Usage:' in result.stdout |
0 commit comments