File: test_waiters.py

package info (click to toggle)
python-botocore 1.12.103%2Brepack-1
  • links: PTS, VCS
  • area: main
  • in suites: buster
  • size: 41,552 kB
  • sloc: python: 43,119; xml: 15,052; makefile: 131
file content (742 lines) | stat: -rw-r--r-- 29,606 bytes parent folder | download
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
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
# Copyright 2012-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
#
# 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 os
from tests import unittest, BaseEnvVar

import mock

import botocore
from botocore.compat import six
from botocore.exceptions import ClientError, WaiterConfigError, WaiterError
from botocore.waiter import Waiter, WaiterModel, SingleWaiterConfig
from botocore.waiter import create_waiter_with_client
from botocore.waiter import NormalizedOperationMethod
from botocore.loaders import Loader
from botocore.model import ServiceModel


class TestWaiterModel(unittest.TestCase):
    def setUp(self):
        self.boiler_plate_config = {
            'description': 'Waiter description',
            'operation': 'HeadBucket',
            'delay': 5,
            'maxAttempts': 20,
        }

    def create_acceptor_function(self, for_config):
        single_waiter = {
            'acceptors': [for_config]
        }
        single_waiter.update(self.boiler_plate_config)
        config = SingleWaiterConfig(single_waiter)
        return config.acceptors[0].matcher_func

    def test_waiter_version(self):
        self.assertEqual(WaiterModel({'version': 2, 'waiters': {}}).version, 2)

    def test_wont_load_missing_version_in_config(self):
        # We only load waiter configs if we know for sure that we're
        # loading version 2 of the format.
        waiters = {
            # Missing the 'version' key.
            'waiters': {}
        }
        with self.assertRaises(WaiterConfigError):
            WaiterModel(waiters)

    def test_unsupported_waiter_version(self):
        waiters = {
            'version': 1,
            'waiters': {}
        }
        with self.assertRaises(WaiterConfigError):
            WaiterModel(waiters)

    def test_waiter_names(self):
        waiters = {
            'version': 2,
            'waiters': {
                'BarWaiter': {},
                'FooWaiter': {},
            }
        }
        self.assertEqual(WaiterModel(waiters).waiter_names, ['BarWaiter',
                                                             'FooWaiter'])

    def test_get_single_waiter_config(self):
        single_waiter = {
            'description': 'Waiter description',
            'operation': 'HeadBucket',
            'delay': 5,
            'maxAttempts': 20,
            'acceptors': [
                {'state': 'success', 'matcher': 'status', 'expected': 200},
                {'state': 'retry', 'matcher': 'status', 'expected': 404},
            ],
        }
        waiters = {
            'version': 2,
            'waiters': {
                'BucketExists': single_waiter,
            }
        }
        model = WaiterModel(waiters)
        config = model.get_waiter('BucketExists')
        self.assertEqual(config.operation, 'HeadBucket')

    def test_get_waiter_does_not_exist(self):
        waiters = {
            'version': 2,
            'waiters': {}
        }
        model = WaiterModel(waiters)
        with self.assertRaises(ValueError):
            model.get_waiter('UnknownWaiter')

    def test_single_waiter_config_attributes(self):
        single_waiter = {
            'description': 'Waiter description',
            'operation': 'HeadBucket',
            'delay': 5,
            'maxAttempts': 20,
            'acceptors': [
            ],
        }
        config = SingleWaiterConfig(single_waiter)
        self.assertEqual(config.description, 'Waiter description')
        self.assertEqual(config.operation, 'HeadBucket')
        self.assertEqual(config.delay, 5)
        self.assertEqual(config.max_attempts, 20)

    def test_single_waiter_acceptors_built_with_matcher_func(self):
        # When the list of acceptors are requested, we actually will transform
        # them into values that are easier to use.
        single_waiter = {
            'acceptors': [
                {'state': 'success', 'matcher': 'status', 'expected': 200},
            ],
        }
        single_waiter.update(self.boiler_plate_config)
        config = SingleWaiterConfig(single_waiter)
        success_acceptor = config.acceptors[0]

        self.assertEqual(success_acceptor.state, 'success')
        self.assertEqual(success_acceptor.matcher, 'status')
        self.assertEqual(success_acceptor.expected, 200)
        self.assertTrue(callable(success_acceptor.matcher_func))

    def test_single_waiter_acceptor_matches_jmespath(self):
        single_waiter = {
            'acceptors': [
                {'state': 'success', 'matcher': 'path',
                 'argument': 'Table.TableStatus', 'expected': 'ACCEPTED'},
            ],
        }
        single_waiter.update(self.boiler_plate_config)
        config = SingleWaiterConfig(single_waiter)
        success_acceptor = config.acceptors[0].matcher_func
        # success_acceptor is a callable that takes a response dict and returns
        # True or False.
        self.assertTrue(
            success_acceptor({'Table': {'TableStatus': 'ACCEPTED'}}))
        self.assertFalse(
            success_acceptor({'Table': {'TableStatus': 'CREATING'}}))

    def test_single_waiter_supports_status_code(self):
        single_waiter = {
            'acceptors': [
                {'state': 'success', 'matcher': 'status',
                 'expected': 200}
            ],
        }
        single_waiter.update(self.boiler_plate_config)
        config = SingleWaiterConfig(single_waiter)
        success_acceptor = config.acceptors[0].matcher_func
        self.assertTrue(
            success_acceptor({'ResponseMetadata': {'HTTPStatusCode': 200}}))
        self.assertFalse(
            success_acceptor({'ResponseMetadata': {'HTTPStatusCode': 404}}))

    def test_single_waiter_supports_error(self):
        single_waiter = {
            'acceptors': [
                {'state': 'success', 'matcher': 'error',
                 'expected': 'DoesNotExistError'}
            ],
        }
        single_waiter.update(self.boiler_plate_config)
        config = SingleWaiterConfig(single_waiter)
        success_acceptor = config.acceptors[0].matcher_func
        self.assertTrue(
            success_acceptor({'Error': {'Code': 'DoesNotExistError'}}))
        self.assertFalse(
            success_acceptor({'Error': {'Code': 'DoesNotExistErorr'}}))

    def test_unknown_matcher(self):
        unknown_type = 'arbitrary_type'
        single_waiter = {
            'acceptors': [
                {'state': 'success', 'matcher': unknown_type,
                 'expected': 'foo'}
            ]
        }
        single_waiter.update(self.boiler_plate_config)
        config = SingleWaiterConfig(single_waiter)
        with self.assertRaises(WaiterConfigError):
            config.acceptors

    def test_single_waiter_supports_path_all(self):
        matches = self.create_acceptor_function(
            for_config={'state': 'success', 'matcher': 'pathAll',
                        'argument': 'Tables[].State', 'expected': 'GOOD'})
        self.assertTrue(
            matches({'Tables': [{"State": "GOOD"}]}))
        self.assertTrue(
            matches({'Tables': [{"State": "GOOD"}, {"State": "GOOD"}]}))

    def test_single_waiter_supports_path_any(self):
        matches = self.create_acceptor_function(
            for_config={'state': 'failure', 'matcher': 'pathAny',
                        'argument': 'Tables[].State', 'expected': 'FAIL'})
        self.assertTrue(
            matches({'Tables': [{"State": "FAIL"}]}))
        self.assertTrue(
            matches({'Tables': [{"State": "GOOD"}, {"State": "FAIL"}]}))

    def test_waiter_handles_error_responses_with_path_matchers(self):
        path_any = self.create_acceptor_function(
            for_config={'state': 'success', 'matcher': 'pathAny',
                        'argument': 'length(Tables) > `0`',
                        'expected': True})
        path_all = self.create_acceptor_function(
            for_config={'state': 'success', 'matcher': 'pathAll',
                        'argument': 'length(Tables) > `0`',
                        'expected': True})
        path = self.create_acceptor_function(
            for_config={'state': 'success', 'matcher': 'path',
                        'argument': 'length(Tables) > `0`',
                        'expected': True})
        self.assertFalse(path_any({'Error': {'Code': 'DoesNotExist'}}))
        self.assertFalse(path_all({'Error': {'Code': 'DoesNotExist'}}))
        self.assertFalse(path({'Error': {'Code': 'DoesNotExist'}}))

    def test_single_waiter_does_not_match_path_all(self):
        matches = self.create_acceptor_function(
            for_config={'state': 'success', 'matcher': 'pathAll',
                        'argument': 'Tables[].State', 'expected': 'GOOD'})
        self.assertFalse(
            matches({'Tables': [{"State": "GOOD"}, {"State": "BAD"}]}))
        self.assertFalse(
            matches({'Tables': [{"State": "BAD"}, {"State": "GOOD"}]}))
        self.assertFalse(
            matches({'Tables': [{"State": "BAD"}, {"State": "BAD"}]}))
        self.assertFalse(
            matches({'Tables': []}))
        self.assertFalse(
            matches({'Tables': [{"State": "BAD"},
                                {"State": "BAD"},
                                {"State": "BAD"},
                                {"State": "BAD"}]}))

    def test_path_all_missing_field(self):
        matches = self.create_acceptor_function(
            for_config={'state': 'success', 'matcher': 'pathAll',
                        'argument': 'Tables[].State', 'expected': 'GOOD'})
        self.assertFalse(
            matches({'Tables': [{"NotState": "GOOD"}, {"NotState": "BAD"}]}))

    def test_path_all_matcher_does_not_receive_list(self):
        matches = self.create_acceptor_function(
            for_config={'state': 'success', 'matcher': 'pathAll',
                        'argument': 'Tables[].State', 'expected': 'GOOD'})
        self.assertFalse(
            matches({"NotTables": []}))

    def test_single_waiter_supports_all_three_states(self):
        single_waiter = {
            'acceptors': [
                {'state': 'success', 'matcher': 'error',
                 'expected': 'DoesNotExistError'},
                {'state': 'success', 'matcher': 'status',
                 'expected': 200},
                {'state': 'success', 'matcher': 'path',
                 'argument': 'Foo.Bar', 'expected': 'baz'},
            ],
        }
        single_waiter.update(self.boiler_plate_config)
        config = SingleWaiterConfig(single_waiter)
        acceptors = config.acceptors
        # Each acceptors should be able to handle not matching
        # any type of response.
        matches_nothing = {}
        self.assertFalse(acceptors[0].matcher_func(matches_nothing))
        self.assertFalse(acceptors[1].matcher_func(matches_nothing))
        self.assertFalse(acceptors[2].matcher_func(matches_nothing))


