import logging
import subprocess
import unittest
import urllib2

logging.basicConfig(level=logging.INFO)


class FloodlightDaemonTest(unittest.TestCase):
    def testOpenvSwitchDaemons(self):
        cmd = ["pgrep", "ovs-vswitchd"]
        logging.debug("Cmd: %s" % (cmd))
        output = subprocess.Popen(cmd, stdout=subprocess.PIPE).communicate()[0]
        logging.debug("Cmd output: %s", output)
        self.assertTrue(output.count('\n') >= 1,
                        "ovs-vswitchd not running or to many daemons"
                        " running: %s" % output)
        cmd = ["pgrep", "ovsdb-server"]
        logging.debug("Cmd: %s" % (cmd))
        output = subprocess.Popen(cmd, stdout=subprocess.PIPE).communicate()[0]
        logging.debug("Cmd output: %s", output)
        self.assertTrue(output.count('\n') >= 1,
                        "ovsdb-server not running or to many daemons"
                        "running: %s" % output)

    def testFloodlightDaemon(self):
        cmd = ["service", "floodlight", "status"]
        logging.debug("Cmd: %s" % (cmd))
        output = subprocess.Popen(cmd, stdout=subprocess.PIPE).communicate()[0]
        logging.debug("Cmd output: %s", output)
        self.assertTrue("running" in output,
                        "Floodlight daemon is not running: %s" % output)

    def testPorts(self):
        cmd = ["netstat", "-an"]
        logging.debug("Cmd: %s" % (cmd))
        output = subprocess.Popen(cmd, stdout=subprocess.PIPE).communicate()[0]
        logging.debug("Cmd output: %s", output)
        self.assertTrue(":::6633" in output,
                        "Floodlight Openflow Controller Port not found (6633)")
        self.assertTrue(":::8080" in output,
                        "Floodlight Web UI Port not found (8080)")
        self.assertTrue(":::6655" in output,
                        "Floodlight Debug Port not found (6655)")

    def testWebUI(self):
        local_host_url = 'http://localhost:8080/ui/index.html'
        try:
            fh = urllib2.urlopen(local_host_url)
        except urllib2.HTTPError, e:
            logging.error("Failed to open localhost, '%s' error", e)
            self.fail("Failed to connect to the localhost")
        output = fh.read()
        self.assertTrue('Big Switch Networks' in output,
                        output)


if __name__ == '__main__':
    unittest.main()
