-
Notifications
You must be signed in to change notification settings - Fork 124
Fixed AttributeError when loading CommandSet #980
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
Merged
Merged
Changes from all commits
Commits
Show all changes
5 commits
Select commit
Hold shift + click to select a range
30d010f
Fixed AttributeError when CommandSet that uses as_subcommand_to decor…
kmvanbrunt 9a20e7c
Added validation of subcommand handler attributes
anselor c622931
Updated documentation with more explicit discussions on testing
anselor dddf868
Minor formatting changes. Fixed some inaccurate comments
anselor 27b1093
Added tests for invalid subcommands
anselor File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -259,22 +259,6 @@ def __init__(self, completekey: str = 'tab', stdin=None, stdout=None, *, | |
multiline_commands=multiline_commands, | ||
shortcuts=shortcuts) | ||
|
||
# Load modular commands | ||
self._installed_command_sets = [] # type: List[CommandSet] | ||
self._cmd_to_command_sets = {} # type: Dict[str, CommandSet] | ||
if command_sets: | ||
for command_set in command_sets: | ||
self.register_command_set(command_set) | ||
|
||
if auto_load_commands: | ||
self._autoload_commands() | ||
|
||
# Verify commands don't have invalid names (like starting with a shortcut) | ||
for cur_cmd in self.get_all_commands(): | ||
valid, errmsg = self.statement_parser.is_valid_command(cur_cmd) | ||
if not valid: | ||
raise ValueError("Invalid command name {!r}: {}".format(cur_cmd, errmsg)) | ||
|
||
# Stores results from the last command run to enable usage of results in a Python script or interactive console | ||
# Built-in commands don't make use of this. It is purely there for user-defined commands and convenience. | ||
self.last_result = None | ||
|
@@ -412,6 +396,28 @@ def __init__(self, completekey: str = 'tab', stdin=None, stdout=None, *, | |
# If False, then complete() will sort the matches using self.default_sort_key before they are displayed. | ||
self.matches_sorted = False | ||
|
||
############################################################################################################ | ||
# The following code block loads CommandSets, verifies command names, and registers subcommands. | ||
# This block should appear after all attributes have been created since the registration code | ||
# depends on them and it's possible a module's on_register() method may need to access some. | ||
############################################################################################################ | ||
# Load modular commands | ||
self._installed_command_sets = [] # type: List[CommandSet] | ||
self._cmd_to_command_sets = {} # type: Dict[str, CommandSet] | ||
if command_sets: | ||
for command_set in command_sets: | ||
self.register_command_set(command_set) | ||
|
||
if auto_load_commands: | ||
self._autoload_commands() | ||
|
||
# Verify commands don't have invalid names (like starting with a shortcut) | ||
for cur_cmd in self.get_all_commands(): | ||
valid, errmsg = self.statement_parser.is_valid_command(cur_cmd) | ||
if not valid: | ||
raise ValueError("Invalid command name {!r}: {}".format(cur_cmd, errmsg)) | ||
|
||
# Add functions decorated to be subcommands | ||
self._register_subcommands(self) | ||
|
||
def find_commandsets(self, commandset_type: Type[CommandSet], *, subclass_match: bool = False) -> List[CommandSet]: | ||
|
@@ -631,10 +637,14 @@ def _register_subcommands(self, cmdset: Union[CommandSet, 'Cmd']) -> None: | |
|
||
# iterate through all matching methods | ||
for method_name, method in methods: | ||
subcommand_name = getattr(method, constants.SUBCMD_ATTR_NAME) | ||
subcommand_name = getattr(method, constants.SUBCMD_ATTR_NAME) # type: str | ||
full_command_name = getattr(method, constants.SUBCMD_ATTR_COMMAND) # type: str | ||
subcmd_parser = getattr(method, constants.CMD_ATTR_ARGPARSER) | ||
|
||
subcommand_valid, errmsg = self.statement_parser.is_valid_command(subcommand_name, is_subcommand=True) | ||
if not subcommand_valid: | ||
raise CommandSetRegistrationError('Subcommand {} is not valid: {}'.format(str(subcommand_name), errmsg)) | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Thanks for adding a better error message |
||
|
||
command_tokens = full_command_name.split() | ||
command_name = command_tokens[0] | ||
subcommand_names = command_tokens[1:] | ||
|
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,9 @@ | ||
cmd2_ext_test | ||
============= | ||
|
||
External Test Plugin | ||
|
||
|
||
.. autoclass:: cmd2_ext_test.ExternalTestMixin | ||
:members: | ||
|
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,46 @@ | ||
Testing | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Thanks for adding this section on testing! |
||
======= | ||
|
||
.. toctree:: | ||
:maxdepth: 1 | ||
|
||
Overview | ||
~~~~~~~~ | ||
|
||
This covers special considerations when writing unit tests for a cmd2 application. | ||
|
||
|
||
Testing Commands | ||
~~~~~~~~~~~~~~~~ | ||
|
||
The :doc:`External Test Plugin <plugins/external_test>` provides a mixin class with an :meth:`` function that | ||
allows external calls to application commands. The :meth:`~cmd2_ext_test.ExternalTestMixin.app_cmd()` function captures | ||
and returns stdout, stderr, and the command-specific result data. | ||
|
||
|
||
Mocking | ||
~~~~~~~ | ||
|
||
.. _python_mock_autospeccing: | ||
https://docs.python.org/3/library/unittest.mock.html#autospeccing | ||
.. _python_mock_patch: | ||
https://docs.python.org/3/library/unittest.mock.html#patch | ||
|
||
If you need to mock anything in your cmd2 application, and most specifically in sub-classes of :class:`~cmd2.Cmd` or | ||
:class:`~cmd2.command_definition.CommandSet`, you must use `Autospeccing <python_mock_autospeccing_>`_, | ||
`spec=True <python_mock_patch_>`_, or whatever equivalant is provided in the mocking library you're using. | ||
|
||
In order to automatically load functions as commands cmd2 performs a number of reflection calls to look up attributes | ||
of classes defined in your cmd2 application. Many mocking libraries will automatically create mock objects to match any | ||
attribute being requested, regardless of whether they're present in the object being mocked. This behavior can | ||
incorrectly instruct cmd2 to treat a function or attribute as something it needs to recognize and process. To prevent | ||
this, you should always mock with `Autospeccing <python_mock_autospeccing_>`_ or `spec=True <python_mock_patch_>`_ | ||
enabled. | ||
|
||
Example of spec=True | ||
==================== | ||
.. code-block:: python | ||
def test_mocked_methods(): | ||
with mock.patch.object(MockMethodApp, 'foo', spec=True): | ||
cli = MockMethodApp() |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.