"""Tests for ceilometer/publisher/udp.py
"""

import datetime
import mock
import msgpack
from oslo.config import cfg

from ceilometer import sample
from ceilometer.publisher import udp
from ceilometer.tests import base
from ceilometer.openstack.common import network_utils


COUNTER_SOURCE = 'testsource'


class TestUDPPublisher(base.TestCase):

    test_data = [
        sample.Sample(
            name='test',
            type=sample.TYPE_CUMULATIVE,
            unit='',
            volume=1,
            user_id='test',
            project_id='test',
            resource_id='test_run_tasks',
            timestamp=datetime.datetime.utcnow().isoformat(),
            resource_metadata={'name': 'TestPublish'},
            source=COUNTER_SOURCE,
        ),
        sample.Sample(
            name='test',
            type=sample.TYPE_CUMULATIVE,
            unit='',
            volume=1,
            user_id='test',
            project_id='test',
            resource_id='test_run_tasks',
            timestamp=datetime.datetime.utcnow().isoformat(),
            resource_metadata={'name': 'TestPublish'},
            source=COUNTER_SOURCE,
        ),
        sample.Sample(
            name='test2',
            type=sample.TYPE_CUMULATIVE,
            unit='',
            volume=1,
            user_id='test',
            project_id='test',
            resource_id='test_run_tasks',
            timestamp=datetime.datetime.utcnow().isoformat(),
            resource_metadata={'name': 'TestPublish'},
            source=COUNTER_SOURCE,
        ),
        sample.Sample(
            name='test2',
            type=sample.TYPE_CUMULATIVE,
            unit='',
            volume=1,
            user_id='test',
            project_id='test',
            resource_id='test_run_tasks',
            timestamp=datetime.datetime.utcnow().isoformat(),
            resource_metadata={'name': 'TestPublish'},
            source=COUNTER_SOURCE,
        ),
        sample.Sample(
            name='test3',
            type=sample.TYPE_CUMULATIVE,
            unit='',
            volume=1,
            user_id='test',
            project_id='test',
            resource_id='test_run_tasks',
            timestamp=datetime.datetime.utcnow().isoformat(),
            resource_metadata={'name': 'TestPublish'},
            source=COUNTER_SOURCE,
        ),
    ]

    def _make_fake_socket(self, published):
        def _fake_socket_socket(family, type):
            def record_data(msg, dest):
                published.append((msg, dest))
            udp_socket = self.mox.CreateMockAnything()
            udp_socket.sendto = record_data
            self.mox.ReplayAll()
            return udp_socket
        return _fake_socket_socket

    def test_published(self):
        self.data_sent = []
        with mock.patch('socket.socket',
                        self._make_fake_socket(self.data_sent)):
            publisher = udp.UDPPublisher(
                network_utils.urlsplit('udp://somehost'))
        publisher.publish_samples(None,
                                  self.test_data)

        self.assertEqual(len(self.data_sent), 5)

        sent_counters = []

        for data, dest in self.data_sent:
            counter = msgpack.loads(data)
            sent_counters.append(counter)

            # Check destination
            self.assertEqual(dest, ('somehost',
                                    cfg.CONF.collector.udp_port))

        # Check that counters are equal
        self.assertEqual(sorted(sent_counters),
                         sorted([dict(d.as_dict()) for d in self.test_data]))

    @staticmethod
    def _raise_ioerror():
        raise IOError

    def _make_broken_socket(self, family, type):
        udp_socket = self.mox.CreateMockAnything()
        udp_socket.sendto = self._raise_ioerror
        self.mox.ReplayAll()

    def test_publish_error(self):
        with mock.patch('socket.socket',
                        self._make_broken_socket):
            publisher = udp.UDPPublisher(
                network_utils.urlsplit('udp://localhost'))
        publisher.publish_samples(None,
                                  self.test_data)
