Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

🐛 Make sure rich_markup_mode=None disables Rich formatting #726

Closed
wants to merge 11 commits into from
21 changes: 0 additions & 21 deletions tests/test_others.py
Original file line number Diff line number Diff line change
Expand Up @@ -208,27 +208,6 @@ def main(name: str = typer.Option(..., autocompletion=name_callback)):
assert exc_info.value.message == "Invalid autocompletion callback parameters: val2"


def test_forward_references():
app = typer.Typer()

@app.command()
def main(arg1, arg2: int, arg3: "int", arg4: bool = False, arg5: "bool" = False):
print(f"arg1: {type(arg1)} {arg1}")
print(f"arg2: {type(arg2)} {arg2}")
print(f"arg3: {type(arg3)} {arg3}")
print(f"arg4: {type(arg4)} {arg4}")
print(f"arg5: {type(arg5)} {arg5}")

result = runner.invoke(app, ["Hello", "2", "invalid"])

assert "Invalid value for 'ARG3': 'invalid' is not a valid integer" in result.stdout
result = runner.invoke(app, ["Hello", "2", "3", "--arg4", "--arg5"])
assert (
"arg1: <class 'str'> Hello\narg2: <class 'int'> 2\narg3: <class 'int'> 3\narg4: <class 'bool'> True\narg5: <class 'bool'> True\n"
in result.stdout
)


def test_context_settings_inheritance_single_command():
app = typer.Typer(context_settings={"help_option_names": ["-h", "--help"]})

Expand Down
116 changes: 116 additions & 0 deletions tests/test_rich_markup_mode.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,116 @@
import typer
import typer.completion
from typer.testing import CliRunner

runner = CliRunner()
rounded = ["╭", "─", "┬", "╮", "│", "├", "┼", "┤", "╰", "┴", "╯"]


def test_rich_markup_mode_default():
app = typer.Typer()

@app.command()
def main(arg: str):
"""Main function"""
print(f"Hello {arg}")

assert app.rich_markup_mode is None

result = runner.invoke(app, ["World"])
assert "Hello World" in result.stdout

result = runner.invoke(app, ["--help"])
assert all(c not in result.stdout for c in rounded)


def test_rich_markup_mode_rich():
app = typer.Typer(rich_markup_mode="rich")

@app.command()
def main(arg: str):
"""Main function"""
print(f"Hello {arg}")

assert app.rich_markup_mode == "rich"

result = runner.invoke(app, ["World"])
assert "Hello World" in result.stdout

result = runner.invoke(app, ["--help"])
assert any(c in result.stdout for c in rounded)


# Test mostly for coverage
def test_clickexception_rich():
app = typer.Typer(rich_markup_mode="rich")

@app.command()
def main(arg1, arg2: int, arg3: "int", arg4: bool = False, arg5: "bool" = False):
print(f"arg1: {type(arg1)} {arg1}")
print(f"arg2: {type(arg2)} {arg2}")
print(f"arg3: {type(arg3)} {arg3}")
print(f"arg4: {type(arg4)} {arg4}")
print(f"arg5: {type(arg5)} {arg5}")

result = runner.invoke(app, ["Hello", "2", "invalid"])

assert "Invalid value for 'ARG3': 'invalid' is not a valid integer" in result.stdout
print(result.stdout)
result = runner.invoke(app, ["Hello", "2", "3", "--arg4", "--arg5"])
assert (
"arg1: <class 'str'> Hello\narg2: <class 'int'> 2\narg3: <class 'int'> 3\narg4: <class 'bool'> True\narg5: <class 'bool'> True\n"
in result.stdout
)
print(result.stdout)


# Test mostly for coverage
def test_clickexception_no_rich():
app = typer.Typer(rich_markup_mode=None)

@app.command()
def main(arg1, arg2: int, arg3: "int", arg4: bool = False, arg5: "bool" = False):
print(f"arg1: {type(arg1)} {arg1}")
print(f"arg2: {type(arg2)} {arg2}")
print(f"arg3: {type(arg3)} {arg3}")
print(f"arg4: {type(arg4)} {arg4}")
print(f"arg5: {type(arg5)} {arg5}")

result = runner.invoke(app, ["Hello", "2", "invalid"])

