diff --git a/CHANGELOG.md b/CHANGELOG.md index e8f30f407..84e3d98f3 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,6 +7,8 @@ - Tab completion now works when a `choices_provider` or `completer` is a module-level lambda. `get_defining_class()` also handles functions whose module cannot be found and unbound methods of nested classes without raising `AttributeError`. + - Unbound completers defined on a nested `CommandSet` now receive the registered command set as + `self`. Previously, they received the application, which could cause tab completion to fail. - `history /` and `History.regex_search("/")` now return only history entries containing a forward slash. Previously, a lone slash was treated as an empty regex and matched every entry. - Macros now expand `{1}` correctly when it is followed by an escaped `{{1}}`. For example, diff --git a/cmd2/annotated.py b/cmd2/annotated.py index 1f9f82dee..3b85891e7 100644 --- a/cmd2/annotated.py +++ b/cmd2/annotated.py @@ -301,6 +301,7 @@ def do_build(self, target: str, common: CommonArgs): ArgparseCommandSpec, Cmd2ArgumentParser, SubcommandSpec, + _registered_in_enclosing_factory, ) from .completion import CompletionItem from .decorators import _parse_positionals @@ -3087,6 +3088,7 @@ def with_annotated( "Configure these behaviors on the base command instead." ) + inline_ns_provider = _registered_in_enclosing_factory(ns_provider) options = _ParserBuildOptions( groups=groups, mutually_exclusive_groups=mutually_exclusive_groups, @@ -3167,7 +3169,7 @@ def cmd_wrapper(*args: Any, **kwargs: Any) -> _CommandReturn: if ns_provider is None: namespace = None else: - provider_self = cmd_app._resolve_func_self(ns_provider, args[0]) + provider_self = cmd_app._resolve_func_self(ns_provider, owner, include_enclosing_class=inline_ns_provider) namespace = ns_provider(provider_self if provider_self is not None else cmd_app) try: diff --git a/cmd2/argparse_completer.py b/cmd2/argparse_completer.py index 7644acaf1..95f557a10 100644 --- a/cmd2/argparse_completer.py +++ b/cmd2/argparse_completer.py @@ -23,6 +23,8 @@ from rich.text import Text from .argparse_utils import ( + _CHOICES_PROVIDER_SOURCE, + _COMPLETER_SOURCE, Cmd2ArgumentParser, build_range_error, ) @@ -31,7 +33,10 @@ CompletionItem, Completions, ) -from .constants import INFINITY +from .constants import ( + INFINITY, + PARSER_ATTR_OWNER_ID, +) from .exceptions import CompletionError from .rich_utils import Cmd2SimpleTable from .types import ( @@ -366,6 +371,12 @@ def consume_argument(arg_state: _ArgumentState, arg_token: str) -> None: parent_tokens[action.dest] = [token] parser = self._subcommand_action.choices[token] + # An attached subcommand may belong to a different set or to the app itself. + owner_id = getattr(parser, PARSER_ATTR_OWNER_ID, None) + if owner_id is not None: + cmd_set = next( + (owner for owner in self._cmd_app._installed_command_sets if id(owner) == owner_id), None + ) completer = parser.completer_class(parser, self._cmd_app, parent_tokens=parent_tokens) return completer.complete(text, line, begidx, endidx, tokens[token_index + 1 :], cmd_set=cmd_set) @@ -719,6 +730,7 @@ def _choices_to_items(self, arg_state: _ArgumentState) -> list[CompletionItem]: def _prepare_callable_params( self, to_call: UnboundChoicesProvider[CmdOrSetT] | UnboundCompleter[CmdOrSetT], + source_attr: str, arg_state: _ArgumentState, text: str, consumed_arg_values: dict[str, list[str]], @@ -729,7 +741,14 @@ def _prepare_callable_params( kwargs: dict[str, Any] = {} # Resolve the 'self' instance for the method - self_arg = self._cmd_app._resolve_func_self(to_call, cmd_set) + source_ref = getattr(arg_state.action, source_attr, None) + original = source_ref() if source_ref is not None else None + receiver = self._cmd_app if cmd_set is None else cmd_set + self_arg = self._cmd_app._resolve_func_self( + original if original is not None else to_call, + receiver, + include_enclosing_class=getattr(arg_state.action, f"{source_attr}.inline", False), + ) if self_arg is None: raise CompletionError("Could not find CommandSet instance matching defining type") @@ -765,6 +784,7 @@ def _complete_arg( if completer is not None: args, kwargs = self._prepare_callable_params( completer, + _COMPLETER_SOURCE, arg_state, text, consumed_arg_values, @@ -779,6 +799,7 @@ def _complete_arg( if choices_provider is not None: args, kwargs = self._prepare_callable_params( choices_provider, + _CHOICES_PROVIDER_SOURCE, arg_state, text, consumed_arg_values, diff --git a/cmd2/argparse_utils.py b/cmd2/argparse_utils.py index cee16a398..b21c87fa4 100644 --- a/cmd2/argparse_utils.py +++ b/cmd2/argparse_utils.py @@ -226,9 +226,12 @@ def get_choices(self) -> Choices: import argparse import contextlib +import functools +import inspect import re import sys import threading +import weakref from argparse import ArgumentError from collections.abc import ( Callable, @@ -425,7 +428,35 @@ def _action_set_custom_parameter(self: argparse.Action, value: Any) -> None: _CUSTOM_ACTION_ATTRIBS.add(param_name) -def _validate_completion_callable(self: argparse.Action, value: Any) -> Any: +class _CompletionSource(weakref.ref[functools.partial[Any]]): + """Track a partial's live class identity across parser copies.""" + + def __deepcopy__(self, memo: dict[int, Any]) -> "_CompletionSource": + return self + + def __reduce__(self) -> tuple[type, tuple[()]]: + # Ownership belongs to classes in this process. A deserialized action resolves its own callback. + return type(None), () + + +def _registered_in_enclosing_factory(callback: Callable[..., Any] | None) -> bool: + """Check at registration whether a local callback's enclosing factory is active.""" + while isinstance(callback, functools.partial): + callback = callback.func + if not inspect.isfunction(callback): + return False + factory, local_scope, _ = callback.__qualname__.partition("..") + if local_scope: + # Helpers and public action setters may sit between the factory and registration. + frame = sys._getframe().f_back + while frame is not None: + if frame.f_globals is callback.__globals__ and frame.f_code.co_qualname == factory: + return True + frame = frame.f_back + return False + + +def _validate_completion_callable(self: argparse.Action, value: Any, *, source_attr: str) -> Any: """Validate choices_provider and completer values for potential conflicts.""" if value is None: return None @@ -438,13 +469,24 @@ def _validate_completion_callable(self: argparse.Action, value: Any) -> Any: "None of the following parameters can be used on an action that takes no arguments:\nchoices_provider, completer" ) raise ValueError(err_msg) + # deepcopy creates a new partial (and copies its bound arguments). Keep the + # original identity for receiver lookup while invoking the parser's own copy. + setattr(self, source_attr, _CompletionSource(value) if isinstance(value, functools.partial) else None) + setattr(self, f"{source_attr}.inline", _registered_in_enclosing_factory(value)) return value # Add new attributes to argparse.Action. # See _ActionsContainer_add_argument() for details on these attributes. -register_argparse_argument_parameter("choices_provider", validator=_validate_completion_callable) -register_argparse_argument_parameter("completer", validator=_validate_completion_callable) +# Custom parameter names must be Python identifiers, so they cannot collide with these dotted names. +_CHOICES_PROVIDER_SOURCE = constants.cmd2_private_attr_name("choices_provider.source") +_COMPLETER_SOURCE = constants.cmd2_private_attr_name("completer.source") +register_argparse_argument_parameter( + "choices_provider", validator=functools.partial(_validate_completion_callable, source_attr=_CHOICES_PROVIDER_SOURCE) +) +register_argparse_argument_parameter( + "completer", validator=functools.partial(_validate_completion_callable, source_attr=_COMPLETER_SOURCE) +) register_argparse_argument_parameter("table_columns") register_argparse_argument_parameter("nargs_range") register_argparse_argument_parameter("suppress_tab_hint") diff --git a/cmd2/cmd2.py b/cmd2/cmd2.py index 27ad738e6..adddf2437 100644 --- a/cmd2/cmd2.py +++ b/cmd2/cmd2.py @@ -215,6 +215,7 @@ def __init__(self, msg: str = "") -> None: ) from .utils import ( Settable, + _get_defining_classes, get_defining_class, get_types, strip_doc_annotations, @@ -6584,6 +6585,8 @@ def _resolve_func_self( self, cmd_support_func: Callable[..., Any], cmd_self: CmdOrSet | None, + *, + include_enclosing_class: bool = False, ) -> object | None: """Attempt to resolve a candidate instance to pass as 'self'. @@ -6594,40 +6597,22 @@ def _resolve_func_self( :param cmd_support_func: command support function. This could be a completer or namespace provider :param cmd_self: The `self` associated with the command or subcommand + :param include_enclosing_class: whether the enclosing factory registered this callback """ - # figure out what class the command support function was defined in - func_class: type[Any] | None = get_defining_class(cmd_support_func) - - # Was there a defining class identified? If so, is it a sub-class of CommandSet? - if func_class is not None and issubclass(func_class, CommandSet): - # Since the support function is provided as an unbound function, we need to locate the instance - # of the CommandSet to pass in as `self` to emulate a bound method call. - # We're searching for candidates that match the support function's defining class type in this order: - # 1. Is the command's CommandSet a sub-class of the support function's class? - # 2. Do any of the registered CommandSets in the Cmd2 application exactly match the type? - # 3. Is there a registered CommandSet that is is the only matching subclass? - - func_self: CmdOrSet | None - - # check if the command's CommandSet is a sub-class of the support function's defining class - if isinstance(cmd_self, func_class): - # Case 1: Command's CommandSet is a sub-class of the support function's CommandSet - func_self = cmd_self - else: - # Search all registered CommandSets - func_self = None - candidate_sets: list[CommandSet[Any]] = [] - for installed_cmd_set in self._installed_command_sets: - if type(installed_cmd_set) == func_class: # noqa: E721 - # Case 2: CommandSet is an exact type match for the function's CommandSet - func_self = installed_cmd_set - break - - # Add candidate for Case 3: - if isinstance(installed_cmd_set, func_class): - candidate_sets.append(installed_cmd_set) - if func_self is None and len(candidate_sets) == 1: - # Case 3: There exists exactly 1 CommandSet that is a sub-class match of the function's CommandSet - func_self = candidate_sets[0] - return func_self - return self + owners = _get_defining_classes(cmd_support_func, include_enclosing_class=include_enclosing_class) + owner_ids = {id(owner) for owner in owners} + + def matches_owner(receiver: object) -> bool: + # A provider may be defined on a Protocol that disallows runtime instance checks. + return any(id(base) in owner_ids for base in type(receiver).__mro__) + + if cmd_self is not None and matches_owner(cmd_self): + return cmd_self + if not any(issubclass(owner, CommandSet) for owner in owners): + return self + + # Include the app among live owners and prefer an exact owner over an inheriting instance. + matches = [receiver for receiver in (self, *self._installed_command_sets) if matches_owner(receiver)] + exact = [receiver for receiver in matches if id(type(receiver)) in owner_ids] + candidates = exact or matches + return candidates[0] if len(candidates) == 1 else None diff --git a/cmd2/decorators.py b/cmd2/decorators.py index b3167e499..ba12ab377 100644 --- a/cmd2/decorators.py +++ b/cmd2/decorators.py @@ -23,6 +23,7 @@ NoParamParserFactory, ParserSource, SubcommandSpec, + _registered_in_enclosing_factory, ) from .command_set import CommandSet from .exceptions import Cmd2ArgparseError @@ -301,6 +302,7 @@ def do_argprint(self, args: argparse.Namespace, unknown_args: list[str]): ``` """ + inline_ns_provider = _registered_in_enclosing_factory(ns_provider) def arg_decorator(func: ArgparseCommandFunc[CmdOrSetT]) -> RawCommandFunc[CmdOrSetT]: """Decorate function that ingests an Argparse Command Function and returns a raw command function. @@ -339,7 +341,7 @@ def cmd_wrapper(*args: Any, **kwargs: Any) -> bool | None: # The namespace provider may or may not be defined in the same class as the command. Since provider # functions are registered with the command argparser before anything is instantiated, we # need to find an instance at runtime that matches the types during declaration - provider_self = cmd_app._resolve_func_self(ns_provider, args[0]) + provider_self = cmd_app._resolve_func_self(ns_provider, args[0], include_enclosing_class=inline_ns_provider) initial_namespace = ns_provider(provider_self if provider_self is not None else cmd_app) try: diff --git a/cmd2/utils.py b/cmd2/utils.py index da1212a58..50622633a 100644 --- a/cmd2/utils.py +++ b/cmd2/utils.py @@ -26,7 +26,6 @@ TextIO, TypeVar, Union, - cast, ) from rich.text import Text @@ -1570,6 +1569,25 @@ def do_echo(self, arglist): setattr(cur_func, constants.COMMAND_ATTR_HELP_CATEGORY, category) +def _factory_method_owners(factory_class: type[Any], callback: Callable[..., Any]) -> tuple[type, ...]: + """Find each class in the factory's hierarchy that installed this callback.""" + pending = [factory_class] + visited: set[int] = set() + owners: list[type] = [] + while pending: + cls = pending.pop() + if id(cls) in visited: + continue + visited.add(id(cls)) + for member in vars(cls).values(): + target = member.__func__ if isinstance(member, (staticmethod, classmethod)) else member + if target is callback: + owners.append(cls) + break + pending.extend(type.__subclasses__(cls)) + return tuple(owners) + + def get_defining_class(meth: Callable[..., Any]) -> type[Any] | None: """Attempt to resolve the class that defined a method. @@ -1577,23 +1595,46 @@ def get_defining_class(meth: Callable[..., Any]) -> type[Any] | None: https://stackoverflow.com/a/25959545/1956611 :param meth: method to inspect - :return: class type in which the supplied method was defined. None if it couldn't be resolved. + :return: class type in which the supplied method was defined. None if it couldn't be uniquely resolved. """ - if isinstance(meth, functools.partial): - return get_defining_class(meth.func) + owners = _get_defining_classes(meth) + return owners[0] if len(owners) == 1 else None + + +def _get_defining_classes(meth: Callable[..., Any], *, include_enclosing_class: bool = False) -> tuple[type, ...]: + """Resolve method ownership, including factory callbacks installed on several classes.""" + original = meth + while isinstance(meth, functools.partial): + meth = meth.func if inspect.ismethod(meth) or ( inspect.isbuiltin(meth) and hasattr(meth, "__self__") and hasattr(meth.__self__, "__class__") ): for cls in inspect.getmro(meth.__self__.__class__): if meth.__name__ in cls.__dict__: - return cls + return (cls,) meth = getattr(meth, "__func__", meth) # fallback to __qualname__ parsing if inspect.isfunction(meth): - # The name isn't necessarily in the module, as with a module-level lambda whose __qualname__ is "" - owner = getattr(inspect.getmodule(meth), meth.__qualname__.split(".", 1)[0].rsplit(".", 1)[0], None) + # For a local function, the reachable path ends at its enclosing factory. + reachable_name, local_scope, _ = meth.__qualname__.partition("..") + owner: object = inspect.getmodule(meth) + for name in reachable_name.split(".")[:-1]: + if owner is None: + break + owner = getattr(owner, name, None) if isinstance(owner, type): - return owner - return cast(type, getattr(meth, "__objclass__", None)) # handle special descriptor objects + if not local_scope: + return (owner,) + owners = _factory_method_owners(owner, original) + if not owners and original is not meth: + # A partial of an installed method inherits that method's owner. + owners = _factory_method_owners(owner, meth) + if owners: + return owners + if include_enclosing_class: + # A class's factory registered its own local callback. + return (owner,) + descriptor_owner = getattr(meth, "__objclass__", None) + return (descriptor_owner,) if descriptor_owner is not None else () class CustomCompletionSettings: diff --git a/tests/test_argparse_utils.py b/tests/test_argparse_utils.py index 0bed9a979..bfa686c44 100644 --- a/tests/test_argparse_utils.py +++ b/tests/test_argparse_utils.py @@ -1,6 +1,8 @@ """Unit/functional testing for argparse customizations in cmd2""" import argparse +import functools +import pickle import sys import pytest @@ -335,6 +337,41 @@ def test_register_argparse_argument_parameter() -> None: delattr(argparse.Action, attr_name) +def _palette_callback(receiver, *args, color): + return cmd2.Completions.from_values([color]) + + +@pytest.mark.parametrize("parameter", ["completer", "choices_provider"]) +def test_custom_callback_source_parameter(parameter) -> None: + source = f"{parameter}_source" + register_argparse_argument_parameter(source) + try: + parser = Cmd2ArgumentParser() + callback = functools.partial(_palette_callback, color="purple") + action = parser.add_argument("color", **{parameter: callback, source: "custom"}) + + class App(cmd2.Cmd): + @cmd2.with_argparser(parser) + def do_palette(self, ns: argparse.Namespace) -> None: + pass + + app = App(auto_load_commands=False) + line = "palette " + assert app.complete("", line, len(line), len(line)).to_strings() == ("purple",) + assert getattr(action, f"get_{source}")() == "custom" + finally: + argparse_utils._CUSTOM_ACTION_ATTRIBS.remove(source) + delattr(argparse.Action, f"get_{source}") + delattr(argparse.Action, f"set_{source}") + + +def test_pickle_action_with_partial_provider() -> None: + action = argparse.Action(option_strings=[], dest="color") + action.set_choices_provider(functools.partial(_palette_callback, color="purple")) + restored = pickle.loads(pickle.dumps(action)) + assert restored.get_choices_provider()(None).to_strings() == ("purple",) + + def test_subcommand_attachment() -> None: """Test Cmd2ArgumentParser convenience methods for attaching and detaching subcommands.""" diff --git a/tests/test_commandset.py b/tests/test_commandset.py index 0f6f1747e..5a6fcf800 100644 --- a/tests/test_commandset.py +++ b/tests/test_commandset.py @@ -1,7 +1,9 @@ """Test CommandSet""" import argparse +import functools import signal +from typing import Protocol import pytest @@ -754,6 +756,265 @@ def test_static_subcommands(static_subcommands_app) -> None: assert completions.to_strings() == Completions.from_values(["diced", "quartered"]).to_strings() +class ColorPlugin: + class Commands(cmd2.CommandSet): + def __init__(self, colors: list[str]) -> None: + super().__init__() + self.colors = colors + + def complete_color(self, text: str, line: str, begidx: int, endidx: int) -> Completions: + return self._cmd.basic_complete(text, line, begidx, endidx, self.colors) + + @staticmethod + def make_color_choices(): + return lambda receiver, *, key="colors", limit=None: Completions.from_values(getattr(receiver, key)[:limit]) + + color_choices = make_color_choices() + first_color = functools.partial(make_color_choices(), limit=1) + paint_parser = cmd2.Cmd2ArgumentParser() + paint_parser.add_argument("color", completer=complete_color) + paint_parser.add_argument("--accent", choices_provider=color_choices) + paint_parser.add_argument("--first", choices_provider=first_color) + paint_parser.add_argument("--app", choices_provider=functools.partial(first_color.func, key="app_colors")) + + @cmd2.with_argparser(paint_parser) + def do_paint(self, ns: argparse.Namespace) -> None: + self._cmd.poutput(ns.color) + + +def test_nested_command_set_completer(manual_command_sets_app) -> None: + manual_command_sets_app.register_command_set(ColorPlugin.Commands(["blue", "green"])) + line = "paint " + completions = manual_command_sets_app.complete("", line, len(line), len(line)) + assert completions.to_strings() == ("blue", "green") + + +@pytest.mark.parametrize(("option", "expected"), [("--accent", ("blue", "green")), ("--first", ("blue",))]) +def test_nested_command_set_factory_choices_provider(manual_command_sets_app, option, expected) -> None: + manual_command_sets_app.register_command_set(ColorPlugin.Commands(["blue", "green"])) + line = f"paint blue {option} " + completions = manual_command_sets_app.complete("", line, len(line), len(line)) + assert completions.to_strings() == expected + + +class PaletteCommands(ColorPlugin.Commands): + palette_choices = ColorPlugin.Commands.make_color_choices() + palette_parser = cmd2.Cmd2ArgumentParser() + palette_parser.add_argument("color", choices_provider=palette_choices) + + @cmd2.with_argparser(palette_parser) + def do_palette(self, ns: argparse.Namespace) -> None: + self._cmd.poutput(ns.color) + + +def test_subclass_installed_factory_choices_provider(manual_command_sets_app) -> None: + manual_command_sets_app.register_command_set(PaletteCommands(["red", "yellow"])) + line = "palette " + completions = manual_command_sets_app.complete("", line, len(line), len(line)) + assert completions.to_strings() == ("red", "yellow") + + +def test_standalone_partial_of_factory_provider(manual_command_sets_app) -> None: + manual_command_sets_app.app_colors = ["purple"] + manual_command_sets_app.register_command_set(ColorPlugin.Commands(["blue", "green"])) + line = "paint blue --app " + completions = manual_command_sets_app.complete("", line, len(line), len(line)) + assert completions.to_strings() == ("purple",) + + +class SharedChoiceFactory: + @staticmethod + def make_choices(): + return lambda receiver: Completions.from_values(receiver.colors) + + +shared_choices = SharedChoiceFactory.make_choices() + + +class WarmPalette(SharedChoiceFactory, cmd2.CommandSet): + choices = shared_choices + + def __init__(self, colors: list[str]) -> None: + super().__init__() + self.colors = colors + + parser = cmd2.Cmd2ArgumentParser() + parser.add_argument("color", choices_provider=choices) + + @cmd2.with_argparser(parser) + def do_warm(self, ns: argparse.Namespace) -> None: + self._cmd.poutput(ns.color) + + +class CoolPalette(SharedChoiceFactory, cmd2.CommandSet): + choices = shared_choices + + def __init__(self, colors: list[str]) -> None: + super().__init__() + self.colors = colors + + +def test_shared_factory_callback_receivers(manual_command_sets_app) -> None: + app = manual_command_sets_app + warm = WarmPalette(["red"]) + cool = CoolPalette(["blue"]) + app.register_command_set(warm) + line = "warm " + assert app.complete("", line, len(line), len(line)).to_strings() == ("red",) + assert app._resolve_func_self(shared_choices, app) is warm + + app.register_command_set(cool) + assert app._resolve_func_self(shared_choices, warm) is warm + assert app._resolve_func_self(shared_choices, cool) is cool + assert app._resolve_func_self(shared_choices, app) is None + + +class PaletteApp(SharedChoiceFactory, cmd2.Cmd): + choices = shared_choices + colors = ("purple",) + + @cmd2.with_argparser(WarmPalette.parser) + def do_palette(self, ns: argparse.Namespace) -> None: + self.poutput(ns.color) + + +def _add_color_option(parser, provider) -> None: + parser.add_argument("--helper", choices_provider=provider) + + +class ParserFactoryPalette(cmd2.CommandSet): + def __init__(self, colors) -> None: + super().__init__() + self.colors = colors + + @staticmethod + def build_parser(): + parser = cmd2.Cmd2ArgumentParser() + parser.add_argument("color", choices_provider=lambda receiver: Completions.from_values(receiver.colors)) + parser.add_argument("--setter").set_choices_provider(lambda receiver: Completions.from_values(receiver.colors)) + parser.add_argument("--completer").set_completer(lambda receiver, *args: Completions.from_values(receiver.colors)) + _add_color_option(parser, lambda receiver: Completions.from_values(receiver.colors)) + return parser + + @cmd2.with_argparser(build_parser) + def do_factory_palette(self, ns: argparse.Namespace) -> None: + pass + + @cmd2.with_argparser(build_parser()) + def do_prebuilt_palette(self, ns: argparse.Namespace) -> None: + pass + + @staticmethod + def command_with_colors(annotated=False): + def namespace(receiver): + return argparse.Namespace(color=receiver.colors[0]) + + if annotated: + return cmd2.with_annotated(ns_provider=namespace) + return cmd2.with_argparser(cmd2.Cmd2ArgumentParser(), ns_provider=namespace) + + @command_with_colors() + def do_namespace_palette(self, ns: argparse.Namespace) -> None: + self._cmd.poutput(ns.color) + + @command_with_colors(annotated=True) + def do_annotated_palette(self, color: str = "default") -> None: + self._cmd.poutput(color) + + +@pytest.mark.parametrize("command", ["factory_palette", "prebuilt_palette"]) +@pytest.mark.parametrize("option", ["", "value --setter ", "value --helper ", "value --completer "]) +def test_inline_parser_factory_provider(command, option) -> None: + app = PaletteApp(command_sets=[ParserFactoryPalette(["green"])], auto_load_commands=False) + line = f"{command} {option}" + assert app.complete("", line, len(line), len(line)).to_strings() == ("green",) + + +@pytest.mark.parametrize("command", ["namespace_palette", "annotated_palette"]) +def test_inline_namespace_provider(command) -> None: + app = PaletteApp(command_sets=[ParserFactoryPalette(["green"])], auto_load_commands=False) + assert run_cmd(app, command) == (["green"], []) + + +class ProtocolPalette(Protocol): + colors: tuple[str, ...] + + def choices(self) -> Completions: + return Completions.from_values(self.colors) + + +class BorrowedPalette(cmd2.CommandSet): + def __init__(self, colors) -> None: + super().__init__() + self.colors = colors + + parser = cmd2.Cmd2ArgumentParser() + parser.add_argument("--shared", choices_provider=shared_choices) + parser.add_argument("--protocol", choices_provider=ProtocolPalette.choices) + + @cmd2.with_argparser(parser) + def do_borrow(self, ns: argparse.Namespace) -> None: + pass + + +@pytest.mark.parametrize("option", ["--shared", "--protocol"]) +def test_unrelated_command_uses_app_provider(option) -> None: + app = PaletteApp(command_sets=[BorrowedPalette(["green"])], auto_load_commands=False) + line = f"borrow {option} " + assert app.complete("", line, len(line), len(line)).to_strings() == ("purple",) + + +def test_unrelated_command_with_two_live_owners_is_ambiguous() -> None: + app = PaletteApp(command_sets=[BorrowedPalette(["green"]), WarmPalette(["red"])], auto_load_commands=False) + line = "borrow --shared " + completions = app.complete("", line, len(line), len(line)) + assert not completions + assert "Could not find CommandSet instance" in completions.error + + +@pytest.mark.parametrize("sets", [[], [WarmPalette(["red"])]]) +def test_app_owns_shared_choices(sets) -> None: + app = PaletteApp(command_sets=sets, auto_load_commands=False) + line = "palette " + assert app.complete("", line, len(line), len(line)).to_strings() == ("purple",) + + +def test_attached_subcommand_owns_shared_choices() -> None: + class Parent(WarmPalette): + group_parser = cmd2.Cmd2ArgumentParser() + group_parser.add_subparsers() + + @cmd2.with_argparser(group_parser) + def do_group(self, ns: argparse.Namespace) -> None: + pass + + class Child(CoolPalette): + @cmd2.as_subcommand_to("group", "child", WarmPalette.parser) + def child(self, ns: argparse.Namespace) -> None: + pass + + @cmd2.as_subcommand_to("app_group", "child", WarmPalette.parser) + def child_of_app(self, ns: argparse.Namespace) -> None: + pass + + class App(PaletteApp): + @cmd2.with_argparser(Parent.group_parser) + def do_app_group(self, ns: argparse.Namespace) -> None: + pass + + @cmd2.as_subcommand_to("app_group", "app_child", WarmPalette.parser) + def app_child(self, ns: argparse.Namespace) -> None: + pass + + app = App(command_sets=[Parent(["red"]), Child(["blue"])], auto_load_commands=False) + line = "group child " + assert app.complete("", line, len(line), len(line)).to_strings() == ("blue",) + line = "app_group child " + assert app.complete("", line, len(line), len(line)).to_strings() == ("blue",) + line = "app_group app_child " + assert app.complete("", line, len(line), len(line)).to_strings() == ("purple",) + + complete_states_expected_self = None diff --git a/tests/test_utils_defining_class.py b/tests/test_utils_defining_class.py index 4f0de6387..b0d72471c 100644 --- a/tests/test_utils_defining_class.py +++ b/tests/test_utils_defining_class.py @@ -89,3 +89,85 @@ def test_get_defining_class_module_level_lambda() -> None: # A module-level lambda's __qualname__ is "", which isn't an attribute of its module assert cu.get_defining_class(module_level_lambda) is None assert cu.get_defining_class(functools.partial(module_level_lambda)) is None + + +class Outer: + class Inner(ParentClass): + def method(self) -> None: + pass + + @staticmethod + def make_choices(): + return lambda app: app.get_all_commands() + + static_choices = staticmethod(make_choices()) + class_choices = classmethod(make_choices()) + partial_choices = functools.partial(make_choices()) + + +def test_get_defining_class_nested_class() -> None: + assert cu.get_defining_class(Outer.Inner.method) is Outer.Inner + assert cu.get_defining_class(functools.partial(Outer.Inner.method)) is Outer.Inner + assert cu.get_defining_class(Outer.Inner.parent_only_func) is ParentClass + + +def test_get_defining_class_factory_callback() -> None: + assert cu.get_defining_class(Outer.Inner.make_choices()) is None + assert cu.get_defining_class(Outer.Inner.static_choices) is Outer.Inner + assert cu.get_defining_class(Outer.Inner.class_choices) is Outer.Inner + assert cu.get_defining_class(Outer.Inner.partial_choices) is Outer.Inner + assert cu.get_defining_class(Outer.Inner.partial_choices.func) is None + assert cu.get_defining_class(functools.partial(Outer.Inner.partial_choices.func, "other")) is None + + +def test_get_defining_class_nested_class_in_unknown_module(monkeypatch) -> None: + monkeypatch.setattr(Outer.Inner.method, "__module__", "missing_cmd2_test_module") + assert cu.get_defining_class(Outer.Inner.method) is None + + +def test_factory_lookup_through_unhashable_diamond() -> None: + class UnhashableMeta(type): + __hash__ = None + + class Left(Outer.Inner): + pass + + class Right(Outer.Inner): + pass + + class Diamond(Left, Right, metaclass=UnhashableMeta): + choices = Outer.Inner.make_choices() + + assert cu.get_defining_class(Diamond.choices) is Diamond + assert cu.get_defining_class(Outer.Inner.make_choices()) is None + + +def test_factory_lookup_without_receiver_requires_unique_owner() -> None: + choices = Outer.Inner.make_choices() + + class First(Outer.Inner): + provider = choices + + class Second(Outer.Inner): + provider = choices + + assert cu.get_defining_class(First.provider) is None + assert cu.get_defining_class(Second.provider) is None + + +def test_installed_partial_has_its_own_owner() -> None: + callback = Outer.Inner.make_choices() + + class Raw(Outer.Inner): + choices = callback + + class Wrapped(Outer.Inner): + choices = functools.partial(callback) + + assert cu.get_defining_class(Raw.choices) is Raw + assert cu.get_defining_class(Wrapped.choices) is Wrapped + assert cu.get_defining_class(functools.partial(Raw.choices)) is Raw + + +def test_get_defining_class_descriptor_fallback() -> None: + assert cu.get_defining_class(str.join) is str