From 810644614022d8835b7d78d1afe074387605e1a3 Mon Sep 17 00:00:00 2001 From: Adrian Garcia Badaracco <1755071+adriangb@users.noreply.github.com> Date: Wed, 16 Mar 2022 19:27:15 -0500 Subject: [PATCH 1/2] postpone referencing sys.modules["__main"] in click.utils._detect_program_name --- src/click/utils.py | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) 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] From 38e6174452ed161c3732a6948c31f7997452e405 Mon Sep 17 00:00:00 2001 From: David Lord Date: Thu, 17 Mar 2022 15:03:19 -0700 Subject: [PATCH 2/2] fix test_detect_program_name --- tests/test_utils.py | 14 +++----------- 1 file changed, 3 insertions(+), 11 deletions(-) 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):