from unittest import TestCase

from amqp.adapter.data_message_factory import DataMessageFactory
from amqp.adapter.data_response_factory import DataResponseFactory
from amqp.model.model import DataMessageMagicByte
from amqp.model.snowflake_id import SnowflakeId


class TestDataResponseFactory(TestCase):

    def test_create_async_response_message(self):
        _f = DataResponseFactory()
        _g = DataMessageFactory(111)
        _resp = _f.create_async_response_message(_g.generate_snowflake_id())
        self.assertEqual("200", _resp.response_code())
        self.assertEqual(b"OK", _resp.body())

    def test_serialize(self):
        _f = DataResponseFactory()
        _g = DataMessageFactory(111)
        _snowflakeId: SnowflakeId = _g.generate_snowflake_id()
        _resp = _f.create_async_response_message(_snowflakeId)
        _ser = _f.serialize(_resp)
        self.assertEqual(
            2,
            str(_ser[2:]).index(DataMessageMagicByte.HTTP_REQUEST.value + _snowflakeId.as_string()),
            "Magic byte and SnowflakeId not found",
        )
        self.assertGreater(str(_ser[2:]).index("|e=|"), 2)
        self.assertEqual((_ser[0] + _ser[1]), len(_ser) - 2 - len("T0s="))

    def test_from_bytes(self):
        _f = DataResponseFactory()
        _g = DataMessageFactory(111)
        _snowflakeId: SnowflakeId = _g.generate_snowflake_id()
        _resp = _f.create_async_response_message(_snowflakeId)
        _ser = _f.serialize(_resp)
        _deser = _f.from_bytes(_ser)
        self.assertEqual(_snowflakeId.as_string(), _deser.id())
        self.assertEqual("200", _deser.response_code())
        self.assertEqual(b"OK", _deser.body())
