
from io import StringIO
from time import sleep
import unittest

from tqdmpromproxy.proxy import TqdmPrometheusProxy


class ProxyIntegrationTest(unittest.TestCase):
    def test_export(self):
        try:
            proxy = TqdmPrometheusProxy()
            proxy.start()

            instances = [proxy.tqdm(i, desc=f'Item#{i}', total=100, position=i)
                         for i in range(10)]

            counter = 0
            for i in instances:
                i.update(counter*10)
                counter += 1

            def test():
                _buf = StringIO()
                proxy.http_server.bucketer.export(_buf)
                buf = _buf.getvalue()

                return 'Item#0' in buf, f"Wanted Item#0 in '{buf}'"

            self._retryable_assertion(test)
        finally:
            proxy.stop()

    def _retryable_assertion(self, test: callable, max_wait=10.0):
        delay = 0.2
        assertion = False
        while not assertion:
            assertion, message = test()
            if not assertion:
                delay *= 2
                if delay > max_wait:
                    break

                print(
                    f"Assertion failed. Recieved: {message}")
                sleep(delay)

        return self.assertTrue(assertion, message)