assert "Invalid value for 'ARG3': 'invalid' is not a valid integer" in result.stdout
print(result.stdout)
result = runner.invoke(app, ["Hello", "2", "3", "--arg4", "--arg5"])
assert (
"arg1: <class 'str'> Hello\narg2: <class 'int'> 2\narg3: <class 'int'> 3\narg4: <class 'bool'> True\narg5: <class 'bool'> True\n"
in result.stdout
)
print(result.stdout)


# Test mostly for coverage
def test_aborted_rich():
from docs_src.multiple_values.options_with_multiple_values import tutorial001 as mod

runner = CliRunner()
app = typer.Typer(rich_markup_mode="rich")
app.command()(mod.main)

result = runner.invoke(app)
assert result.exit_code != 0
assert "No user provided" in result.output
assert "Aborted" in result.output


# Test mostly for coverage
def test_aborted_no_rich():
from docs_src.multiple_values.options_with_multiple_values import tutorial001 as mod

runner = CliRunner()
app = typer.Typer(rich_markup_mode=None)
app.command()(mod.main)

result = runner.invoke(app)
assert result.exit_code != 0
assert "No user provided" in result.output
assert "Aborted" in result.output
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import os
import subprocess
import sys

Expand Down Expand Up @@ -32,5 +33,6 @@ def test_script():
[sys.executable, "-m", "coverage", "run", mod.__file__, "--help"],
capture_output=True,
encoding="utf-8",
env={**os.environ, "PYTHONIOENCODING": "utf-8"},
svlandeg marked this conversation as resolved.
Show resolved Hide resolved
)
assert "Usage" in result.stdout
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import os
import subprocess
import sys

Expand Down Expand Up @@ -32,5 +33,6 @@ def test_script():
[sys.executable, "-m", "coverage", "run", mod.__file__, "--help"],
capture_output=True,
encoding="utf-8",
env={**os.environ, "PYTHONIOENCODING": "utf-8"},
)
assert "Usage" in result.stdout
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@

runner = CliRunner()

app = typer.Typer()
app = typer.Typer(rich_markup_mode="rich")
app.command()(mod.main)


Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@

runner = CliRunner()

app = typer.Typer()
app = typer.Typer(rich_markup_mode="rich")
app.command()(mod.main)


Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,14 +16,14 @@ def test_help():
assert "create" in result.output
assert "Create a user." in result.output
assert "delete" in result.output
assert "(deprecated)" in result.output
assert "(deprecated)" in result.output or "(Deprecated)" in result.output
assert "Delete a user." in result.output


def test_help_delete():
result = runner.invoke(app, ["delete", "--help"])
assert result.exit_code == 0
assert "(deprecated)" in result.output
assert "(deprecated)" in result.output or "(Deprecated)" in result.output
assert "Delete a user." in result.output


Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
import subprocess
import sys

from typer.testing import CliRunner

from docs_src.commands.help import tutorial003 as mod

app = mod.app
app.rich_markup_mode = "rich"

runner = CliRunner()


def test_help():
result = runner.invoke(app, ["--help"])
assert result.exit_code == 0
assert "create" in result.output
assert "Create a user." in result.output
assert "delete" in result.output
assert "(deprecated)" in result.output
assert "Delete a user." in result.output


def test_help_delete():
result = runner.invoke(app, ["delete", "--help"])
assert result.exit_code == 0
assert "(deprecated)" in result.output
assert "Delete a user." in result.output


def test_call():
# Mainly for coverage
result = runner.invoke(app, ["create", "Camila"])
assert result.exit_code == 0
result = runner.invoke(app, ["delete", "Camila"])
assert result.exit_code == 0


def test_script():
result = subprocess.run(
[sys.executable, "-m", "coverage", "run", mod.__file__, "--help"],
capture_output=True,
encoding="utf-8",
)
assert "Usage" in result.stdout
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@

runner = CliRunner()

app = typer.Typer()
app = typer.Typer(rich_markup_mode="rich")
app.command()(mod.main)


Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@

runner = CliRunner()

app = typer.Typer()
app = typer.Typer(rich_markup_mode="rich")
app.command()(mod.main)


