# -*- coding: utf-8 -*-
"""ciscosparkapi/restsession.py Fixtures & Tests"""


import logging

import pytest


# Helper Classes
class RateLimitDetector(logging.Handler):
    """Detects occurrences of rate limiting."""

    def __init__(self):
        super(RateLimitDetector, self).__init__()

        self.rate_limit_detected = False

    def emit(self, record):
        """Check record to see if it is a rate-limit message."""
        assert isinstance(record, logging.LogRecord)

        if record.msg.startswith("Received rate-limit message"):
            self.rate_limit_detected = True


# CiscoSparkAPI Tests
class TestRestSession:
    """Test edge cases of core RestSession functionality."""

    @pytest.mark.ratelimit
    def test_rate_limit_retry_indefinitely(self, api, rooms_list, add_rooms):
        logger = logging.getLogger(__name__)

        # Save state and initialize test setup
        original_rate_limit_timer = api._session.rate_limit_timeout
        api._session.rate_limit_timeout = None

        # Add log handler
        root_logger = logging.getLogger()
        rate_limit_detector = RateLimitDetector()
        root_logger.addHandler(rate_limit_detector)

        try:
            # Try and trigger a rate-limit
            rooms = api.rooms.list(max=1)
            request_count = 0
            while not rate_limit_detector.rate_limit_detected:
                for room in rooms:
                    request_count += 1
                    if rate_limit_detector.rate_limit_detected:
                        break

        finally:
            logger.info("Rate-limit reached with approximately %s requests.",
                        request_count)
            # Remove the log handler and restore the pre-test state
            root_logger.removeHandler(rate_limit_detector)
            api._session.rate_limit_timeout = original_rate_limit_timer

        # Assert test condition
        assert rate_limit_detector.rate_limit_detected == True

@@ -490,30 +490,8 @@
  if 
-record.msg.startswith(
 %22Rec
@@ -515,17 +515,30 @@
 message%22
-)
+ in record.msg
 :%0A      
@@ -744,21 +744,8 @@
 etry
-_indefinitely
 (sel
@@ -878,32 +878,40 @@
        original_
+wait_on_
 rate_limit_timer
@@ -904,22 +904,16 @@
 te_limit
-_timer
  = api._
@@ -912,32 +912,40 @@
  = api._session.
+wait_on_
 rate_limit_timeo
@@ -938,24 +938,16 @@
 te_limit
-_timeout
 %0A       
@@ -952,32 +952,40 @@
    api._session.
+wait_on_
 rate_limit_timeo
@@ -982,22 +982,14 @@
 imit
-_timeout = Non
+ = Tru
 e%0A%0A 
@@ -1156,16 +1156,112 @@
 etector)
+%0A        logger = logging.getLogger(__name__)%0A        logger.info(%22Starting Rate Limit Testing%22)
 %0A%0A      
@@ -1900,16 +1900,24 @@
 session.
+wait_on_
 rate_lim
@@ -1922,16 +1922,8 @@
 imit
-_timeout
  = o
@@ -1930,16 +1930,24 @@
 riginal_
+wait_on_
 rate_lim
@@ -1952,14 +1952,8 @@
 imit
-_timer
 %0A%0A  

Update Rate Limit Test