Skip to content
Myr

:memo: :sparkles: :bug: Commands: docs, examples, tests, and fix

Before adoption: this commit came in with the history the project adopted, so no landing records it.

authored by Sebastián Ramírez · committed by GitHub · parents 57b3cc1, 5095102 · Browse files · 20 files+1073 added−24 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

20 files+1073 added−24 removed

  • tests:+330 added−0 removed
  • other:+743 added−24 removed

20 files+1073 added−24 removed

added:docs/src/commands/tutorial001.py+12 added
1import typer23app = typer.Typer()456@app.command()7def main(name: str):8 typer.echo(f"Hello {name}")91011if __name__ == "__main__":12 app()
added:docs/src/commands/tutorial002.py+17 added
1import typer23app = typer.Typer()456@app.command()7def create():8 typer.echo("Creating user: Hiro Hamada")91011@app.command()12def delete():13 typer.echo("Deleting user: Hiro Hamada")141516if __name__ == "__main__":17 app()
added:docs/src/commands/tutorial003.py+17 added
1import typer23app = typer.Typer()456@app.command()7def create(username: str):8 typer.echo(f"Creating user: {username}")91011@app.command()12def delete(username: str):13 typer.echo(f"Deleting user: {username}")141516if __name__ == "__main__":17 app()
added:docs/src/commands/tutorial004.py+38 added
1import typer23app = typer.Typer()456@app.command()7def create(username: str):8 typer.echo(f"Creating user: {username}")91011@app.command()12def delete(13 username: str,14 force: bool = typer.Option(..., prompt="Are you sure you want to delete the user?"),15):16 if force:17 typer.echo(f"Deleting user: {username}")18 else:19 typer.echo("Operation cancelled")202122@app.command()23def delete_all(24 force: bool = typer.Option(..., prompt="Are you sure you want to delete ALL users?")25):26 if force:27 typer.echo("Deleting all users")28 else:29 typer.echo("Operation cancelled")303132@app.command()33def init():34 typer.echo("Initializing user database")353637if __name__ == "__main__":38 app()
added:docs/src/commands/tutorial005.py+62 added
1import typer23app = typer.Typer(help="Awesome CLI user manager.")456@app.command()7def create(username: str):8 """9 Create a new user with USERNAME.10 """11 typer.echo(f"Creating user: {username}")121314@app.command()15def delete(16 username: str,17 force: bool = typer.Option(18 ...,19 prompt="Are you sure you want to delete the user?",20 help="Force deletion without confirmation.",21 ),22):23 """24 Delete a user with USERNAME.2526 If --force is not used, will ask for confirmation.27 """28 if force:29 typer.echo(f"Deleting user: {username}")30 else:31 typer.echo("Operation cancelled")323334@app.command()35def delete_all(36 force: bool = typer.Option(37 ...,38 prompt="Are you sure you want to delete ALL users?",39 help="Force deletion without confirmation.",40 )41):42 """43 Delete ALL users in the database.4445 If --force is not used, will ask for confirmation.46 """47 if force:48 typer.echo("Deleting all users")49 else:50 typer.echo("Operation cancelled")515253@app.command()54def init():55 """56 Initialize the users database.57 """58 typer.echo("Initializing user database")596061if __name__ == "__main__":62 app()
added:docs/src/commands/tutorial006.py+17 added
1import typer23app = typer.Typer()456@app.command("create")7def cli_create_user(username: str):8 typer.echo(f"Creating user: {username}")91011@app.command("delete")12def cli_delete_user(username: str):13 typer.echo(f"Deleting user: {username}")141516if __name__ == "__main__":17 app()
modified:docs/tutorial/arguments.md+4 added-4 removed
11 unmodified lines
12But you can change that.1314In fact, it's very common to have **optional** *CLI arguments*, it's way more common than having **required** *CLI options*.1516As an example of how it could be useful, let's see how the `ls` command works.16As an example of how it could be useful, let's see how the `ls` CLI program works.1718<div class="termy">1920```console
136 unmodified lines
157158</div>159160!!! tip161 Notice that "`Camila`" here is an optional *CLI argument*, not a *CLI option*, because we didn't use something like "`--name Camila`", we just passed "`Camila`" directly to the program/command.161 Notice that "`Camila`" here is an optional *CLI argument*, not a *CLI option*, because we didn't use something like "`--name Camila`", we just passed "`Camila`" directly to the program.162163## An optional *CLI argument* with a default164165We can also make a *CLI argument* have a default value other than `None`:
27 unmodified lines
193They are normally required and, when present, they are normally the main subject of whatever the command is doing.194195For that reason, Typer (actually Click underneath) doesn't attempt to automatically document *CLI arguments*.196197And you should document them as part of the command documentation, normally in a <abbr title="a multi-line string as the first expression inside a function (not assigned to any variable) used for documentation">docstring</abbr>.197And you should document them as part of the CLI app documentation, normally in a <abbr title="a multi-line string as the first expression inside a function (not assigned to any variable) used for documentation">docstring</abbr>.198199Check the last example from the <a href="https://typer.tiangolo.com/tutorial/first-steps/#document-your-cli-app" target="_blank">First Steps</a>:200201```Python hl_lines="5 6 7 8 9"202{!./src/first_steps/tutorial006.py!}203```204205Here the *CLI argument* `NAME` is documented as part of the command help text.205Here the *CLI argument* `NAME` is documented as part of the help text.206207You should document your *CLI arguments* the same way.208209## Other uses
4 unmodified lines
added:docs/tutorial/commands.md+555 added
1We have seen how to create a CLI program with possibly several *CLI Options* and *CLI Arguments*.23But **Typer** allows you to create CLI programs with several commands (also known as subcommands).45For example, the program `git` has several commands.67One command of `git` is `git push`. And `git push` in turn takes its own *CLI arguments* and *CLI options*.89For example:1011<div class="termy">1213```console14// The push command with no parameters15$ git push1617---> 100%1819// The push command with one CLI option --set-upstream and 2 CLI arguments20$ git push --set-upstream origin master2122---> 100%23```2425</div>2627Another command of `git` is `git pull`, it also has some *CLI parameters*.2829It's like if the same big program `git` had several small programs inside.3031!!! tip32 A command looks the same as a *CLI argument*, it's just some name without a preceding `--`. But commands have predefined name, and are used to group different sets of functionalities into the same CLI application.3334## Command or subcommand3536It's common to call a CLI program a "command".3738But when one of these programs have subcommands, those subcommands are also frequently called just "commands".3940Have that in mind so you don't get confused.4142Here I'll use **CLI application** or **program** to refer to the program you are building in Python with Typer, and **command** to refer to one of these "subcommands" of your program.4344## Explicit application4546Before creating CLI applications with multiple commands/subcommands we need to understand how to create an explicit `typer.Typer()` application.4748In the *CLI Options* and *CLI Argument* tutorials you have seen how to create a single function and then pass that function to `typer.run()`.4950For example:5152```Python hl_lines="9"53{!./src/first_steps/tutorial002.py!}54```5556But that is actually a shortcut. Under the hood, **Typer** converts that to a CLI application with `typer.Typer()` and executes it. All that inside of `typer.run()`.5758There's also a more explicit way to achieve the same:5960```Python hl_lines="3 6 12"61{!./src/commands/tutorial001.py!}62```6364When you use `typer.run()`, **Typer** is doing more or less the same as above, it will:6566* Create a new `typer.Typer()` "application".67* Create a new "`command`" with your function.68* Call the same "application" as if it was a function with "`app()`".6970!!! info "`@decorator` Info"71 That `@something` syntax in Python is called a "decorator".7273 You put it on top of a function. Like a pretty decorative hat (I guess that's where the term came from).7475 A "decorator" takes the function below and does something with it.7677 In our case, this decorator tells **Typer** that the function below is a "`command`".7879Both ways, with `typer.run()` and creating the explicit application, achieve the same.8081!!! tip82 If your use case is solved with just `typer.run()`, that's fine, you don't have to create the explicit `app` and use `@app.command()`, etc.8384 You might want to do that later when your app needs the extra features, but if it doesn't need them yet, that's fine.8586If you run the second example, with the explicit `app`, it works exactly the same:8788<div class="termy">8990```console91// Without a CLI argument92$ python main.py9394Usage: main.py [OPTIONS] NAME95Try "main.py --help" for help.9697Error: Missing argument "NAME".9899// With the NAME CLI argument100$ python main.py Camila101102Hello Camila103104// Asking for help105$ python main.py --help106107Usage: main.py [OPTIONS] NAME108109Options:110 --install-completion Install completion for the current shell.111 --show-completion Show completion for the current shell, to copy it or customize the installation.112 --help Show this message and exit.113```114115</div>116117## A CLI application with multiple commands118119Coming back to the CLI applications with multiple commands/subcommands, **Typer** allows creating CLI applications with multiple of them.120121Now that you know how to create an explicit `typer.Typer()` application and add one command, let's see how to add multiple commands.122123Let's say that we have a CLI application to manage users.124125We'll have a command to `create` users and another command to `delete` them.126127To begin, let's say it can only create and delete one single predefined user:128129```Python hl_lines="6 11"130{!./src/commands/tutorial002.py!}131```132133Now we have a CLI application with 2 commands, `create` and `delete`:134135<div class="termy">136137```console138// Check the help139$ python main.py --help140141Usage: main.py [OPTIONS] COMMAND [ARGS]...142143Options:144 --install-completion Install completion for the current shell.145 --show-completion Show completion for the current shell, to copy it or customize the installation.146 --help Show this message and exit.147148Commands:149 create150 delete151152// Test them153$ python main.py create154155Creating user: Hiro Hamada156157$ python main.py delete158159Deleting user: Hiro Hamada160161// Now we have 2 commands! 🎉162```163164</div>165166Notice that the help text now shows the 2 commands: `create` and `delete`.167168!!! tip169 By default, the names of the commands are generated from the function name.170171## Command *CLI arguments*172173The same way as with a CLI application with a single command, subcommands (or just "commands") can also have their own *CLI arguments*:174175```Python hl_lines="7 12"176{!./src/commands/tutorial003.py!}177```178179<div class="termy">180181```console182// Check the help for create183$ python main.py create --help184185Usage: main.py create [OPTIONS] USERNAME186187Options:188 --help Show this message and exit.189190// Call it with a CLI argument191$ python main.py create Camila192193Creating user: Camila194195// The same for delete196$ python main.py delete Camila197198Deleting user: Camila199```200201</div>202203!!! tip204 Everything to the *right* of the *command* are *CLI parameters* (*CLI arguments* and *CLI options*) for that command.205206!!! note "Technical Details"207 Actually, it's everything to the right of that command, *before any subcommand*.208209 It's possible to have groups of *subcommands*, it's like if one *command* also had *subcommands*. And then those *subcommands* could have their own *CLI parameters*, taking their own *CLI parameters*.210211 You will see about them later in another section.212213## Command *CLI options*214215Commands can also have their own *CLI options*.216217In fact, each command can have different *CLI arguments* and *CLI options*:218219```Python hl_lines="7 13 14 24 33"220{!./src/commands/tutorial004.py!}221```222223Here we have multiple commands, with different *CLI parameters*:224225* `create`:226 * `username`: a *CLI argument*.227* `delete`:228 * `username`: a *CLI argument*.229 * `--force`: a *CLI option*, if not provided, it's prompted.230* `delete-all`:231 * `--force`: a *CLI option*, if not provided, it's prompted.232* `init`:233 * Doesn't take any *CLI parameters*.234235<div class="termy">236237```console238// Check the help239python main.py --help240241Usage: main.py [OPTIONS] COMMAND [ARGS]...242243Options:244 --install-completion Install completion for the current shell.245 --show-completion Show completion for the current shell, to copy it or customize the installation.246 --help Show this message and exit.247248Commands:249 create250 delete251 delete-all252 info253```254255</div>256257!!! tip258 Check the command `delete-all`, by default command names are generated from the function name, replacing `_` with `-`.259260Test it:261262<div class="termy">263264```console265// Check the command create266$ python main.py create Camila267268Creating user: Camila269270// Now test the command delete271$ python main.py delete Camila272273# Are you sure you want to delete the user? [y/N]: $ y274275Deleting user: Camila276277$ python main.py delete Wade278279# Are you sure you want to delete the user? [y/N]: $ n280281Operation cancelled282283// And finally, the command delete-all284// Notice it doesn't have CLI arguments, only a CLI option285286$ python main.py delete-all287288# Are you sure you want to delete ALL users? [y/N]: $ y289290Deleting all users291292$ python main.py delete-all293294# Are you sure you want to delete ALL users? [y/N]: $ n295296Operation cancelled297298// And if you pass the --force CLI option, it doesn't need to confirm299300$ python main.py delete-all --force301302Deleting all users303304// And init that doesn't take any CLI parameter305$ python main.py init306307Initializing user database308```309310</div>311312## Command help313314The same as before, you can add help for the commands in the docstrings and the *CLI options*.315316And the `typer.Typer()` application receives a parameter `help` that you can pass with the main help text for your CLI program:317318```Python hl_lines="3 8 9 10 20 23 24 25 26 27 39 42 43 44 45 46 55 56 57"319{!./src/commands/tutorial005.py!}320```321322Check it:323324<div class="termy">325326```console327// Check the new help328$ python main.py --help329330Usage: main.py [OPTIONS] COMMAND [ARGS]...331332 Awesome CLI user manager.333334Options:335 --install-completion Install completion for the current shell.336 --show-completion Show completion for the current shell, to copy it or customize the installation.337 --help Show this message and exit.338339Commands:340 create Create a new user with USERNAME.341 delete Delete a user with USERNAME.342 delete-all Delete ALL users in the database.343 init Initialize the users database.344345// Now the commands have inline help 🎉346347// Check the help for create348$ python main.py create --help349350Usage: main.py create [OPTIONS] USERNAME351352 Create a new user with USERNAME.353354Options:355 --help Show this message and exit.356357// Check the help for delete358$ python main.py delete --help359360Usage: main.py delete [OPTIONS] USERNAME361362 Delete a user with USERNAME.363364 If --force is not used, will ask for confirmation.365366Options:367 --force / --no-force Force deletion without confirmation. [required]368 --help Show this message and exit.369370// Check the help for delete-all371$ python main.py delete-all --help372373Usage: main.py delete-all [OPTIONS]374375 Delete ALL users in the database.376377 If --force is not used, will ask for confirmation.378379Options:380 --force / --no-force Force deletion without confirmation. [required]381 --help Show this message and exit.382383// Check the help for init384$ python main.py init --help385386Usage: main.py init [OPTIONS]387388 Initialize the users database.389390Options:391 --help Show this message and exit.392```393394</div>395396!!! tip397 `typer.Typer()` receives several other parameters for other things, we'll see that later.398399 You will also see how to use "Callbacks" later, and those include a way to add this same help message in a function docstring.400401## Custom command name402403By default, the command names are generated from the function name.404405So, if your function is something like:406407```Python408def create(username: str):409 ...410```411412Then the command name will be `create`.413414But if you already had a function called `create()` somewhere in your code, you would have to name your CLI function differently.415416And what if you wanted the command to still be named `create`?417418For this, you can set the name of the command in the first parameter for the `@app.command()` decorator:419420```Python hl_lines="6 11"421{!./src/commands/tutorial006.py!}422```423424Now, even though the functions are named `cli_create_user()` and `cli_delete_user()`, the commands will still be named `create` and `delete`:425426<div class="termy">427428```console429$ python main.py --help430431Usage: main.py [OPTIONS] COMMAND [ARGS]...432433Options:434 --install-completion Install completion for the current shell.435 --show-completion Show completion for the current shell, to copy it or customize the installation.436 --help Show this message and exit.437438Commands:439 create440 delete441442// Test it443$ python main.py create Camila444445Creating user: Camila446```447448</div>449450## One command vs multiple commands451452You might have noticed that if you create a single command, as in the first example:453454```Python hl_lines="3 6 12"455{!./src/commands/tutorial001.py!}456```457458**Typer** is smart enough to create a CLI application with that single function as the main CLI application, not as a command/subcommand:459460<div class="termy">461462```console463// Without a CLI argument464$ python main.py465466Usage: main.py [OPTIONS] NAME467Try "main.py --help" for help.468469Error: Missing argument "NAME".470471// With the NAME CLI argument472$ python main.py Camila473474Hello Camila475476// Asking for help477$ python main.py478479Usage: main.py [OPTIONS] NAME480481Options:482 --install-completion Install completion for the current shell.483 --show-completion Show completion for the current shell, to copy it or customize the installation.484 --help Show this message and exit.485```486487</div>488489!!! tip490 Notice that it doesn't show a command `main`, even though the function name is `main`.491492But if you add multiple commands, **Typer** will create one *CLI command* for each one of them:493494```Python hl_lines="6 11"495{!./src/commands/tutorial002.py!}496```497498Here we have 2 commands `create` and `delete`:499500<div class="termy">501502```console503// Check the help504$ python main.py --help505506Usage: main.py [OPTIONS] COMMAND [ARGS]...507508Options:509 --install-completion Install completion for the current shell.510 --show-completion Show completion for the current shell, to copy it or customize the installation.511 --help Show this message and exit.512513Commands:514 create515 delete516517// Test the commands518$ python main.py create519520Creating user: Hiro Hamada521522$ python main.py delete523524Deleting user: Hiro Hamada525```526527</div>528529!!! tip530 This is **Typer**'s behavior by default, but you could still create a CLI application with one single command, like:531532 ```533 $ python main.py main534 ```535536 instead of just:537538 ```539 $ python main.py540 ```541542 You will learn more about this in the section about application Callbacks.543544## Decorator Technical Details545546When you use `@app.command()` the function under the decorator is registered in the **Typer** application and is then used later by the application.547548But Typer doesn't modify that function itself, the function is left as is.549550That means that if your function is simple enough that you could create it without using `typer.Option()` or `typer.Argument()`, you could use the same function for a **Typer** application and a **FastAPI** application putting both decorators on top, or similar tricks.551552!!! note "Click Technical Details"553 This behavior is a design difference with Click.554555 In Click, when you add a `@click.command()` decorator it actually modifies the function underneath and replaces it with an object.
modified:docs/features.md+1 added-1 removed
modified:docs/index.md+1 added-1 removed
29 unmodified lines
3031The key features are:3233* **Intuitive to write**: Great editor support. <abbr title="also known as auto-complete, autocompletion, IntelliSense">Completion</abbr> everywhere. Less time debugging. Designed to be easy to use and learn. Less time reading docs.34* **Easy to use**: It's easy to use for the final users. Automatic help commands, and (optional) automatic completion for all shells.34* **Easy to use**: It's easy to use for the final users. Automatic help, and (optional) automatic completion for all shells.35* **Short**: Minimize code duplication. Multiple features from each parameter declaration. Fewer bugs.36* **Start simple**: The simplest example adds only 2 lines of code to your app: **1 import, 1 function call**.37* **Grow large**: Grow in complexity as much as you want, create arbitrarily complex trees of commands and groups subcommands, with options and arguments.38
236 unmodified lines
added:tests/test_tutorial/test_commands/__init__.py
added:tests/test_tutorial/test_commands/test_tutorial001.py+30 added
1import subprocess2from commands import tutorial001 as mod34from typer.testing import CliRunner56app = mod.app78runner = CliRunner()91011def test_no_arg():12 result = runner.invoke(app)13 assert result.exit_code != 014 assert 'Error: Missing argument "NAME".' in result.output151617def test_arg():18 result = runner.invoke(app, ["Camila"])19 assert result.exit_code == 020 assert "Hello Camila" in result.output212223def test_script():24 result = subprocess.run(25 ["coverage", "run", mod.__file__, "--help"],26 stdout=subprocess.PIPE,27 stderr=subprocess.PIPE,28 encoding="utf-8",29 )30 assert "Usage" in result.stdout
added:tests/test_tutorial/test_commands/test_tutorial002.py+39 added
1import subprocess2from commands import tutorial002 as mod34from typer.testing import CliRunner56app = mod.app78runner = CliRunner()91011def test_help():12 result = runner.invoke(app, ["--help"])13 assert result.exit_code == 014 assert "[OPTIONS] COMMAND [ARGS]..." in result.output15 assert "Commands:" in result.output16 assert "create" in result.output17 assert "delete" in result.output181920def test_create():21 result = runner.invoke(app, ["create"])22 assert result.exit_code == 023 assert "Creating user: Hiro Hamada" in result.output242526def test_delete():27 result = runner.invoke(app, ["delete"])28 assert result.exit_code == 029 assert "Deleting user: Hiro Hamada" in result.output303132def test_script():33 result = subprocess.run(34 ["coverage", "run", mod.__file__, "--help"],35 stdout=subprocess.PIPE,36 stderr=subprocess.PIPE,37 encoding="utf-8",38 )39 assert "Usage" in result.stdout
added:tests/test_tutorial/test_commands/test_tutorial003.py+42 added
1import subprocess2from commands import tutorial003 as mod34from typer.testing import CliRunner56app = mod.app78runner = CliRunner()91011def test_help_create():12 result = runner.invoke(app, ["create", "--help"])13 assert result.exit_code == 014 assert "create [OPTIONS] USERNAME" in result.output151617def test_help_delete():18 result = runner.invoke(app, ["delete", "--help"])19 assert result.exit_code == 020 assert "delete [OPTIONS] USERNAME" in result.output212223def test_create():24 result = runner.invoke(app, ["create", "Camila"])25 assert result.exit_code == 026 assert "Creating user: Camila" in result.output272829def test_delete():30 result = runner.invoke(app, ["delete", "Camila"])31 assert result.exit_code == 032 assert "Deleting user: Camila" in result.output333435def test_script():36 result = subprocess.run(37 ["coverage", "run", mod.__file__, "--help"],38 stdout=subprocess.PIPE,39 stderr=subprocess.PIPE,40 encoding="utf-8",41 )42 assert "Usage" in result.stdout
added:tests/test_tutorial/test_commands/test_tutorial004.py+75 added
1import subprocess2from commands import tutorial004 as mod34from typer.testing import CliRunner56app = mod.app78runner = CliRunner()91011def test_help():12 result = runner.invoke(app, ["--help"])13 assert result.exit_code == 014 assert "Commands:" in result.output15 assert "create" in result.output16 assert "delete" in result.output17 assert "delete-all" in result.output18 assert "init" in result.output192021def test_create():22 result = runner.invoke(app, ["create", "Camila"])23 assert result.exit_code == 024 assert "Creating user: Camila" in result.output252627def test_delete():28 result = runner.invoke(app, ["delete", "Camila"], input="y\n")29 assert result.exit_code == 030 assert "Are you sure you want to delete the user? [y/N]:" in result.output31 assert "Deleting user: Camila" in result.output323334def test_no_delete():35 result = runner.invoke(app, ["delete", "Camila"], input="n\n")36 assert result.exit_code == 037 assert "Are you sure you want to delete the user? [y/N]:" in result.output38 assert "Operation cancelled" in result.output394041def test_delete_all():42 result = runner.invoke(app, ["delete-all"], input="y\n")43 assert result.exit_code == 044 assert "Are you sure you want to delete ALL users? [y/N]:" in result.output45 assert "Deleting all users" in result.output464748def test_no_delete_all():49 result = runner.invoke(app, ["delete-all"], input="n\n")50 assert result.exit_code == 051 assert "Are you sure you want to delete ALL users? [y/N]:" in result.output52 assert "Operation cancelled" in result.output535455def test_delete_all_force():56 result = runner.invoke(app, ["delete-all", "--force"])57 assert result.exit_code == 058 assert "Are you sure you want to delete ALL users? [y/N]:" not in result.output59 assert "Deleting all users" in result.output606162def test_init():63 result = runner.invoke(app, ["init"])64 assert result.exit_code == 065 assert "Initializing user database" in result.output666768def test_script():69 result = subprocess.run(70 ["coverage", "run", mod.__file__, "--help"],71 stdout=subprocess.PIPE,72 stderr=subprocess.PIPE,73 encoding="utf-8",74 )75 assert "Usage" in result.stdout
added:tests/test_tutorial/test_commands/test_tutorial005.py+106 added
1import subprocess2from commands import tutorial005 as mod34from typer.testing import CliRunner56app = mod.app78runner = CliRunner()91011def test_help():12 result = runner.invoke(app, ["--help"])13 assert result.exit_code == 014 assert "Awesome CLI user manager." in result.output15 assert "create" in result.output16 assert "Create a new user with USERNAME." in result.output17 assert "delete" in result.output18 assert "Delete a user with USERNAME." in result.output19 assert "delete-all" in result.output20 assert "Delete ALL users in the database." in result.output21 assert "init" in result.output22 assert "Initialize the users database." in result.output232425def test_help_create():26 result = runner.invoke(app, ["create", "--help"])27 assert result.exit_code == 028 assert "create [OPTIONS] USERNAME" in result.output29 assert "Create a new user with USERNAME." in result.output303132def test_help_delete():33 result = runner.invoke(app, ["delete", "--help"])34 assert result.exit_code == 035 assert "delete [OPTIONS] USERNAME" in result.output36 assert "Delete a user with USERNAME." in result.output37 assert "--force / --no-force" in result.output38 assert "Force deletion without confirmation." in result.output394041def test_help_delete_all():42 result = runner.invoke(app, ["delete-all", "--help"])43 assert result.exit_code == 044 assert "delete-all [OPTIONS]" in result.output45 assert "Delete ALL users in the database." in result.output46 assert "If --force is not used, will ask for confirmation." in result.output47 assert "[required]" in result.output48 assert "--force / --no-force" in result.output49 assert "Force deletion without confirmation." in result.output505152def test_help_init():53 result = runner.invoke(app, ["init", "--help"])54 assert result.exit_code == 055 assert "init [OPTIONS]" in result.output56 assert "Initialize the users database." in result.output575859def test_create():60 result = runner.invoke(app, ["create", "Camila"])61 assert result.exit_code == 062 assert "Creating user: Camila" in result.output636465def test_delete():66 result = runner.invoke(app, ["delete", "Camila"], input="y\n")67 assert result.exit_code == 068 assert "Are you sure you want to delete the user? [y/N]:" in result.output69 assert "Deleting user: Camila" in result.output707172def test_no_delete():73 result = runner.invoke(app, ["delete", "Camila"], input="n\n")74 assert result.exit_code == 075 assert "Are you sure you want to delete the user? [y/N]:" in result.output76 assert "Operation cancelled" in result.output777879def test_delete_all():80 result = runner.invoke(app, ["delete-all",], input="y\n")81 assert result.exit_code == 082 assert "Are you sure you want to delete ALL users? [y/N]:" in result.output83 assert "Deleting all users" in result.output848586def test_no_delete_all():87 result = runner.invoke(app, ["delete-all",], input="n\n")88 assert result.exit_code == 089 assert "Are you sure you want to delete ALL users? [y/N]:" in result.output90 assert "Operation cancelled" in result.output919293def test_init():94 result = runner.invoke(app, ["init",])95 assert result.exit_code == 096 assert "Initializing user database" in result.output979899def test_script():100 result = subprocess.run(101 ["coverage", "run", mod.__file__, "--help"],102 stdout=subprocess.PIPE,103 stderr=subprocess.PIPE,104 encoding="utf-8",105 )106 assert "Usage" in result.stdout
added:tests/test_tutorial/test_commands/test_tutorial006.py+38 added
1import subprocess2from commands import tutorial006 as mod34from typer.testing import CliRunner56app = mod.app78runner = CliRunner()91011def test_help():12 result = runner.invoke(app, ["--help"])13 assert result.exit_code == 014 assert "Commands:" in result.output15 assert "create" in result.output16 assert "delete" in result.output171819def test_create():20 result = runner.invoke(app, ["create", "Camila"])21 assert result.exit_code == 022 assert "Creating user: Camila" in result.output232425def test_delete():26 result = runner.invoke(app, ["delete", "Camila"])27 assert result.exit_code == 028 assert "Deleting user: Camila" in result.output293031def test_script():32 result = subprocess.run(33 ["coverage", "run", mod.__file__, "--help"],34 stdout=subprocess.PIPE,35 stderr=subprocess.PIPE,36 encoding="utf-8",37 )38 assert "Usage" in result.stdout
modified:typer/models.py+17 added-17 removed
101 unmodified lines
102103class TyperInfo:104 def __init__(105 self,106 typer_instance: Optional["Typer"] = None,106 typer_instance: Optional["Typer"] = Default(None),107 *,108 name: Optional[str] = None,109 cls: Optional[Type[click.Command]] = None,110 invoke_without_command: bool = False,111 no_args_is_help: Optional[bool] = None,112 subcommand_metavar: Optional[str] = None,113 chain: bool = False,114 result_callback: Optional[Callable] = None,108 name: Optional[str] = Default(None),109 cls: Optional[Type[click.Command]] = Default(None),110 invoke_without_command: bool = Default(False),111 no_args_is_help: Optional[bool] = Default(None),112 subcommand_metavar: Optional[str] = Default(None),113 chain: bool = Default(False),114 result_callback: Optional[Callable] = Default(None),115 # Command116 context_settings: Optional[Dict[Any, Any]] = None,117 callback: Optional[Callable[..., Any]] = None,118 help: Optional[str] = None,119 epilog: Optional[str] = None,120 short_help: Optional[str] = None,121 options_metavar: str = "[OPTIONS]",122 add_help_option: bool = True,123 hidden: bool = False,124 deprecated: bool = False,116 context_settings: Optional[Dict[Any, Any]] = Default(None),117 callback: Optional[Callable[..., Any]] = Default(None),118 help: Optional[str] = Default(None),119 epilog: Optional[str] = Default(None),120 short_help: Optional[str] = Default(None),121 options_metavar: str = Default("[OPTIONS]"),122 add_help_option: bool = Default(True),123 hidden: bool = Default(False),124 deprecated: bool = Default(False),125 ):126 self.typer_instance = typer_instance127 self.name = name128 self.cls = cls
258 unmodified lines
modified:mkdocs.yml+1 added
23 unmodified lines
24 - Tutorial - User Guide - Intro: 'tutorial/index.md'25 - First Steps: 'tutorial/first-steps.md'26 - CLI Options: 'tutorial/options.md'27 - CLI Arguments: 'tutorial/arguments.md'28 - Commands: 'tutorial/commands.md'29 - Alternatives, Inspiration and Comparisons: 'alternatives.md'30 - Help Typer - Get Help: 'help-typer.md'31 - Development - Contributing: 'contributing.md'32 - Release Notes: release-notes.md
34 unmodified lines
modified:README.md+1 added-1 removed
29 unmodified lines
3031The key features are:3233* **Intuitive to write**: Great editor support. <abbr title="also known as auto-complete, autocompletion, IntelliSense">Completion</abbr> everywhere. Less time debugging. Designed to be easy to use and learn. Less time reading docs.34* **Easy to use**: It's easy to use for the final users. Automatic help commands, and (optional) automatic completion for all shells.34* **Easy to use**: It's easy to use for the final users. Automatic help, and (optional) automatic completion for all shells.35* **Short**: Minimize code duplication. Multiple features from each parameter declaration. Fewer bugs.36* **Start simple**: The simplest example adds only 2 lines of code to your app: **1 import, 1 function call**.37* **Grow large**: Grow in complexity as much as you want, create arbitrarily complex trees of commands and groups subcommands, with options and arguments.38
236 unmodified lines