"""
Tests for get_brmacs functionality in http_client.
"""

import asyncio
import unittest
from preseem.ssh_client import SshClient, NoBridgeError


class FakeSshClient(SshClient):
    """Stub out SSH Client."""

    async def scmd(self, cmd):
        """Fake scmd method to stub the ssh querying."""
        showmacs_output =  \
           """port no mac addr                is local?       ageing timer
                2     60:22:32:39:4d:32       no                 0.51
                1     60:22:32:6f:ab:a0       yes                0.00
                1     60:22:32:6f:ab:a0       yes                0.00
                2     62:22:32:39:4d:32       yes                0.00
                2     62:22:32:39:4d:32       yes                0.00
                1     c4:ad:34:2c:e3:6e       no                 0.05
                2     dc:2c:6e:c3:6d:88       no                 0.00
                2     dc:2c:6e:d1:76:cd       no                 1.43"""
        showmacs_output_br2 =  \
           """port no mac addr                is local?       ageing timer
                1     60:22:32:6f:ab:a0       yes                0.00
                1     60:22:32:6f:ab:a0       yes                0.00
                2     62:22:32:39:4d:32       yes                0.00
                2     62:22:32:39:4d:32       yes                0.00"""
        cmd = cmd.split()
        if cmd[0] == 'brctl' and len(cmd) > 2:
            if cmd[1] == 'showstp':
                if cmd[2] in ('br0', 'br2'):
                    return 'eth0 (1)\nprs0 (2)'
                else:
                    return ''
            elif cmd[1] == 'showmacs':
                if cmd[2] == 'br0':
                    return showmacs_output
                if cmd[2] == 'br2':
                    return showmacs_output_br2


class TestSshClient(unittest.TestCase):
    """Tests for SSH client."""

    def setUp(self):
        self.loop = asyncio.new_event_loop()  # needed to initialize asyncio
        asyncio.set_event_loop(self.loop)

    def tearDown(self):
        self.loop.close()

    def _await(self, co):
        return self.loop.run_until_complete(co)

    def test_get_brmacs(self):
        """Test functionality of get_brmacs for ssh_client."""
        # Test valid brname
        client = FakeSshClient('127.0.0.1')
        brmacs_results = self._await(client.get_brmacs('br0'))
        assert (brmacs_results)
        eth_macs = brmacs_results.get('eth0')
        self.assertEqual(eth_macs[0], 'c4:ad:34:2c:e3:6e')

        # Test invalid brname
        with self.assertRaises(NoBridgeError):
            brmacs_results = self._await(client.get_brmacs('br1'))

        # Test case with all local mac_address in the showmacs output
        brmacs_results = self._await(client.get_brmacs('br2'))
        assert (brmacs_results)
        eth_macs = brmacs_results.get('eth0')
        self.assertEqual(len(eth_macs), 0)
