|
| 1 | +"""Integration tests |
| 2 | +
|
| 3 | +Higher-level tests integrating with 3rd party modules using iodiomatic |
| 4 | +backoff patterns. |
| 5 | +""" |
| 6 | + |
| 7 | +import backoff |
| 8 | + |
| 9 | + |
| 10 | +import requests |
| 11 | +from requests import HTTPError |
| 12 | +import responses |
| 13 | + |
| 14 | + |
| 15 | +@responses.activate |
| 16 | +def test_on_predicate_runtime(monkeypatch): |
| 17 | + |
| 18 | + log = [] |
| 19 | + |
| 20 | + def sleep(seconds): |
| 21 | + log.append(seconds) |
| 22 | + |
| 23 | + monkeypatch.setattr("time.sleep", sleep) |
| 24 | + |
| 25 | + url = "http://example.com" |
| 26 | + |
| 27 | + responses.add(responses.GET, url, status=429, headers={"Retry-After": "1"}) |
| 28 | + responses.add(responses.GET, url, status=429, headers={"Retry-After": "3"}) |
| 29 | + responses.add(responses.GET, url, status=429, headers={"Retry-After": "7"}) |
| 30 | + responses.add(responses.GET, url, status=200) |
| 31 | + |
| 32 | + @backoff.on_predicate( |
| 33 | + backoff.runtime, |
| 34 | + predicate=lambda r: r.status_code == 429, |
| 35 | + value=lambda r: int(r.headers.get("Retry-After")), |
| 36 | + jitter=None, |
| 37 | + ) |
| 38 | + def get_url(): |
| 39 | + return requests.get(url) |
| 40 | + |
| 41 | + resp = get_url() |
| 42 | + assert resp.status_code == 200 |
| 43 | + |
| 44 | + assert log == [1, 3, 7] |
| 45 | + |
| 46 | + |
| 47 | +@responses.activate |
| 48 | +def test_on_exception_runtime(monkeypatch): |
| 49 | + |
| 50 | + log = [] |
| 51 | + |
| 52 | + def sleep(seconds): |
| 53 | + log.append(seconds) |
| 54 | + |
| 55 | + monkeypatch.setattr("time.sleep", sleep) |
| 56 | + |
| 57 | + url = "http://example.com" |
| 58 | + |
| 59 | + responses.add(responses.GET, url, status=429, headers={"Retry-After": "1"}) |
| 60 | + responses.add(responses.GET, url, status=429, headers={"Retry-After": "3"}) |
| 61 | + responses.add(responses.GET, url, status=429, headers={"Retry-After": "7"}) |
| 62 | + responses.add(responses.GET, url, status=200) |
| 63 | + |
| 64 | + @backoff.on_exception( |
| 65 | + backoff.runtime, |
| 66 | + HTTPError, |
| 67 | + value=lambda e: int(e.response.headers.get("Retry-After")), |
| 68 | + jitter=None, |
| 69 | + ) |
| 70 | + def get_url(): |
| 71 | + resp = requests.get(url) |
| 72 | + resp.raise_for_status() |
| 73 | + return resp |
| 74 | + |
| 75 | + resp = get_url() |
| 76 | + assert resp.status_code == 200 |
| 77 | + |
| 78 | + assert log == [1, 3, 7] |
0 commit comments