|
| 1 | +# -*- coding: utf-8 -*- |
| 2 | +"""ciscosparkapi/restsession.py Fixtures & Tests""" |
| 3 | + |
| 4 | + |
| 5 | +import logging |
| 6 | + |
| 7 | +import pytest |
| 8 | + |
| 9 | +from ciscosparkapi.exceptions import SPARK_RESPONSE_CODES |
| 10 | + |
| 11 | +# Constants |
| 12 | +RATE_LIMIT_RESPONSE_CODE = 429 |
| 13 | +RATE_LIMIT_RESPONSE_TEXT = SPARK_RESPONSE_CODES[RATE_LIMIT_RESPONSE_CODE] |
| 14 | +RATE_LIMIT_LOG_MESSAGE = ("Received a [%s] rate limit response. " |
| 15 | + "Attempting to retry.") |
| 16 | + |
| 17 | + |
| 18 | +# Helper Classes |
| 19 | +class RateLimitDetector(logging.Handler): |
| 20 | + """Detects occurrences of rate limiting.""" |
| 21 | + |
| 22 | + def __init__(self): |
| 23 | + super(RateLimitDetector, self).__init__() |
| 24 | + |
| 25 | + self.rate_limit_detected = False |
| 26 | + |
| 27 | + def emit(self, record): |
| 28 | + """Check record to see if it is a rate-limit message.""" |
| 29 | + assert isinstance(record, logging.LogRecord) |
| 30 | + |
| 31 | + if (RATE_LIMIT_RESPONSE_CODE in record.args |
| 32 | + and record.msg == RATE_LIMIT_LOG_MESSAGE): |
| 33 | + |
| 34 | + self.rate_limit_detected = True |
| 35 | + |
| 36 | + |
| 37 | +# CiscoSparkAPI Tests |
| 38 | +class TestRestSession: |
| 39 | + """Test edge cases of core RestSession functionality.""" |
| 40 | + |
| 41 | + @pytest.mark.ratelimit |
| 42 | + def test_rate_limit_support(self, api, rooms_list, add_rooms): |
| 43 | + # Add log handler |
| 44 | + root_logger = logging.getLogger() |
| 45 | + rate_limit_detector = RateLimitDetector() |
| 46 | + root_logger.addHandler(rate_limit_detector) |
| 47 | + |
| 48 | + try: |
| 49 | + # Try and trigger a rate-limit |
| 50 | + rooms = api.rooms.list(max=1) |
| 51 | + while not rate_limit_detector.rate_limit_detected: |
| 52 | + for room in rooms: |
| 53 | + # Do nothing |
| 54 | + pass |
| 55 | + |
| 56 | + finally: |
| 57 | + # Remove the log handler |
| 58 | + root_logger.removeHandler(rate_limit_detector) |
| 59 | + |
| 60 | + assert rate_limit_detector.rate_limit_detected == True |
0 commit comments