diff --git a/tests/test_coercion.py b/tests/test_coercion.py index 9015c57d92..9cbc671016 100644 --- a/tests/test_coercion.py +++ b/tests/test_coercion.py @@ -51,6 +51,32 @@ def main(config: Path = typer.Option(..., exists=True)): assert seen == [target] +def test_coercion_path_dash(tmp_path: Path) -> None: + """Ensure that allow_dash=True is honored with a Path annotation.""" + existing = tmp_path / "config.txt" + existing.write_text("hello\n", encoding="utf-8") + app = typer.Typer() + seen: list[Path] = [] + + @app.command() + def main(config: Path = typer.Argument(..., allow_dash=True, exists=True)): + seen.append(config) + + # regression test, cf. #2020 + result = runner.invoke(app, ["-"]) + assert result.exit_code == 0, result.output + assert seen == [Path("-")] + + # ensure an existing file still passes + result = runner.invoke(app, [str(existing)]) + assert result.exit_code == 0, result.output + assert seen == [Path("-"), existing] + + # ensure a missing file still errors + result = runner.invoke(app, [str(tmp_path / "missing.txt")]) + assert result.exit_code == 2 + + def test_coercion_tuple_files(tmp_path: Path) -> None: first = tmp_path / "first.txt" second = tmp_path / "second.txt" diff --git a/typer/_param_types.py b/typer/_param_types.py index 3f6b190a80..356e0c7528 100644 --- a/typer/_param_types.py +++ b/typer/_param_types.py @@ -241,7 +241,10 @@ def coerce_cli_path( raise BadParameter(get_error_msg(exc), ctx=ctx, param=param) from exc is_dash = ( - parameter_info.file_okay and parameter_info.allow_dash and rv in (b"-", "-") + parameter_info.file_okay + and parameter_info.allow_dash + # Use os.fspath() as rv may already have been coerced to a Path + and os.fspath(rv) in (b"-", "-") ) if not is_dash: