File: GithubRetry.py

package info (click to toggle)
pygithub 2.6.1-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 33,476 kB
  • sloc: python: 38,409; sh: 7; makefile: 6
file content (408 lines) | stat: -rw-r--r-- 17,261 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
############################ Copyrights and license ############################
#                                                                              #
# Copyright 2023 Enrico Minack <github@enrico.minack.dev>                      #
# Copyright 2023 Jirka Borovec <6035284+Borda@users.noreply.github.com>        #
# Copyright 2023 Patryk Szulczyk <therealsoulcheck@gmail.com>                  #
# Copyright 2025 Enrico Minack <github@enrico.minack.dev>                      #
#                                                                              #
# This file is part of PyGithub.                                               #
# http://pygithub.readthedocs.io/                                              #
#                                                                              #
# PyGithub is free software: you can redistribute it and/or modify it under    #
# the terms of the GNU Lesser General Public License as published by the Free  #
# Software Foundation, either version 3 of the License, or (at your option)    #
# any later version.                                                           #
#                                                                              #
# PyGithub is distributed in the hope that it will be useful, but WITHOUT ANY  #
# WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS    #
# FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more #
# details.                                                                     #
#                                                                              #
# You should have received a copy of the GNU Lesser General Public License     #
# along with PyGithub. If not, see <http://www.gnu.org/licenses/>.             #
#                                                                              #
################################################################################

import contextlib
import logging
import sys
import unittest
from datetime import datetime
from io import BytesIO
from unittest import mock

import urllib3.response
from urllib3 import Retry

import github
from github.GithubRetry import DEFAULT_SECONDARY_RATE_WAIT

from . import Requester

PrimaryRateLimitMessage = Requester.Requester.PrimaryRateLimitErrors[0]
PrimaryRateLimitJson = (
    '{"message":"'
    + PrimaryRateLimitMessage
    + '","documentation_url":"https://docs.github.com/rest/overview/resources-in-the-rest-api#rate-limiting"}'
)

SecondaryRateLimitMessage = Requester.Requester.SecondaryRateLimitErrors[0]
SecondaryRateLimitJson = (
    '{"message":"'
    + SecondaryRateLimitMessage
    + '","documentation_url": "https://docs.github.com/en/free-pro-team@latest/rest/overview/resources-in-the-rest-api#secondary-rate-limits"}'
)