Expand Down
11 changes: 7 additions & 4 deletions typer/core.py
Original file line number Diff line number Diff line change
Expand Up @@ -167,6 +167,7 @@ def _main(
complete_var: Optional[str] = None,
standalone_mode: bool = True,
windows_expand_args: bool = True,
rich_markup_mode: MarkupMode = None,
**extra: Any,
) -> Any:
# Typer override, duplicated from click.main() to handle custom rich exceptions
Expand Down Expand Up @@ -208,7 +209,7 @@ def _main(
if not standalone_mode:
raise
# Typer override
if rich:
if rich and rich_markup_mode is not None:
rich_utils.rich_format_error(e)
else:
e.show()
Expand Down Expand Up @@ -238,7 +239,7 @@ def _main(
if not standalone_mode:
raise
# Typer override
if rich:
if rich and rich_markup_mode is not None:
rich_utils.rich_abort_error()
else:
click.echo(_("Aborted!"), file=sys.stderr)
Expand Down Expand Up @@ -665,11 +666,12 @@ def main(
complete_var=complete_var,
standalone_mode=standalone_mode,
windows_expand_args=windows_expand_args,
rich_markup_mode=self.rich_markup_mode,
**extra,
)

def format_help(self, ctx: click.Context, formatter: click.HelpFormatter) -> None:
if not rich:
if not rich or self.rich_markup_mode is None:
return super().format_help(ctx, formatter)
return rich_utils.rich_format_help(
obj=self,
Expand Down Expand Up @@ -727,11 +729,12 @@ def main(
complete_var=complete_var,
standalone_mode=standalone_mode,
windows_expand_args=windows_expand_args,
rich_markup_mode=self.rich_markup_mode,
**extra,
)

def format_help(self, ctx: click.Context, formatter: click.HelpFormatter) -> None:
if not rich:
if not rich or self.rich_markup_mode is None:
return super().format_help(ctx, formatter)
return rich_utils.rich_format_help(
obj=self,
Expand Down
12 changes: 6 additions & 6 deletions typer/rich_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -144,7 +144,7 @@ def _get_rich_console(stderr: bool = False) -> Console:
)


def _make_rich_rext(
def _make_rich_text(
*, text: str, style: str = "", markup_mode: MarkupMode
) -> Union[Markdown, Text]:
"""Take a string, remove indentations, and return styled text.
Expand Down Expand Up @@ -194,7 +194,7 @@ def _get_help_text(
# Remove single linebreaks
if markup_mode != MARKUP_MODE_MARKDOWN and not first_line.startswith("\b"):
first_line = first_line.replace("\n", " ")
yield _make_rich_rext(
yield _make_rich_text(
text=first_line.strip(),
style=STYLE_HELPTEXT_FIRST_LINE,
markup_mode=markup_mode,
Expand All @@ -217,7 +217,7 @@ def _get_help_text(
# Join with double linebreaks if markdown
remaining_lines = "\n\n".join(remaining_paragraphs)

yield _make_rich_rext(
yield _make_rich_text(
text=remaining_lines,
style=STYLE_HELPTEXT,
markup_mode=markup_mode,
Expand Down Expand Up @@ -272,7 +272,7 @@ def _get_parameter_help(
for x in paragraphs
]
items.append(
_make_rich_rext(
_make_rich_text(
text="\n".join(paragraphs).strip(),
style=STYLE_OPTION_HELP,
markup_mode=markup_mode,
Expand Down Expand Up @@ -331,7 +331,7 @@ def _make_command_help(
paragraphs[0] = paragraphs[0].replace("\n", " ")
elif paragraphs[0].startswith("\b"):
paragraphs[0] = paragraphs[0].replace("\b\n", "")
return _make_rich_rext(
return _make_rich_text(
text=paragraphs[0].strip(),
style=STYLE_OPTION_HELP,
markup_mode=markup_mode,
Expand Down Expand Up @@ -674,7 +674,7 @@ def rich_format_help(
# Remove single linebreaks, replace double with single
lines = obj.epilog.split("\n\n")
epilogue = "\n".join([x.replace("\n", " ").strip() for x in lines])
epilogue_text = _make_rich_rext(text=epilogue, markup_mode=markup_mode)
epilogue_text = _make_rich_text(text=epilogue, markup_mode=markup_mode)
console.print(Padding(Align(epilogue_text, pad=False), 1))


Expand Down
Loading