class TestWaitersObjects(unittest.TestCase):
    def setUp(self):
        pass

    def client_responses_are(self, *responses, **kwargs):
        operation_method = kwargs['for_operation']
        operation_method.side_effect = responses
        return operation_method

    def create_waiter_config(self, operation='MyOperation',
                             delay=0, max_attempts=3,
                             acceptors=None):
        if acceptors is None:
            # Create some arbitrary acceptor that will never match.
            acceptors = [{'state': 'success', 'matcher': 'status',
                          'expected': 1000}]
        waiter_config = {
            'operation': operation,
            'delay': delay,
            'maxAttempts': max_attempts,
            'acceptors': acceptors
        }
        config = SingleWaiterConfig(waiter_config)
        return config

    def test_waiter_waits_until_acceptor_matches(self):
        config = self.create_waiter_config(
            max_attempts=3,
            acceptors=[{'state': 'success', 'matcher': 'path',
                        'argument': 'Foo', 'expected': 'SUCCESS'}])
        # Simulate the client having two calls that don't
        # match followed by a third call that matches the
        # acceptor.
        operation_method = mock.Mock()
        waiter = Waiter('MyWaiter', config, operation_method)
        self.client_responses_are(
            {'Foo': 'FAILURE'},
            {'Foo': 'FAILURE'},
            {'Foo': 'SUCCESS'},
            for_operation=operation_method
        )
        waiter.wait()
        self.assertEqual(operation_method.call_count, 3)

    def test_waiter_never_matches(self):
        # Verify that a matcher will fail after max_attempts
        # is exceeded.
        config = self.create_waiter_config(max_attempts=3)
        operation_method = mock.Mock()
        self.client_responses_are(
            {'Foo': 'FAILURE'},
            {'Foo': 'FAILURE'},
            {'Foo': 'FAILURE'},
            for_operation=operation_method
        )
        waiter = Waiter('MyWaiter', config, operation_method)
        with self.assertRaises(WaiterError):
            waiter.wait()

    def test_unspecified_errors_stops_waiter(self):
        # If a waiter receives an error response, then the
        # waiter immediately stops.
        config = self.create_waiter_config()
        operation_method = mock.Mock()
        self.client_responses_are(
            # This is an unknown error that's not called out
            # in any of the waiter config, so when the
            # waiter encounters this response it will transition
            # to the failure state.
            {'Error': {'Code': 'UnknownError', 'Message': 'bad error'}},
            for_operation=operation_method
        )
        waiter = Waiter('MyWaiter', config, operation_method)
        with self.assertRaises(WaiterError):
            waiter.wait()

    def test_last_response_available_on_waiter_error(self):
        last_response = {'Error': {'Code': 'UnknownError', 'Message': 'bad error'}}
        config = self.create_waiter_config()
        operation_method = mock.Mock()
        self.client_responses_are(last_response,
                                  for_operation=operation_method)
        waiter = Waiter('MyWaiter', config, operation_method)
        with self.assertRaises(WaiterError) as e:
            waiter.wait()
        self.assertEqual(e.exception.last_response, last_response)

    def test_unspecified_errors_propagate_error_code(self):
        # If a waiter receives an error response, then the
        # waiter should pass along the error code
        config = self.create_waiter_config()
        operation_method = mock.Mock()
        error_code = 'error_message'
        error_message = 'error_message'
        self.client_responses_are(
            # This is an unknown error that's not called out
            # in any of the waiter config, so when the
            # waiter encounters this response it will transition
            # to the failure state.
            {'Error': {'Code': error_code, 'Message': error_message}},
            for_operation=operation_method
        )
        waiter = Waiter('MyWaiter', config, operation_method)

        with self.assertRaisesRegexp(WaiterError, error_message):
            waiter.wait()

    def test_waiter_transitions_to_failure_state(self):
        acceptors = [
            # A success state that will never be hit.
            {'state': 'success', 'matcher': 'status', 'expected': 1000},
            {'state': 'failure', 'matcher': 'error', 'expected': 'FailError'},
        ]
        config = self.create_waiter_config(acceptors=acceptors)
        operation_method = mock.Mock()
        self.client_responses_are(
            {'Nothing': 'foo'},
            # And on the second attempt, a FailError is seen, which
            # causes the waiter to fail fast.
            {'Error': {'Code': 'FailError', 'Message': 'foo'}},
            {'WillNeverGetCalled': True},
            for_operation=operation_method
        )
        waiter = Waiter('MyWaiter', config, operation_method)
        with self.assertRaises(WaiterError):
            waiter.wait()
        # Not only should we raise an exception, but we should have
        # only called the operation_method twice because the second
        # response triggered a fast fail.
        self.assertEqual(operation_method.call_count, 2)

    def test_waiter_handles_retry_state(self):
        acceptor_with_retry_state = [
            {'state': 'success', 'matcher': 'status', 'expected': 200},
            {'state': 'retry', 'matcher': 'error', 'expected': 'RetryMe'},
        ]
        config = self.create_waiter_config(
            acceptors=acceptor_with_retry_state)
        operation_method = mock.Mock()
        self.client_responses_are(
            {'Nothing': 'foo'},
            {'Error': {'Code': 'RetryMe', 'Message': 'foo'}},
            {'Success': True,
             'ResponseMetadata': {'HTTPStatusCode': 200}},
            {'NeverCalled': True},
            for_operation=operation_method
        )
        waiter = Waiter('MyWaiter', config, operation_method)
        waiter.wait()
        self.assertEqual(operation_method.call_count, 3)

    def test_waiter_transitions_to_retry_but_max_attempts_exceeded(self):
        acceptors = [
            {'state': 'success', 'matcher': 'status', 'expected': 200},
            {'state': 'retry', 'matcher': 'error', 'expected': 'RetryMe'},
        ]
        config = self.create_waiter_config(acceptors=acceptors)
        operation_method = mock.Mock()
        self.client_responses_are(
            {'Success': False},
            {'Error': {'Code': 'RetryMe', 'Message': 'foo'}},
            {'Success': False},
            {'Success': False},
            for_operation=operation_method
        )
        waiter = Waiter('MyWaiter', config, operation_method)
        with self.assertRaises(WaiterError):
            waiter.wait()

    def test_kwargs_are_passed_through(self):
        acceptors = [
            {'state': 'success', 'matcher': 'error', 'expected': 'MyError'},
        ]
        config = self.create_waiter_config(acceptors=acceptors)
        operation_method = mock.Mock()
        self.client_responses_are(
            {'Error': {'Code': 'MyError'}},
            for_operation=operation_method)
        waiter = Waiter('MyWaiter', config, operation_method)
        waiter.wait(Foo='foo', Bar='bar', Baz='baz')

        operation_method.assert_called_with(Foo='foo', Bar='bar',
                                            Baz='baz')

    @mock.patch('time.sleep')
    def test_waiter_honors_delay_time_between_retries(self, sleep_mock):
        delay_time = 5
        config = self.create_waiter_config(delay=delay_time)
        operation_method = mock.Mock()
        self.client_responses_are(
            # This is an unknown error that's not called out
            # in any of the waiter config, so when the
            # waiter encounters this response it will transition
            # to the failure state.
            {'Success': False},
            {'Success': False},
            {'Success': False},
            for_operation=operation_method
        )
        waiter = Waiter('MyWaiter', config, operation_method)
        with self.assertRaises(WaiterError):
            waiter.wait()

        # We attempt three times, which means we need to sleep
        # twice, once before each subsequent request.
        self.assertEqual(sleep_mock.call_count, 2)
        sleep_mock.assert_called_with(delay_time)

    @mock.patch('time.sleep')
    def test_waiter_invocation_config_honors_delay(self, sleep_mock):
        config = self.create_waiter_config()
        operation_method = mock.Mock()
        self.client_responses_are(
            {'Success': False},
            {'Success': False},
            {'Success': False},
            for_operation=operation_method
        )
        waiter = Waiter('MyWaiter', config, operation_method)
        custom_delay = 3
        with self.assertRaises(WaiterError):
            waiter.wait(WaiterConfig={'Delay': custom_delay})

        # We attempt three times, which means we need to sleep
        # twice, once before each subsequent request.
        self.assertEqual(sleep_mock.call_count, 2)
        sleep_mock.assert_called_with(custom_delay)

    def test_waiter_invocation_config_honors_max_attempts(self):
        config = self.create_waiter_config()
        operation_method = mock.Mock()
        self.client_responses_are(
            {'Success': False},
            {'Success': False},
            for_operation=operation_method
        )
        waiter = Waiter('MyWaiter', config, operation_method)
        custom_max = 2
        with self.assertRaises(WaiterError):
            waiter.wait(WaiterConfig={'MaxAttempts': custom_max})

        self.assertEqual(operation_method.call_count, 2)


