File size: 13,742 Bytes
f50dbbb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
diff --git a/awscli/botocore/hooks.py b/awscli/botocore/hooks.py
index 90db67d6fe69..1530bbf158ee 100644
--- a/awscli/botocore/hooks.py
+++ b/awscli/botocore/hooks.py
@@ -196,7 +196,7 @@ def __init__(self):
         # read only access (we never modify self._handlers).
         # A cache of event name to handler list.
         self._lookup_cache = {}
-        self._handlers = _PrefixTrie()
+        self._handlers = PrefixTrie()
         # This is used to ensure that unique_id's are only
         # registered once.
         self._unique_id_handlers = {}
@@ -398,7 +398,7 @@ def __copy__(self):
         return new_instance
 
 
-class _PrefixTrie:
+class PrefixTrie:
     """Specialized prefix trie that handles wildcards.
 
     The prefixes in this case are based on dot separated
diff --git a/awscli/lazy.py b/awscli/lazy.py
new file mode 100644
index 000000000000..58eccd7df515
--- /dev/null
+++ b/awscli/lazy.py
@@ -0,0 +1,72 @@
+# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License"). You
+# may not use this file except in compliance with the License. A copy of
+# the License is located at
+#
+#     http://aws.amazon.com/apache2.0/
+#
+# or in the "license" file accompanying this file. This file is
+# distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF
+# ANY KIND, either express or implied. See the License for the specific
+# language governing permissions and limitations under the License.
+import importlib
+
+from awscli.commands import CLICommand
+
+
+class LazyCommand(CLICommand):
+    """A command-table entry that defers importing its real implementation.
+
+    Sits in the command table like any other CLICommand, but only imports
+    the actual module (and creates the real command object) when the command
+    is invoked or its help is accessed.
+    """
+
+    def __init__(self, name, session, module_path, class_name):
+        self._name = name
+        self._session = session
+        self._module_path = module_path
+        self._class_name = class_name
+        self._real = None
+        self._lineage = [self]
+
+    def _resolve(self):
+        if self._real is None:
+            mod = importlib.import_module(self._module_path)
+            cls = getattr(mod, self._class_name)
+            self._real = cls(self._session)
+            self._real.lineage = self._lineage
+        return self._real
+
+    def __call__(self, args, parsed_globals):
+        return self._resolve()(args, parsed_globals)
+
+    def create_help_command(self):
+        return self._resolve().create_help_command()
+
+    @property
+    def arg_table(self):
+        return self._resolve().arg_table
+
+    @property
+    def subcommand_table(self):
+        return self._resolve().subcommand_table
+
+    @property
+    def name(self):
+        return self._name
+
+    @name.setter
+    def name(self, value):
+        self._name = value
+
+    @property
+    def lineage(self):
+        return self._lineage
+
+    @lineage.setter
+    def lineage(self, value):
+        self._lineage = value
+        if self._real is not None:
+            self._real.lineage = value
diff --git a/tests/functional/test_lazy.py b/tests/functional/test_lazy.py
new file mode 100644
index 000000000000..fc8d33edd359
--- /dev/null
+++ b/tests/functional/test_lazy.py
@@ -0,0 +1,51 @@
+# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License"). You
+# may not use this file except in compliance with the License. A copy of
+# the License is located at
+#
+#     http://aws.amazon.com/apache2.0/
+#
+# or in the "license" file accompanying this file. This file is
+# distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF
+# ANY KIND, either express or implied. See the License for the specific
+# language governing permissions and limitations under the License.
+import pytest
+
+from awscli.lazy import LazyCommand
+from awscli.testutils import mock
+
+
+class TestLazyCommandErrorPaths:
+    def test_invalid_module_path_raises_on_resolve(self):
+        session = mock.MagicMock()
+        cmd = LazyCommand(
+            'bad-cmd',
+            session,
+            'awscli.nonexistent.module',
+            'FakeCommand',
+        )
+        with pytest.raises(ModuleNotFoundError):
+            cmd([], mock.MagicMock())
+
+    def test_invalid_class_name_raises_on_resolve(self):
+        session = mock.MagicMock()
+        cmd = LazyCommand(
+            'bad-cmd',
+            session,
+            'awscli.customizations.dynamodb.ddb',
+            'NonexistentClass',
+        )
+        with pytest.raises(AttributeError):
+            cmd([], mock.MagicMock())
+
+    def test_invalid_module_path_raises_on_help(self):
+        session = mock.MagicMock()
+        cmd = LazyCommand(
+            'bad-cmd',
+            session,
+            'awscli.nonexistent.module',
+            'FakeCommand',
+        )
+        with pytest.raises(ModuleNotFoundError):
+            cmd.create_help_command()
diff --git a/tests/unit/botocore/test_hooks.py b/tests/unit/botocore/test_hooks.py
index 23d9b4985d6c..b55e98bd1e77 100644
--- a/tests/unit/botocore/test_hooks.py
+++ b/tests/unit/botocore/test_hooks.py
@@ -14,7 +14,12 @@
 import functools
 from functools import partial
 
-from botocore.hooks import HierarchicalEmitter, first_non_none_response
+import pytest
+from botocore.hooks import (
+    HierarchicalEmitter,
+    PrefixTrie,
+    first_non_none_response,
+)
 
 from tests import unittest
 
@@ -584,5 +589,55 @@ def handler(a, b, **kwargs):
         )
 
 
+@pytest.fixture
+def trie():
+    return PrefixTrie()
+
+
+class TestPrefixTrie:
+    def test_append_and_prefix_search_exact_match(self, trie):
+        trie.append_item('building-command-table.main', 'handler1')
+        results = trie.prefix_search('building-command-table.main')
+        assert 'handler1' in results
+
+    def test_prefix_search_matches_parent(self, trie):
+        trie.append_item('building-command-table', 'handler1')
+        results = trie.prefix_search('building-command-table.main')
+        assert 'handler1' in results
+
+    def test_prefix_search_does_not_match_sibling(self, trie):
+        trie.append_item('building-command-table.ecs', 'handler1')
+        results = trie.prefix_search('building-command-table.main')
+        assert 'handler1' not in results
+
+    def test_prefix_search_does_not_match_child(self, trie):
+        trie.append_item('building-command-table.main.sub', 'handler1')
+        results = trie.prefix_search('building-command-table.main')
+        assert 'handler1' not in results
+
+    def test_wildcard_match(self, trie):
+        trie.append_item('building-command-table.*', 'handler1')
+        results = trie.prefix_search('building-command-table.main')
+        assert 'handler1' in results
+
+    def test_multiple_items_at_same_key(self, trie):
+        trie.append_item('building-command-table.main', 'handler1')
+        trie.append_item('building-command-table.main', 'handler2')
+        results = trie.prefix_search('building-command-table.main')
+        assert 'handler1' in results
+        assert 'handler2' in results
+
+    def test_multiple_levels_all_returned(self, trie):
+        trie.append_item('building-command-table', 'parent')
+        trie.append_item('building-command-table.main', 'exact')
+        results = trie.prefix_search('building-command-table.main')
+        assert 'parent' in results
+        assert 'exact' in results
+
+    def test_empty_trie_returns_empty(self, trie):
+        results = trie.prefix_search('building-command-table.main')
+        assert len(results) == 0
+
+
 if __name__ == '__main__':
     unittest.main()
diff --git a/tests/unit/test_lazy.py b/tests/unit/test_lazy.py
new file mode 100644
index 000000000000..63a1ff5ea44b
--- /dev/null
+++ b/tests/unit/test_lazy.py
@@ -0,0 +1,139 @@
+# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License"). You
+# may not use this file except in compliance with the License. A copy of
+# the License is located at
+#
+#     http://aws.amazon.com/apache2.0/
+#
+# or in the "license" file accompanying this file. This file is
+# distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF
+# ANY KIND, either express or implied. See the License for the specific
+# language governing permissions and limitations under the License.
+from unittest.mock import MagicMock, patch
+
+import pytest
+
+from awscli.lazy import LazyCommand
+
+
+@pytest.fixture
+def session():
+    return MagicMock()
+
+
+@pytest.fixture
+def mock_command_class():
+    cls = MagicMock()
+    instance = MagicMock()
+    cls.return_value = instance
+    return cls
+
+
+@pytest.fixture
+def mock_module(mock_command_class):
+    module = MagicMock()
+    module.MyCommand = mock_command_class
+    return module
+
+
+class TestLazyCommandResolution:
+    def test_does_not_import_on_construction(self, session):
+        with patch('importlib.import_module') as imp:
+            LazyCommand('cmd', session, 'some.module', 'MyCommand')
+        imp.assert_not_called()
+
+    def test_imports_module_on_call(self, session, mock_module):
+        cmd = LazyCommand('cmd', session, 'some.module', 'MyCommand')
+        with patch('importlib.import_module', return_value=mock_module):
+            cmd(['arg1'], MagicMock())
+        mock_module.MyCommand.assert_called_once_with(session)
+
+    def test_imports_module_on_help(self, session, mock_module):
+        cmd = LazyCommand('cmd', session, 'some.module', 'MyCommand')
+        with patch('importlib.import_module', return_value=mock_module):
+            cmd.create_help_command()
+        mock_module.MyCommand.assert_called_once_with(session)
+
+    def test_imports_module_on_arg_table(self, session, mock_module):
+        cmd = LazyCommand('cmd', session, 'some.module', 'MyCommand')
+        with patch('importlib.import_module', return_value=mock_module):
+            _ = cmd.arg_table
+        mock_module.MyCommand.assert_called_once_with(session)
+
+    def test_imports_module_on_subcommand_table(self, session, mock_module):
+        cmd = LazyCommand('cmd', session, 'some.module', 'MyCommand')
+        with patch('importlib.import_module', return_value=mock_module):
+            _ = cmd.subcommand_table
+        mock_module.MyCommand.assert_called_once_with(session)
+
+    def test_resolves_only_once(self, session, mock_module):
+        cmd = LazyCommand('cmd', session, 'some.module', 'MyCommand')
+        with patch('importlib.import_module', return_value=mock_module) as imp:
+            cmd(['arg1'], MagicMock())
+            cmd(['arg2'], MagicMock())
+        imp.assert_called_once_with('some.module')
+
+    def test_delegates_call_to_real_command(self, session, mock_module):
+        cmd = LazyCommand('cmd', session, 'some.module', 'MyCommand')
+        args = ['arg1']
+        parsed_globals = MagicMock()
+        with patch('importlib.import_module', return_value=mock_module):
+            cmd(args, parsed_globals)
+        mock_module.MyCommand.return_value.assert_called_once_with(
+            args, parsed_globals
+        )
+
+    def test_delegates_help_to_real_command(self, session, mock_module):
+        cmd = LazyCommand('cmd', session, 'some.module', 'MyCommand')
+        with patch('importlib.import_module', return_value=mock_module):
+            result = cmd.create_help_command()
+        assert (
+            result == mock_module.MyCommand.return_value.create_help_command()
+        )
+
+
+class TestLazyCommandProperties:
+    def test_name_returns_initial_name(self, session):
+        cmd = LazyCommand('my-cmd', session, 'some.module', 'MyCommand')
+        assert cmd.name == 'my-cmd'
+
+    def test_name_setter_updates_name(self, session):
+        cmd = LazyCommand('old-name', session, 'some.module', 'MyCommand')
+        cmd.name = 'new-name'
+        assert cmd.name == 'new-name'
+
+    def test_lineage_defaults_to_self(self, session):
+        cmd = LazyCommand('cmd', session, 'some.module', 'MyCommand')
+        assert cmd.lineage == [cmd]
+
+    def test_lineage_setter_updates_lineage(self, session):
+        cmd = LazyCommand('cmd', session, 'some.module', 'MyCommand')
+        new_lineage = [MagicMock(), cmd]
+        cmd.lineage = new_lineage
+        assert cmd.lineage == new_lineage
+
+    def test_lineage_propagated_to_real_on_resolve(self, session, mock_module):
+        cmd = LazyCommand('cmd', session, 'some.module', 'MyCommand')
+        new_lineage = [MagicMock(), cmd]
+        cmd.lineage = new_lineage
+        with patch('importlib.import_module', return_value=mock_module):
+            cmd.create_help_command()
+        assert mock_module.MyCommand.return_value.lineage == new_lineage
+
+    def test_lineage_setter_propagates_to_already_resolved(
+        self, session, mock_module
+    ):
+        cmd = LazyCommand('cmd', session, 'some.module', 'MyCommand')
+        with patch('importlib.import_module', return_value=mock_module):
+            cmd.create_help_command()
+        new_lineage = [MagicMock(), cmd]
+        cmd.lineage = new_lineage
+        assert mock_module.MyCommand.return_value.lineage == new_lineage
+
+    def test_lineage_not_propagated_if_not_resolved(self, session):
+        cmd = LazyCommand('cmd', session, 'some.module', 'MyCommand')
+        new_lineage = [MagicMock(), cmd]
+        # Should not raise even though underlying command is not resolved.
+        cmd.lineage = new_lineage
+        assert cmd.lineage == new_lineage