diff --git a/src/click/utils.py b/src/click/utils.py index 467b7b677..8283788ac 100644 --- a/src/click/utils.py +++ b/src/click/utils.py @@ -475,7 +475,7 @@ def __getattr__(self, attr: str) -> t.Any: def _detect_program_name( - path: t.Optional[str] = None, _main: ModuleType = sys.modules["__main__"] + path: t.Optional[str] = None, _main: t.Optional[ModuleType] = None ) -> str: """Determine the command used to run the program, for use in help text. If a file or entry point was executed, the file name is @@ -497,6 +497,9 @@ def _detect_program_name( :meta private: """ + if _main is None: + _main = sys.modules["__main__"] + if not path: path = sys.argv[0] diff --git a/tests/test_utils.py b/tests/test_utils.py index 7ef7fa5ee..5dfeb0223 100644 --- a/tests/test_utils.py +++ b/tests/test_utils.py @@ -444,20 +444,12 @@ def __init__(self, package_name): ("example.py", None, "example.py"), (str(pathlib.Path("/foo/bar/example.py")), None, "example.py"), ("example", None, "example"), - ( - str(pathlib.Path("example/__main__.py")), - MockMain(".example"), - "python -m example", - ), - ( - str(pathlib.Path("example/cli.py")), - MockMain(".example"), - "python -m example.cli", - ), + (str(pathlib.Path("example/__main__.py")), "example", "python -m example"), + (str(pathlib.Path("example/cli.py")), "example", "python -m example.cli"), ], ) def test_detect_program_name(path, main, expected): - assert click.utils._detect_program_name(path, _main=main) == expected + assert click.utils._detect_program_name(path, _main=MockMain(main)) == expected def test_expand_args(monkeypatch):