class TestCreateWaiter(unittest.TestCase):
    def setUp(self):
        self.waiter_config = {
            'version': 2,
            'waiters': {
                'WaiterName': {
                    'operation': 'Foo',
                    'delay': 1,
                    'maxAttempts': 1,
                    'acceptors': [],
                },
            },
        }
        self.waiter_model = WaiterModel(self.waiter_config)
        self.service_json_model = {
            'metadata': {
                'serviceFullName': 'Amazon MyService'
            },
            'operations': {
                'Foo': {
                    'name': 'Foo',
                    'input': {'shape': 'FooInputOutput'},
                    'output': {'shape': 'FooInputOutput'}
                }
            },
            'shapes': {
                'FooInputOutput': {
                    'type': 'structure',
                    'members': {
                        'bar': {
                            'shape': 'String',
                            'documentation': 'Documents bar'
                        }
                    }
                },
                'String': {
                    'type': 'string'
                }
            }
        }
        self.service_model = ServiceModel(self.service_json_model, 'myservice')
        self.client = mock.Mock()
        self.client.meta.service_model = self.service_model

    def test_can_create_waiter_from_client(self):
        waiter_name = 'WaiterName'
        waiter = create_waiter_with_client(
            waiter_name, self.waiter_model, self.client)
        self.assertIsInstance(waiter, Waiter)

    def test_waiter_class_name(self):
        waiter_name = 'WaiterName'
        waiter = create_waiter_with_client(
            waiter_name, self.waiter_model, self.client)
        self.assertEqual(
            waiter.__class__.__name__,
            'MyService.Waiter.WaiterName'
        )

    def test_waiter_help_documentation(self):
        waiter_name = 'WaiterName'
        waiter = create_waiter_with_client(
            waiter_name, self.waiter_model, self.client)
        with mock.patch('sys.stdout', six.StringIO()) as mock_stdout:
            help(waiter.wait)
        content = mock_stdout.getvalue()
        lines = [
            ('    Polls :py:meth:`MyService.Client.foo` every 1 '
             'seconds until a successful state is reached. An error '
             'is returned after 1 failed checks.'),
            '    **Request Syntax** ',
            '    ::',
            '      waiter.wait(',
            "          bar='string'",
            '      )',
            '    :type bar: string',
            '    :param bar: Documents bar',
            '    :returns: None',
        ]
        for line in lines:
            self.assertIn(line, content)


