: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
Provenance
- Commit
ed6701b- Tree
bda65e6- Author
Sebastián Ramírez <tiangolo@gmail.com>- Committer
GitHub <noreply@github.com>- Parent 1
57b3cc1- Parent 2
5095102
20 files changed+1073 added−24 removed
added:docs/src/commands/tutorial001.py+12 added
1+import typer2+3+app = typer.Typer()4+5+6+@app.command()7+def main(name: str):8+ typer.echo(f"Hello {name}")9+10+11+if __name__ == "__main__":12+ app()added:docs/src/commands/tutorial002.py+17 added
1+import typer2+3+app = typer.Typer()4+5+6+@app.command()7+def create():8+ typer.echo("Creating user: Hiro Hamada")9+10+11+@app.command()12+def delete():13+ typer.echo("Deleting user: Hiro Hamada")14+15+16+if __name__ == "__main__":17+ app()added:docs/src/commands/tutorial003.py+17 added
1+import typer2+3+app = typer.Typer()4+5+6+@app.command()7+def create(username: str):8+ typer.echo(f"Creating user: {username}")9+10+11+@app.command()12+def delete(username: str):13+ typer.echo(f"Deleting user: {username}")14+15+16+if __name__ == "__main__":17+ app()added:docs/src/commands/tutorial004.py+38 added
1+import typer2+3+app = typer.Typer()4+5+6+@app.command()7+def create(username: str):8+ typer.echo(f"Creating user: {username}")9+10+11+@app.command()12+def 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")20+21+22+@app.command()23+def 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")30+31+32+@app.command()33+def init():34+ typer.echo("Initializing user database")35+36+37+if __name__ == "__main__":38+ app()added:docs/src/commands/tutorial005.py+62 added
1+import typer2+3+app = typer.Typer(help="Awesome CLI user manager.")4+5+6+@app.command()7+def create(username: str):8+ """9+ Create a new user with USERNAME.10+ """11+ typer.echo(f"Creating user: {username}")12+13+14+@app.command()15+def 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.25+26+ 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")32+33+34+@app.command()35+def 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.44+45+ 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")51+52+53+@app.command()54+def init():55+ """56+ Initialize the users database.57+ """58+ typer.echo("Initializing user database")59+60+61+if __name__ == "__main__":62+ app()added:docs/src/commands/tutorial006.py+17 added
1+import typer2+3+app = typer.Typer()4+5+6+@app.command("create")7+def cli_create_user(username: str):8+ typer.echo(f"Creating user: {username}")9+10+11+@app.command("delete")12+def cli_delete_user(username: str):13+ typer.echo(f"Deleting user: {username}")14+15+16+if __name__ == "__main__":17+ app()modified:docs/tutorial/arguments.md+4 added-4 removed
11 unmodified lines12 But you can change that.13 14 In fact, it's very common to have **optional** *CLI arguments*, it's way more common than having **required** *CLI options*.15 16-As an example of how it could be useful, let's see how the `ls` command works.16+As an example of how it could be useful, let's see how the `ls` CLI program works.17 18 <div class="termy">19 20 ```console136 unmodified lines157 158 </div>159 160 !!! 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.162 163 ## An optional *CLI argument* with a default164 165 We can also make a *CLI argument* have a default value other than `None`:27 unmodified lines193 They are normally required and, when present, they are normally the main subject of whatever the command is doing.194 195 For that reason, Typer (actually Click underneath) doesn't attempt to automatically document *CLI arguments*.196 197-And 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>.197+And 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>.198 199 Check the last example from the <a href="https://typer.tiangolo.com/tutorial/first-steps/#document-your-cli-app" target="_blank">First Steps</a>:200 201 ```Python hl_lines="5 6 7 8 9"202 {!./src/first_steps/tutorial006.py!}203 ```204 205-Here the *CLI argument* `NAME` is documented as part of the command help text.205+Here the *CLI argument* `NAME` is documented as part of the help text.206 207 You should document your *CLI arguments* the same way.208 209 ## Other uses4 unmodified linesadded:docs/tutorial/commands.md+555 added
1+We have seen how to create a CLI program with possibly several *CLI Options* and *CLI Arguments*.2+3+But **Typer** allows you to create CLI programs with several commands (also known as subcommands).4+5+For example, the program `git` has several commands.6+7+One command of `git` is `git push`. And `git push` in turn takes its own *CLI arguments* and *CLI options*.8+9+For example:10+11+<div class="termy">12+13+```console14+// The push command with no parameters15+$ git push16+17+---> 100%18+19+// The push command with one CLI option --set-upstream and 2 CLI arguments20+$ git push --set-upstream origin master21+22+---> 100%23+```24+25+</div>26+27+Another command of `git` is `git pull`, it also has some *CLI parameters*.28+29+It's like if the same big program `git` had several small programs inside.30+31+!!! 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.33+34+## Command or subcommand35+36+It's common to call a CLI program a "command".37+38+But when one of these programs have subcommands, those subcommands are also frequently called just "commands".39+40+Have that in mind so you don't get confused.41+42+Here 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.43+44+## Explicit application45+46+Before creating CLI applications with multiple commands/subcommands we need to understand how to create an explicit `typer.Typer()` application.47+48+In the *CLI Options* and *CLI Argument* tutorials you have seen how to create a single function and then pass that function to `typer.run()`.49+50+For example:51+52+```Python hl_lines="9"53+{!./src/first_steps/tutorial002.py!}54+```55+56+But 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()`.57+58+There's also a more explicit way to achieve the same:59+60+```Python hl_lines="3 6 12"61+{!./src/commands/tutorial001.py!}62+```63+64+When you use `typer.run()`, **Typer** is doing more or less the same as above, it will:65+66+* 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()`".69+70+!!! info "`@decorator` Info"71+ That `@something` syntax in Python is called a "decorator".72+73+ You put it on top of a function. Like a pretty decorative hat (I guess that's where the term came from).74+75+ A "decorator" takes the function below and does something with it.76+77+ In our case, this decorator tells **Typer** that the function below is a "`command`".78+79+Both ways, with `typer.run()` and creating the explicit application, achieve the same.80+81+!!! 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.83+84+ 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.85+86+If you run the second example, with the explicit `app`, it works exactly the same:87+88+<div class="termy">89+90+```console91+// Without a CLI argument92+$ python main.py93+94+Usage: main.py [OPTIONS] NAME95+Try "main.py --help" for help.96+97+Error: Missing argument "NAME".98+99+// With the NAME CLI argument100+$ python main.py Camila101+102+Hello Camila103+104+// Asking for help105+$ python main.py --help106+107+Usage: main.py [OPTIONS] NAME108+109+Options: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+```114+115+</div>116+117+## A CLI application with multiple commands118+119+Coming back to the CLI applications with multiple commands/subcommands, **Typer** allows creating CLI applications with multiple of them.120+121+Now that you know how to create an explicit `typer.Typer()` application and add one command, let's see how to add multiple commands.122+123+Let's say that we have a CLI application to manage users.124+125+We'll have a command to `create` users and another command to `delete` them.126+127+To begin, let's say it can only create and delete one single predefined user:128+129+```Python hl_lines="6 11"130+{!./src/commands/tutorial002.py!}131+```132+133+Now we have a CLI application with 2 commands, `create` and `delete`:134+135+<div class="termy">136+137+```console138+// Check the help139+$ python main.py --help140+141+Usage: main.py [OPTIONS] COMMAND [ARGS]...142+143+Options: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.147+148+Commands:149+ create150+ delete151+152+// Test them153+$ python main.py create154+155+Creating user: Hiro Hamada156+157+$ python main.py delete158+159+Deleting user: Hiro Hamada160+161+// Now we have 2 commands! 🎉162+```163+164+</div>165+166+Notice that the help text now shows the 2 commands: `create` and `delete`.167+168+!!! tip169+ By default, the names of the commands are generated from the function name.170+171+## Command *CLI arguments*172+173+The same way as with a CLI application with a single command, subcommands (or just "commands") can also have their own *CLI arguments*:174+175+```Python hl_lines="7 12"176+{!./src/commands/tutorial003.py!}177+```178+179+<div class="termy">180+181+```console182+// Check the help for create183+$ python main.py create --help184+185+Usage: main.py create [OPTIONS] USERNAME186+187+Options:188+ --help Show this message and exit.189+190+// Call it with a CLI argument191+$ python main.py create Camila192+193+Creating user: Camila194+195+// The same for delete196+$ python main.py delete Camila197+198+Deleting user: Camila199+```200+201+</div>202+203+!!! tip204+ Everything to the *right* of the *command* are *CLI parameters* (*CLI arguments* and *CLI options*) for that command.205+206+!!! note "Technical Details"207+ Actually, it's everything to the right of that command, *before any subcommand*.208+209+ 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*.210+211+ You will see about them later in another section.212+213+## Command *CLI options*214+215+Commands can also have their own *CLI options*.216+217+In fact, each command can have different *CLI arguments* and *CLI options*:218+219+```Python hl_lines="7 13 14 24 33"220+{!./src/commands/tutorial004.py!}221+```222+223+Here we have multiple commands, with different *CLI parameters*:224+225+* `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*.234+235+<div class="termy">236+237+```console238+// Check the help239+python main.py --help240+241+Usage: main.py [OPTIONS] COMMAND [ARGS]...242+243+Options: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.247+248+Commands:249+ create250+ delete251+ delete-all252+ info253+```254+255+</div>256+257+!!! tip258+ Check the command `delete-all`, by default command names are generated from the function name, replacing `_` with `-`.259+260+Test it:261+262+<div class="termy">263+264+```console265+// Check the command create266+$ python main.py create Camila267+268+Creating user: Camila269+270+// Now test the command delete271+$ python main.py delete Camila272+273+# Are you sure you want to delete the user? [y/N]: $ y274+275+Deleting user: Camila276+277+$ python main.py delete Wade278+279+# Are you sure you want to delete the user? [y/N]: $ n280+281+Operation cancelled282+283+// And finally, the command delete-all284+// Notice it doesn't have CLI arguments, only a CLI option285+286+$ python main.py delete-all287+288+# Are you sure you want to delete ALL users? [y/N]: $ y289+290+Deleting all users291+292+$ python main.py delete-all293+294+# Are you sure you want to delete ALL users? [y/N]: $ n295+296+Operation cancelled297+298+// And if you pass the --force CLI option, it doesn't need to confirm299+300+$ python main.py delete-all --force301+302+Deleting all users303+304+// And init that doesn't take any CLI parameter305+$ python main.py init306+307+Initializing user database308+```309+310+</div>311+312+## Command help313+314+The same as before, you can add help for the commands in the docstrings and the *CLI options*.315+316+And the `typer.Typer()` application receives a parameter `help` that you can pass with the main help text for your CLI program:317+318+```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+```321+322+Check it:323+324+<div class="termy">325+326+```console327+// Check the new help328+$ python main.py --help329+330+Usage: main.py [OPTIONS] COMMAND [ARGS]...331+332+ Awesome CLI user manager.333+334+Options: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.338+339+Commands: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.344+345+// Now the commands have inline help 🎉346+347+// Check the help for create348+$ python main.py create --help349+350+Usage: main.py create [OPTIONS] USERNAME351+352+ Create a new user with USERNAME.353+354+Options:355+ --help Show this message and exit.356+357+// Check the help for delete358+$ python main.py delete --help359+360+Usage: main.py delete [OPTIONS] USERNAME361+362+ Delete a user with USERNAME.363+364+ If --force is not used, will ask for confirmation.365+366+Options:367+ --force / --no-force Force deletion without confirmation. [required]368+ --help Show this message and exit.369+370+// Check the help for delete-all371+$ python main.py delete-all --help372+373+Usage: main.py delete-all [OPTIONS]374+375+ Delete ALL users in the database.376+377+ If --force is not used, will ask for confirmation.378+379+Options:380+ --force / --no-force Force deletion without confirmation. [required]381+ --help Show this message and exit.382+383+// Check the help for init384+$ python main.py init --help385+386+Usage: main.py init [OPTIONS]387+388+ Initialize the users database.389+390+Options:391+ --help Show this message and exit.392+```393+394+</div>395+396+!!! tip397+ `typer.Typer()` receives several other parameters for other things, we'll see that later.398+399+ You will also see how to use "Callbacks" later, and those include a way to add this same help message in a function docstring.400+401+## Custom command name402+403+By default, the command names are generated from the function name.404+405+So, if your function is something like:406+407+```Python408+def create(username: str):409+ ...410+```411+412+Then the command name will be `create`.413+414+But if you already had a function called `create()` somewhere in your code, you would have to name your CLI function differently.415+416+And what if you wanted the command to still be named `create`?417+418+For this, you can set the name of the command in the first parameter for the `@app.command()` decorator:419+420+```Python hl_lines="6 11"421+{!./src/commands/tutorial006.py!}422+```423+424+Now, even though the functions are named `cli_create_user()` and `cli_delete_user()`, the commands will still be named `create` and `delete`:425+426+<div class="termy">427+428+```console429+$ python main.py --help430+431+Usage: main.py [OPTIONS] COMMAND [ARGS]...432+433+Options: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.437+438+Commands:439+ create440+ delete441+442+// Test it443+$ python main.py create Camila444+445+Creating user: Camila446+```447+448+</div>449+450+## One command vs multiple commands451+452+You might have noticed that if you create a single command, as in the first example:453+454+```Python hl_lines="3 6 12"455+{!./src/commands/tutorial001.py!}456+```457+458+**Typer** is smart enough to create a CLI application with that single function as the main CLI application, not as a command/subcommand:459+460+<div class="termy">461+462+```console463+// Without a CLI argument464+$ python main.py465+466+Usage: main.py [OPTIONS] NAME467+Try "main.py --help" for help.468+469+Error: Missing argument "NAME".470+471+// With the NAME CLI argument472+$ python main.py Camila473+474+Hello Camila475+476+// Asking for help477+$ python main.py478+479+Usage: main.py [OPTIONS] NAME480+481+Options: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+```486+487+</div>488+489+!!! tip490+ Notice that it doesn't show a command `main`, even though the function name is `main`.491+492+But if you add multiple commands, **Typer** will create one *CLI command* for each one of them:493+494+```Python hl_lines="6 11"495+{!./src/commands/tutorial002.py!}496+```497+498+Here we have 2 commands `create` and `delete`:499+500+<div class="termy">501+502+```console503+// Check the help504+$ python main.py --help505+506+Usage: main.py [OPTIONS] COMMAND [ARGS]...507+508+Options: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.512+513+Commands:514+ create515+ delete516+517+// Test the commands518+$ python main.py create519+520+Creating user: Hiro Hamada521+522+$ python main.py delete523+524+Deleting user: Hiro Hamada525+```526+527+</div>528+529+!!! tip530+ This is **Typer**'s behavior by default, but you could still create a CLI application with one single command, like:531+532+ ```533+ $ python main.py main534+ ```535+536+ instead of just:537+538+ ```539+ $ python main.py540+ ```541+542+ You will learn more about this in the section about application Callbacks.543+544+## Decorator Technical Details545+546+When you use `@app.command()` the function under the decorator is registered in the **Typer** application and is then used later by the application.547+548+But Typer doesn't modify that function itself, the function is left as is.549+550+That 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.551+552+!!! note "Click Technical Details"553+ This behavior is a design difference with Click.554+555+ 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
40 unmodified lines4142434445454647484928 unmodified lines40 unmodified lines## User friendly CLI apps
The resulting CLI apps created with **Typer** have the nice features of many "pro" command line programs you probably already love.
* Automatic help commands and options.* Automatic help options for the main CLI program and all the its subcommands.* Automatic command and subcommand structure handling (you will see more about subcommands in the Tutorial - User Guide).* Automatic autocompletion for the CLI app in all operating systems, in all the shells (Bash, Zsh, Fish, PowerShell), so that the final user of your app can just hit <kbd>TAB</kbd> and get the available options or subcommands. *
!!! note "* Autocompletion"28 unmodified linesmodified:docs/index.md+1 added-1 removed
29 unmodified lines30 31 The key features are:32 33 * **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 linesadded:tests/test_tutorial/test_commands/__init__.py
added:tests/test_tutorial/test_commands/test_tutorial001.py+30 added
1+import subprocess2+from commands import tutorial001 as mod3+4+from typer.testing import CliRunner5+6+app = mod.app7+8+runner = CliRunner()9+10+11+def test_no_arg():12+ result = runner.invoke(app)13+ assert result.exit_code != 014+ assert 'Error: Missing argument "NAME".' in result.output15+16+17+def test_arg():18+ result = runner.invoke(app, ["Camila"])19+ assert result.exit_code == 020+ assert "Hello Camila" in result.output21+22+23+def 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.stdoutadded:tests/test_tutorial/test_commands/test_tutorial002.py+39 added
1+import subprocess2+from commands import tutorial002 as mod3+4+from typer.testing import CliRunner5+6+app = mod.app7+8+runner = CliRunner()9+10+11+def 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.output18+19+20+def test_create():21+ result = runner.invoke(app, ["create"])22+ assert result.exit_code == 023+ assert "Creating user: Hiro Hamada" in result.output24+25+26+def test_delete():27+ result = runner.invoke(app, ["delete"])28+ assert result.exit_code == 029+ assert "Deleting user: Hiro Hamada" in result.output30+31+32+def 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.stdoutadded:tests/test_tutorial/test_commands/test_tutorial003.py+42 added
1+import subprocess2+from commands import tutorial003 as mod3+4+from typer.testing import CliRunner5+6+app = mod.app7+8+runner = CliRunner()9+10+11+def test_help_create():12+ result = runner.invoke(app, ["create", "--help"])13+ assert result.exit_code == 014+ assert "create [OPTIONS] USERNAME" in result.output15+16+17+def test_help_delete():18+ result = runner.invoke(app, ["delete", "--help"])19+ assert result.exit_code == 020+ assert "delete [OPTIONS] USERNAME" in result.output21+22+23+def test_create():24+ result = runner.invoke(app, ["create", "Camila"])25+ assert result.exit_code == 026+ assert "Creating user: Camila" in result.output27+28+29+def test_delete():30+ result = runner.invoke(app, ["delete", "Camila"])31+ assert result.exit_code == 032+ assert "Deleting user: Camila" in result.output33+34+35+def 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.stdoutadded:tests/test_tutorial/test_commands/test_tutorial004.py+75 added
1+import subprocess2+from commands import tutorial004 as mod3+4+from typer.testing import CliRunner5+6+app = mod.app7+8+runner = CliRunner()9+10+11+def 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.output19+20+21+def test_create():22+ result = runner.invoke(app, ["create", "Camila"])23+ assert result.exit_code == 024+ assert "Creating user: Camila" in result.output25+26+27+def 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.output32+33+34+def 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.output39+40+41+def 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.output46+47+48+def 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.output53+54+55+def 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.output60+61+62+def test_init():63+ result = runner.invoke(app, ["init"])64+ assert result.exit_code == 065+ assert "Initializing user database" in result.output66+67+68+def 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.stdoutadded:tests/test_tutorial/test_commands/test_tutorial005.py+106 added
1+import subprocess2+from commands import tutorial005 as mod3+4+from typer.testing import CliRunner5+6+app = mod.app7+8+runner = CliRunner()9+10+11+def 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.output23+24+25+def 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.output30+31+32+def 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.output39+40+41+def 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.output50+51+52+def 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.output57+58+59+def test_create():60+ result = runner.invoke(app, ["create", "Camila"])61+ assert result.exit_code == 062+ assert "Creating user: Camila" in result.output63+64+65+def 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.output70+71+72+def 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.output77+78+79+def 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.output84+85+86+def 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.output91+92+93+def test_init():94+ result = runner.invoke(app, ["init",])95+ assert result.exit_code == 096+ assert "Initializing user database" in result.output97+98+99+def 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.stdoutadded:tests/test_tutorial/test_commands/test_tutorial006.py+38 added
1+import subprocess2+from commands import tutorial006 as mod3+4+from typer.testing import CliRunner5+6+app = mod.app7+8+runner = CliRunner()9+10+11+def 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+18+19+def test_create():20+ result = runner.invoke(app, ["create", "Camila"])21+ assert result.exit_code == 022+ assert "Creating user: Camila" in result.output23+24+25+def test_delete():26+ result = runner.invoke(app, ["delete", "Camila"])27+ assert result.exit_code == 028+ assert "Deleting user: Camila" in result.output29+30+31+def 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.stdoutmodified:typer/models.py+17 added-17 removed
101 unmodified lines102 103 class 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 = cls258 unmodified linesmodified:mkdocs.yml+1 added
23 unmodified lines24 - 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.md34 unmodified linesmodified:README.md+1 added-1 removed
29 unmodified lines30 31 The key features are:32 33 * **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