# Copyright (c) 2015 Nicolas JOUANIN
#
# See the file license.txt for copying permission.
import anyio
import unittest

from hbmqtt.mqtt.subscribe import SubscribePacket, SubscribePayload
from hbmqtt.mqtt.packet import PacketIdVariableHeader
from hbmqtt.mqtt.constants import QOS_1, QOS_2
from hbmqtt.adapters import BufferAdapter


class SubscribePacketTest(unittest.TestCase):
    def test_from_stream(self):
        data = b'\x80\x0e\x00\x0a\x00\x03a/b\x01\x00\x03c/d\x02'
        stream = BufferAdapter(data)
        message = anyio.run(SubscribePacket.from_stream, stream)
        (topic, qos) = message.payload.topics[0]
        self.assertEqual(topic, 'a/b')
        self.assertEqual(qos, QOS_1)
        (topic, qos) = message.payload.topics[1]
        self.assertEqual(topic, 'c/d')
        self.assertEqual(qos, QOS_2)

    def test_to_stream(self):
        variable_header = PacketIdVariableHeader(10)
        payload = SubscribePayload(
            [
                ('a/b', QOS_1),
                ('c/d', QOS_2)
            ])
        publish = SubscribePacket(variable_header=variable_header, payload=payload)
        out = publish.to_bytes()
        self.assertEqual(out, b'\x82\x0e\x00\x0a\x00\x03a/b\x01\x00\x03c/d\x02')

[((16, 17, 16, 36), 'hbmqtt.adapters.BufferAdapter', 'BufferAdapter', ({(16, 31, 16, 35): 'data'}, {}), '(data)', False, 'from hbmqtt.adapters import BufferAdapter\n'), ((17, 18, 17, 64), 'anyio.run', 'anyio.run', ({(17, 28, 17, 55): 'SubscribePacket.from_stream', (17, 57, 17, 63): 'stream'}, {}), '(SubscribePacket.from_stream, stream)', False, 'import anyio\n'), ((26, 26, 26, 52), 'hbmqtt.mqtt.packet.PacketIdVariableHeader', 'PacketIdVariableHeader', ({(26, 49, 26, 51): '10'}, {}), '(10)', False, 'from hbmqtt.mqtt.packet import PacketIdVariableHeader\n'), ((27, 18, 31, 14), 'hbmqtt.mqtt.subscribe.SubscribePayload', 'SubscribePayload', ({(28, 12, 31, 13): "[('a/b', QOS_1), ('c/d', QOS_2)]"}, {}), "([('a/b', QOS_1), ('c/d', QOS_2)])", False, 'from hbmqtt.mqtt.subscribe import SubscribePacket, SubscribePayload\n'), ((32, 18, 32, 83), 'hbmqtt.mqtt.subscribe.SubscribePacket', 'SubscribePacket', (), '', False, 'from hbmqtt.mqtt.subscribe import SubscribePacket, SubscribePayload\n')]