class TestOperationMethods(unittest.TestCase):
    def test_normalized_op_method_makes_call(self):
        client_method = mock.Mock()
        op = NormalizedOperationMethod(client_method)
        op(Foo='a', Bar='b')

        client_method.assert_called_with(Foo='a', Bar='b')

    def test_normalized_op_returns_error_response(self):
        # Client objects normally throw exceptions when an error
        # occurs, but we need to return the parsed error response.
        client_method = mock.Mock()
        op = NormalizedOperationMethod(client_method)
        parsed_response = {
            'Error': {'Code': 'Foo', 'Message': 'bar'}
        }
        exception = ClientError(parsed_response, 'OperationName')
        client_method.side_effect = exception
        actual_response = op(Foo='a', Bar='b')
        self.assertEqual(actual_response, parsed_response)


class ServiceWaiterFunctionalTest(BaseEnvVar):
    """
    This class is used as a base class if you want to functionally test the
    waiters for a specific service.
    """
    def setUp(self):
        super(ServiceWaiterFunctionalTest, self).setUp()
        self.data_path = os.path.join(
            os.path.dirname(botocore.__file__), 'data')
        self.environ['AWS_DATA_PATH'] = self.data_path
        self.loader = Loader([self.data_path])

    def get_waiter_model(self, service, api_version=None):
        """Get the waiter model for the service."""
        with mock.patch('botocore.loaders.Loader.list_available_services',
                        return_value=[service]):
            return WaiterModel(self.loader.load_service_model(
                service, type_name='waiters-2', api_version=api_version))

    def get_service_model(self, service, api_version=None):
        """Get the service model for the service."""
        with mock.patch('botocore.loaders.Loader.list_available_services',
                        return_value=[service]):
            return ServiceModel(
                self.loader.load_service_model(
                    service, type_name='service-2', api_version=api_version),
                service_name=service
            )


