File: test_collection.py

package info (click to toggle)
python-boto3 1.26.27%2Bdfsg-1
  • links: PTS, VCS
  • area: main
  • in suites: bookworm
  • size: 7,880 kB
  • sloc: python: 12,629; makefile: 128
file content (635 lines) | stat: -rw-r--r-- 22,027 bytes parent folder | download | duplicates (2)
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
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
# Copyright 2014 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
#
# https://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 botocore.hooks import HierarchicalEmitter
from botocore.model import ServiceModel

from boto3.resources.base import ResourceMeta
from boto3.resources.collection import (
    CollectionFactory,
    CollectionManager,
    ResourceCollection,
)
from boto3.resources.factory import ResourceFactory
from boto3.resources.model import Collection
from boto3.utils import ServiceContext
from tests import BaseTestCase, mock


class TestCollectionFactory(BaseTestCase):
    def setUp(self):
        super().setUp()

        self.client = mock.Mock()
        self.client.can_paginate.return_value = False
        self.parent = mock.Mock()
        self.parent.meta = ResourceMeta('test', client=self.client)
        self.resource_factory = ResourceFactory(mock.Mock())
        self.service_model = ServiceModel({})
        self.event_emitter = HierarchicalEmitter()

        self.factory = CollectionFactory()
        self.load = self.factory.load_from_definition

    def test_create_subclasses(self):
        resource_defs = {
            'Frob': {},
            'Chain': {
                'hasMany': {
                    'Frobs': {
                        'request': {'operation': 'GetFrobs'},
                        'resource': {'type': 'Frob'},
                    }
                }
            },
        }
        collection_model = Collection(
            'Frobs', resource_defs['Chain']['hasMany']['Frobs'], resource_defs
        )

        service_context = ServiceContext(
            service_name='test',
            resource_json_definitions=resource_defs,
            service_model=self.service_model,
            service_waiter_model=None,
        )
        collection_cls = self.load(
            resource_name='Chain',
            collection_model=collection_model,
            service_context=service_context,
            event_emitter=self.event_emitter,
        )
        collection = collection_cls(
            collection_model=collection_model,
            parent=self.parent,
            factory=self.resource_factory,
            service_context=service_context,
        )

        assert collection_cls.__name__ == 'test.Chain.FrobsCollectionManager'
        assert isinstance(collection, CollectionManager)

        # Make sure that collection manager created from the factory
        # returns a ResourceCollection.
        assert isinstance(collection.all(), ResourceCollection)

        # Make sure that the collection returned from the collection
        # manager can be chained and return a ResourceCollection as well.
        assert isinstance(collection.all().all(), ResourceCollection)

    @mock.patch('boto3.resources.collection.BatchAction')
    def test_create_batch_actions(self, action_mock):
        resource_defs = {
            'Frob': {
                'batchActions': {
                    'Delete': {'request': {'operation': 'DeleteFrobs'}}
                }
            },
            'Chain': {
                'hasMany': {
                    'Frobs': {
                        'request': {'operation': 'GetFrobs'},
                        'resource': {'type': 'Frob'},
                    }
                }
            },
        }

        collection_model = Collection(
            'Frobs', resource_defs['Chain']['hasMany']['Frobs'], resource_defs
        )

        service_context = ServiceContext(
            service_name='test',
            resource_json_definitions=resource_defs,
            service_model=self.service_model,
            service_waiter_model=None,
        )
        collection_cls = self.load(
            resource_name='Chain',
            collection_model=collection_model,
            service_context=service_context,
            event_emitter=self.event_emitter,
        )
        collection = collection_cls(
            collection_model=collection_model,
            parent=self.parent,
            factory=self.resource_factory,
            service_context=service_context,
        )

        assert hasattr(collection, 'delete')

        collection.delete()

        action_mock.return_value.assert_called_with(collection)


