# -*- coding: utf-8 -*-
from __future__ import absolute_import, with_statement

import sys
import time
import unittest

from json import loads

from abl.webconnector import UsageReporter
from StringIO import StringIO


class NonClosingStringIO(StringIO):
    def close(self):
        pass


class UsageReporterTests(unittest.TestCase):
    def test_exception_reporting(self):

        outf = NonClosingStringIO()

        ur = UsageReporter(outf)

        class TestException(Exception):
            pass

        try:
            with ur:
                raise TestException(u"Föö")
        except TestException:
            pass

        content = outf.getvalue()
        for line in content.split("\n"):
            if "=" in line:
                _, payload = line.split("=", 1)
                kind, json = payload.split(" ", 1)
                d = loads(json)
                assert "stacktrace" in d

        outf = NonClosingStringIO()
        ur = UsageReporter(outf)
        with ur:
            ur.log("foo")

        assert not "exception" in outf.getvalue()

        # test that SystemExit isn't reported.
        outf = NonClosingStringIO()
        ur = UsageReporter(outf)
        try:
            with ur:
                sys.exit()
        except SystemExit:
            pass

        assert not "SystemExit" in outf.getvalue()

    def test_none_as_file(self):
        ur = UsageReporter(None)
        ur.log("foobar")

    def test_microseconds(self):
        outf = NonClosingStringIO()

        ur = UsageReporter(outf)

        with ur:
            for _ in xrange(10):
                ur.log("foobar")
                time.sleep(0.01)

        content = outf.getvalue()

        ms_stamps = []
        for line in content.split("\n"):
            if not line.strip():
                continue
            ts = line.split("=")[0]
            ms = ts.split(".")[-1]
            self.assertEqual(len(ms), 6)
            ms_stamps += [ms]

        assert len(set(ms_stamps)) > 1, (
            "All microsecond stamps are the same: %s" % ms_stamps
        )


if __name__ == "__main__":
    import unittest

    unittest.main()