class CloudFrontWaitersTest(ServiceWaiterFunctionalTest):
    def setUp(self):
        super(CloudFrontWaitersTest, self).setUp()
        self.client = mock.Mock()
        self.service = 'cloudfront'
        self.old_api_versions = ['2014-05-31']

    def assert_distribution_deployed_call_count(self, api_version=None):
        waiter_name = 'DistributionDeployed'
        waiter_model = self.get_waiter_model(self.service, api_version)
        self.client.meta.service_model = self.get_service_model(
            self.service, api_version)
        self.client.get_distribution.side_effect = [
            {'Distribution': {'Status': 'Deployed'}}
        ]
        waiter = create_waiter_with_client(waiter_name, waiter_model,
                                           self.client)
        waiter.wait()
        self.assertEqual(self.client.get_distribution.call_count, 1)

    def assert_invalidation_completed_call_count(self, api_version=None):
        waiter_name = 'InvalidationCompleted'
        waiter_model = self.get_waiter_model(self.service, api_version)
        self.client.meta.service_model = self.get_service_model(
            self.service, api_version)
        self.client.get_invalidation.side_effect = [
            {'Invalidation': {'Status': 'Completed'}}
        ]
        waiter = create_waiter_with_client(waiter_name, waiter_model,
                                           self.client)
        waiter.wait()
        self.assertEqual(self.client.get_invalidation.call_count, 1)

    def assert_streaming_distribution_deployed_call_count(
            self, api_version=None):
        waiter_name = 'StreamingDistributionDeployed'
        waiter_model = self.get_waiter_model(self.service, api_version)
        self.client.meta.service_model = self.get_service_model(
            self.service, api_version)
        self.client.get_streaming_distribution.side_effect = [
            {'StreamingDistribution': {'Status': 'Deployed'}}
        ]
        waiter = create_waiter_with_client(waiter_name, waiter_model,
                                           self.client)
        waiter.wait()
        self.assertEqual(self.client.get_streaming_distribution.call_count, 1)

    def test_distribution_deployed(self):
        # Test the latest version.
        self.assert_distribution_deployed_call_count()
        self.client.reset_mock()

        # Test previous api versions.
        for api_version in self.old_api_versions:
            self.assert_distribution_deployed_call_count(api_version)
            self.client.reset_mock()

    def test_invalidation_completed(self):
        # Test the latest version.
        self.assert_invalidation_completed_call_count()
        self.client.reset_mock()

        # Test previous api versions.
        for api_version in self.old_api_versions:
            self.assert_invalidation_completed_call_count(api_version)
            self.client.reset_mock()

    def test_streaming_distribution_deployed(self):
        # Test the latest version.
        self.assert_streaming_distribution_deployed_call_count()
        self.client.reset_mock()

        # Test previous api versions.
        for api_version in self.old_api_versions:
            self.assert_streaming_distribution_deployed_call_count(api_version)
            self.client.reset_mock()