class TestResourceCollection(BaseTestCase):
    def setUp(self):
        super().setUp()

        # Minimal definition so things like repr work
        self.collection_def = {
            'request': {'operation': 'TestOperation'},
            'resource': {'type': 'Frob'},
        }
        self.client = mock.Mock()
        self.client.can_paginate.return_value = False
        self.parent = mock.Mock()
        self.parent.meta = ResourceMeta('test', client=self.client)
        self.factory = ResourceFactory(mock.Mock())
        self.service_model = ServiceModel({})

    def get_collection(self):
        resource_defs = {'Frob': {'identifiers': []}}

        # Build up a resource def identifier list based on what
        # the collection is expecting to be required from its
        # definition. This saves a bunch of repetitive typing
        # and lets you just define a collection in the tests
        # below. Any identifiers you expect to be availabe in
        # the resource definition will automatically be there.
        resource_def = self.collection_def.get('resource', {})
        for identifier in resource_def.get('identifiers', []):
            resource_defs['Frob']['identifiers'].append(
                {'name': identifier['target']}
            )

        collection_model = Collection(
            'test', self.collection_def, resource_defs
        )

        collection = CollectionManager(
            collection_model=collection_model,
            parent=self.parent,
            factory=self.factory,
            service_context=ServiceContext(
                service_name='test',
                service_model=self.service_model,
                resource_json_definitions=resource_defs,
                service_waiter_model=None,
            ),
        )
        return collection

    def test_repr(self):
        collection = self.get_collection()
        assert 'CollectionManager' in repr(collection)

    def test_iteration_manager(self):
        # A collection manager is not iterable. You must first call
        # .all or .filter or another method to get an iterable.
        collection = self.get_collection()
        with pytest.raises(TypeError):
            list(collection)

    def test_iteration_non_paginated(self):
        self.collection_def = {
            'request': {'operation': 'GetFrobs'},
            'resource': {
                'type': 'Frob',
                'identifiers': [
                    {
                        'target': 'Id',
                        'source': 'response',
                        'path': 'Frobs[].Id',
                    }
                ],
            },
        }
        self.client.get_frobs.return_value = {
            'Frobs': [
                {'Id': 'one'},
                {'Id': 'two'},
                {'Id': 'three'},
                {'Id': 'four'},
            ]
        }
        collection = self.get_collection()
        items = list(collection.all())
        assert len(items) == 4
        assert items[0].id == 'one'
        assert items[1].id == 'two'
        assert items[2].id == 'three'
        assert items[3].id == 'four'

    def test_limit_param_non_paginated(self):
        self.collection_def = {
            'request': {'operation': 'GetFrobs'},
            'resource': {
                'type': 'Frob',
                'identifiers': [
                    {
                        'target': 'Id',
                        'source': 'response',
                        'path': 'Frobs[].Id',
                    }
                ],
            },
        }
        self.client.get_frobs.return_value = {
            'Frobs': [
                {'Id': 'one'},
                {'Id': 'two'},
                {'Id': 'three'},
                {'Id': 'four'},
            ]
        }
        collection = self.get_collection()
        items = list(collection.all().limit(2))
        assert len(items) == 2

        # Only the first two should be present
        assert items[0].id == 'one'
        assert items[1].id == 'two'

    def test_limit_method_non_paginated(self):
        self.collection_def = {
            'request': {'operation': 'GetFrobs'},
            'resource': {
                'type': 'Frob',
                'identifiers': [
                    {
                        'target': 'Id',
                        'source': 'response',
                        'path': 'Frobs[].Id',
                    }
                ],
            },
        }
        self.client.get_frobs.return_value = {
            'Frobs': [
                {'Id': 'one'},
                {'Id': 'two'},
                {'Id': 'three'},
                {'Id': 'four'},
            ]
        }
        collection = self.get_collection()
        items = list(collection.limit(2))
        assert len(items) == 2

        # Only the first two should be present
        assert items[0].id == 'one'
        assert items[1].id == 'two'

    @mock.patch('boto3.resources.collection.ResourceHandler')
    def test_filters_non_paginated(self, handler):
        self.collection_def = {
            'request': {'operation': 'GetFrobs'},
            'resource': {'type': 'Frob', 'identifiers': []},
        }
        self.client.get_frobs.return_value = {}
        handler.return_value.return_value = []
        collection = self.get_collection()

        list(collection.filter(Param1='foo', Param2=3).limit(2))

        # Note - limit is not passed through to the low-level call
        self.client.get_frobs.assert_called_with(Param1='foo', Param2=3)

    def test_page_iterator_returns_pages_of_items(self):
        self.collection_def = {
            'request': {'operation': 'GetFrobs'},
            'resource': {
                'type': 'Frob',
                'identifiers': [
                    {
                        'target': 'Id',
                        'source': 'response',
                        'path': 'Frobs[].Id',
                    }
                ],
            },
        }
        self.client.can_paginate.return_value = True
        self.client.get_paginator.return_value.paginate.return_value = [
            {'Frobs': [{'Id': 'one'}, {'Id': 'two'}]},
            {'Frobs': [{'Id': 'three'}, {'Id': 'four'}]},
        ]
        collection = self.get_collection()
        pages = list(collection.limit(3).pages())
        assert len(pages) == 2
        assert len(pages[0]) == 2
        assert len(pages[1]) == 1

    def test_page_iterator_page_size(self):
        self.collection_def = {
            'request': {'operation': 'GetFrobs'},
            'resource': {
                'type': 'Frob',
                'identifiers': [
                    {
                        'target': 'Id',
                        'source': 'response',
                        'path': 'Frobs[].Id',
                    }
                ],
            },
        }
        self.client.can_paginate.return_value = True
        paginator = self.client.get_paginator.return_value
        paginator.paginate.return_value = []

        collection = self.get_collection()
        list(collection.page_size(5).pages())

        paginator.paginate.assert_called_with(
            PaginationConfig={'PageSize': 5, 'MaxItems': None}
        )

    def test_iteration_paginated(self):
        self.collection_def = {
            'request': {'operation': 'GetFrobs'},
            'resource': {
                'type': 'Frob',
                'identifiers': [
                    {
                        'target': 'Id',
                        'source': 'response',
                        'path': 'Frobs[].Id',
                    }
                ],
            },
        }
        self.client.can_paginate.return_value = True
        self.client.get_paginator.return_value.paginate.return_value = [
            {'Frobs': [{'Id': 'one'}, {'Id': 'two'}]},
            {'Frobs': [{'Id': 'three'}, {'Id': 'four'}]},
        ]
        collection = self.get_collection()
        items = list(collection.all())
        assert len(items) == 4
        assert items[0].id == 'one'
        assert items[1].id == 'two'
        assert items[2].id == 'three'
        assert items[3].id == 'four'

        # Low-level pagination should have been called
        self.client.get_paginator.assert_called_with('get_frobs')
        paginator = self.client.get_paginator.return_value
        paginator.paginate.assert_called_with(
            PaginationConfig={'PageSize': None, 'MaxItems': None}
        )

    def test_limit_param_paginated(self):
        self.collection_def = {
            'request': {'operation': 'GetFrobs'},
            'resource': {
                'type': 'Frob',
                'identifiers': [
                    {
                        'target': 'Id',
                        'source': 'response',
                        'path': 'Frobs[].Id',
                    }
                ],
            },
        }
        self.client.can_paginate.return_value = True
        self.client.get_paginator.return_value.paginate.return_value = [
            {'Frobs': [{'Id': 'one'}, {'Id': 'two'}]},
            {'Frobs': [{'Id': 'three'}, {'Id': 'four'}]},
        ]
        collection = self.get_collection()
        items = list(collection.all().limit(2))
        assert len(items) == 2

        # Only the first two should be present
        assert items[0].id == 'one'
        assert items[1].id == 'two'

    def test_limit_method_paginated(self):
        self.collection_def = {
            'request': {'operation': 'GetFrobs'},
            'resource': {
                'type': 'Frob',
                'identifiers': [
                    {
                        'target': 'Id',
                        'source': 'response',
                        'path': 'Frobs[].Id',
                    }
                ],
            },
        }
        self.client.can_paginate.return_value = True
        self.client.get_paginator.return_value.paginate.return_value = [
            {'Frobs': [{'Id': 'one'}, {'Id': 'two'}]},
            {'Frobs': [{'Id': 'three'}, {'Id': 'four'}]},
        ]
        collection = self.get_collection()
        items = list(collection.all().limit(2))
        assert len(items) == 2

        # Only the first two should be present
        assert items[0].id == 'one'
        assert items[1].id == 'two'

    @mock.patch('boto3.resources.collection.ResourceHandler')
    def test_filters_paginated(self, handler):
        self.client.can_paginate.return_value = True
        self.client.get_paginator.return_value.paginate.return_value = []
        handler.return_value.return_value = []
        collection = self.get_collection()

        list(collection.filter(Param1='foo', Param2=3).limit(2))

        paginator = self.client.get_paginator.return_value
        paginator.paginate.assert_called_with(
            PaginationConfig={'PageSize': None, 'MaxItems': 2},
            Param1='foo',
            Param2=3,
        )

    @mock.patch('boto3.resources.collection.ResourceHandler')
    def test_filter_does_not_clobber_existing_list_values(self, handler):
        self.collection_def = {
            'request': {
                'operation': 'GetFrobs',
                "params": [
                    {
                        "target": "Filters[0].Name",
                        "source": "string",
                        "value": "frob-id",
                    },
                    {
                        "target": "Filters[0].Values[0]",
                        "source": "identifier",
                        "name": "Id",
                    },
                ],
            },
            'resource': {
                'type': 'Frob',
                'identifiers': [
                    {
                        'target': 'Id',
                        'source': 'response',
                        'path': 'Frobs[].Id',
                    }
                ],
            },
        }
        self.client.can_paginate.return_value = True
        self.client.get_paginator.return_value.paginate.return_value = []
        handler.return_value.return_value = []
        collection = self.get_collection()

        self.parent.id = 'my-id'
        list(
            collection.filter(
                Filters=[{'Name': 'another-filter', 'Values': ['foo']}]
            )
        )
        paginator = self.client.get_paginator.return_value
        paginator.paginate.assert_called_with(
            PaginationConfig={'PageSize': None, 'MaxItems': None},
            Filters=[
                {'Values': ['my-id'], 'Name': 'frob-id'},
                {'Values': ['foo'], 'Name': 'another-filter'},
            ],
        )

    @mock.patch('boto3.resources.collection.ResourceHandler')
    def test_page_size_param(self, handler):
        self.client.can_paginate.return_value = True
        self.client.get_paginator.return_value.paginate.return_value = []
        handler.return_value.return_value = []
        collection = self.get_collection()

        list(collection.all().page_size(1))

        paginator = self.client.get_paginator.return_value
        paginator.paginate.assert_called_with(
            PaginationConfig={'PageSize': 1, 'MaxItems': None}
        )

    @mock.patch('boto3.resources.collection.ResourceHandler')
    def test_page_size_method(self, handler):
        self.client.can_paginate.return_value = True
        self.client.get_paginator.return_value.paginate.return_value = []
        handler.return_value.return_value = []
        collection = self.get_collection()

        list(collection.page_size(1))

        paginator = self.client.get_paginator.return_value
        paginator.paginate.assert_called_with(
            PaginationConfig={'PageSize': 1, 'MaxItems': None}
        )

    def test_chaining(self):
        self.collection_def = {
            'request': {'operation': 'GetFrobs'},
            'resource': {
                'type': 'Frob',
                'identifiers': [
                    {
                        'target': 'Id',
                        'source': 'response',
                        'path': 'Frobs[].Id',
                    }
                ],
            },
        }
        self.client.get_frobs.return_value = {
            'Frobs': [
                {'Id': 'one'},
                {'Id': 'two'},
                {'Id': 'three'},
                {'Id': 'four'},
            ]
        }
        collection = self.get_collection()

        items = list(collection.filter().all().all())

        assert len(items) == 4
        assert items[0].id == 'one'
        assert items[1].id == 'two'
        assert items[2].id == 'three'
        assert items[3].id == 'four'

    @mock.patch('boto3.resources.collection.ResourceHandler')
    def test_chaining_copies_parameters(self, handler):
        self.client.can_paginate.return_value = True
        self.client.get_paginator.return_value.paginate.return_value = []
        handler.return_value.return_value = []
        collection = self.get_collection()

        list(collection.all().filter(CustomArg=1).limit(3).page_size(3))

        paginator = self.client.get_paginator.return_value
        paginator.paginate.assert_called_with(
            PaginationConfig={'PageSize': 3, 'MaxItems': 3}, CustomArg=1
        )

    @mock.patch('boto3.resources.collection.ResourceHandler')
    def test_chaining_filters_does_not_clobber_list_values(self, handler):
        self.collection_def = {
            'request': {
                'operation': 'GetFrobs',
                "params": [
                    {
                        "target": "Filters[0].Name",
                        "source": "string",
                        "value": "frob-id",
                    },
                    {
                        "target": "Filters[0].Values[0]",
                        "source": "identifier",
                        "name": "Id",
                    },
                ],
            },
            'resource': {
                'type': 'Frob',
                'identifiers': [
                    {
                        'target': 'Id',
                        'source': 'response',
                        'path': 'Frobs[].Id',
                    }
                ],
            },
        }
        self.client.can_paginate.return_value = True
        self.client.get_paginator.return_value.paginate.return_value = []
        handler.return_value.return_value = []
        collection = self.get_collection()

        self.parent.id = 'my-id'
        collection = collection.filter(
            Filters=[{'Name': 'second-filter', 'Values': ['foo']}]
        )
        list(
            collection.filter(
                Filters=[{'Name': 'third-filter', 'Values': ['bar']}]
            )
        )
        paginator = self.client.get_paginator.return_value
        paginator.paginate.assert_called_with(
            PaginationConfig={'PageSize': None, 'MaxItems': None},
            Filters=[
                {'Values': ['my-id'], 'Name': 'frob-id'},
                {'Values': ['foo'], 'Name': 'second-filter'},
                {'Values': ['bar'], 'Name': 'third-filter'},
            ],
        )

    def test_chained_repr(self):
        collection = self.get_collection()

        assert 'ResourceCollection' in repr(collection.all())