Skip to content

Commit

Permalink
add docs and test for 'no_args_is_help'
Browse files Browse the repository at this point in the history
  • Loading branch information
svlandeg committed Mar 18, 2024
1 parent 74433d2 commit 91e5529
Show file tree
Hide file tree
Showing 3 changed files with 78 additions and 0 deletions.
32 changes: 32 additions & 0 deletions docs/tutorial/commands/index.md
Expand Up @@ -211,6 +211,38 @@ Notice that the help text now shows the 2 commands: `create` and `delete`.
!!! tip
By default, the names of the commands are generated from the function name.

## Show the help message if no command is given

By default, we need to specify `--help` to get the command's help page.

However, by setting `no_args_is_help=True` when defining the `typer.Typer()` application, the help function will be shown whenever no argument is given:

```Python hl_lines="3"
{!../docs_src/commands/index/tutorial003.py!}
```

Now we can run this:

<div class="termy">

```console
// Check the help without having to type --help
$ python main.py

Usage: main.py [OPTIONS] COMMAND [ARGS]...

Options:
--install-completion Install completion for the current shell.
--show-completion Show completion for the current shell, to copy it or customize the installation.
--help Show this message and exit.

Commands:
create
delete
```

</div>

## Click Group

If you come from Click, a `typer.Typer` app with subcommands is more or less the equivalent of a <a href="https://click.palletsprojects.com/en/7.x/quickstart/#nesting-commands" class="external-link" target="_blank">Click Group</a>.
Expand Down
17 changes: 17 additions & 0 deletions docs_src/commands/index/tutorial003.py
@@ -0,0 +1,17 @@
import typer

app = typer.Typer(no_args_is_help=True)


@app.command()
def create():
print("Creating user: Hiro Hamada")


@app.command()
def delete():
print("Deleting user: Hiro Hamada")


if __name__ == "__main__":
app()
29 changes: 29 additions & 0 deletions tests/test_tutorial/test_commands/test_index/test_tutorial003.py
@@ -0,0 +1,29 @@
import subprocess
import sys

from typer.testing import CliRunner

from docs_src.commands.index import tutorial003 as mod

app = mod.app

runner = CliRunner()


def test_no_arg():
result = runner.invoke(app)
assert result.exit_code == 0
assert "[OPTIONS] COMMAND [ARGS]..." in result.output
assert "Commands" in result.output
assert "create" in result.output
assert "delete" in result.output


def test_script():
result = subprocess.run(
[sys.executable, "-m", "coverage", "run", mod.__file__, "--help"],
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
encoding="utf-8",
)
assert "Usage" in result.stdout

0 comments on commit 91e5529

Please sign in to comment.