class GithubRetry(unittest.TestCase):
    def get_test_increment_func(self, expected_rate_limit_error):
        is_primary = expected_rate_limit_error == PrimaryRateLimitMessage

        def test_increment(
            retry,
            response,
            expected_total=None,
            expected_backoff=None,
            expected_retry_backoff=None,
            expect_retry_error=False,
            has_reset=False,
        ):
            # fmt: off
            self.assertTrue(
                expected_total is not None and expected_backoff is not None and not expect_retry_error or  # noqa: W504
                expected_total is None and expected_backoff is None and expect_retry_error
            )
            # fmt: on

            orig_retry = retry
            with mock.patch.object(retry, "_GithubRetry__log") as log:
                if expect_retry_error:
                    with self.assertRaises(urllib3.exceptions.MaxRetryError):
                        retry.increment("TEST", "URL", response)
                    retry = None
                else:
                    retry = retry.increment("TEST", "URL", response)

                    self.assertEqual(expected_total, retry.total)
                    self.assertEqual(
                        expected_backoff if expected_retry_backoff is None else expected_retry_backoff,
                        retry.get_backoff_time(),
                    )
                    self.assertEqual(orig_retry.secondary_rate_wait, retry.secondary_rate_wait)

                # fmt: off
                log.assert_has_calls(
                    [
                        mock.call(20, "Request TEST URL failed with 403: None"),
                        mock.call(10, f"Response body indicates retry-able {'primary' if is_primary else 'secondary'} rate limit error: {expected_rate_limit_error}"),
                    ] + ([
                        mock.call(10, "Reset occurs in 0:00:12 (1644768012 / 2022-02-13 16:00:12+00:00)")
                    ] if has_reset else []) + ([
                        mock.call(10, f"Retry backoff of {expected_retry_backoff}s exceeds required rate limit backoff of {expected_backoff}s")
                    ] if expected_retry_backoff and expected_backoff > 0 else []) + ([
                        mock.call(20, f"Setting next backoff to {expected_backoff if expected_retry_backoff is None else expected_retry_backoff}s")
                    ] if not expect_retry_error else []),
                    any_order=False,
                )
                # fmt: on
            return retry

        return test_increment

    @staticmethod
    def response_func(content, reset=None):
        def response():
            stream = BytesIO(content.encode("utf8"))
            return urllib3.response.HTTPResponse(
                body=stream,
                preload_content=False,
                headers={"X-RateLimit-Reset": f"{reset}"} if reset else {},
                status=403,
            )

        return response

    @contextlib.contextmanager
    def mock_retry_now(self, now):
        if sys.version_info[0] > 3 or sys.version_info[0] == 3 and sys.version_info[1] >= 11:
            attr = "github.GithubRetry.GithubRetry._GithubRetry__datetime"
        else:
            attr = "github.GithubRetry._GithubRetry__datetime"
        with mock.patch(attr) as dt:
            dt.now = lambda tz=None: datetime.fromtimestamp(now, tz=tz)
            dt.fromtimestamp = datetime.fromtimestamp
            yield

    def test_primary_rate_error_with_reset(self):
        retry = github.GithubRetry(total=3)
        response = self.response_func(PrimaryRateLimitJson, 1644768012)
        test_increment = self.get_test_increment_func(PrimaryRateLimitMessage)

        # test 12 seconds before reset, note backoff will be 12+1 second
        with self.mock_retry_now(1644768000):
            retry = test_increment(
                retry,
                response(),
                expected_total=2,
                expected_backoff=12 + 1,
                has_reset=True,
            )
        with self.mock_retry_now(1644768000):
            retry = test_increment(
                retry,
                response(),
                expected_total=1,
                expected_backoff=12 + 1,
                has_reset=True,
            )

        # test 2 seconds after reset, no backoff expected
        with self.mock_retry_now(1644768014):
            retry = test_increment(retry, response(), expected_total=0, expected_backoff=0)
            test_increment(retry, response(), expect_retry_error=True)

    def test_primary_rate_error_with_reset_and_exponential_backoff(self):
        retry = github.GithubRetry(total=3, backoff_factor=10)
        response = self.response_func(PrimaryRateLimitJson, 1644768012)
        test_increment = self.get_test_increment_func(PrimaryRateLimitMessage)

        # test 12 seconds before reset, note backoff will be 12+1 second
        with self.mock_retry_now(1644768000):
            retry = test_increment(
                retry,
                response(),
                expected_total=2,
                expected_backoff=12 + 1,
                has_reset=True,
            )
        with self.mock_retry_now(1644768000):
            retry = test_increment(
                retry,
                response(),
                expected_total=1,
                expected_backoff=12 + 1,
                expected_retry_backoff=20,
                has_reset=True,
            )

        # test 2 seconds after reset, no backoff expected
        with self.mock_retry_now(1644768014):
            retry = test_increment(
                retry,
                response(),
                expected_total=0,
                expected_backoff=-2,
                expected_retry_backoff=40,
            )
            test_increment(retry, response(), expect_retry_error=True)

    def test_primary_rate_error_without_reset(self):
        retry = github.GithubRetry(total=3)
        response = self.response_func(PrimaryRateLimitJson, reset=None)
        test_increment = self.get_test_increment_func(PrimaryRateLimitMessage)

        # test without reset
        retry = test_increment(retry, response(), expected_total=2, expected_backoff=0)
        retry = test_increment(retry, response(), expected_total=1, expected_backoff=0)
        retry = test_increment(retry, response(), expected_total=0, expected_backoff=0)
        test_increment(retry, response(), expect_retry_error=True)

    def test_primary_rate_error_without_reset_with_exponential_backoff(self):
        retry = github.GithubRetry(total=3, backoff_factor=10)
        response = self.response_func(PrimaryRateLimitJson, reset=None)
        test_increment = self.get_test_increment_func(PrimaryRateLimitMessage)

        # test without reset
        retry = test_increment(
            retry,
            response(),
            expected_total=2,
            expected_backoff=0,
            expected_retry_backoff=0,
        )
        retry = test_increment(
            retry,
            response(),
            expected_total=1,
            expected_backoff=0,
            expected_retry_backoff=20,
        )
        retry = test_increment(
            retry,
            response(),
            expected_total=0,
            expected_backoff=0,
            expected_retry_backoff=40,
        )
        test_increment(retry, response(), expect_retry_error=True)

    def test_secondary_rate_error_with_reset(self):
        retry = github.GithubRetry(total=3)
        response = self.response_func(SecondaryRateLimitJson, 1644768012)
        test_increment = self.get_test_increment_func(SecondaryRateLimitMessage)

        # test 12 seconds before reset, expect secondary wait seconds of 60
        with self.mock_retry_now(1644768000):
            retry = test_increment(
                retry,
                response(),
                expected_total=2,
                expected_backoff=60,
                has_reset=False,
            )
        with self.mock_retry_now(1644768000):
            retry = test_increment(
                retry,
                response(),
                expected_total=1,
                expected_backoff=60,
                has_reset=False,
            )

        # test 2 seconds after reset, still expect secondary wait seconds of 60
        with self.mock_retry_now(1644768014):
            retry = test_increment(retry, response(), expected_total=0, expected_backoff=60)
            test_increment(retry, response(), expect_retry_error=True)

    def test_secondary_rate_error_with_reset_and_exponential_backoff(self):
        retry = github.GithubRetry(total=3, backoff_factor=10, secondary_rate_wait=15)
        response = self.response_func(SecondaryRateLimitJson, 1644768012)
        test_increment = self.get_test_increment_func(SecondaryRateLimitMessage)

        # test 12 seconds before reset, expect secondary wait seconds of 15
        with self.mock_retry_now(1644768000):
            retry = test_increment(
                retry,
                response(),
                expected_total=2,
                expected_backoff=15,
                has_reset=False,
            )
        with self.mock_retry_now(1644768000):
            retry = test_increment(
                retry,
                response(),
                expected_total=1,
                expected_backoff=15,
                expected_retry_backoff=20,
                has_reset=False,
            )

        # test 2 seconds after reset, exponential backoff exceeds secondary wait seconds of 15
        with self.mock_retry_now(1644768014):
            retry = test_increment(
                retry,
                response(),
                expected_total=0,
                expected_backoff=15,
                expected_retry_backoff=40,
            )
            test_increment(retry, response(), expect_retry_error=True)

    def test_secondary_rate_error_without_reset(self):
        retry = github.GithubRetry(total=3)
        response = self.response_func(SecondaryRateLimitJson, reset=None)
        test_increment = self.get_test_increment_func(SecondaryRateLimitMessage)

        retry = test_increment(
            retry,
            response(),
            expected_total=2,
            expected_backoff=DEFAULT_SECONDARY_RATE_WAIT,
        )
        retry = test_increment(
            retry,
            response(),
            expected_total=1,
            expected_backoff=DEFAULT_SECONDARY_RATE_WAIT,
        )
        retry = test_increment(
            retry,
            response(),
            expected_total=0,
            expected_backoff=DEFAULT_SECONDARY_RATE_WAIT,
        )
        test_increment(retry, response(), expect_retry_error=True)

    def test_secondary_rate_error_without_reset_with_exponential_backoff(self):
        retry = github.GithubRetry(total=3, backoff_factor=10, secondary_rate_wait=5)
        response = self.response_func(SecondaryRateLimitJson, reset=None)
        test_increment = self.get_test_increment_func(SecondaryRateLimitMessage)

        retry = test_increment(retry, response(), expected_total=2, expected_backoff=5)
        retry = test_increment(
            retry,
            response(),
            expected_total=1,
            expected_backoff=5,
            expected_retry_backoff=20,
        )
        retry = test_increment(
            retry,
            response(),
            expected_total=0,
            expected_backoff=5,
            expected_retry_backoff=40,
        )
        test_increment(retry, response(), expect_retry_error=True)

    def do_test_default_behaviour(self, retry, response):
        expected = Retry(total=retry.total, backoff_factor=retry.backoff_factor)
        self.assertTrue(retry.total > 0)
        for _ in range(retry.total):
            retry = retry.increment("TEST", "URL", response)
            expected = expected.increment("TEST", "URL", response)
            self.assertEqual(expected.total, retry.total)
            self.assertEqual(expected.get_backoff_time(), retry.get_backoff_time())

        with self.assertRaises(urllib3.exceptions.MaxRetryError):
            retry.increment("TEST", "URL", response)
        with self.assertRaises(urllib3.exceptions.MaxRetryError):
            expected.increment("TEST", "URL", response)

    def test_403_with_retry_after(self):
        retry = github.GithubRetry(total=3)
        response = urllib3.response.HTTPResponse(status=403, headers={"Retry-After": "123"})
        self.do_test_default_behaviour(retry, response)

    def test_403_with_non_retryable_error(self):
        retry = github.GithubRetry(total=3)
        with self.assertRaises(github.BadUserAgentException):
            retry.increment(
                "TEST",
                "URL",
                self.response_func('{"message":"Missing or invalid User Agent string."}')(),
            )

    def test_misc_response(self):
        retry = github.GithubRetry(total=3)
        response = urllib3.response.HTTPResponse()
        self.do_test_default_behaviour(retry, response)

    def test_misc_response_exponential_backoff(self):
        retry = github.GithubRetry(total=3, backoff_factor=10)
        response = urllib3.response.HTTPResponse()
        self.do_test_default_behaviour(retry, response)

    def test_error_in_get_content(self):
        retry = github.GithubRetry(total=3)
        response = urllib3.response.HTTPResponse(status=403, reason="NOT GOOD")

        with mock.patch.object(retry, "_GithubRetry__log") as log:
            with self.assertRaises(github.GithubException) as exp:
                retry.increment("TEST", "URL", response)
            self.assertIsNone(exp.exception.message)
            self.assertEqual(403, exp.exception.status)
            self.assertEqual("NOT GOOD", exp.exception.data)
            self.assertEqual({}, exp.exception.headers)

            self.assertIsInstance(exp.exception.__cause__, RuntimeError)
            self.assertEqual(("Failed to inspect response message",), exp.exception.__cause__.args)

            self.assertIsInstance(exp.exception.__cause__.__cause__, ValueError)
            self.assertEqual(
                ("Unable to determine whether fp is closed.",),
                exp.exception.__cause__.__cause__.args,
            )

        log.assert_called_once_with(logging.INFO, "Request TEST URL failed with 403: NOT GOOD")