import asyncio

import pytest

from aiospb.shared import DataType, UtcClock


class A_UTCClock:
    async def should_tick_every_fixed_time(self):
        clock = UtcClock()

        prev = 0

        async def tick(n: int):
            nonlocal prev
            count = 0
            async for tick in clock.get_ticker(50):
                if not prev:
                    prev = tick
                count += 1
                if count > n:
                    return n

        n = 4
        await asyncio.wait_for(tick(n), timeout=1)
        elapsed = clock.timestamp() - prev
        assert elapsed < n * 50 * 1.05
        assert elapsed > n * 50 * 0.95


class A_DataType:
    def should_convert_string_to_value(self):
        assert DataType.Int16.convert_value("11.6") == 11
        assert DataType.Float.convert_value("11.6") == 11.6
        assert DataType.String.convert_value("11.6") == "11.6"
        assert DataType.Boolean.convert_value("11.6") == True
        assert DataType.Bytes.convert_value("11.6") == b"11.6"
