def testTimeEvent4(self):
        """
        Run test with time interval in seconds.
        """
        self._log.debug( "\n\ntestTimeEvent4" )
        loader = EventRouterLoader()
        loader.loadHandlers( getDictFromXmlString(testConfigTime4) )

        loader.start()  # all tasks

        self._router = loader.getEventRouter()

        self.waitNEvents( 1 )
        TestEventLogger.logEvents()

        # first event should be isDark
        self.assert_( len(TestEventLogger._events) > 0)
        self.assertEqual( TestEventLogger._events[0].getType(), u'http://id.webbrick.co.uk/events/time/isDark' )
        self.assertEqual( TestEventLogger._events[0].getSource(), "time/isDark" )

        self.waitNEvents( 5 )
        TestEventLogger.logEvents()
        self.assert_( len(TestEventLogger._events) > 4)
        evt = TestEventLogger._events[1]
        od = evt.getPayload()
        self.assertEqual( len(od["timestr"]),8 )
        self.assertEqual( len(od["datestr"]),10 )
        self.assertEqual( len(od["datetimestr"]),19 )

        loader.stop()  # all tasks
        self.dumpEvents = False
class TestCalendarEvent(unittest.TestCase):

    def setUp(self):
        self._log = logging.getLogger( "TestCalendarEvent" )
        self._log.debug( "\n\nsetUp" )
        self.runner = None

    def tearDown(self):
        self._log.debug( "\n\ntearDown" )

        if self.runner:
            self.runner.stop()  # all tasks
            self.runner = None

    # Actual tests follow
    def testLoad(self):
        self._log.debug( "\ntestLoad" )
        self.loader = EventRouterLoader()
        self.loader.loadHandlers( getDictFromXmlString(testCalendarConfig) )
        self.loader.start()  # all tasks
        self.router = self.loader.getEventRouter()

    def testStartupAtHome(self):
        self._log.debug( "\ntestStartupAtHome" )
        self.loader = EventRouterLoader()
        self.loader.loadHandlers( getDictFromXmlString(testCalendarConfig) )
        self.loader.start()  # all tasks
        self.router = self.loader.getEventRouter()

        self.router.publish( EventAgent("TestCalendarEvent"), evtMinuteAtHome )

        self.assert_( TestEventLogger.expectNevents(2), "Expected 2 events only seen %s" % (len(TestEventLogger._events)) )
        # first is subscribe event
        self.assertEqual( TestEventLogger._events[0].getSource(), "time/minute" )
        self.assertEqual( TestEventLogger._events[1].getSource(), "occupants/home" )
        self.assertEqual( TestEventLogger._events[1].getPayload()["val"], 1 )
        
        
       
    
    def testDummy(self):
        return
Esempio n. 3
0
class Root(controllers.Root):

    # Class attributes overridden by instance value in start() method
    # (tested by stop() method below.)
    despatch = None
    discover = None

    def start(self):
        # Load and start the event dispatcher, 
        # and associated logic that performs WebBrick discovery

        self.eventloader = EventRouterLoader()
        # system files first.
        self.eventloader.loadHandlers( despatchConfig )
        if self.eventloader:
            self.eventloader.start()
        # now disovery handler.
        self.discover = Discovery.DiscoverHandler()
        self.discover.start(self.eventloader.getEventRouter())

        # wbtst     = WebBrick.WebBrickTest()
        # Assignments to the controller instance (or class) are used to define handing 
        # of URIs.  See cherrypy_cputil.get_object_trail() for some of the details.
        # (TODO: consider how this is affected by local instance attributes like
        #        'despatch' and 'discover' above.)
        if 0:
            # Local testing
            self.wbcnf = MockWbConfig.MockWebBrickCfgEdit()
        else:
            # Production / live WebBricks
            self.wbcnf = WbCfgManagerForm.WbCfgManagerForm(self.discover )
        self.testwbcnf = MockWbConfig.MockWebBrickCfgEdit()
#        self._log.warning( "**** System Configured ****" )

    def stop(self):
        """
        helper to shut down some class stuff.
        """
        if self.despatch:
            self.discover.stop(self.despatch)
            self.despatch.stop()

    @turbogears.expose(template="WebBrickConfig.templates.WbCfgWelcome")
    def index(self):
        return dict(now=time.ctime())

    @turbogears.expose(template="WebBrickConfig.templates.quiet")
    def quiet(self):
        return dict()

    # @turbogears.expose()
    def default(self,*args):
        raise cherrypy.HTTPRedirect(turbogears.url("/panels"))
    def testTimeEvent1(self):
        """
        Run test with time interval in minutes.
        """
        self._log.debug( "\n\ntestTimeEvent1" )
        loader = EventRouterLoader()
        loader.loadHandlers( getDictFromXmlString(testConfigTime1) )

        loader.start()  # all tasks

        self._router = loader.getEventRouter()

        self.waitNEvents( 1 )

        # should have isDark or isLight event
        TestEventLogger.logEvents()

        self.assertEqual( len(TestEventLogger._events), 1)
        self.assertEqual( TestEventLogger._events[0].getType(), u'http://id.webbrick.co.uk/events/time/isDark' )
        self.assertEqual( TestEventLogger._events[0].getSource(), "time/isDark" )
        # assume testing during daylight hours
        od = TestEventLogger._events[0].getPayload()
        #self.assertEqual( od["state"], 0 )

        maxTime = 70
        while (TestEventLogger._events[-1].getType() != u'http://id.webbrick.co.uk/events/time/minute') and (maxTime > 0):
            maxTime -= 1
            time.sleep(1)

        TestEventLogger.logEvents()

        # now look for correct url requests
        self.failUnless( len(TestEventLogger._events) >= 2)
        self.assertEqual( TestEventLogger._events[-1].getType(), u'http://id.webbrick.co.uk/events/time/minute' )
        self.assertEqual( TestEventLogger._events[-1].getSource(), "time/minute" )
        od = TestEventLogger._events[-1].getPayload()
        self.failUnless( od.has_key("second") ) 
        self.failUnless( od.has_key("minute") ) 
        self.failUnless( od.has_key("hour") ) 
        self.failUnless( od.has_key("day") ) 
        self.failUnless( od.has_key("date") ) 
        self.failUnless( od.has_key("month") ) 
        self.failUnless( od.has_key("year") ) 
        self.failUnless( od.has_key("week") ) 
        self.failUnless( od.has_key("dayofyear") ) 
        self.failUnless( od.has_key("timestr") ) 
        self.failUnless( od.has_key("datestr") ) 
        self.failUnless( od.has_key("datetimestr") ) 

        loader.stop()  # all tasks
        self.dumpEvents = False
Esempio n. 5
0
class TestEventState(unittest.TestCase):
    def setUp(self):
        self._log = logging.getLogger( "TestEventState" )
        self.router = None
        self.loader = None
        self.eventState = None
        return

    def tearDown(self):
        if self.eventState:
            self.eventState.stop( self.router )
            self.eventState = None

        if self.loader:
            self.loader.stop()  # all tasks
            self.loader = None
        self.router = None

        time.sleep(1)

    # Actual tests follow

    def TestEventState(self):
        # create testDespatch
        self.loader = EventRouterLoader()
        self.loader.loadHandlers( getDictFromXmlString(testConfigEvent) )
        self.loader.start()  # all tasks
        self.router = self.loader.getEventRouter()

        self.eventState = EventState()

        self.eventState.start( self.router );

        # request URL from .. 
        q1 = self.eventState.queryCache( 'webbrick/100/DO/0', 'state' )
        self.assertEqual( q1["stsval"], None )
        self.assertEqual( q1["stserr"], 'Not Known' )

        # send event
        self.router.publish( EventSource("TestEventState"), EventHandlers.tests.Events.evtDO_0_off )    # 0 Off
        # request good URL
        q2 = self.eventState.queryCache( 'webbrick/100/DO/0', 'state' )
        self.assertEqual( q2["stsval"], '0' )
        self.assertEqual( q2["stserr"], None )

        # request bad URL
        q3 = self.eventState.queryCache( 'webbrick/100/DO/1', 'state' )
        self.assertEqual( q3["stsval"], None )
        self.assertEqual( q3["stserr"], 'Not Known' )
Esempio n. 6
0
class TestDataset(unittest.TestCase):

    def setUp(self):
        self._log = logging.getLogger( "TestDataset" )
        self._log.debug( "\n\nsetUp" )

        self.router = None
        self.loader = None

    def tearDown(self):
        self._log.debug( "\n\ntearDown" )

        if self.loader:
            self.loader.stop()  # all tasks
            self.loader = None
        self.router = None

    # Actual tests follow
    def testDataset(self):
        """
        Test the data set creator
        """
        self._log.debug( "\ntestDataset" )
        logHandler = testLogHandler()
        addTestLogHandler(logHandler,"Dataset")

        self.loader = EventRouterLoader()
        self.loader.loadHandlers( getDictFromXmlString(testConfigDataset) )
        self.loader.start()  # all tasks
        self.router = self.loader.getEventRouter()

        self.router.publish( EventAgent("TestLogEvent"), Events.evtAI_1_50 )
        self.router.publish( EventAgent("TestLogEvent"), Events.evtCT_1_25 )
        self.router.publish( EventAgent("TestLogEvent"), Events.evtMinute1 )
        time.sleep(1.0)

        self.assertEqual( logHandler.count(), 2 )
        TestEventLogger.expectNevents(4)
        TestEventLogger.logEvents()

        removeTestLogHandler(logHandler,"Dataset")

    def testDummy(self):
        return
Esempio n. 7
0
class TestLogEvents(unittest.TestCase):

    def setUp(self):
        self._log = logging.getLogger( "TestLogEvents" )
        elog = logging.getLogger( "EventLog" )
        elog.setLevel(logging.INFO)
        self._log.debug( "\n\nsetUp" )

        self.router = None
        self.loader = None

    def tearDown(self):
        self._log.debug( "\n\ntearDown" )

        if self.loader:
            self.loader.stop()  # all tasks
            self.loader = None
        self.router = None

    # Actual tests follow
    def testEventLogger(self):
        """
        Test the even logger
        """
        self._log.debug( "\ntestEventLogger" )
        logHandler = testLogHandler()
        # need to ensure log level is at INFO for the eventlog stream otherwise test fails.
        addTestLogHandler(logHandler,"EventLog")

        self.loader = EventRouterLoader()
        self.loader.loadHandlers( getDictFromXmlString(testConfigEventLogger) )
        self.loader.start()  # all tasks
        self.router = self.loader.getEventRouter()

        self.router.publish( EventAgent("TestLogEvent"), Events.evtTD0 )
        self.router.publish( EventAgent("TestLogEvent"), Events.evtDI_1_off )
        time.sleep(1.0)

        self.assertEqual( logHandler.count(),1 )

        removeTestLogHandler(logHandler,"EventLog")

    def testDummy(self):
        return
    def testTimeEvent3(self):
        """
        Run test with time interval in seconds.
        """
        self._log.debug( "\n\ntestTimeEvent3" )
        loader = EventRouterLoader()
        loader.loadHandlers( getDictFromXmlString(testConfigTime3) )

        loader.start()  # all tasks

        self._router = loader.getEventRouter()

        self.waitNEvents( 16, 20 )

        TestEventLogger.logEvents()
        self.assert_( len(TestEventLogger._events) > 16)

        loader.stop()  # all tasks
        self.dumpEvents = False
class TestShellAction(unittest.TestCase):

    def setUp(self):
        self._log = logging.getLogger( "TestShellAction" )
        self._log.debug( "\n\nsetUp" )
        ClearDirectory( "TestOut" )

        self.router = None
        self.loader = None

    def tearDown(self):
        self._log.debug( "\n\ntearDown" )

        if self.loader:
            self.loader.stop()  # all tasks
            self.loader = None
        self.router = None

    # Actual tests follow
    def testShellEvent(self):
        self._log.debug( "\n\ntestShellEvent" )

        self.loader = EventRouterLoader()
        self.loader.loadHandlers( getDictFromXmlString(testConfigShell) )
        self.loader.start()  # all tasks
        self.router = self.loader.getEventRouter()

        self.router.publish( EventAgent("TestDelayedEvent"), Events.evtTD0 )
        self.router.publish( EventAgent("TestDelayedEvent"), Events.evtTD1 )
        time.sleep(1.0)

        # now look for correct contents in TestShellAction.txt
        try:
            res =  readFile(TestOutFile)
        except Exception, ex:
            self._log.exception(ex)
            res =""
        self.assertEqual( res, "response string1\nresponse string2\n" )
        ClearDirectory( "TestOut" )
class TestScheduleProcessor(unittest.TestCase):
    def setUp(self):
        self._log = logging.getLogger( "TestScheduleProcessor" )
        self._log.debug( "\n\nsetUp" )

        self.loader = None
        self.router = None
        self.setCwd = False
        if exists("EventHandlers/tests/resources"):
            self.setCwd = True
            os.chdir("EventHandlers/tests")

    def tearDown(self):
        self._log.debug( "\ntearDown" )

        if self.loader:
            self.loader.stop()  # all tasks
            self.loader = None
        self.router = None
        if self.setCwd:
            os.chdir("../..")

        time.sleep(1)

    # Actual tests follow
    def testLoad(self):
        self._log.debug( "\ntestLoad" )
        self.loader = EventRouterLoader()
        self.loader.loadHandlers( getDictFromXmlString(testConfig1) )
        self.loader.start()  # all tasks
        self.router = self.loader.getEventRouter()
        time.sleep(1.0)

        # We should see lots of events here as initial pass.
        TestEventLogger.logEvents()
        oldLen = len(TestEventLogger._events)
        self.assertEqual( oldLen, 11 )  # twice sent.

    def testRun(self):
        self._log.debug( "\ntestRun" )
        self.loader = EventRouterLoader()
        self.loader.loadHandlers( getDictFromXmlString(testConfig1) )
        self.loader.start()  # all tasks
        self.router = self.loader.getEventRouter()
        time.sleep(0.1)

        # We should see lots of events here as initial pass.
        TestEventLogger.logEvents()
        oldLen = len(TestEventLogger._events)
        self.assertEqual( oldLen, 11 )  # twice sent.
        TestEventLogger.clearEvents()
        
        # send midnight
        # no new events, just me
        self.router.publish( EventAgent("TestScheduleProcessor"), evtMidnightMon )
        time.sleep(0.1)
        oldLen = len(TestEventLogger._events)
        TestEventLogger.logEvents()
        self.assertEqual( oldLen, 1 )
        self.assertEqual( TestEventLogger._events[0].getSource(), "time/minute" )

        # first event time
        self.router.publish( EventAgent("TestScheduleProcessor"), evt0530 )
        time.sleep(0.2)
        # time and two actions
        oldLen = len(TestEventLogger._events)
        TestEventLogger.logEvents()
        self.assertEqual( oldLen, 4 )
        self.assertEqual( TestEventLogger._events[1].getSource(), "time/minute" )
        self.assertEqual( TestEventLogger._events[2].getSource(), "zone1/set" )
        self.assertEqual( TestEventLogger._events[3].getSource(), "boiler/On" )

        # second event time
        self.router.publish( EventAgent("TestScheduleProcessor"), evt0800 )
        time.sleep(0.1)
        # time and one actions
        oldLen = len(TestEventLogger._events)
        TestEventLogger.logEvents()
        self.assertEqual( oldLen, 6 )
        self.assertEqual( TestEventLogger._events[4].getSource(), "time/minute" )
        self.assertEqual( TestEventLogger._events[5].getSource(), "zone1/set" )

        # third event time
        self.router.publish( EventAgent("TestScheduleProcessor"), evt1600 )
        time.sleep(0.1)
        # time and one actions
        oldLen = len(TestEventLogger._events)
        TestEventLogger.logEvents()
        self.assertEqual( oldLen, 8 )
        self.assertEqual( TestEventLogger._events[6].getSource(), "time/minute" )
        self.assertEqual( TestEventLogger._events[7].getSource(), "boiler/Off" )

        # fourth event time
        self.router.publish( EventAgent("TestScheduleProcessor"), evt2200 )
        time.sleep(0.1)
        # time and two actions
        oldLen = len(TestEventLogger._events)
        TestEventLogger.logEvents()
        self.assertEqual( oldLen, 11 )
        self.assertEqual( TestEventLogger._events[8].getSource(), "time/minute" )
        self.assertEqual( TestEventLogger._events[9].getSource(), "zone1/set" )
        self.assertEqual( TestEventLogger._events[10].getSource(), "boiler/On" )


    def testDummy(self):
        return
Esempio n. 11
0
class TestWebbrick(unittest.TestCase):
    def setUp(self):
        self._log = logging.getLogger( "TestWebbrick" )
        self.loader = None
        self.router = None
        self.nameCache = WebbrickNodeNameCache()
        self.cache = WebbrickStatusCache( self.nameCache )
        return

    def tearDown(self):
        self.cache.stop( self.router );
        if self.loader:
            self.loader.stop()  # all tasks
            self.loader = None
        self.router = None
        return

    # Actual tests follow

    def testWebbrickNameCache(self):
        self.loader = EventRouterLoader()
        self.loader.loadHandlers( getDictFromXmlString(testConfigEventLogOnly) )
        self.loader.start()  # all tasks
        self.router = self.loader.getEventRouter()

        self.nameCache.start( self.router );
        self.router.publish( "TestWebbrick", Event( "http://id.webbrick.co.uk/events/webbrick/config/nodename", 
                "webbrick/100", 
                { "fromNode": 5, "nodename":"NameTest", "ipAdr": "1.2.3.4" } ) )
        self.assertEqual( self.nameCache.getNodeNumber("NameTest"), 5 )
        self.assertEqual( self.nameCache.getIpAddress("NameTest"), "1.2.3.4" )
        self.assertEqual( self.nameCache.getIpAddress(5), "1.2.3.4" )
        self.assertEqual( self.nameCache.getNodeNumFromIpAdr("1.2.3.4"), 5 )

    def testWebbrickStatusCache(self):
        self.loader = EventRouterLoader()
        self.loader.loadHandlers( getDictFromXmlString(testConfigEventLogOnly) )
        self.loader.start()  # all tasks
        self.router = self.loader.getEventRouter()

        self.nameCache.start( self.router );
        self.cache.start( self.router );

        # send some test values.
        typeRoot = "http://id.webbrick.co.uk/events/webbrick/"
        srcRoot = "webbrick/100/"
        self.router.publish( "TestWebbrick", Event( typeRoot+"CT", 
                srcRoot + "CT/1", 
                { "fromNode": 100, "srcChannel": 1, "val": 21.5 } ) )
        self.router.publish( "TestWebbrick", Event( typeRoot+"DI", 
                srcRoot + "DI/1", 
                { "fromNode": 100, "srcChannel": 1, "state": 1 } ) )
        self.router.publish( "TestWebbrick", Event( typeRoot+"DO", 
                srcRoot + "DO/1", 
                { "fromNode": 100, "srcChannel": 1, "state": 1 } ) )
        self.router.publish( "TestWebbrick", Event( typeRoot+"AI", 
                srcRoot + "AI/1", 
                { "fromNode": 100, "srcChannel": 1, "val": 49.5 } ) )
        self.router.publish( "TestWebbrick", Event( typeRoot+"AO", 
                srcRoot + "AO/1", 
                { "fromNode": 100, "srcChannel": 1, "val": 49.5 } ) )
        #
        # now query cache.
        #
        res = self.cache.queryCache( "100","Tmp","1" )
        self._log.debug( "queryCache %s", ( res ) )
        self.assertEqual( res["stsval"], 21.5 )
        self.assertEqual( res["stserr"], None )

        res = self.cache.queryCache( "100","DI","1" )
        self._log.debug( "queryCache %s", ( res ) )
        self.assertEqual( res["stsval"], "True" )
        self.assertEqual( res["stserr"], None )

        res = self.cache.queryCache( "100","DO","1" )
        self._log.debug( "queryCache %s", ( res ) )
        self.assertEqual( res["stsval"], "True" )
        self.assertEqual( res["stserr"], None )

        res = self.cache.queryCache( "100","AI","1" )
        self._log.debug( "queryCache %s", ( res ) )
        self.assertEqual( res["stsval"], 49.5 )
        self.assertEqual( res["stserr"], None )

        res = self.cache.queryCache( "100","AO","1" )
        self._log.debug( "queryCache %s", ( res ) )
        self.assertEqual( res["stsval"], 49.5 )
        self.assertEqual( res["stserr"], None )

        res = self.cache.queryCache( "100","AO","0" )
        self._log.debug( "queryCache %s", ( res ) )
        self.assertEqual( res["stsval"], None )
        self.assertNotEqual( res["stserr"], None )


    def testWebbrickStatusCache2(self):
        # create testDespatch
        self.loader = EventRouterLoader()
        self.loader.loadHandlers( getDictFromXmlString(testConfigWebbrickStatusCache2) )
        self.loader.start()  # all tasks
        self.router = self.loader.getEventRouter()

        self.nameCache.start( self.router );
        self.cache.start( self.router );

        # Fiddle time, i.e. speed it up.
        self.router.publish( "TestWebbrick", Event( "http://id.webbrick.co.uk/events/time/minute", 
                "time/minute", { "minute": 0, "second": 1 } ) )
        time.sleep( 5 )
        # retrieve config
        self.router.publish( "TestWebbrick", Event( "http://id.webbrick.co.uk/events/time/second", 
                "time/second", { "minute": 0, "second": 5 } ) )
        time.sleep( 5 )
        # retrieve status
        self.router.publish( "TestWebbrick", Event( "http://id.webbrick.co.uk/events/time/second", 
                "time/second", { "minute": 0, "second": 10 } ) )
        time.sleep( 5 )

        #
        # now query cache.
        #
        nodeNr="UnNamed"
        res = self.cache.queryCache( nodeNr,"Tmp","0" )
        self._log.debug( "queryCache %s", ( res ) )
        self.assertNotEqual( res["stsval"], None )
        self.assertEqual( res["stserr"], None )

        res = self.cache.queryCache( nodeNr,"DI","0" )
        self._log.debug( "queryCache %s", ( res ) )
        self.assertNotEqual( res["stsval"], None )
        self.assertEqual( res["stserr"], None )

        res = self.cache.queryCache( nodeNr,"DO","0" )
        self._log.debug( "queryCache %s", ( res ) )
        self.assertNotEqual( res["stsval"], None )
        self.assertEqual( res["stserr"], None )

        res = self.cache.queryCache( nodeNr,"AI","0" )
        self._log.debug( "queryCache %s", ( res ) )
        self.assertNotEqual( res["stsval"], None )
        self.assertEqual( res["stserr"], None )

        res = self.cache.queryCache( nodeNr,"AO","0" )
        self._log.debug( "queryCache %s", ( res ) )
        self.assertNotEqual( res["stsval"], None )
        self.assertEqual( res["stserr"], None )
Esempio n. 12
0
class TestPersistDatabase(unittest.TestCase):
    def persistDatabaseEmpty(self):
        host = "127.0.0.1"
        port = "6379"
        tn = telnetlib.Telnet(host, port)
        self._log.debug(tn.read_eager())
        tn.write("FLUSHDB\n")
        tn.close()

    def persistDatabaseWrite4(self):
        r = redis.Redis(host="localhost", port=6379, db=0)
        r.set("http://id.webbrick.co.uk/events/config/set,test/source1.new", pickle.dumps("{'name':'value1'}"))
        r.set("http://id.webbrick.co.uk/events/config/set,test/source2.new", pickle.dumps("{'name':'value2'}"))
        r.set("http://id.webbrick.co.uk/events/config/set,test/source3.new", pickle.dumps("{'name':'value3'}"))
        r.set(
            "http://id.webbrick.co.uk/events/config/set,test/source4.new",
            pickle.dumps("{'name':'value4', 'name2':'value5'}"),
        )

    def queryDatabase(self, key):
        # self._log.info("Entering query database with key %s (cont.d)", key)
        r = redis.Redis(host="localhost", port=6379, db=0)
        value = r.get(key)
        if not value:
            value = {}
        else:
            value = pickle.loads(value)

        return value

    def setUp(self):
        self._log = logging.getLogger("TestPersistDatabase")
        self._log.debug("\nsetUp")
        self.persistDatabaseEmpty()
        self._log.info("Emptying Database")
        self.router = None
        self.loader = None

    def tearDown(self):
        self._log.debug("\n\ntearDown")
        if self.loader:
            self.loader.stop()  # all tasks
            self.loader = None
        self.router = None

    def expectNevents(self, cnt):
        idx = 2000
        while (len(TestEventLogger._events) < cnt) and (idx > 0):
            time.sleep(0.05)
            idx = idx - 1

        if len(TestEventLogger._events) != cnt:
            TestEventLogger.logEvents()

        self.assertEqual(len(TestEventLogger._events), cnt)

    def testWriteEmptyDatabase(self):
        """
        Test to write one entry to an empty database
        """
        self._log.debug("\ntestWriteEmptyDatabase")

        self.loader = EventRouterLoader()
        self.loader.loadHandlers(getDictFromXmlString(testPersistCfg))
        self.loader.start()  # all tasks
        self.router = self.loader.getEventRouter()

        self.router.publish(
            EventAgent("TestPersistDatabase"),
            Event("http://id.webbrick.co.uk/events/config/set", "test/persist4", {"val": 4}),
        )
        self.expectNevents(2)
        self.assertEqual(self.queryDatabase("http://id.webbrick.co.uk/events/config/set,test/persist4"), {"val": 4})

    def testDatabaseWriteNew(self):
        """
        Test to write new data to database using events 
        """
        self._log.debug("\ntestDatabaseWrite4")

        self.loader = EventRouterLoader()
        self.loader.loadHandlers(getDictFromXmlString(testPersistCfg))
        self.loader.start()  # all tasks
        self.router = self.loader.getEventRouter()

        self.router.publish(
            EventAgent("TestPersistDatabase"),
            Event("http://id.webbrick.co.uk/events/config/set", "test/source1", {"name": "value1.0"}),
        )
        self.router.publish(
            EventAgent("TestPersistDatabase"),
            Event("http://id.webbrick.co.uk/events/config/set", "test/source2", {"name": "value2.0"}),
        )
        self.router.publish(
            EventAgent("TestPersistDatabase"),
            Event("http://id.webbrick.co.uk/events/config/set", "test/source3", {"name": "value3.0"}),
        )
        self.router.publish(
            EventAgent("TestPersistDatabase"),
            Event(
                "http://id.webbrick.co.uk/events/config/set", "test/source4", {"name": "value4.0", "name2": "value5.0"}
            ),
        )

        self.expectNevents(8)

        self.assertEqual(
            self.queryDatabase("http://id.webbrick.co.uk/events/config/set,test/source1"), {"name": "value1.0"}
        )
        self.assertEqual(
            self.queryDatabase("http://id.webbrick.co.uk/events/config/set,test/source2"), {"name": "value2.0"}
        )
        self.assertEqual(
            self.queryDatabase("http://id.webbrick.co.uk/events/config/set,test/source3"), {"name": "value3.0"}
        )
        self.assertEqual(
            self.queryDatabase("http://id.webbrick.co.uk/events/config/set,test/source4"),
            {"name": "value4.0", "name2": "value5.0"},
        )

    def testDatabaseWrite4(self):
        """
        Test to over-write existing keys with new data; 4 keys present    
        """
        self.persistDatabaseEmpty()
        self.persistDatabaseWrite4()
        self._log.debug("\ntestDatabaseWrite4")

        self.loader = EventRouterLoader()
        self.loader.loadHandlers(getDictFromXmlString(testPersistCfg))
        self.loader.start()  # all tasks
        self.router = self.loader.getEventRouter()

        self.router.publish(
            EventAgent("TestPersistDatabase"),
            Event("http://id.webbrick.co.uk/events/config/set", "test/source1.new", {"name": "value1.0"}),
        )
        self.router.publish(
            EventAgent("TestPersistDatabase"),
            Event("http://id.webbrick.co.uk/events/config/set", "test/source2.new", {"name": "value2.0"}),
        )
        self.router.publish(
            EventAgent("TestPersistDatabase"),
            Event("http://id.webbrick.co.uk/events/config/set", "test/source3.new", {"name": "value3.0"}),
        )
        self.router.publish(
            EventAgent("TestPersistDatabase"),
            Event(
                "http://id.webbrick.co.uk/events/config/set",
                "test/source4.new",
                {"name": "value4.0", "name2": "value5.0"},
            ),
        )
        self.expectNevents(8)
        self.assertEqual(
            self.queryDatabase("http://id.webbrick.co.uk/events/config/set,test/source1.new"), {"name": "value1.0"}
        )
        self.assertEqual(
            self.queryDatabase("http://id.webbrick.co.uk/events/config/set,test/source2.new"), {"name": "value2.0"}
        )
        self.assertEqual(
            self.queryDatabase("http://id.webbrick.co.uk/events/config/set,test/source3.new"), {"name": "value3.0"}
        )
        self.assertEqual(
            self.queryDatabase("http://id.webbrick.co.uk/events/config/set,test/source4.new"),
            {"name": "value4.0", "name2": "value5.0"},
        )

    def testDatabaseWriteLoop(self):
        """
        Test to write x number of NvPs to empty database, default 2000
        """
        self.persistDatabaseEmpty()
        self._log.debug("\ntestDatabaseWriteLoop")
        self.loader = EventRouterLoader()
        self.loader.loadHandlers(getDictFromXmlString(testPersistCfg))
        self.loader.start()  # all tasks
        self.router = self.loader.getEventRouter()

        for i in range(0, 2000):
            self.router.publish(
                EventAgent("TestPersistDatabase"),
                Event(
                    "http://id.webbrick.co.uk/events/config/set",
                    "test/source" + str(i) + ".new",
                    {"name" + str(i): "value" + str(i) + ".0"},
                ),
            )

        self.expectNevents(4000)

        for i in range(0, 2000):
            self.assertEqual(
                self.queryDatabase("http://id.webbrick.co.uk/events/config/set,test/source" + str(i) + ".new"),
                {"name" + str(i): "value" + str(i) + ".0"},
            )

    def testDatabaseMultiValue(self):
        """
        Test to write multi value to database
        """
        self.persistDatabaseEmpty()
        self._log.debug("\ntestDatabaseMultiValue")
        self.loader = EventRouterLoader()
        self.loader.loadHandlers(getDictFromXmlString(testPersistCfg))
        self.loader.start()  # all tasks
        self.router = self.loader.getEventRouter()
        self.router.publish(
            EventAgent("TestPersistDatabase"),
            Event(
                "http://id.webbrick.co.uk/events/config/set",
                "test/multivalue",
                {0: 0, 1: 1, 1: "name", "name": 1, "key": "var", 9: 9},
            ),
        )
        self.expectNevents(2)
        self.assertEqual(
            self.queryDatabase("http://id.webbrick.co.uk/events/config/set,test/multivalue"),
            {0: 0, 1: 1, 1: "name", "name": 1, "key": "var", 9: 9},
        )

    def testDatabaseSameSource(self):
        """
        Test to multi-event, same source
        """
        self.persistDatabaseEmpty()
        self._log.debug("\ntestDatabaseSameSource")
        self.loader = EventRouterLoader()
        self.loader.loadHandlers(getDictFromXmlString(testPersistCfg))
        self.loader.start()  # all tasks
        self.router = self.loader.getEventRouter()

        for i in range(0, 2000):
            self.router.publish(
                EventAgent("TestPersistDatabase"),
                Event("http://id.webbrick.co.uk/events/config/set", "test/same", {1: 0, 2: i}),
            )

        self.expectNevents(4000)
        self.assertEqual(self.queryDatabase("http://id.webbrick.co.uk/events/config/set,test/same"), {1: 0, 2: 1999})

    def testCompress(self):
        """
        Test database compression    
        """
        self._aofFilePath = "/home/tombushby/Documents/Redis/redis2rc/redis-2.0.0-rc2/appendonly.aof"
        self._startSize = os.path.getsize(self._aofFilePath)
        self.persistDatabaseEmpty()
        self.persistDatabaseWrite4()
        self.persistDatabaseWrite4()
        self.persistDatabaseWrite4()
        self.persistDatabaseWrite4()
        self.persistDatabaseWrite4()
        self._log.debug("\ntestDatabaseCompress")
        self.loader = EventRouterLoader()
        self.loader.loadHandlers(getDictFromXmlString(testPersistCfg))
        self.loader.start()  # all tasks
        self.router = self.loader.getEventRouter()

        self.router.publish(
            EventAgent("TestPersistDatabase"),
            Event("http://id.webbrick.co.uk/events/time/minute", "test/source", {"hour": 2, "minute": 5}),
        )

        time.sleep(5)  # BGREWRITEAOF (compressing the AOF file) is a background process, it needs time

        self._endSize = os.path.getsize(self._aofFilePath)
        self.assertEqual(self._startSize > self._endSize, True)

    def testDummy(self):
        return
Esempio n. 13
0
class TestHeating(unittest.TestCase):
    def setUp(self):
        self._log = logging.getLogger( "TestHeating" )
        self._log.debug( "\n\nsetUp" )

        self.loader = None
        self.router = None

    def tearDown(self):
        self._log.debug( "\ntearDown" )

        if self.loader:
            self.loader.stop()  # all tasks
            self.loader = None
        self.router = None

        time.sleep(1)

    # Actual tests follow
    def testLoad(self):
        self._log.debug( "\ntestLoad" )
        self.loader = EventRouterLoader()
        self.loader.loadHandlers( getDictFromXmlString(testConfigHeating) )
        self.loader.start()  # all tasks
        self.router = self.loader.getEventRouter()

        # We should see lots of events here as initial pass.
        oldLen = len(EventHandlers.tests.TestEventLogger._events)
        self.assert_( oldLen > 0 )
        EventHandlers.tests.TestEventLogger.logEvents()

    def testLoadVerify(self):
        self._log.debug( "\ntestLoadVerify" )
        self.loader = EventRouterLoader()
        self.loader.loadHandlers( getDictFromXmlString(testConfigHeating) )
        self.loader.start()  # all tasks
        self.router = self.loader.getEventRouter()

        deviceDict = dict(verifyDevices)
        schedDict = dict(verifySched)
        actionDict = dict(verifyActions)
        time.sleep(1)

        # see whether we received what we expected
        self._log.debug( "************************************************************" )
        for ev in EventHandlers.tests.TestEventLogger._events:
            od = ev.getPayload()
            self._log.debug( "%s:%s:%s" % (ev.getType(),ev.getSource(),od) )
            if ev.getSource() == 'schedule/device':
                if deviceDict.has_key( od["devKey"] ):
                    del deviceDict[od["devKey"]]
            elif ev.getSource() == 'schedule/time':
                if schedDict.has_key( od["schKey"] ):
                    del schedDict[od["schKey"]]
            elif ev.getSource() == 'schedule/action':
                if actionDict.has_key( od["schKey"] ):
                    del actionDict[od["schKey"]]

        self._log.debug( "************************************************************" )
        #verify devices
        for ent in deviceDict:
            self._log.debug( "%s, %s" % (ent,deviceDict[ent]) )
        self.assertEqual( len(deviceDict.keys()),  0 )
        #verify schedules
        for ent in schedDict:
            self._log.debug( "%s, %s" % (ent,schedDict[ent]) )
        self.assertEqual( len(schedDict.keys()),  0 )
        #verify actions
        for ent in actionDict:
            self._log.debug( "%s, %s" % (ent,actionDict[ent]) )
        self.assertEqual( len(actionDict.keys()),  0 )
Esempio n. 14
0
class TestCounters(unittest.TestCase):

    def setUp(self):
        _log.debug( "\n\nsetUp" )

    def tearDown(self):
        _log.debug( "\n\ntearDown" )

    # Actual tests follow
    def testLoad(self):
        _log.debug( "\ntestLoad" )
        self.loader = EventRouterLoader()
        errCount = self.loader.loadHandlers( getDictFromXmlString(testConfigIncrement) )
        self.assertEqual( errCount, 0)

        self.loader.start()  # all tasks
        self.router = self.loader.getEventRouter()

        self.router.publish( EventAgent("testCounters"), Events.evtMinute1 )

        Utils.expectNevents(self, 1)

        TestEventLogger.logEvents()
        self.assertEqual( len(TestEventLogger._events), 1)
        self.assertEqual( TestEventLogger._events[0].getSource(), "time/minute" )

    def testIntCounterSet(self):
        """
        Set Counter to a fixed value 
        """
        _log.debug( "\ntestIntCounterSet" )
        self.loader = EventRouterLoader()
        errCount = self.loader.loadHandlers( getDictFromXmlString(testConfigCounterSet) )
        self.assertEqual( errCount, 0)

        self.loader.start()  # all tasks
        self.router = self.loader.getEventRouter()

        self.router.publish( EventAgent("testCounters"), makeEvent( 'test/event', 'set/counter', { 'val':'200' } ) )

        TestEventLogger.logEvents()
        expectedEvents = { 
                    "test/event" : 
                            [
                                ("set/counter" , 'val', 200)
                            ],
                    "test/1" : 
                            [   ("test/entryCount",'val', 200)
                            ]
                     }
       
        Utils.expectNevents(self, 2)
        
        haveErr, excessEvents = Utils.verifyEvents2( expectedEvents, TestEventLogger._events )
        _log.debug( "Excess Events %s " % (excessEvents) )

        self.assertEqual( haveErr, False, "Incorrect event set" )


    def testFloatCounterSet(self):
        """
        Set Counter to a fixed value 
        """
        _log.debug( "\ntestFloatCounterSet" )
        self.loader = EventRouterLoader()
        errCount = self.loader.loadHandlers( getDictFromXmlString(testConfigFloatCounterSet) )
        self.assertEqual( errCount, 0)

        self.loader.start()  # all tasks
        self.router = self.loader.getEventRouter()

        self.router.publish( EventAgent("testCounters"), makeEvent( 'test/event', 'set/counter', { 'val':'300.45' } ) )

        TestEventLogger.logEvents()
        expectedEvents = { 
                    "test/event" : 
                            [
                                ("set/counter" , 'val', 300.45)
                            ],
                    "test/1" : 
                            [   ("test/entryCount",'val', 300.45)
                            ]
                     }
       
        Utils.expectNevents(self, 2)

        
        haveErr, excessEvents = Utils.verifyEvents2( expectedEvents, TestEventLogger._events )
        _log.debug( "Excess Events %s " % (excessEvents) )

        self.assertEqual( haveErr, False, "Incorrect event set" )


    def testIntCounter(self):
        """
        Normal increment, no events on increment just a reset
        """
        _log.debug( "\ntestIntCounter" )
        self.loader = EventRouterLoader()
        errCount = self.loader.loadHandlers( getDictFromXmlString(testConfigIncrement) )
        self.assertEqual( errCount, 0)

        self.loader.start()  # all tasks
        self.router = self.loader.getEventRouter()

        self.router.publish( EventAgent("testCounters"), Events.evtTD0 )
        self.router.publish( EventAgent("testCounters"), Events.evtTD0 )
        self.router.publish( EventAgent("testCounters"), Events.evtHour03 )

        TestEventLogger.logEvents()
        expectedEvents = { 
                    "http://id.webbrick.co.uk/events/webbrick/TD" : 
                            [
                                ("webbrick/100/TD/0" , None, None),
                                ("webbrick/100/TD/0" , None, None)
                            ],
                    "http://id.webbrick.co.uk/events/time/hour" : 
                            [   ("time/hour",None, None)
                            ],
                    "test/entryCount" : 
                            [   ("test/entryCount",'val', 2)
                            ],
                     }
        Utils.expectNevents(self, 4)

        haveErr, excessEvents = Utils.verifyEvents2( expectedEvents, TestEventLogger._events )
        _log.debug( "Excess Events %s " % (excessEvents) )

        self.assertEqual( haveErr, False, "Incorrect event set" )

    def testIntCounterPublish(self):
        """
        Normal increment, events on limit and a reset event
        """
        _log.debug( "\ntestIntCounterPublish" )
        self.loader = EventRouterLoader()
        errCount = self.loader.loadHandlers( getDictFromXmlString(testConfigIncrementPublish) )
        self.assertEqual( errCount, 0)

        self.loader.start()  # all tasks
        self.router = self.loader.getEventRouter()

        self.router.publish( EventAgent("testCounters"), Events.evtTD0 )
        self.router.publish( EventAgent("testCounters"), Events.evtTD0 )
        self.router.publish( EventAgent("testCounters"), Events.evtHour03 )

        TestEventLogger.logEvents()
        expectedEvents = { 
                    "http://id.webbrick.co.uk/events/webbrick/TD" : 
                            [
                                ("webbrick/100/TD/0" , None, None),
                                ("webbrick/100/TD/0" , None, None)
                            ],
                    "http://id.webbrick.co.uk/events/time/hour" : 
                            [   ("time/hour",None, None)
                            ],
                    "test/entryCount" : 
                            [   ("test/entryCount",'val', 1)
                            ,   ("test/entryCount",'val', 2)
                            ,   ("test/entryCountTotal",'val', 2)
                            ],
                     }

        Utils.expectNevents(self, 6)

        haveErr, excessEvents = Utils.verifyEvents2( expectedEvents, TestEventLogger._events )
        _log.debug( "Excess Events %s " % (excessEvents) )

        self.assertEqual( haveErr, False, "Incorrect event set" )


    def testIntCounter2(self):
        """
        Normal increment, events on limit and a reset event
        """
        _log.debug( "\ntestIntCounter2" )
        self.loader = EventRouterLoader()
        errCount = self.loader.loadHandlers( getDictFromXmlString(testConfigIncrement2) )
        self.assertEqual( errCount, 0)

        self.loader.start()  # all tasks
        self.router = self.loader.getEventRouter()

        self.router.publish( EventAgent("testCounters"), Events.evtTD0 )
        self.router.publish( EventAgent("testCounters"), Events.evtTD0 )
        self.router.publish( EventAgent("testCounters"), Events.evtHour03 )

        TestEventLogger.logEvents()
        expectedEvents = { 
                    "http://id.webbrick.co.uk/events/webbrick/TD" : 
                            [
                                ("webbrick/100/TD/0" , None, None),
                                ("webbrick/100/TD/0" , None, None)
                            ],
                    "http://id.webbrick.co.uk/events/time/hour" : 
                            [   ("time/hour",None, None)
                            ],
                    "test/entryCount" : 
                            [   ("test/entryCount",'val', 2)
                            ,   ("test/entryCountTotal",'val', 2)
                            ],
                     }
        Utils.expectNevents(self, 5)

        haveErr, excessEvents = Utils.verifyEvents2( expectedEvents, TestEventLogger._events )
        _log.debug( "Excess Events %s " % (excessEvents) )

        self.assertEqual( haveErr, False, "Incorrect event set" )

    def testIntCounter2Reset(self):
        """
        Normal increment, events on limit and a reset event
        """
        _log.debug( "\ntestIntCounter2" )
        self.loader = EventRouterLoader()
        errCount = self.loader.loadHandlers( getDictFromXmlString(testConfigIncrement2Reset) )
        self.assertEqual( errCount, 0)

        self.loader.start()  # all tasks
        self.router = self.loader.getEventRouter()

        self.router.publish( EventAgent("testCounters"), Events.evtTD0 )
        self.router.publish( EventAgent("testCounters"), Events.evtTD0 )
        self.router.publish( EventAgent("testCounters"), Events.evtHour03 )

        TestEventLogger.logEvents()
        expectedEvents = { 
                    "http://id.webbrick.co.uk/events/webbrick/TD" : 
                            [
                                ("webbrick/100/TD/0" , None, None),
                                ("webbrick/100/TD/0" , None, None)
                            ],
                    "http://id.webbrick.co.uk/events/time/hour" : 
                            [   ("time/hour",None, None)
                            ],
                    "test/entryCount" : 
                            [   ("test/entryCount",'val', 2)
                            ,   ("test/entryCountTotal",'val', 0)   # we resetted counter
                            ],
                     }

        Utils.expectNevents(self, 5)

        haveErr, excessEvents = Utils.verifyEvents2( expectedEvents, TestEventLogger._events )
        _log.debug( "Excess Events %s " % (excessEvents) )

        self.assertEqual( haveErr, False, "Incorrect event set" )

    def testIntCounter3(self):
        """
        Normal increment, events on limit no reset until twice below limit.
        """
        _log.debug( "\ntestIntCounter3" )
        self.loader = EventRouterLoader()
        errCount = self.loader.loadHandlers( getDictFromXmlString(testConfigIncrement2) )
        self.assertEqual( errCount, 0)

        self.loader.start()  # all tasks
        self.router = self.loader.getEventRouter()

        self.router.publish( EventAgent("testCounters"), Events.evtTD0 )
        self.router.publish( EventAgent("testCounters"), Events.evtTD0 )
        self.router.publish( EventAgent("testCounters"), Events.evtTD0 )
        self.router.publish( EventAgent("testCounters"), Events.evtHour03 )

        TestEventLogger.logEvents()
        expectedEvents = { 
                    "http://id.webbrick.co.uk/events/webbrick/TD" : 
                            [
                                ("webbrick/100/TD/0" , None, None),
                                ("webbrick/100/TD/0" , None, None),
                                ("webbrick/100/TD/0" , None, None)
                            ],
                    "http://id.webbrick.co.uk/events/time/hour" : 
                            [   ("time/hour",None, None)
                            ],
                    "test/entryCount" : 
                            [   ("test/entryCount",'val', 2)
                            ,   ("test/entryCount",'val', 3)
                            ,   ("test/entryCountTotal",'val', 3)
                            ],
                     }
        Utils.expectNevents(self, 7)

        haveErr, excessEvents = Utils.verifyEvents2( expectedEvents, TestEventLogger._events )
        _log.debug( "Excess Events %s " % (excessEvents) )

        self.assertEqual( haveErr, False, "Incorrect event set" )

    def testIntCounter3Reset(self):
        """
        """
        _log.debug( "\ntestIntCounter3Reset" )
        self.loader = EventRouterLoader()
        errCount = self.loader.loadHandlers( getDictFromXmlString(testConfigIncrement2Reset) )
        self.assertEqual( errCount, 0)

        self.loader.start()  # all tasks
        self.router = self.loader.getEventRouter()

        self.router.publish( EventAgent("testCounters"), Events.evtTD0 )
        self.router.publish( EventAgent("testCounters"), Events.evtTD0 )
        self.router.publish( EventAgent("testCounters"), Events.evtTD0 )
        self.router.publish( EventAgent("testCounters"), Events.evtHour03 )

        TestEventLogger.logEvents()
        expectedEvents = { 
                    "http://id.webbrick.co.uk/events/webbrick/TD" : 
                            [
                                ("webbrick/100/TD/0" , None, None),
                                ("webbrick/100/TD/0" , None, None),
                                ("webbrick/100/TD/0" , None, None)
                            ],
                    "http://id.webbrick.co.uk/events/time/hour" : 
                            [   ("time/hour",None, None)
                            ],
                    "test/entryCount" : 
                            [   ("test/entryCount",'val', 2)
                            ,   ("test/entryCountTotal",'val', 1)
                            ],
                     }
        Utils.expectNevents(self, 6)

        haveErr, excessEvents = Utils.verifyEvents2( expectedEvents, TestEventLogger._events )
        _log.debug( "Excess Events %s " % (excessEvents) )

        self.assertEqual( haveErr, False, "Incorrect event set" )

    def testIntCounterDec(self):
        _log.debug( "\ntestIntCounterDec" )
        self.loader = EventRouterLoader()
        errCount = self.loader.loadHandlers( getDictFromXmlString(testConfigDecrement) )
        self.assertEqual( errCount, 0)

        self.loader.start()  # all tasks
        self.router = self.loader.getEventRouter()

        self.router.publish( EventAgent("testCounters"), Events.evtTD0 )
        self.router.publish( EventAgent("testCounters"), Events.evtTD0 )
        self.router.publish( EventAgent("testCounters"), Events.evtHour03 )

        TestEventLogger.logEvents()

        expectedEvents = { 
                    "http://id.webbrick.co.uk/events/webbrick/TD" : 
                            [
                                ("webbrick/100/TD/0" , None, None),
                                ("webbrick/100/TD/0" , None, None)
                            ],
                    "http://id.webbrick.co.uk/events/time/hour" : 
                            [   ("time/hour",None, None)
                            ],
                    "test/entryCount" : 
                            [   ("test/entryCount",'val', 98)
                            ],
                     }
        Utils.expectNevents(self, 4)

        haveErr, excessEvents = Utils.verifyEvents2( expectedEvents, TestEventLogger._events )
        _log.debug( "Excess Events %s " % (excessEvents) )

        self.assertEqual( haveErr, False, "Incorrect event set" )

    def testIntCounterDec2(self):
        _log.debug( "\ntestIntCounterDec2" )
        self.loader = EventRouterLoader()
        errCount = self.loader.loadHandlers( getDictFromXmlString(testConfigDecrement2) )
        self.assertEqual( errCount, 0)

        self.loader.start()  # all tasks
        self.router = self.loader.getEventRouter()

        self.router.publish( EventAgent("testCounters"), Events.evtTD0 )
        self.router.publish( EventAgent("testCounters"), Events.evtTD0 )
        self.router.publish( EventAgent("testCounters"), Events.evtHour03 )

        TestEventLogger.logEvents()

        expectedEvents = { 
                    "http://id.webbrick.co.uk/events/webbrick/TD" : 
                            [
                                ("webbrick/100/TD/0" , None, None),
                                ("webbrick/100/TD/0" , None, None)
                            ],
                    "http://id.webbrick.co.uk/events/time/hour" : 
                            [   ("time/hour",None, None)
                            ],
                    "test/entryCount" : 
                            [   ("test/entryCount",'val', 98)
                            ,   ("test/entryCountTotal",'val', 98)
                            ],
                     }
        Utils.expectNevents(self, 5)

        haveErr, excessEvents = Utils.verifyEvents2( expectedEvents, TestEventLogger._events )
        _log.debug( "Excess Events %s " % (excessEvents) )

        self.assertEqual( haveErr, False, "Incorrect event set" )

    def testIntCounterDec2Reset(self):
        _log.debug( "\ntestIntCounterDec2Reset" )
        self.loader = EventRouterLoader()
        errCount = self.loader.loadHandlers( getDictFromXmlString(testConfigDecrement2Reset) )
        self.assertEqual( errCount, 0)

        self.loader.start()  # all tasks
        self.router = self.loader.getEventRouter()

        self.router.publish( EventAgent("testCounters"), Events.evtTD0 )
        self.router.publish( EventAgent("testCounters"), Events.evtTD0 )
        self.router.publish( EventAgent("testCounters"), Events.evtHour03 )

        TestEventLogger.logEvents()

        expectedEvents = { 
                    "http://id.webbrick.co.uk/events/webbrick/TD" : 
                            [
                                ("webbrick/100/TD/0" , None, None),
                                ("webbrick/100/TD/0" , None, None)
                            ],
                    "http://id.webbrick.co.uk/events/time/hour" : 
                            [   ("time/hour",None, None)
                            ],
                    "test/entryCount" : 
                            [   ("test/entryCount",'val', 98)
                            ,   ("test/entryCountTotal",'val', 100)
                            ],
                     }
        Utils.expectNevents(self, 5)

        haveErr, excessEvents = Utils.verifyEvents2( expectedEvents, TestEventLogger._events )
        _log.debug( "Excess Events %s " % (excessEvents) )

        self.assertEqual( haveErr, False, "Incorrect event set" )

    def testIntCounterDec3(self):
        _log.debug( "\ntestIntCounterDec3" )
        self.loader = EventRouterLoader()
        errCount = self.loader.loadHandlers( getDictFromXmlString(testConfigDecrement2) )
        self.assertEqual( errCount, 0)

        self.loader.start()  # all tasks
        self.router = self.loader.getEventRouter()

        self.router.publish( EventAgent("testCounters"), Events.evtTD0 )
        self.router.publish( EventAgent("testCounters"), Events.evtTD0 )
        self.router.publish( EventAgent("testCounters"), Events.evtTD0 )
        self.router.publish( EventAgent("testCounters"), Events.evtHour03 )

        TestEventLogger.logEvents()

        expectedEvents = { 
                    "http://id.webbrick.co.uk/events/webbrick/TD" : 
                            [
                                ("webbrick/100/TD/0" , None, None),
                                ("webbrick/100/TD/0" , None, None),
                                ("webbrick/100/TD/0" , None, None)
                            ],
                    "http://id.webbrick.co.uk/events/time/hour" : 
                            [   ("time/hour",None, None)
                            ],
                    "test/entryCount" : 
                            [   ("test/entryCount",'val', 98)
                            ,   ("test/entryCount",'val', 97)
                            ,   ("test/entryCountTotal",'val', 97)
                            ],
                     }
        Utils.expectNevents(self, 7)

        haveErr, excessEvents = Utils.verifyEvents2( expectedEvents, TestEventLogger._events )
        _log.debug( "Excess Events %s " % (excessEvents) )

        self.assertEqual( haveErr, False, "Incorrect event set" )

    def testIntCounterDec3Reset(self):
        _log.debug( "\ntestIntCounterDec3Reset" )
        self.loader = EventRouterLoader()
        errCount = self.loader.loadHandlers( getDictFromXmlString(testConfigDecrement2Reset) )
        self.assertEqual( errCount, 0)

        self.loader.start()  # all tasks
        self.router = self.loader.getEventRouter()

        self.router.publish( EventAgent("testCounters"), Events.evtTD0 )
        self.router.publish( EventAgent("testCounters"), Events.evtTD0 )
        self.router.publish( EventAgent("testCounters"), Events.evtTD0 )
        self.router.publish( EventAgent("testCounters"), Events.evtHour03 )

        TestEventLogger.logEvents()

        expectedEvents = { 
                    "http://id.webbrick.co.uk/events/webbrick/TD" : 
                            [
                                ("webbrick/100/TD/0" , None, None),
                                ("webbrick/100/TD/0" , None, None),
                                ("webbrick/100/TD/0" , None, None)
                            ],
                    "http://id.webbrick.co.uk/events/time/hour" : 
                            [   ("time/hour",None, None)
                            ],
                    "test/entryCount" : 
                            [   ("test/entryCount",'val', 98)
                            ,   ("test/entryCountTotal",'val', 99)
                            ],
                     }
        Utils.expectNevents(self, 6)

        haveErr, excessEvents = Utils.verifyEvents2( expectedEvents, TestEventLogger._events )
        _log.debug( "Excess Events %s " % (excessEvents) )

        self.assertEqual( haveErr, False, "Incorrect event set" )

    def testFloatCounter(self):
        _log.debug( "\ntestFloatCounter" )
        self.loader = EventRouterLoader()
        errCount = self.loader.loadHandlers( getDictFromXmlString(testConfigFloatIncrement) )
        self.assertEqual( errCount, 0)

        self.loader.start()  # all tasks
        self.router = self.loader.getEventRouter()

        self.router.publish( EventAgent("testCounters"), Events.evtTD0 )
        self.router.publish( EventAgent("testCounters"), Events.evtTD0 )
        self.router.publish( EventAgent("testCounters"), Events.evtHour03 )

        TestEventLogger.logEvents()
        expectedEvents = { 
                    "http://id.webbrick.co.uk/events/webbrick/TD" : 
                            [
                                ("webbrick/100/TD/0" , None, None),
                                ("webbrick/100/TD/0" , None, None)
                            ],
                    "http://id.webbrick.co.uk/events/time/hour" : 
                            [   ("time/hour",None, None)
                            ],
                    "test/entryCount" : 
                            [   ("test/entryCount",'val', 5.0)
                            ],
                     }
        Utils.expectNevents(self, 4)

        haveErr, excessEvents = Utils.verifyEvents2( expectedEvents, TestEventLogger._events )
        _log.debug( "Excess Events %s " % (excessEvents) )

        self.assertEqual( haveErr, False, "Incorrect event set" )

    def testFloatCounterDec(self):
        _log.debug( "\ntestIntCounterDec" )
        self.loader = EventRouterLoader()
        errCount = self.loader.loadHandlers( getDictFromXmlString(testConfigFloatDecrement) )
        self.assertEqual( errCount, 0)

        self.loader.start()  # all tasks
        self.router = self.loader.getEventRouter()

        self.router.publish( EventAgent("testCounters"), Events.evtTD0 )
        self.router.publish( EventAgent("testCounters"), Events.evtTD0 )
        self.router.publish( EventAgent("testCounters"), Events.evtHour03 )

        TestEventLogger.logEvents()

        expectedEvents = { 
                    "http://id.webbrick.co.uk/events/webbrick/TD" : 
                            [
                                ("webbrick/100/TD/0" , None, None),
                                ("webbrick/100/TD/0" , None, None)
                            ],
                    "http://id.webbrick.co.uk/events/time/hour" : 
                            [   ("time/hour",None, None)
                            ],
                    "test/entryCount" : 
                            [   ("test/entryCount",'val', 90.5)
                            ],
                     }
        Utils.expectNevents(self, 4)

        haveErr, excessEvents = Utils.verifyEvents2( expectedEvents, TestEventLogger._events )
        _log.debug( "Excess Events %s " % (excessEvents) )

        self.assertEqual( haveErr, False, "Incorrect event set" )

    def testIntCounterReset(self):
        _log.debug( "\ntestIntCounterReset" )
        self.loader = EventRouterLoader()
        errCount = self.loader.loadHandlers( getDictFromXmlString(testConfigIncrementReset) )
        self.assertEqual( errCount, 0)

        self.loader.start()  # all tasks
        self.router = self.loader.getEventRouter()

        self.router.publish( EventAgent("testCounters"), Events.evtTD0 )
        self.router.publish( EventAgent("testCounters"), Events.evtMinute1 )
        self.router.publish( EventAgent("testCounters"), Events.evtTD0 )
        self.router.publish( EventAgent("testCounters"), Events.evtHour03 )

        TestEventLogger.logEvents()
        expectedEvents = { 
                    "http://id.webbrick.co.uk/events/webbrick/TD" : 
                            [
                                ("webbrick/100/TD/0" , None, None),
                                ("webbrick/100/TD/0" , None, None)
                            ],
                    "http://id.webbrick.co.uk/events/time/minute" : 
                            [   ("time/minute",None, None)
                            ],
                    "http://id.webbrick.co.uk/events/time/hour" : 
                            [   ("time/hour",None, None)
                            ],
                    "test/entryCount" : 
                            [   ("test/entryCount",'val', 1)
                            ],
                     }
        Utils.expectNevents(self, 5)

        haveErr, excessEvents = Utils.verifyEvents2( expectedEvents, TestEventLogger._events )
        _log.debug( "Excess Events %s " % (excessEvents) )

        self.assertEqual( haveErr, False, "Incorrect event set" )

    def testDummy(self):
        expectedEvents = { 
                    "local/url" : 
                            { 
                                "local/BoilerOn": 1,
                                "local/HwOn": 1 
                            },
                    "http://id.webbrick.co.uk/events/webbrick/DO" : 
                            {   "webbrick/100/DO/0": 1,
                                "webbrick/100/DO/1": 2,
                            },
                     }
                     
        haveErr, excessEvents = Utils.verifyEvents( expectedEvents, TestEventLogger._events )
        _log.debug( "Excess Events %s " % (excessEvents) )

        self.assertEqual( haveErr, False, "Incorrect event set" )
Esempio n. 15
0
class testITunes(unittest.TestCase):

    def setUp(self):
        self._log = logging.getLogger( "testITunes" )
        self._log.debug( "\n\nsetUp" )

        self.router = None
        self.loader = None

    def tearDown(self):
        self._log.debug( "\n\ntearDown" )

        if self.loader:
            self.loader.stop()  # all tasks
            self.loader = None
        self.router = None

        time.sleep(5)

    # Actual tests follow
    def testLoad(self):
        self._log.debug( "\nTestLoad" )

        self.loader = EventRouterLoader()
        self.loader.loadHandlers( getDictFromXmlString(testConfigUPNP) )
        self.loader.start()  # all tasks
        self.router = self.loader.getEventRouter()

        time.sleep(5)

    def testStartStop(self):
        self._log.debug( "\ntestStartStop" )

        self.loader = EventRouterLoader()
        self.loader.loadHandlers( getDictFromXmlString(testConfigUPNP) )
        self.loader.start()  # all tasks
        self.router = self.loader.getEventRouter()

        time.sleep(5)

        self.router.publish( EventAgent("testITunes"), evt_Play )
        time.sleep(5)

        self.router.publish( EventAgent("testITunes"), evt_Next )
        time.sleep(5)

        self.router.publish( EventAgent("testITunes"), evt_Next )
        time.sleep(5)

        self.router.publish( EventAgent("testITunes"), evt_Pause )
        time.sleep(5)

        self.router.publish( EventAgent("testITunes"), evt_Play )
        time.sleep(5)

        self.router.publish( EventAgent("testITunes"), evt_Prev )
        time.sleep(5)

        self.router.publish( EventAgent("testITunes"), evt_Stop )
        time.sleep(5)

    def testVolume(self):
        self._log.debug( "\ntestVolume" )

        self.loader = EventRouterLoader()
        self.loader.loadHandlers( getDictFromXmlString(testConfigUPNP) )
        self.loader.start()  # all tasks
        self.router = self.loader.getEventRouter()

        time.sleep(5)

        self.router.publish( EventAgent("testITunes"), evt_Play )
        time.sleep(5)

        self.router.publish( EventAgent("testITunes"), evt_Volume100 )
        time.sleep(5)

        self.router.publish( EventAgent("testITunes"), evt_Volume50 )
        time.sleep(5)

        self.router.publish( EventAgent("testITunes"), evt_Volume0 )
        time.sleep(5)

        self.router.publish( EventAgent("testITunes"), evt_Volume100 )
        time.sleep(5)

    def testDummy(self):
        return
Esempio n. 16
0
class TestBackupHandler(unittest.TestCase):

    def clearDirectory(self, dname):
        for fn in os.listdir( dname ):
            fnf = "%s/%s" % (dname,fn)
            if isfile(fnf):
                _log.debug( "remove %s", fnf )
                os.remove( fnf )

    def setUp(self):
        _log.debug( "setup" )

        self.router = None
        self.loader = None

        ClearDirectory(workDir)
        ClearDirectory(outputDir)
        CopyDirectory(sourceDir, workDir)

        return

    def tearDown(self):

        if self.loader:
            self.loader.stop()  # all tasks
            self.loader = None
        self.router = None

        if isfile(testdata3):
            os.remove( testdata3 )

        return

    def waitForFile(self, fname, timeout=1.0 ):
        wait = timeout
        while wait > 0 and not isfile(fname):
            wait = wait - 0.1
            time.sleep(0.1)
            

    # Actual tests follow
    def testSingleFileLocal(self):
        """
        Initial single file backup
        """
        _log.debug( "\ntestSingleFileLocal" )

        self.loader = EventRouterLoader()
        self.loader.loadHandlers( getDictFromXmlString(testConfigSingleFile) )
        self.loader.start()  # all tasks
        self.router = self.loader.getEventRouter()

        self.router.publish( EventAgent("TestBackup"), Events.evtMinute1 )    # do initial backup
        self.waitForFile(fname01sd)

        self.loader.stop()  # all tasks
        self.loader = None

        # now verify file exists.
        self.failUnless( isfile( fname01sd ) )
        self.failUnless( zipfile.is_zipfile( fname01sd ) )
        # read zip info.
        zf = zipfile.ZipFile(fname01sd, 'r' ) # read only
        zfi = zf.infolist()
        self.assertEqual( len(zfi), 1 ) # one entry
        self.assertEqual( zfi[0].filename, "work/file1.txt" ) # one entry
        zf.close()

    def testSingleFileLocalCleanUp(self):
        """
        Initial single file backup
        """
        _log.debug( "\ntestSingleFileLocalCleanUp" )

        self.loader = EventRouterLoader()
        self.loader.loadHandlers( getDictFromXmlString(testConfigSingleFileCleanUp) )
        self.loader.start()  # all tasks
        self.router = self.loader.getEventRouter()

        self.router.publish( EventAgent("TestBackup"), Events.evtMinute1)    # do initial backup
        self.waitForFile(fname01sd)
                
        # now verify file exists.
        self.failUnless( isfile( fname01sd ) )
        self.failUnless( zipfile.is_zipfile( fname01sd ) )
        # read zip info.

        now = time.time()
        
        # change the timestamp of the file to make it appear to be 6 days old  days old
        past6 = now - 3600*24*6
        os.utime(fname01sd, (past6, past6))
        # invoke cleanup
        self.router.publish( EventAgent("TestBackup"), Events.evtMinute2 )
        time.sleep(0.5)
        # verify file still exists.
        self.failUnless( isfile( fname01sd ) )
        
        # change the timestamp of the file to make it appear to be 6 days old  days old
        past8 = now - 3600*24*8
        os.utime(fname01sd, (past8, past8))
        # invoke cleanup
        self.router.publish( EventAgent("TestBackup"), Events.evtMinute2 )
        time.sleep(0.5)
        # verify file has been deleted
        self.failIf( isfile( fname01sd ) )
        
        self.loader.stop()  # all tasks
        self.loader = None

    def testSingleFileLocalDelete(self):
        """
        Initial single file backup
        """
        _log.debug( "\ntestSingleFileLocalDelete" )

        copyfile( testdata1, testdata3 )
        self.loader = EventRouterLoader()
        self.loader.loadHandlers( getDictFromXmlString(testConfigSingleFileDelete) )
        self.loader.start()  # all tasks
        self.router = self.loader.getEventRouter()

        self.router.publish( EventAgent("TestBackup"), Events.evtMinute1 )    # do initial backup
        self.waitForFile(fname01)

        self.loader.stop()  # all tasks
        self.loader = None

        # now verify file exists.
        self.failUnless( isfile( fname01 ) )
        self.failUnless( zipfile.is_zipfile( fname01 ) )
        # read zip info.
        zf = zipfile.ZipFile(fname01, 'r' ) # read only
        zfi = zf.infolist()
        self.assertEqual( len(zfi), 1 ) # one entry
        self.assertEqual( zfi[0].filename, "work/file1_delete.txt" )
        self.failIf( isfile( testdata3 ) )  # should be deleted
        zf.close()
    
    def testSingleDirectoryLocal(self):
        _log.debug( "\ntestSingleDirectoryLocal" )

        self.loader = EventRouterLoader()
        self.loader.loadHandlers( getDictFromXmlString(testConfigSingleDirectory) )
        self.loader.start()  # all tasks
        self.router = self.loader.getEventRouter()

        self.router.publish( EventAgent("TestBackup"), Events.evtMinute1 )    # do initial backup
        self.waitForFile(fname01)

        self.loader.stop()  # all tasks
        self.loader = None

        # now verify file exists.
        self.failUnless( isfile( fname01 ) )
        self.failUnless( zipfile.is_zipfile( fname01 ) )
        # read zip info.
        zf = zipfile.ZipFile(fname01, 'r' ) # read only
        zfi = zf.infolist()
        self.assertEqual( len(zfi), 2 ) # two entrys
        self.assertEqual( zfi[0].filename, "file1.txt" )
        self.assertEqual( zfi[1].filename, "file2.txt" )
        zf.close()

    def testMultipleFilesLocal(self):
        _log.debug( "\ntestMultipleFilesLocal" )

        self.loader = EventRouterLoader()
        self.loader.loadHandlers( getDictFromXmlString(testConfigMultipleFile) )
        self.loader.start()  # all tasks
        self.router = self.loader.getEventRouter()

        self.router.publish( EventAgent("TestBackup"), Events.evtMinute1 )    # do initial backup
        self.waitForFile(fname01)

        self.loader.stop()  # all tasks
        self.loader = None

        # now verify file exists.
        self.failUnless( isfile( fname01 ) )
        self.failUnless( zipfile.is_zipfile( fname01 ) )
        # read zip info.
        zf = zipfile.ZipFile(fname01, 'r' ) # read only
        zfi = zf.infolist()
        self.assertEqual( len(zfi), 2 ) # two entrys
        self.assertEqual( zfi[0].filename, "work/file1.txt" )
        self.assertEqual( zfi[1].filename, "work/file2.txt" )
        zf.close()
        
        
    def testMultipleFilesLocalCleanUp(self):
        _log.debug( "\ntestMultipleFilesLocalCleanUp" )

        self.loader = EventRouterLoader()
        self.loader.loadHandlers( getDictFromXmlString(testConfigMultipleFileCleanUp) )
        self.loader.start()  # all tasks
        self.router = self.loader.getEventRouter()

        self.router.publish( EventAgent("TestBackup"), Events.evtMinute1 )    # do backup 1
        self.waitForFile(fname01)

        self.router.publish( EventAgent("TestBackup"), Events.evtMinute2 )    # do backup 2
        self.waitForFile(fname02)

        self.router.publish( EventAgent("TestBackup"), Events.evtMinute3 )    # do backup 3
        self.waitForFile(fname03)

        # now verify file exists.
        self.failUnless( isfile( fname01 ) )
        self.failUnless( isfile( fname02 ) )
        self.failUnless( isfile( fname03 ) )
       
        now = time.time()
        
        # change the timestamp of the file to make it appear to be 6 days old  days old
        past6 = now - 3600*24*6
        os.utime(fname02, (past6, past6))
        # invoke cleanup
        self.router.publish( EventAgent("TestBackup"), Events.evtMinute4 )
        time.sleep(0.5)
        # verify file still exists.
        self.failUnless( isfile( fname02 ) )
        
        # change the timestamp of the file to make it appear to be 6 days old  days old
        past8 = now - 3600*24*8
        os.utime(fname01, (past8, past8))
        os.utime(fname03, (past8, past8))
        # invoke cleanup
        self.router.publish( EventAgent("TestBackup"), Events.evtMinute4 )
        time.sleep(0.5)
        # verify file has been deleted
        self.failIf( isfile( fname01 ) )
        self.failUnless( isfile( fname02 ) )
        self.failIf( isfile( fname03 ) )
       
        self.loader.stop()  # all tasks
        self.loader = None

    def testMultipleDirectorysLocal(self):
        _log.debug( "\ntestMultipleDirectorysLocal" )

        self.loader = EventRouterLoader()
        self.loader.loadHandlers( getDictFromXmlString(testConfigMultipleDirectories) )
        self.loader.start()  # all tasks
        self.router = self.loader.getEventRouter()

        self.router.publish( EventAgent("TestBackup"), Events.evtMinute1 )    # do initial backup
        self.waitForFile(fname01)

        self.loader.stop()  # all tasks
        self.loader = None

        # now verify file exists.
        self.failUnless( isfile( fname01 ) )
        self.failUnless( zipfile.is_zipfile( fname01 ) )
        # read zip info.
        zf = zipfile.ZipFile(fname01, 'r' ) # read only
        zfi = zf.infolist()
        self.assertEqual( len(zfi), 4 )
        self.assertEqual( zfi[0].filename, "file1.txt" )
        self.assertEqual( zfi[1].filename, "file2.txt" )
        self.assertEqual( zfi[2].filename, "file1.1.txt" )
        self.assertEqual( zfi[3].filename, "file1.2.txt" )
        zf.close()

    def testSingleDirectoryRecursiveLocal(self):
        _log.debug( "\ntestSingleDirectoryRecursiveLocal" )

        self.loader = EventRouterLoader()
        self.loader.loadHandlers( getDictFromXmlString(testConfigSingleDirectoryRecursive) )
        self.loader.start()  # all tasks
        self.router = self.loader.getEventRouter()

        self.router.publish( EventAgent("TestBackup"), Events.evtMinute1 )    # do initial backup
        self.waitForFile(fname01)

        self.loader.stop()  # all tasks
        self.loader = None

        # now verify file exists.
        self.failUnless( isfile( fname01 ) )
        self.failUnless( zipfile.is_zipfile( fname01 ) )
        # read zip info.
        zf = zipfile.ZipFile(fname01, 'r' ) # read only
        zfi = zf.infolist()
        self.assertEqual( len(zfi), 4 )
        self.assertEqual( zfi[0].filename, "file1.txt" )
        self.assertEqual( zfi[1].filename, "file2.txt" )
        self.assertEqual( zfi[2].filename, "dir2/file1.1.txt" )
        self.assertEqual( zfi[3].filename, "dir2/file1.2.txt" )
        zf.close()

    def testMixedDataSetLocal(self):
        _log.debug( "\ntestMixedDataSetLocal" )

        self.loader = EventRouterLoader()
        self.loader.loadHandlers( getDictFromXmlString(testConfigMixed) )
        self.loader.start()  # all tasks
        self.router = self.loader.getEventRouter()

        self.router.publish( EventAgent("TestBackup"), Events.evtMinute1 )    # do initial backup
        self.waitForFile(fname01)

        self.loader.stop()  # all tasks
        self.loader = None

        # now verify file exists.
        self.failUnless( isfile( fname01 ) )
        self.failUnless( zipfile.is_zipfile( fname01 ) )
        # read zip info.
        zf = zipfile.ZipFile(fname01, 'r' ) # read only
        zfi = zf.infolist()
        self.assertEqual( len(zfi), 4 )
        self.assertEqual( zfi[0].filename, "work/file1.txt" )
        self.assertEqual( zfi[1].filename, "work/file2.txt" )
        self.assertEqual( zfi[2].filename, "file1.1.txt" )
        self.assertEqual( zfi[3].filename, "file1.2.txt" )
        zf.close()

    def testSingleDirectoryAbsoluteLocal(self):
        _log.debug( "\ntestSingleDirectoryAbsoluteLocal" )

        self.loader = EventRouterLoader()
        self.loader.loadHandlers( getDictFromXmlString(testConfigSingleDirectoryAbsolute) )
        self.loader.start()  # all tasks
        self.router = self.loader.getEventRouter()
        self.waitForFile(fname01)

        self.router.publish( EventAgent("TestBackup"), Events.evtMinute1 )    # do initial backup
        self.waitForFile(fname01)

        self.loader.stop()  # all tasks
        self.loader = None

        # now verify file exists.
        self.failUnless( isfile( fname01 ) )
        self.failUnless( zipfile.is_zipfile( fname01 ) )
        # read zip info.
        zf = zipfile.ZipFile(fname01, 'r' ) # read only
        zfi = zf.infolist()
        self.assertEqual( len(zfi), 2 ) # two entrys
        self.failUnless( zfi[0].filename.endswith("/work/file1.txt") )
        self.failUnless( zfi[1].filename.endswith("/work/file2.txt") )
        zf.close()

    def testMultipleFilesAbsoluteLocal(self):
        _log.debug( "\ntestMultipleFilesAbsoluteLocal" )

        self.loader = EventRouterLoader()
        self.loader.loadHandlers( getDictFromXmlString(testConfigMultipleFileAbsolute) )
        self.loader.start()  # all tasks
        self.router = self.loader.getEventRouter()

        self.router.publish( EventAgent("TestBackup"), Events.evtMinute1 )    # do initial backup
        self.waitForFile(fname01)

        self.loader.stop()  # all tasks
        self.loader = None

        # now verify file exists.
        self.failUnless( isfile( fname01 ) )
        self.failUnless( zipfile.is_zipfile( fname01 ) )
        # read zip info.
        zf = zipfile.ZipFile(fname01, 'r' ) # read only
        zfi = zf.infolist()
        self.assertEqual( len(zfi), 2 ) # two entrys
        self.failUnless( zfi[0].filename.endswith("/work/file1.txt") )
        self.failUnless( zfi[1].filename.endswith("/work/file2.txt") )
        zf.close()

    def testSingleDirectoryRecursiveAbsoluteLocal(self):
        _log.debug( "\ntestSingleDirectoryRecursiveAbsoluteLocal" )

        self.loader = EventRouterLoader()
        self.loader.loadHandlers( getDictFromXmlString(testConfigSingleDirectoryRecursiveAbsolute) )
        self.loader.start()  # all tasks
        self.router = self.loader.getEventRouter()

        self.router.publish( EventAgent("TestBackup"), Events.evtMinute1 )    # do initial backup
        self.waitForFile(fname01)

        self.loader.stop()  # all tasks
        self.loader = None

        # now verify file exists.
        self.failUnless( isfile( fname01 ) )
        self.failUnless( zipfile.is_zipfile( fname01 ) )
        # read zip info.
        zf = zipfile.ZipFile(fname01, 'r' ) # read only
        zfi = zf.infolist()
        self.assertEqual( len(zfi), 4 ) # two entrys
        self.failUnless( zfi[0].filename.endswith("/work/file1.txt") )
        self.failUnless( zfi[1].filename.endswith("/work/file2.txt") )
        self.failUnless( zfi[2].filename.endswith("/work/dir2/file1.1.txt") )
        self.failUnless( zfi[3].filename.endswith("/work/dir2/file1.2.txt") )
        zf.close()

    def testMultipleFileChangeLocal(self):
        """
        single file backup followed by no single file and then single file
        """
        _log.debug( "\ntestMultipleFileChangeLocal" )

        self.loader = EventRouterLoader()
        self.loader.loadHandlers( getDictFromXmlString(testConfigMultipleFileChange) )
        self.loader.start()  # all tasks
        self.router = self.loader.getEventRouter()

        self.router.publish( EventAgent("TestBackup"), Events.evtMinute1 )    # do initial backup
        self.waitForFile(fname01)

        # now verify file exists.
        self.failUnless( isfile( fname01 ) )
        self.failUnless( zipfile.is_zipfile( fname01 ) )
        # read zip info.
        zf = zipfile.ZipFile(fname01, 'r' ) # read only
        zfi = zf.infolist()
        self.assertEqual( len(zfi), 2 ) # one entry
        self.assertEqual( zfi[0].filename, "work/file1.txt" )
        self.assertEqual( zfi[1].filename, "work/file2.txt" )

        self.router.publish( EventAgent("TestBackup"), Events.evtMinute2 )    # no change should not create file
        time.sleep(0.1)
        self.failIf( exists( fname02 ) )    # should not exist

        file(testdata1, 'wb+').close()  # touch file
        time.sleep(0.1)
        zf.close()

        self.router.publish( EventAgent("TestBackup"), Events.evtMinute3 )    # no change should not create file
        self.waitForFile(fname03)
        # read zip info.
        zf = zipfile.ZipFile(fname03, 'r' ) # read only
        zfi = zf.infolist()
        self.assertEqual( len(zfi), 2 ) # one entry
        self.assertEqual( zfi[0].filename, "work/file1.txt" )
        self.assertEqual( zfi[1].filename, "work/file2.txt" )

        self.loader.stop()  # all tasks
        self.loader = None
        zf.close()

    def testMixedDataSetChangeLocal(self):
        _log.debug( "\ntestMixedDataSetLocal" )

        self.loader = EventRouterLoader()
        self.loader.loadHandlers( getDictFromXmlString(testConfigMixedChange) )
        self.loader.start()  # all tasks
        self.router = self.loader.getEventRouter()

        self.router.publish( EventAgent("TestBackup"), Events.evtMinute1 )    # do initial backup
        self.waitForFile(fname01)

        # now verify file exists.
        self.failUnless( isfile( fname01 ) )
        self.failUnless( zipfile.is_zipfile( fname01 ) )
        # read zip info.
        zf = zipfile.ZipFile(fname01, 'r' ) # read only
        zfi = zf.infolist()
        self.assertEqual( len(zfi), 4 )
        self.assertEqual( zfi[0].filename, "work/file1.txt" )
        self.assertEqual( zfi[1].filename, "work/file2.txt" )
        self.assertEqual( zfi[2].filename, "file1.1.txt" )
        self.assertEqual( zfi[3].filename, "file1.2.txt" )
        zf.close()

        self.router.publish( EventAgent("TestBackup"), Events.evtMinute2 )    # no change should not create file
        time.sleep(0.2)
        self.failIf( exists( fname02 ) )    # should not exist

        file(testdata2, 'wb+').close()  # touch file
        time.sleep(0.2)   # so clock rolls over

        self.router.publish( EventAgent("TestBackup"), Events.evtMinute3 )    # no change should not create file
        self.waitForFile(fname03)
        # read zip info.
        self.failUnless( zipfile.is_zipfile( fname03 ) )
        zf = zipfile.ZipFile(fname03, 'r' ) # read only
        zfi = zf.infolist()
        self.assertEqual( len(zfi), 4 )
        self.assertEqual( zfi[0].filename, "work/file1.txt" )
        self.assertEqual( zfi[1].filename, "work/file2.txt" )
        self.assertEqual( zfi[2].filename, "file1.1.txt" )
        self.assertEqual( zfi[3].filename, "file1.2.txt" )
        zf.close()

        self.loader.stop()  # all tasks
        self.loader = None

    def testMultipleFileDeltaLocal(self):
        """
        single file backup followed by no single file and then single file
        """
        _log.debug( "\ntestMultipleFileDeltaLocal" )

        self.loader = EventRouterLoader()
        self.loader.loadHandlers( getDictFromXmlString(testConfigMultipleFileDelta) )
        self.loader.start()  # all tasks
        self.router = self.loader.getEventRouter()

        self.router.publish( EventAgent("TestBackup"), Events.evtMinute1 )    # do initial backup
        self.waitForFile(fname01)

        # now verify file exists.
        self.failUnless( isfile( fname01 ) )
        self.failUnless( zipfile.is_zipfile( fname01 ) )
        # read zip info.
        zf = zipfile.ZipFile(fname01, 'r' ) # read only
        zfi = zf.infolist()
        self.assertEqual( len(zfi), 2 ) # one entry
        self.assertEqual( zfi[0].filename, "work/file1.txt" )
        self.assertEqual( zfi[1].filename, "work/file2.txt" )
        zf.close()

        self.router.publish( EventAgent("TestBackup"), Events.evtMinute2 )    # no change should not create file
        time.sleep(0.2)
        self.failIf( exists( fname02 ) )    # should not exist

        file(testdata1, 'wb+').close()  # touch file
        time.sleep(0.2)

        self.router.publish( EventAgent("TestBackup"), Events.evtMinute3 )    # no change should not create file
        self.waitForFile(fname03)
        # read zip info.
        zf = zipfile.ZipFile(fname03, 'r' ) # read only
        zfi = zf.infolist()
        self.assertEqual( len(zfi), 1 ) # one entry
        self.assertEqual( zfi[0].filename, "work/file1.txt" )
        zf.close()

        self.loader.stop()  # all tasks
        self.loader = None

    def testMixedDataSetDeltaLocal(self):
        _log.debug( "\ntestMixedDataSetDeltaLocal" )

        self.loader = EventRouterLoader()
        self.loader.loadHandlers( getDictFromXmlString(testConfigMixedDelta) )
        self.loader.start()  # all tasks
        self.router = self.loader.getEventRouter()

        self.router.publish( EventAgent("TestBackup"), Events.evtMinute1 )    # do initial backup
        self.waitForFile(fname01)

        # now verify file exists.
        self.failUnless( isfile( fname01 ) )
        self.failUnless( zipfile.is_zipfile( fname01 ) )
        # read zip info.
        zf = zipfile.ZipFile(fname01, 'r' ) # read only
        zfi = zf.infolist()
        self.assertEqual( len(zfi), 4 )
        self.assertEqual( zfi[0].filename, "work/file1.txt" )
        self.assertEqual( zfi[1].filename, "work/file2.txt" )
        self.assertEqual( zfi[2].filename, "file1.1.txt" )
        self.assertEqual( zfi[3].filename, "file1.2.txt" )
        zf.close()

        self.router.publish( EventAgent("TestBackup"), Events.evtMinute2 )    # no change should not create file
        time.sleep(0.2)
        self.failIf( exists( fname02 ) )    # should not exist

        file(testdata2, 'wb+').close()  # touch file
        time.sleep(0.2)   # so clock rolls over

        self.router.publish( EventAgent("TestBackup"), Events.evtMinute3 )    # no change should not create file
        self.waitForFile(fname03)
        # read zip info.
        self.failUnless( zipfile.is_zipfile( fname03 ) )
        zf = zipfile.ZipFile(fname03, 'r' ) # read only
        zfi = zf.infolist()
        self.assertEqual( len(zfi), 1 ) # subversion control files get in the way.
        self.assertEqual( zfi[0].filename, "work/file2.txt" )
        zf.close()

        self.loader.stop()  # all tasks
        self.loader = None

    def testSingleDirectoryHttpS(self):
        _log.debug( "\ntestSingleDirectoryHttpS" )

        self.loader = EventRouterLoader()
        self.loader.loadHandlers( getDictFromXmlString(testConfigSingleDirectoryHttpS) )
        self.loader.start()  # all tasks
        self.router = self.loader.getEventRouter()

        self.router.publish( EventAgent("TestBackup"), Events.evtMinute1 )    # do initial backup
        self.waitForFile(HttpSfname01)

        self.loader.stop()  # all tasks
        self.loader = None

        # now verify file exists.
        self.failUnless( isfile( HttpSfname01 ) )
        self.failUnless( zipfile.is_zipfile( HttpSfname01 ) )
        # read zip info.
        zf = zipfile.ZipFile(HttpSfname01, 'r' ) # read only
        zfi = zf.infolist()
        self.assertEqual( len(zfi), 2 ) # two entrys
        self.assertEqual( zfi[0].filename, "file1.txt" )
        self.assertEqual( zfi[1].filename, "file2.txt" )
        zf.close()

    def testSingleDirectoryFtp(self):
        _log.debug( "\ntestSingleDirectoryFtp" )

        self.loader = EventRouterLoader()
        self.loader.loadHandlers( getDictFromXmlString(testConfigFtp) )
        self.loader.start()  # all tasks
        self.router = self.loader.getEventRouter()

        self.router.publish( EventAgent("TestBackup"), Events.evtMinute1 )    # do initial backup
        self.waitForFile(Ftpfname01)

        self.loader.stop()  # all tasks
        self.loader = None

        # now verify file exists.
        self.failUnless( isfile( Ftpfname01 ) )
        self.failUnless( zipfile.is_zipfile( Ftpfname01 ) )
        # read zip info.
        zf = zipfile.ZipFile(HttpSfname01, 'r' ) # read only
        zfi = zf.infolist()
        self.assertEqual( len(zfi), 2 ) # two entrys
        self.assertEqual( zfi[0].filename, "file1.txt" )
        self.assertEqual( zfi[1].filename, "file2.txt" )
        zf.close()

    def testCommandLine(self):
        """
        Initial single file backup using command line disposal
        """
        _log.debug( "\ntestCommandLine" )

        self.loader = EventRouterLoader()
        self.loader.loadHandlers( getDictFromXmlString(testConfigCommandLine) )
        self.loader.start()  # all tasks
        self.router = self.loader.getEventRouter()

        self.router.publish( EventAgent("TestBackup"), Events.evtMinute1 )    # do initial backup
        self.waitForFile(fname01)

        self.loader.stop()  # all tasks
        self.loader = None

        # now verify file exists.
        self.failUnless( isfile( fname01 ) )
        self.failUnless( zipfile.is_zipfile( fname01 ) )
        # read zip info.
        zf = zipfile.ZipFile(fname01, 'r' ) # read only
        zfi = zf.infolist()
        self.assertEqual( len(zfi), 1 ) # one entry
        self.assertEqual( zfi[0].filename, "work/file1.txt" ) # one entry
        zf.close()
Esempio n. 17
0
class TestAsterisk(unittest.TestCase):

    def setUp(self):
        self._log = logging.getLogger( "TestAsterisk" )
        self._log.debug( "\n\nsetUp" )
        self.router = None
        self.loader = None
        return

    def tearDown(self):
        if self.loader:
            self.loader.stop()  # all tasks
            self.loader = None
        self.router = None

        self._log.debug( "tearDown" )
        return

    # Actual tests follow
    def testListen(self):
        self._log.debug( "\ntestListen" )
        self.loader = EventRouterLoader()
        self.loader.loadHandlers( getDictFromXmlString(testConfigAsteriskListen) )
        self.loader.start()  # all tasks
        self.router = self.loader.getEventRouter()

        cDown = 120
        while cDown > 0 and len(TestEventLogger._events) <= 0:
            cDown = cDown - 1
            time.sleep(1)

        TestEventLogger.logEvents()
        self.assert_( len(TestEventLogger._events) >= 1)

    def testSend(self):
        self._log.debug( "\ntestListen" )
        self.loader = EventRouterLoader()
        self.loader.loadHandlers( getDictFromXmlString(testConfigAsteriskSend) )
        self.loader.start()  # all tasks
        self.router = self.loader.getEventRouter()
        
        skt = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        skt.connect(("localhost", 20998))

        skt.send( " agi_request: dialparties.agi\n" )
        skt.send( " agi_channel: SIP/100-b7a017f8\n" )
        skt.send( " agi_language: en\n" )
        skt.send( " agi_type: SIP\n" )
        skt.send( " agi_uniqueid: 1173178145.6\n" )
        skt.send( " agi_callerid: 100\n" )
        skt.send( " agi_calleridname: SNOM\n" )
        skt.send( " agi_callingpres: 0\n" )
        skt.send( " agi_callingani2: 0\n" )
        skt.send( " agi_callington: 0\n" )
        skt.send( " agi_callingtns: 0\n" )
        skt.send( " agi_dnid: 200\n" )
        skt.send( " agi_rdnis: unknown\n" )
        skt.send( " agi_context: macro-dial\n" )
        skt.send( " agi_extension: s\n" )
        skt.send( " agi_priority: 1\n" )
        skt.send( " agi_enhanced: 0.0\n" )
        skt.send( " agi_accountcode:\n" )
        skt.send( "\n" )

        skt.close()
    
        time.sleep(2)
        TestEventLogger.logEvents()
        self.assert_( len(TestEventLogger._events) >= 1)
Esempio n. 18
0
class Root(controllers.RootController):

    def __init__( self ):
        self.eventloader = None
        self.homeTemplate = None
        
    def start(self):
        log_versions()
        # TODO         validateTemplateDirectory() on WebBrickGateway.templates
        persistFile = turbogears.config.get("client_profiles", None, False, "gateway" )

        ClientProfiles.load( persistFile )

        self.homeTemplate = turbogears.config.get("homepage", None, False, "gateway" )

        cfgStr = turbogears.config.get("templateDirectory", None, False, "gateway" )
        if cfgStr:
            _log.info( "additional template directory %s" % (cfgStr) )
            validateTemplateDirectory( cfgStr )

            #WbConfigSettings.addTemplateDir( cfgStr )
            sys.path.insert( 1, cfgStr )
            import kid
            _log.info( "Kid Paths %s"  % (str(kid.path.paths)) )
            ### tempdir = tempdir[:-(len(tempsuf)-1)]
            kid.path.insert( cfgStr )
            _log.info( "Kid Paths %s"  % (str(kid.path.paths)) )

        cfgStr = turbogears.config.get("network", None, False, "wbcfg" )
        if cfgStr:
            WbConfigBase.addNetwork( cfgStr )

        cfgStr = turbogears.config.get("webbrickDirectory", None, False, "wbcfg" )
        if cfgStr:
            WbConfigSettings.ConfDir = cfgStr
            _log.info( "updated webbrick configuration directory %s" % (cfgStr) )

        userDir = turbogears.config.get("despatchConfig", None, False, "gateway" )
        sysDir = turbogears.config.get("despatchConfigSystem", None, False, "gateway" )
        self.eventloader = EventRouterLoader()
        # system files first.

        self.eventloader.loadFromDirectories( [sysDir, userDir] )

        #print WbConfigSettings_hga.ConfDir
        #print WbConfigSettings.ConfDir
        
        ###self.panel = PanelRenderer.PanelRenderer()

        self.local       = LocalData.LocalData()
        self.userinterface = UserInterface.UserInterface()

        self.nameCache = Webbrick.WebbrickNodeNameCache()
        self.wbsts = Webbrick.WebbrickStatusCache( self.nameCache )
        self.wbcmd = Webbrick.WebbrickCommand( self.nameCache )
        self.eventstate = EventState.EventState( )
        self.discover = DiscoverHandler()
        self.media = Media.Media()

        # need to handle discovery better
        self.wbcnf = WbCfgManagerForm( self.discover )

        # THIS IS FOR ARMOUR gateway config and discovery only 
        if ARMOUR_DEV:
            self.wbgwcnf = WbGwCfgManager()
        
        self.schedule = Schedule.Schedule()
        self.sendevent = SendEvent.SendEventLocal(self.eventloader.getEventRouter())
        self.wbproxy = Webbrick.WebbrickProxy()

        self.eventstate.start(self.eventloader.getEventRouter())
        
        self.nameCache.start(self.eventloader.getEventRouter())
        self.wbsts.start(self.eventloader.getEventRouter())
        self.discover.start(self.eventloader.getEventRouter())
        self.schedule.start()
        self.media.start(self.eventloader.getEventRouter())
        
        # event handlers last
        if self.eventloader:
            self.eventloader.start()
        
        if not self.eventloader.getEventRouter():
            print "EVENT DESPATCH TASK NOT LOADED/FAILED CONFIGURE"

        _log.info( "Sys Paths %s"  % (sys.path) )

        # Now publish the versions
        router = self.eventloader.getEventRouter()
        publish_versions(router)
        
        
        import kid
        _log.info( "Kid Paths %s"  % (str(kid.path.paths)) )
        _log.warning( "**** System Configured ****" )

    def stop(self):
        """
        helper to shut down some class stuff.
        """
        self.schedule.stop()
        self.discover.stop(self.eventloader.getEventRouter())
        self.wbsts.stop( self.eventloader.getEventRouter() )
        self.nameCache.start( self.eventloader.getEventRouter() )
        self.eventloader.stop()
        self.media.stop(self.eventloader.getEventRouter())

    @turbogears.expose(template="WebBrickGateway.templates.welcome")
    def index(self):
        # look up in client profiles to get homePage.
        if self.homeTemplate:
            result = ClientProfiles.makeStandardResponse( cherrypy.request, self.homeTemplate )
        else:
            result = ClientProfiles.makeStandardResponse( cherrypy.request, "welcome" )
        result["now"] = time.ctime()
        return result

    @turbogears.expose(template="WebBrickGateway.templates.quiet")
    def quiet(self):
        result = ClientProfiles.makeStandardResponse( cherrypy.request )
        return result

    @turbogears.expose(template="WebBrickGateway.templates.listpanels")
    def panels(self):
        result = ClientProfiles.makeStandardResponse( cherrypy.request )

        def selectPanelName((_,nam)): 
            return nam[:-4]

        pattern = re.compile( r'^.+\.xml$' )
        c = CollectFiles("../resources/paneldef/",pattern,recursive=False)
        result['baseuri'] = turbogears.url("/")+"panel/"
        result['panels'] = map(selectPanelName,c)
        return result

    # Serve up media control panel
    @turbogears.expose(template="WebBrickGateway.templates.mediapanel")
    def mediapanel(self, **args):
        result = ClientProfiles.makeStandardResponse( cherrypy.request, "mediapanel" )
        # extract any parameters from the URL and add to the dictionary.
        for arg in args:
            result[arg] = args[arg]

        return result

    @turbogears.expose(template="WebBrickGateway.templates.welcome")
    def template(self, *args):
        """
        This function is used to return an arbitrary template used as
        a static page, but wrapped with the common header and footer
        elements.
        """
        # will set tg_template
        result = ClientProfiles.makeStandardResponse( cherrypy.request, string.join(args,'.') )
        if result.has_key("tg_format") and result["tg_format"] == "xml":
            #cherrypy.response.headers['Content-Type'] = "text/xml"
            cherrypy.response.headerMap['Content-Type'] = "text/xml"

        cherrypy.response.headers['Content-Type'] = "text/xml"
        cherrypy.response.headerMap['Content-Type'] = "text/xml"

        return result

    # obsolete, Andy:No actually turns out to be useful for serving files in pure XML format
    @turbogears.expose(template="WebBrickGateway.templates.welcome", format="xml", content_type="text/xml")
    def templatex(self, *args):
        """
        This function is used to return an arbitrary template used as
        a static page, but wrapped with the common header and footer
        elements.
        """
        # will set tg_template
        result = ClientProfiles.makeStandardResponse( cherrypy.request, string.join(args,'.') )

        result["tg_format"] = "xml"
#        result["tg_template"] = 'WebBrickGateway.templates.'+string.join(args,'.')

        cherrypy.response.headerMap['Refresh'] = "30"

        return result
   
    @turbogears.expose(format="manifest", content_type="text/cache-manifest")
    def manifest(self, *args):
        """
        This function is used to return an arbitrary template used as
        a static page, but wrapped with the common header and footer
        elements.
        """
        # get the path where the manifest is stored and serve it as the correct content type
        _log.debug("Requesting manifest for: " + args[0] + "skin")
        manifestpath = pkg_resources.resource_filename("WebBrickRes", "../resources/skins/") + args[0] + "/static/manifest/" + args[0] + ".manifest"
        result = file(manifestpath).read()

        return result
      
    # Serves dataset from siteLogRoot and graph_prop.xml from /static/css
    # as combined Json for use with OpenFlashChart
    # TODO: Move data processing out of controllers
    @turbogears.expose()
    def jsondata(self, logfile = None, propfile = None):
        """
        """
        result = ""
        
        # for debugging only
        # logPath = "/home/webbrick"
        # propPath = "/home/webbrick"
        
        # get the location of log files
        logPath = turbogears.config.get ('siteLogRoot', None, False, 'DEFAULT')
        
        # get the location of css files
        staticRoot = str(turbogears.config.get("static_filter.root", None, False, "global" ))
        staticCss = str(turbogears.config.get("static_filter.dir", None, False, "/static/css" ))
        if staticCss[0] != "/":
            propPath = staticRoot + staticCss
        else:
            propPath = staticCss
        
        
        if logfile and propfile:
            
        
            # does the log folder exist
            if logPath:
                
                # try to read the log file
                try:
                    
                    processeddata = {}
                    
                    xmldatastring = "<entrys>" + "".join(file(logPath + "/" + logfile).readlines()) + "</entrys>"
                    xmldatablob = parseXmlString(xmldatastring)
                    datadict = getDictFromXml(xmldatablob, typecast=True)
                    for item in datadict["entrys"][0]:
                        processeddata[item] = []
                        for entry in datadict["entrys"]:
                            processeddata[item].append(entry[item][0])
                            
                    result = str(processeddata)
                except:
                    _log.error( "log file: %s does not exist on Path: %s" %(logfile, logPath) )    
                
            if propPath:
                
                # try to read the prop file
                try:
                    xmlpropstring = "".join(file(propPath + "/" + propfile).readlines())
                    xmlpropblob = parseXmlString(xmlpropstring)
                    propdict = getDictFromXml(xmlpropblob, typecast=True)
                    propdict = propdict['graphprop']
                    #result = json.dumps(propdict)
                    #result = str(propdict)
                except:
                    _log.error( "log file: %s does not exist on Path: %s" %(propfile, propPath) )
           
            if processeddata and propdict: 
                try:
                    propdict["datasets"] = []
                    for item in processeddata:
                        if item != "time" and item != "date":
                            propdict["datasets"].append({"text": item.replace(".", " "), "values":processeddata.get(item)})
                        elif item == "time":
                            propdict["x_axis"]["labels"]["times"] = processeddata.get(item)
                        elif item == "date":                    
                            propdict["x_axis"]["labels"]["dates"] = processeddata.get(item)
                except:
                    _log.error( "Could not add data to chart" )
                result = json.dumps(propdict)
                
        else:
            _log.error( "Not enough arguments passed to allow processing" )
         
        return result
    
    # Serves dataset from siteLogRoot and graph_prop.xml from /static/css
    # as combined Json for use with OpenFlashChart
    # TODO: Move data processing out of controllers
    @turbogears.expose()
    def jsonfiles(self, filterstr = None):
        """
        """
        result = ""
        
        # get the location of log files
        logPath = turbogears.config.get ('siteLogRoot', None, False, 'DEFAULT')

        filenames = []
        if logPath:
            if filterstr:
                _log.debug( "Filter Filenames using: %s" %(filterstr))
                for filename in listdir(logPath):
                    if filterstr in filename:
                        filenames.append(filename)
            else:
                _log.debug( "No filter string provided - return all filenames")
                for filename in listdir(logPath):
                    filenames.append(filename)
            
            resultdict = {"options":filenames}
            result = json.dumps(resultdict)
        else: 
            _log.error( "No valid siteRootLog" )
        return result                     
        
    
       
    @turbogears.expose()
    def redirect(self,*args):
        """ 
        generalised redirect, so Gateway can manage locations of cameras etc.
        The URLs returned may be changed dependant on whether client on local network or not
        """
        cfgStr = turbogears.config.get(args[0], None, False, "redirect" )
        if cfgStr:
            raise cherrypy.HTTPRedirect(cfgStr)
        return self.index()

    #@turbogears.expose()
    def default(self,*args):
        return self.panels()
class TestWebbrickMonitor(unittest.TestCase):

    def setUp(self):
        self._log = logging.getLogger( "TestWebbrickMonitor" )
        self._log.debug( "\n\nsetUp" )

        self.httpServer = None
        self.httpServer = TestHttpServer()
        self.httpServer.start()

        self.router = None
        self.loader = None

    def tearDown(self):
        self._log.debug( "\n\ntearDown" )

        if self.loader:
            self.loader.stop()  # all tasks
            self.loader = None
        self.router = None

        if self.httpServer:
            self.httpServer.stop()
            self.httpServer = None

        time.sleep(1)

    def expectNhttp(self, cnt ):
        idx = 20
        while (len(self.httpServer.requests()) < cnt) and (idx > 0):
            time.sleep(0.05)
            idx = idx - 1

        if ( len(self.httpServer.requests()) != cnt):
            self.httpServer.logRequests()

        self.assertEqual( len(self.httpServer.requests()), cnt)

    # Actual tests follow

    def testSetTimeDirect(self):
        """
        This test is a bit of fiddle to work without the event router
        """
        self._log.debug( "\ntestSetTimeDirect" )

        runner = WebBrickMonitor( DummyRouter() )

        runner.handleEvent( Events.evtSS )
        runner.handleEvent( Events.evtSS )
        runner.handleEvent( Events.evtSS )
        runner.handleEvent( Events.evtMinute10 )    # request 
        # check http requests
        self.expectNhttp(0)

        runner.handleEvent( Events.evtSS )
        runner.handleEvent( Events.evtSS )
        runner.handleEvent( Events.evtSS )
        runner.handleEvent( Events.evtMinute11 )    # request 

        self.expectNhttp(2)
        self.assertEqual( self.httpServer.requests()[0], "/hid.spi?com=%3ALG%3bpassword%3A" )
        self.assertEqual( self.httpServer.requests()[1], "/hid.spi?com=%3AST1%3b4%3b11%3A" )

    def testSetTime(self):
        self._log.debug( "\n\ntestSetTime" )
        self.loader = EventRouterLoader()
        self.loader.loadHandlers( getDictFromXmlString(testConfigSetTime) )
        self.loader.start()  # all tasks
        self.router = self.loader.getEventRouter()

        self.router.publish( EventAgent("TestWebbrickMonitor"), Events.evtSS )
        self.router.publish( EventAgent("TestWebbrickMonitor"), Events.evtSS )
        self.router.publish( EventAgent("TestWebbrickMonitor"), Events.evtSS )
        self.router.publish( EventAgent("TestWebbrickMonitor"), Events.evtMinute10 )    # request 
        # check http requests
        self.expectNhttp(0)

        self.router.publish( EventAgent("TestWebbrickMonitor"), Events.evtSS )
        self.router.publish( EventAgent("TestWebbrickMonitor"), Events.evtSS )
        self.router.publish( EventAgent("TestWebbrickMonitor"), Events.evtSS )
        self.router.publish( EventAgent("TestWebbrickMonitor"), Events.evtMinute11 )    # request 

        self.expectNhttp(2)
        self.assertEqual( self.httpServer.requests()[0], "/hid.spi?com=%3ALG%3bpassword%3A" )
        self.assertEqual( self.httpServer.requests()[1], "/hid.spi?com=%3AST1%3b4%3b11%3A" )

    def testTimeSignalReboot(self):
        # see we get a log message for uptime < 120 seconds
        self._log.debug( "\ntestTimeSignalReboot" )
        self.loader = EventRouterLoader()
        self.loader.loadHandlers( getDictFromXmlString(testConfigSetTime) )
        self.loader.start()  # all tasks
        self.router = self.loader.getEventRouter()

        logHandler = testLogHandler()
        logHandler.setLevel( logging.INFO )
        addTestLogHandler(logHandler,'EventHandlers')

        elog = logging.getLogger( "EventHandlers.WebBrickMonitor" )
        elog.setLevel(logging.INFO)

        self.router.publish( EventAgent("TestWebbrickMonitor"), Events.evtST_1MinUpTime )
        time.sleep(1.0) # default router is threaded.
        assert logHandler.count() >= 1

        removeTestLogHandler(logHandler,'EventHandlers')

    def testTimeSignalSetTime(self):
        # see we get time reset when out by more than 60 nseconds for 5 minutes.
        self._log.debug( "\ntestTimeSignalReboot" )
        self.loader = EventRouterLoader()
        self.loader.loadHandlers( getDictFromXmlString(testConfigSetTime) )
        self.loader.start()  # all tasks
        self.router = self.loader.getEventRouter()

        logHandler = testLogHandler()
        addTestLogHandler(logHandler,'EventHandlers')

        self.router.publish( EventAgent("TestWebbrickMonitor"), Events.evtST_10MinUpTime )
        self.router.publish( EventAgent("TestWebbrickMonitor"), Events.evtMinute11 )    # request 
        self.router.publish( EventAgent("TestWebbrickMonitor"), Events.evtST_10MinUpTime )
        self.router.publish( EventAgent("TestWebbrickMonitor"), Events.evtMinute11 )    # request 
        self.router.publish( EventAgent("TestWebbrickMonitor"), Events.evtST_10MinUpTime )
        self.router.publish( EventAgent("TestWebbrickMonitor"), Events.evtMinute11 )    # request 

        # check http requests, should be none so far
        self.expectNhttp(0)

        self.router.publish( EventAgent("TestWebbrickMonitor"), Events.evtST_10MinUpTime )
        self.router.publish( EventAgent("TestWebbrickMonitor"), Events.evtMinute11 )    # request 
        self.router.publish( EventAgent("TestWebbrickMonitor"), Events.evtST_10MinUpTime )
        self.router.publish( EventAgent("TestWebbrickMonitor"), Events.evtMinute11 )    # request 

        self.expectNhttp(2)
        self.assertEqual( self.httpServer.requests()[0], "/hid.spi?com=%3ALG%3bpassword%3A" )
        self.assertEqual( self.httpServer.requests()[1], "/hid.spi?com=%3AST1%3b4%3b11%3A" )

        removeTestLogHandler(logHandler,'EventHandlers')

    def testTimeSignalResetSiteplayer(self):
        # see we get siteplayer reset when no messages from siteplayer for a while
        self._log.debug( "\ntestTimeSignalResetSiteplayer" )
        self.loader = EventRouterLoader()
        self.loader.loadHandlers( getDictFromXmlString(testConfigSetTime) )
        self.loader.start()  # all tasks
        self.router = self.loader.getEventRouter()

        logHandler = testLogHandler()
        addTestLogHandler(logHandler,'EventHandlers')

        self.router.publish( EventAgent("TestWebbrickMonitor"), Events.evtST_10MinUpTime )  # get detected
        self.router.publish( EventAgent("TestWebbrickMonitor"), Events.evtMinute11 )    # request 
        self.router.publish( EventAgent("TestWebbrickMonitor"), Events.evtMinute11 )    # request 

        # check http requests, should be none so far
        self.expectNhttp(0)

        self.router.publish( EventAgent("TestWebbrickMonitor"), Events.evtMinute11 )    # request 
        self.router.publish( EventAgent("TestWebbrickMonitor"), Events.evtMinute11 )    # request 
        self.router.publish( EventAgent("TestWebbrickMonitor"), Events.evtMinute11 )    # request 

        self.expectNhttp(2)
        self.assertEqual( self.httpServer.requests()[0], "/hid.spi?com=%3ALG%3bpassword%3A" )
        self.assertEqual( self.httpServer.requests()[1], "/hid.spi?com=%3ARS%3A" )

        removeTestLogHandler(logHandler,'EventHandlers')

    def testTimeOfDayResetSiteplayer(self):
        # see we get reset at 3 AM
        self._log.debug( "\ntestTimeOfDayResetSiteplayer" )
        self.loader = EventRouterLoader()
        self.loader.loadHandlers( getDictFromXmlString(testConfigSetTime) )
        self.loader.start()  # all tasks
        self.router = self.loader.getEventRouter()

        self.router.publish( EventAgent("TestWebbrickMonitor"), Events.evtST_10MinUpTime )  # get detected

        # check http requests, should be none so far
        self.expectNhttp(0)

        self.router.publish( EventAgent("TestWebbrickMonitor"), Events.evtHour03 )    # request 

        self.expectNhttp(2)
        self.assertEqual( self.httpServer.requests()[0], "/hid.spi?com=%3ALG%3bpassword%3A" )
        self.assertEqual( self.httpServer.requests()[1], "/hid.spi?com=%3ARS%3A" )

    def testDummy(self):
        return
Esempio n. 20
0
class TestEggNunciate(unittest.TestCase):

    def setUp(self):
        self._log = logging.getLogger( "TestEggNunciate" )
        self._log.debug( "\n\nsetUp" )

        self.httpServer = None
        self.httpServer = TestHttpServer()
        self.httpServer.start()

        self.router = None
        self.loader = None

    def tearDown(self):
        self._log.debug( "\n\ntearDown" )

        time.sleep(1)   # allow twisted time
        if self.loader:
            self.loader.stop()  # all tasks
            self.loader = None
        self.router = None

        if self.httpServer:
            self.httpServer.stop()

        time.sleep(5)

    def expectNhttp(self, cnt ):
        idx = 20
        while (len(self.httpServer.requests()) < cnt) and (idx > 0):
            time.sleep(0.05)
            idx = idx - 1

        if ( len(self.httpServer.requests()) != cnt):
            for req in self.httpServer.requests():
                self._log.debug( "request %s", req )

        self.assertEqual( len(self.httpServer.requests()), cnt)

    # Actual tests follow
    def testEggNunciateSingle(self):
        self._log.debug( "\ntestEggNunciateSingle" )
        self.loader = EventRouterLoader()
        self.loader.loadHandlers( getDictFromXmlString(testConfigEggNunciate1) )
        self.loader.start()  # all tasks
        self.router = self.loader.getEventRouter()

        self.router.publish( EventAgent("TestEggNunciate"), Events.evtRuntime5 )    # set up base scene
        self.router.publish( EventAgent("TestEggNunciate"), Events.evtSecond5 )

        # expect single HTTP request for default scene step 1.
        self._log.debug( "testHttpAction %s", self.httpServer.requests() )
        self.expectNhttp( 1)
        self.assertEqual( self.httpServer.requests()[0], "/hid.spi?com=:DM0;16;1;16;2;16:" )

        self.router.publish( EventAgent("TestEggNunciate"), Events.evtSecond5 )
        # expect second HTTP request for default scene step 2.
        self._log.debug( "testHttpAction %s", self.httpServer.requests() )
        self.expectNhttp( 2)
        self.assertEqual( self.httpServer.requests()[1], "/hid.spi?com=:DM0;8;1;8;2;8:" )

        self.router.publish( EventAgent("TestEggNunciate"), Events.evtSecond5 )
        # expect third HTTP request for default scene step 1.
        self._log.debug( "testHttpAction %s", self.httpServer.requests() )
        self.expectNhttp( 3)
        self.assertEqual( self.httpServer.requests()[2], "/hid.spi?com=:DM0;16;1;16;2;16:" )

    def testEggNunciateTwo(self):
        self._log.debug( "\ntestEggNunciateTwo" )
        self.loader = EventRouterLoader()
        self.loader.loadHandlers( getDictFromXmlString(testConfigEggNunciate2) )
        self.loader.start()  # all tasks
        self.router = self.loader.getEventRouter()

        self.router.publish( EventAgent("TestEggNunciate"), Events.evtRuntime5 )    # set up base scene
        self.router.publish( EventAgent("TestEggNunciate"), Events.evtSecond5 )

        # expect single HTTP request for default scene step 1.
        self._log.debug( "testHttpAction %s", self.httpServer.requests() )
        self.expectNhttp( 2)
        self.assertEqual( self.httpServer.requests()[0], "/hid.spi?com=:DM3;16;4;16;5;16:" )
        self.assertEqual( self.httpServer.requests()[1], "/hid.spi?com=:DM0;16;1;16;2;16:" )

        self.router.publish( EventAgent("TestEggNunciate"), Events.evtSecond5 )
        # expect second HTTP request for default scene step 2.
        self._log.debug( "testHttpAction %s", self.httpServer.requests() )
        self.expectNhttp( 4)
        self.assertEqual( self.httpServer.requests()[3], "/hid.spi?com=:DM0;8;1;8;2;8:" )
        self.assertEqual( self.httpServer.requests()[2], "/hid.spi?com=:DM3;8;4;8;5;8:" )

        self.router.publish( EventAgent("TestEggNunciate"), Events.evtSecond5 )
        # expect third HTTP request for default scene step 1.
        self._log.debug( "testHttpAction %s", self.httpServer.requests() )
        self.expectNhttp( 6)
        self.assertEqual( self.httpServer.requests()[5], "/hid.spi?com=:DM0;16;1;16;2;16:" )
        self.assertEqual( self.httpServer.requests()[4], "/hid.spi?com=:DM3;16;4;16;5;16:" )

    def subCheckSeq(self, reqs):
        # each time tick causes another http request
        idx = len(self.httpServer.requests())
        for i in range(len(reqs)):
            self.router.publish( EventAgent("TestEggNunciate"), Events.evtSecond5 )
            self.expectNhttp( idx+1 )
            hReq = self.httpServer.requests()[idx]
            self._log.debug( "testHttpAction (%u:%s) (%u:%s)", idx, hReq, i, reqs[i] )
            self.assertEqual( hReq, reqs[i] )
            idx = idx + 1

    def subTestGarageOpen(self):
        self._log.debug( "\nsubTestGarageOpen" )

        self.router.publish( EventAgent("TestEggNunciate"), Events.evtDO_0_on )

        reqs = ["/hid.spi?com=:DM0;32;1;32;2;32:",
                "/hid.spi?com=:DM0;48;1;48;2;48:",
                "/hid.spi?com=:DM0;4;1;4;2;4:",
                "/hid.spi?com=:DM0;32;1;32;2;32:",
                "/hid.spi?com=:DM0;48;1;48;2;48:",
                "/hid.spi?com=:DM0;4;1;4;2;4:",
            ]
        self.subCheckSeq(reqs)

    def subTestGarageClose(self):
        self._log.debug( "\nsubTestGarageClose" )

        self.router.publish( EventAgent("TestEggNunciate"), Events.evtDO_0_off )

        reqs = ["/hid.spi?com=:DM0;16;1;16;2;16:",
                "/hid.spi?com=:DM0;8;1;8;2;8:",
                "/hid.spi?com=:DM0;16;1;16;2;16:",
                "/hid.spi?com=:DM0;8;1;8;2;8:",
            ]
        self.subCheckSeq(reqs)

    # Actual tests follow
    def testEggNunciateGarage(self):
        self._log.debug( "\ntestEggNunciateEvent" )
        self.loader = EventRouterLoader()
        self.loader.loadHandlers( getDictFromXmlString(testConfigEggNunciate1) )
        self.loader.start()  # all tasks
        self.router = self.loader.getEventRouter()

        self.router.publish( EventAgent("TestEggNunciate"), Events.evtRuntime5 )    # set up base scene
        self.router.publish( EventAgent("TestEggNunciate"), Events.evtSecond5 )

        # expect HTTP request for default scene 1 step 1.
        self._log.debug( "testHttpAction %s", self.httpServer.requests() )
        self.expectNhttp( 1)
        hReq = self.httpServer.requests()[len(self.httpServer.requests())-1]
        self.assertEqual( hReq, "/hid.spi?com=:DM0;16;1;16;2;16:" )

        self.subTestGarageOpen()
        self.expectNhttp( 7)
        self.subTestGarageClose()
        self.expectNhttp( 11)

        self.subTestGarageOpen()
        self.expectNhttp( 17)
        self.subTestGarageClose()
        self.expectNhttp( 21)

    def subTestAlarmOn(self):
        self._log.debug( "\nsubTestAlarmOn" )

        self.router.publish( EventAgent("TestEggNunciate"), Events.evtDO_1_on )

        reqs = ["/hid.spi?com=:DM0;33;1;33;2;33:",
                "/hid.spi?com=:DM0;47;1;47;2;47:",
                "/hid.spi?com=:DM0;4;1;4;2;4:",
                "/hid.spi?com=:DM0;33;1;33;2;33:",
                "/hid.spi?com=:DM0;47;1;47;2;47:",
                "/hid.spi?com=:DM0;4;1;4;2;4:",
            ]
        self.subCheckSeq(reqs)

    def subTestAlarmOff(self):
        self._log.debug( "\nsubTestAlarmOn" )

        self.router.publish( EventAgent("TestEggNunciate"), Events.evtDO_1_off )

        reqs = ["/hid.spi?com=:DM0;16;1;16;2;16:",
                "/hid.spi?com=:DM0;8;1;8;2;8:",
                "/hid.spi?com=:DM0;16;1;16;2;16:",
                "/hid.spi?com=:DM0;8;1;8;2;8:",
            ]
        self.subCheckSeq(reqs)

    # Actual tests follow
    def testEggNunciateAlarm(self):
        self._log.debug( "\ntestEggNunciateAlarm" )
        self.loader = EventRouterLoader()
        self.loader.loadHandlers( getDictFromXmlString(testConfigEggNunciate1) )
        self.loader.start()  # all tasks
        self.router = self.loader.getEventRouter()

        self.router.publish( EventAgent("TestEggNunciate"), Events.evtRuntime5 )    # set up base scene
        self.router.publish( EventAgent("TestEggNunciate"), Events.evtSecond5 )

        # expect HTTP request for default scene 1 step 1.
        self._log.debug( "testHttpAction %s", self.httpServer.requests() )
        self.expectNhttp( 1)
        self.assertEqual( self.httpServer.requests()[0], "/hid.spi?com=:DM0;16;1;16;2;16:" )

        self.subTestAlarmOn()
        self.subTestAlarmOff()

        self.subTestAlarmOn()
        self.subTestAlarmOff()

    # Actual tests follow
    def testEggNunciateGarageAlarm(self):
        self._log.debug( "\ntestEggNunciateGarageAlarm" )
        self.loader = EventRouterLoader()
        self.loader.loadHandlers( getDictFromXmlString(testConfigEggNunciate1) )
        self.loader.start()  # all tasks
        self.router = self.loader.getEventRouter()

        self.router.publish( EventAgent("TestEggNunciate"), Events.evtRuntime5 )    # set up base scene
        self.router.publish( EventAgent("TestEggNunciate"), Events.evtSecond5 )

        # expect HTTP request for default scene 1 step 1.
        self.expectNhttp( 1)
        hReq = self.httpServer.requests()[len(self.httpServer.requests())-1]
        self._log.debug( "testHttpAction %u:%s", (len(self.httpServer.requests())-1,hReq) )
        self.assertEqual( hReq, "/hid.spi?com=:DM0;16;1;16;2;16:" )

        self.subTestGarageOpen()
        self.expectNhttp( 7)

        self.router.publish( EventAgent("TestEggNunciate"), Events.evtDO_1_on )

        reqs = ["/hid.spi?com=:DM0;33;1;33;2;33:",
                "/hid.spi?com=:DM0;47;1;47;2;47:",
                "/hid.spi?com=:DM0;4;1;4;2;4:",
                "/hid.spi?com=:DM0;32;1;32;2;32:",
                "/hid.spi?com=:DM0;48;1;48;2;48:",
                "/hid.spi?com=:DM0;4;1;4;2;4:",
                "/hid.spi?com=:DM0;33;1;33;2;33:",
                "/hid.spi?com=:DM0;47;1;47;2;47:",
                "/hid.spi?com=:DM0;4;1;4;2;4:",
                "/hid.spi?com=:DM0;32;1;32;2;32:",
                "/hid.spi?com=:DM0;48;1;48;2;48:",
                "/hid.spi?com=:DM0;4;1;4;2;4:",
                
            ]
        self.subCheckSeq(reqs)

        self.router.publish( EventAgent("TestEggNunciate"), Events.evtDO_0_off )    # garage closed

        reqs = ["/hid.spi?com=:DM0;33;1;33;2;33:",
                "/hid.spi?com=:DM0;47;1;47;2;47:",
                "/hid.spi?com=:DM0;4;1;4;2;4:",
                "/hid.spi?com=:DM0;33;1;33;2;33:",
                "/hid.spi?com=:DM0;47;1;47;2;47:",
                "/hid.spi?com=:DM0;4;1;4;2;4:",
            ]
        self.subCheckSeq(reqs)

        self.router.publish( EventAgent("TestEggNunciate"), Events.evtDO_1_off )    # Alarm

        reqs = ["/hid.spi?com=:DM0;16;1;16;2;16:",
                "/hid.spi?com=:DM0;8;1;8;2;8:",
                "/hid.spi?com=:DM0;16;1;16;2;16:",
                "/hid.spi?com=:DM0;8;1;8;2;8:",
            ]
        self.subCheckSeq(reqs)

    def testDummy(self):
        pass
Esempio n. 21
0
class TestUPNP(unittest.TestCase):

    def setUp(self):
        self._log = logging.getLogger( "TestUPNP" )
        self._log.info( "\n\nsetUp" )

        self.router = None
        self.loader = None

    def tearDown(self):
        self._log.info( "\n\ntearDown" )

        if self.loader:
            self.loader.stop()  # all tasks
            self.loader = None
        self.router = None

        time.sleep(5)

    # Actual tests follow
    def testLoad(self):
        self._log.info( "\nTestLoad" )

        self.loader = EventRouterLoader()
        self.loader.loadHandlers( getDictFromXmlString(testConfigUPNP) )
        self.loader.start()  # all tasks
        self.router = self.loader.getEventRouter()

        time.sleep(30)

    def testLoadDefaults(self):
        self._log.info( "\nTestLoadDefaults" )

        self.loader = EventRouterLoader()
        self.loader.loadHandlers( getDictFromXmlString(testConfigUPNPDefaults) )
        self.loader.start()  # all tasks
        self.router = self.loader.getEventRouter()

        time.sleep(30)

    def testStartStop(self):
        self._log.info( "\ntestStartStop" )

        self.loader = EventRouterLoader()
        self.loader.loadHandlers( getDictFromXmlString(testConfigUPNP) )
        self.loader.start()  # all tasks
        self.router = self.loader.getEventRouter()

        time.sleep(5)

        self.router.publish( EventAgent("TestUPNP"), evt_Play )
        time.sleep(5)

        self.router.publish( EventAgent("TestUPNP"), evt_Next )
        time.sleep(5)

        self.router.publish( EventAgent("TestUPNP"), evt_Next )
        time.sleep(5)

        self.router.publish( EventAgent("TestUPNP"), evt_Pause )
        time.sleep(5)

        self.router.publish( EventAgent("TestUPNP"), evt_Play )
        time.sleep(5)

        self.router.publish( EventAgent("TestUPNP"), evt_Prev )
        time.sleep(5)

        self.router.publish( EventAgent("TestUPNP"), evt_Stop )
        time.sleep(5)

    def testVolume(self):
        self._log.info( "\ntestVolume" )

        self.loader = EventRouterLoader()
        self.loader.loadHandlers( getDictFromXmlString(testConfigUPNP) )
        self.loader.start()  # all tasks
        self.router = self.loader.getEventRouter()

        time.sleep(5)

        self.router.publish( EventAgent("TestUPNP"), evt_Play )
        time.sleep(5)

        self.router.publish( EventAgent("TestUPNP"), evt_Volume100 )
        time.sleep(5)

        self.router.publish( EventAgent("TestUPNP"), evt_Volume50 )
        time.sleep(5)

        self.router.publish( EventAgent("TestUPNP"), evt_Volume0 )
        time.sleep(5)

        self.router.publish( EventAgent("TestUPNP"), evt_Volume100 )
        time.sleep(5)

    def logBrowseResult(self, result, client, object_id, starting_index ):
        returned_cnt = result['number_returned']
        total_cnt = result['total_matches']
        update_id = result['update_id']
        self._log.info( "logBrowseResult client - %s %s of %s (%s)", client.device.friendly_name, returned_cnt, total_cnt, update_id )
        # result['items'] is a dictionary
        for key,item in result['items'].iteritems():
            if item['upnp_class'] == 'object.container':
                self._log.info( "container item %s", item )
                # now browse that as well.
                self.do_browse(client, item['id'], 0 )
            else:
                self._log.info( "item %s", item )
            
        #'items': {'S:': {'parent_id': '0', 'child_count': 'None', 'id': 'S:', 'upnp_class': 'object.container', 'title': 'Music Shares'}, 'SQ:': {'parent_id': '0', 'child_count': 'None', 'id': 'SQ:', 'upnp_class': 'object.container', 'title': 'Saved Queues'}, 'Q:': {'parent_id': '0', 'child_count': 'None', 'id': 'Q:', 'upnp_class': 'object.container', 'title': 'Queues'}, 'G:': {'parent_id': '0', 'child_count': 'None', 'id': 'G:', 'upnp_class': 'object.container', 'title': 'Now Playing'}, 'R:': {'parent_id': '0', 'child_count': 'None', 'id': 'R:', 'upnp_class': 'object.container', 'title': 'Oldies'}, 'AI:': {'parent_id': '0', 'child_count': 'None', 'id': 'AI:', 'upnp_class': 'object.container', 'title': 'Audio Inputs'}, 'EN:': {'parent_id': '0', 'child_count': 'None', 'id': 'EN:', 'upnp_class': 'object.container', 'title': 'Entire Network'}, 'A:': {'parent_id': '0', 'child_count': 'None', 'id': 'A:', 'upnp_class': 'object.container', 'title': 'Attributes'}}}

        next_index = int(returned_cnt)+int(starting_index)
        if next_index < total_cnt:
            # continue browse
            self.do_browse(client, object_id, next_index )

    def _failure(self, error):
        self._log.error(error.getTraceback())

    def do_browse(self, client, object_id, starting_index ):
        defered = client.content_directory.browse(object_id,
                #browse_flag='BrowseDirectChildren',
                #filter='*', 
                #sort_criteria='',
                #requested_count=0,
                #process_result=True,
                #backward_compatibility=False,
                starting_index=starting_index
                )

        defered.addCallback( self.logBrowseResult, client=client, object_id=object_id, starting_index=0 ).addErrback(self._failure)

    def mediaserver_detected(self, client, udn ):
        self._log.info( "mediaserver_detected %s %s (%s)", client, client.content_directory, udn )
        self.do_browse(client, 0, 0 )

    def testBrowse(self):
        self._log.info( "\ntestBrowse" )

        self.loader = EventRouterLoader()
        self.loader.loadHandlers( getDictFromXmlString(testConfigUPNP) )
        self.loader.start()  # all tasks
        self.router = self.loader.getEventRouter()

        louie.connect( self.mediaserver_detected, 'Coherence.UPnP.ControlPoint.MediaServer.detected')

        time.sleep(30)
        # I want access to all media servers
#        self._coherence = Coherence()   #already started


    def add_server(self, client, udn ):
        self.directory.addClient(client, udn)

    def dumpDirectory(self, dirs):
        for ntry in dirs.enumItems():
            self._log.info( "item %s", ntry )
            
        for dir in dirs.enumContainers():
            self._log.info( "container %s", dir )
            self.dumpDirectory( dir )

    def testBrowse2(self):
        self._log.info( "\ntestBrowse2" )

        louie.connect( self.add_server, 'Coherence.UPnP.ControlPoint.MediaServer.detected')

        self.loader = EventRouterLoader()
        self.loader.loadHandlers( getDictFromXmlString(testConfigUPNP) )
        self.loader.start()  # all tasks
        self.router = self.loader.getEventRouter()
        self.directory = UPNP_Directory()


        time.sleep(5)
        for clnt in self.directory.getContainers():
            self.dumpDirectory(clnt)

    def testDummy(self):
        return
class TestSerialDataConvertor(unittest.TestCase):

    def setUp(self):
        self._log = logging.getLogger( "TestSerialDataConvertor" )
        self._log.debug( "\n\nsetUp" )
        self._router = DummyRouter()

    def tearDown(self):
        self._log.debug( "\n\ntearDown" )

    # Actual tests follow
    def testLexicon(self):
        self._log.debug( "\ntestLexicon" )
        
        self.loader = EventRouterLoader()
        self.loader.loadHandlers( getDictFromXmlString(testConfigLexicon) )
        self.loader.start()  # all tasks
        self.router = self.loader.getEventRouter()

        self.router.publish( EventAgent("testVolume"), evtLexiconVolume0a )

        # time events are not in the log.
        self.assert_(TestEventLogger.expectNevents(2))
        self.assertEqual( TestEventLogger._events[0].getSource(), "webbrick/1/100" )
        evt = TestEventLogger._events[1]
        self.assertEqual( evt.getType(), "avamplifier/volume/current" )
        self.assertEqual( evt.getSource(), "avamplifier/1/volume/main/current" )
        evtod = evt.getPayload()
        self.assert_( evtod.has_key("val") )
        self.assertEqual( evtod["val"], 0 )
        
        self.router.publish( EventAgent("testVolume"), evtLexiconVolume0b )
        self.assert_(TestEventLogger.expectNevents(3))
        
        self.router.publish( EventAgent("testVolume"), evtLexiconVolume50a )
        self.assert_(TestEventLogger.expectNevents(5))
        
        self.router.publish( EventAgent("testVolume"), evtLexiconVolume50b )
        self.assert_(TestEventLogger.expectNevents(6))
        
        self.router.publish( EventAgent("testVolume"), evtLexiconVolume100a )
        self.assert_(TestEventLogger.expectNevents(8))
        
        self.router.publish( EventAgent("testVolume"), evtLexiconVolume100b )
        self.assert_(TestEventLogger.expectNevents(9))
        TestEventLogger.logEvents()
        
    def testOnkyo(self):
        self._log.debug( "\ntestOnkyo" )
        
        self.loader = EventRouterLoader()
        self.loader.loadHandlers( getDictFromXmlString(testConfigOnkyo) )
        self.loader.start()  # all tasks
        self.router = self.loader.getEventRouter()

        self.router.publish( EventAgent("testVolume"), evtOnkyoVolume0 )

        # time events are not in the log.
        self.assert_(TestEventLogger.expectNevents(2))
        self.assertEqual( TestEventLogger._events[0].getSource(), "webbrick/1/100" )
        evt = TestEventLogger._events[1]
        self.assertEqual( evt.getType(), "avamplifier/volume/current" )
        self.assertEqual( evt.getSource(), "avamplifier/1/volume/main/current" )
        evtod = evt.getPayload()
        self.assert_( evtod.has_key("val") )
        self.assertEqual( evtod["val"], 0 )
        
        self.router.publish( EventAgent("testVolume"), evtOnkyoVolume50 )
        self.assert_(TestEventLogger.expectNevents(4))
        
        self.router.publish( EventAgent("testVolume"), evtOnkyoVolume100 )
        self.assert_(TestEventLogger.expectNevents(6))
        
        TestEventLogger.logEvents()
        
    def testDecAscii(self):
        self._log.debug( "\ntestDecAscii" )
        
        self.loader = EventRouterLoader()
        self.loader.loadHandlers( getDictFromXmlString(testDecAscii) )
        self.loader.start()  # all tasks
        self.router = self.loader.getEventRouter()

        self.router.publish( EventAgent("testVolume"), evtDecToAscii )

        # time events are not in the log.
        self.assert_(TestEventLogger.expectNevents(2))
        self.assertEqual( TestEventLogger._events[0].getSource(), "webbrick/1/100" )
        evt = TestEventLogger._events[1]
        self.assertEqual( evt.getType(), "avamplifier/volume/current" )
        self.assertEqual( evt.getSource(), "avamplifier/1/volume/main/current" )
        evtod = evt.getPayload()
        self.assert_( evtod.has_key("val") )
        self.assertEqual( evtod["val"], '110000100000000000000000' )
        
      
        TestEventLogger.logEvents()
        
    def test8BitChecksum(self):
        self._log.debug( "\ntest8BitChecksum" )
        
        self.loader = EventRouterLoader()
        self.loader.loadHandlers( getDictFromXmlString(test8bitchecksum) )
        self.loader.start()  # all tasks
        self.router = self.loader.getEventRouter()

        self.router.publish( EventAgent("testVolume"), evt8bitchecksum )

        # time events are not in the log.
        self.assert_(TestEventLogger.expectNevents(2))
        self.assertEqual( TestEventLogger._events[0].getSource(), "webbrick/1/100" )
        evt = TestEventLogger._events[1]
        self.assertEqual( evt.getType(), "avamplifier/volume/current" )
        self.assertEqual( evt.getSource(), "avamplifier/1/volume/main/current" )
        evtod = evt.getPayload()
        self.assert_( evtod.has_key("val") )
        self.assertEqual( evtod["val"], '20;20;84;55;55;50;2;227:' )
        
      
        TestEventLogger.logEvents()
        
    def testOutOfRange(self):
        self._log.debug( "\ntestOutOfRange" )
        
        self.loader = EventRouterLoader()
        self.loader.loadHandlers( getDictFromXmlString(testConfigOutofRange) )
        self.loader.start()  # all tasks
        self.router = self.loader.getEventRouter()

        self.router.publish( EventAgent("testVolume"), outofrangeoffset )
        time.sleep(1)        
        self.assertEqual( len(TestEventLogger._events), 1 )
        TestEventLogger.logEvents()
        #we should get no resulting events and no exceptions
        
    def testUnit(self):
        return

    def testComponent(self):
        return

    def testIntegration(self):
        return

    def testPending(self):
        return
Esempio n. 23
0
class TestLocalState(unittest.TestCase):
    def setUp(self):
        self._log = logging.getLogger( "TestLocalState" )
        self.loader = None
        self.router = None
        self.cache = LocalState( )
        return

    def tearDown(self):
        self.cache.stop(self.router)
        if self.loader:
            self.loader.stop()  # all tasks
            self.loader = None
        self.router = None
        return

    # Actual tests follow

    def testLocalState(self):
        self.loader = EventRouterLoader()
        self.loader.loadHandlers( getDictFromXmlString(testConfigLocalState) )
        self.loader.start()  # all tasks
        self.router = self.loader.getEventRouter()

        self.cache.start( self.router );

        # Fiddle time, i.e. speed it up.
        self.router.publish( "TestLocalState", Event( "http://id.webbrick.co.uk/events/webbrick/DI", 
                "webbrick/GarageA/DI/8", { "state": 0 } ) )
        self.router.publish( "TestLocalState", Event( "http://id.webbrick.co.uk/events/webbrick/DI", 
                "webbrick/GarageA/DI/9", { "state": 0 } ) )

        res = self.cache.queryCache( "Garage/Door/1" )
        self.assertEqual( res["stsval"], "0" )
        self.assertEqual( res["stserr"], None )

        self.router.publish( "TestLocalState", Event( "http://id.webbrick.co.uk/events/webbrick/DI", 
                "webbrick/GarageA/DI/8", { "state": 0 } ) )
        self.router.publish( "TestLocalState", Event( "http://id.webbrick.co.uk/events/webbrick/DI", 
                "webbrick/GarageA/DI/9", { "state": 1 } ) )
        res = self.cache.queryCache( "Garage/Door/1" )
        self.assertEqual( res["stsval"], "1" )
        self.assertEqual( res["stserr"], None )
                
        self.router.publish( "TestLocalState", Event( "http://id.webbrick.co.uk/events/webbrick/DI", 
                "webbrick/GarageA/DI/8", { "state": 1 } ) )
        self.router.publish( "TestLocalState", Event( "http://id.webbrick.co.uk/events/webbrick/DI", 
                "webbrick/GarageA/DI/9", { "state": 0 } ) )
        res = self.cache.queryCache( "Garage/Door/1" )
        self.assertEqual( res["stsval"], "2" )
        self.assertEqual( res["stserr"], None )
                
        self.router.publish( "TestLocalState", Event( "http://id.webbrick.co.uk/events/webbrick/DI", 
                "webbrick/GarageA/DI/8", { "state": 1 } ) )
        self.router.publish( "TestLocalState", Event( "http://id.webbrick.co.uk/events/webbrick/DI", 
                "webbrick/GarageA/DI/9", { "state": 1 } ) )
        res = self.cache.queryCache( "Garage/Door/1" )
        self.assertEqual( res["stsval"], "3" )
        self.assertEqual( res["stserr"], None )
                
        res = self.cache.queryCache( "Garage/Door/2" )
        self.assertEqual( res["stsval"], None )
        self.assertNotEqual( res["stserr"], None )
class TestWebbrickStatusQuery(unittest.TestCase):

    def setUp(self):
        self._log = logging.getLogger( "TestWebbrickStatusQuery" )
        self._log.debug( "\n\nsetUp" )

        self.router = None
        self.loader = None

    def tearDown(self):
        self._log.debug( "\n\ntearDown" )

        if self.loader:
            self.loader.stop()  # all tasks
            self.loader = None
        self.router = None

        waitNSeconds(2)
            
    def testWebbrickStatusQuery(self):
        self._log.debug( "\n\ntestWebbrickStatusQuery" )

        self.loader = EventRouterLoader()
        self.loader.loadHandlers( getDictFromXmlString(testConfigWebbrickStatusQuery) )
        self.loader.start()  # all tasks
        self.router = self.loader.getEventRouter()

        self.router.publish( EventAgent("TestWebbrickStatusMonitor"), Events.evtSecond5 )   # so webbrick is in list for recover
        self.router.publish( EventAgent("TestWebbrickStatusMonitor"), Events.evtMinute1 )    # do recover
        waitNSeconds(2)   # recover is async
        self.router.publish( EventAgent("TestWebbrickStatusMonitor"), Events.evtSecond5 )   # do scan
        waitNSeconds(2)   # scan is async

        # We should see lots of events here as initial pass.

        # my test rig only has 1 temp sensors.
        # so:
        # 1 temp sensors
        # 4 analogue in
        # 4 analogue out
        # 12 digital in
        # 8 digital out
        # 8 mimic out
        self.assert_( TestEventLogger.expectAtLeastNevents(36+NUM_TEMP_SENSORS), "expecting %u events" % (36+NUM_TEMP_SENSORS)  )
        oldLen = len(TestEventLogger._events)

        self.router.publish( EventAgent("TestWebbrickStatusMonitor"), Events.evtSecond5 )   # do scan
        waitNSeconds(2)   # scan is async

        TestEventLogger.logEvents()
        self.assert_( oldLen <= len(TestEventLogger._events) )
        
    def testWebbrickStatusQueryReal(self):
        self._log.debug( "\n\ntestWebbrickStatusQueryReal" )

        self.loader = EventRouterLoader()
        self.loader.loadHandlers( getDictFromXmlString(testConfigWebbrickStatusQueryReal) )
        self.loader.start()  # all tasks
        self.router = self.loader.getEventRouter()

        self.router.publish( EventAgent("TestWebbrickStatusMonitor"), Events.evtSecond5 )   # so webbrick is in list for recover
        waitNSeconds(2)   # scan is async
        self.router.publish( EventAgent("TestWebbrickStatusMonitor"), Events.evtMinute1 )    # do discover
        waitNSeconds(30)
        self.router.publish( EventAgent("TestWebbrickStatusMonitor"), Events.evtMinute1 )    # do recover
        waitNSeconds(2)   # recover is async
        self.router.publish( EventAgent("TestWebbrickStatusMonitor"), Events.evtSecond5 )   # do scan
        waitNSeconds(2)   # scan is async

        # We should see lots of events here as initial pass.
        self.assert_( TestEventLogger.expectAtLeastNevents(10), "expecting %u events" % (10)  )

        # wait for 5 seconds to pass.
        #time.sleep(5)
        #self.assertEqual( oldLen, len(TestEventLogger._events) )

    def testDummy(self):
        return
class TestReadEventLogs(unittest.TestCase):

    def setUp(self):
        self._log = logging.getLogger( "TestReadEventLogs" )
        elog = logging.getLogger( "EventLog" )
        elog.setLevel(logging.INFO)
        self._log.debug( "\n\nsetUp" )

        self.router = None
        self.loader = None

    def tearDown(self):
        self._log.debug( "\n\ntearDown" )

        if self.loader:
            self.loader.stop()  # all tasks
            self.loader = None
        self.router = None

    # Actual tests follow
    def testEventFromString(self):
        """
        Test the event logger
        """

        self._log.debug( "\ntestEventFromString" )
        
        evtStr = "2008-10-26 18:18:24,184 http://id.webbrick.co.uk/events/webbrick/CT,webbrick/9/CT/3,{'srcChannel': 3, 'curhi': 100.0, 'val': 19.600000000000001, 'fromNode': 9, 'curlo': -50.0, 'defhi': 100.0, 'deflo': -50.0}"

        evt = EventFromString(evtStr)
        self._log.debug( "type %s source %s payload %s", evt.getType(), evt.getSource(), evt.getPayload() )
        self.assertEqual( evt.getType(),"http://id.webbrick.co.uk/events/webbrick/CT" )
        self.assertEqual( evt.getSource(),"webbrick/9/CT/3" )
        self.assertNotEqual( evt.getPayload(),None )
        od = evt.getPayload()
        self.assertEqual( od["srcChannel"], '3')
        self.assertEqual( od["val"], '19.600000000000001')

    def testReadLogFile(self):
        cnt = 0
        rdr = ReadLogFile("resources/EventLog.log")
        ln = rdr.next()
        while ln:
            evt = EventFromString(ln)
            cnt = cnt + 1
            ln = rdr.next()
        self.assertEqual( cnt, 9 )
    
    def testReadLogFile2(self):

        self.loader = EventRouterLoader()
        self.loader.loadHandlers( getDictFromXmlString(testConfig) )
        self.loader.start()  # all tasks
        self.router = self.loader.getEventRouter()

        ReadLogFileSendEvents( "resources/EventLog.log", self.router )

        TestEventLogger.expectNevents(9)
        self.assertEqual( TestEventLogger._events[0].getSource(), "temperature/outside" )
        self.assertEqual( TestEventLogger._events[1].getSource(), "webbrick/3/1" )
        self.assertEqual( TestEventLogger._events[2].getSource(), "webbrick/3/1" )
        self.assertEqual( TestEventLogger._events[3].getSource(), "webbrick/6" )
        self.assertEqual( TestEventLogger._events[4].getSource(), "webbrick/2" )
        self.assertEqual( TestEventLogger._events[5].getSource(), "webbrick/7" )
        self.assertEqual( TestEventLogger._events[6].getSource(), "webbrick/4" )
        self.assertEqual( TestEventLogger._events[7].getSource(), "webbrick/9/CT/3" )
        self.assertEqual( TestEventLogger._events[8].getSource(), "webbrick/9/AI/0" )

    def testLineReader(self):
        cnt = 0
        bytes = file("resources/EventLog.log").read()
        rdr = LineReader(bytes)
        ln = rdr.next()
        while ln:
            evt = EventFromString(ln)
            cnt = cnt + 1
            ln = rdr.next()
        self.assertEqual( cnt, 9 )

    def testDummy(self):
        return
Esempio n. 26
0
class TestUnderFloorAction(unittest.TestCase):

    def setUp(self):
        self._log = logging.getLogger( "TestUnderFloorAction" )
        self._log.debug( "\n\nsetUp" )

        self.router = None
        self.loader = None

    def tearDown(self):
        self._log.debug( "\n\ntearDown" )

        if self.loader:
            self.loader.stop()  # all tasks
            self.loader = None
        self.router = None
        time.sleep(2)

    def expectNevents(self, cnt ):
        idx = 20
        while (len(TestEventLogger._events) < cnt) and (idx > 0):
            time.sleep(0.05)
            idx = idx - 1

        if ( len(TestEventLogger._events) != cnt):
            TestEventLogger.logEvents()

        self.assertEqual( len(TestEventLogger._events), cnt)

    def common_set(self,pump=False, pipe='Cold', tank='Normal' ):
        self.router.publish( EventAgent("TestUnderFloorAction"), Events.evtSecond0 )  # Create a 'second'
        self.router.publish( EventAgent("TestUnderFloorAction"), Events.evtSecond1 )  # Create a 'second'
        self.router.publish( EventAgent("TestUnderFloorAction"), Events.evtSecond2 )  # Create a 'second'
        self.router.publish( EventAgent("TestUnderFloorAction"), Events.evtMinute10 )  # Create a minute that forces a check
        if pipe == 'Cold':
            self.router.publish( EventAgent("TestUnderFloorAction"), Events.evtCT_0_15 )  # Air Temp
        else:
            self.router.publish( EventAgent("TestUnderFloorAction"), Events.evtCT_0_25 )  # Air Temp
        if tank == 'Normal':            
            self.router.publish( EventAgent("TestUnderFloorAction"), Events.evtCT_1_19 )  # Floor Temp
        else:
            self.router.publish( EventAgent("TestUnderFloorAction"), Events.evtCT_1_30 )  # Floor Over Temp

        self.router.publish( EventAgent("TestUnderFloorAction"), Events.evtSecond4 )  # Create a 'second'

    def display_events(self, e_list):
        lc = 0
        for e in e_list:
            print "Event %s Type %s  Source %s Payload %s" % (lc,  e.getType(), e.getSource(), e.getPayload())
            lc += 1

    # Actual tests follow
    def testSolarCheckEvent(self):
        self._log.debug( "\n\ntestSolarCheckEvent" )

        self.loader = EventRouterLoader()
        self.loader.loadHandlers( getDictFromXmlString(testConfigUnderFloor) )
        self.loader.start()  # all tasks
        self.router = self.loader.getEventRouter()
        self.common_set(pump=False, pipe='Cold', tank='Normal')
        time.sleep(1)

        #self.display_events(TestEventLogger._events)

        self.expectNevents( 15 )
        self.assertEqual( TestEventLogger._events[10].getType(), u'http://id.webbrick.co.uk/events/UnderFloor' )
        self.assertEqual( TestEventLogger._events[10].getSource(), u"testing/UnderFloor" )
        self.assertEqual( TestEventLogger._events[10].getPayload()['set_pump_state'], u"check_run" )


    def testSolarStopEvent(self):
        self._log.debug( "\n\ntestSolarStopEvent" )

        self.loader = EventRouterLoader()
        self.loader.loadHandlers( getDictFromXmlString(testConfigUnderFloor) )
        self.loader.start()  # all tasks
        self.router = self.loader.getEventRouter()
        self.common_set(pump=True, pipe='Cold', tank='Normal')
        time.sleep(1)
        self.router.publish( EventAgent("TestUnderFloorAction"), Events.evtSecond5 )  # Create a 'second'
        time.sleep(1)
        self.router.publish( EventAgent("TestUnderFloorAction"), Events.evtSecond6 )  # Create a 'second'
        time.sleep(1)
        self.router.publish( EventAgent("TestUnderFloorAction"), Events.evtSecond7 )  # Create a 'second'
        time.sleep(1)
        self.router.publish( EventAgent("TestUnderFloorAction"), Events.evtCT_1_50 )  # Tank Temp
        time.sleep(1)

        #self.display_events(TestEventLogger._events)

        self.expectNevents( 21 )
        
        self.assertEqual( TestEventLogger._events[19].getType(), u'http://id.webbrick.co.uk/events/UnderFloor' )
        self.assertEqual( TestEventLogger._events[19].getSource(), u"testing/UnderFloor" )
        self.assertEqual( TestEventLogger._events[19].getPayload()['set_pump_state'], u"stop" )


    def testUnderFloorEvent(self):
        self._log.debug( "\n\ntestUnderFloorEvent" )

        self.loader = EventRouterLoader()
        self.loader.loadHandlers( getDictFromXmlString(testConfigUnderFloor) )
        self.loader.start()  # all tasks
        self.router = self.loader.getEventRouter()
        self.common_set(pump=False, pipe='Hot', tank='Normal')
        time.sleep(1)
        self.router.publish( EventAgent("TestUnderFloorAction"), Events.evtCT_0_80 )  # Pipe Temp
        time.sleep(1)
        self.router.publish( EventAgent("TestUnderFloorAction"), Events.evtSecond5 )  # Create a 'second'
        time.sleep(1)
        self.router.publish( EventAgent("TestUnderFloorAction"), Events.evtSecond6 )  # Create a 'second'
        time.sleep(1)
        self.router.publish( EventAgent("TestUnderFloorAction"), Events.evtSecond7 )  # Create a 'second'
        time.sleep(1)

        #self.display_events(TestEventLogger._events)

        #self.expectNevents( 21 )
        
        self.assertEqual( TestEventLogger._events[14].getType(), u'http://id.webbrick.co.uk/events/UnderFloor' )
        self.assertEqual( TestEventLogger._events[14].getSource(), u"testing/UnderFloor" )
        self.assertEqual( TestEventLogger._events[14].getPayload()['set_pump_state'], u"run" )

    def testSolarTankHighEvent(self):
        self._log.debug( "\n\ntestSolarTankHighEvent" )

        self.loader = EventRouterLoader()
        self.loader.loadHandlers( getDictFromXmlString(testConfigUnderFloor) )
        self.loader.start()  # all tasks
        self.router = self.loader.getEventRouter()
        self.common_set(pump=True, pipe='Hot', tank='Over')
        time.sleep(1)
        self.router.publish( EventAgent("TestUnderFloorAction"), Events.evtCT_0_80 )  # Pipe Temp
        time.sleep(1)
        self.router.publish( EventAgent("TestUnderFloorAction"), Events.evtSecond5 )  # Create a 'second'
        time.sleep(1)
        self.router.publish( EventAgent("TestUnderFloorAction"), Events.evtSecond6 )  # Create a 'second'
        time.sleep(1)
        self.router.publish( EventAgent("TestUnderFloorAction"), Events.evtSecond7 )  # Create a 'second'
        time.sleep(1)

        #self.display_events(TestEventLogger._events)

        self.expectNevents( 21 )
        
        self.assertEqual( TestEventLogger._events[16].getType(), u'http://id.webbrick.co.uk/events/UnderFloor' )
        self.assertEqual( TestEventLogger._events[16].getSource(), u"testing/UnderFloor" )
        self.assertEqual( TestEventLogger._events[16].getPayload()['set_pump_state'], u"stop" )


    def testSolarNightEvent(self):
        self._log.debug( "\n\ntestSolarTankHighEvent" )

        self.loader = EventRouterLoader()
        self.loader.loadHandlers( getDictFromXmlString(testConfigUnderFloor) )
        self.loader.start()  # all tasks
        self.router = self.loader.getEventRouter()
        self.common_set(pump=True, pipe='Hot', tank='Normal')
        time.sleep(1)
        self.router.publish( EventAgent("TestUnderFloorAction"), Events.evtCT_0_80 )  # Pipe Temp
        time.sleep(1)
        self.router.publish( EventAgent("TestUnderFloorAction"), Events.evtDark )
        time.sleep(1)
        self.router.publish( EventAgent("TestUnderFloorAction"), Events.evtSecond5 )  # Create a 'second'
        time.sleep(1)
        self.router.publish( EventAgent("TestUnderFloorAction"), Events.evtMinute1 )  # Create a 'minute'
        time.sleep(1)

        #self.display_events(TestEventLogger._events)

        #self.expectNevents( 25 )
        
        self.assertEqual( TestEventLogger._events[19].getType(), u'http://id.webbrick.co.uk/events/UnderFloor' )
        self.assertEqual( TestEventLogger._events[19].getSource(), u"testing/UnderFloor" )
        self.assertEqual( TestEventLogger._events[19].getPayload()['set_pump_state'], u"stop" )
Esempio n. 27
0
class TestValve(unittest.TestCase):
    def setUp(self):
        self._log = logging.getLogger( "TestValve" )
        self._log.debug( "\n\nsetUp" )
        eLogCfg = getDictFromXmlString(testELogger)
        self.loader = EventRouterLoader()
        self.loader.loadHandlers(eLogCfg)
        self.loader.start()
        self.router = self.loader.getEventRouter()
        self.triggered = False
     
        
    def tearDown(self):
        self._log.debug( "\n\nteardown" )
        TestEventLogger.logEvents()
        
    def testAnalogConfig(self):
        """
            Test to make sure the valve is configuring itself properly when using an analog output
        """
        TestEventLogger.logEvents()
        self._log.debug( "\n\nTestConfig")
        valveCfg = getDictFromXmlString(aCfg)
        self.valve = Valve(valveCfg['valve'],self.router)
        
        assert self.valve.aOutput == '3'
        assert self.valve.name == "Test Valve"
        assert self.valve.key == "tv1"
        assert self.valve.ao.aoCmd == 'AA;3;%(val)s:'
    
    def testDigitalConfig(self):
        """
            Test to make sure the valve is configuring itself properly when using a single digital output
            Commonly a spring loaded valve
        """
        TestEventLogger.logEvents()
        self._log.debug( "\n\nTestConfig")
        valveCfg = getDictFromXmlString(digitalCfg)
        valve = Valve(valveCfg['valve'],self.router)
     
        assert valve.wbTarget == "10.100.100.102"
        assert valve.name == "Test Valve"
        assert valve.key == "tv1"
        assert valve.type == 'digital'
        assert valve.move == {'CS':'0','TS':'1'}
        assert valve.dOutput == '1'
        assert valve.do.onCmd == 'DO;1;N:'
    
    def testDigitalTimedConfig(self):
        """
            Test to make sure the valve is configuring itself properly with two digital outputs
        """
        TestEventLogger.logEvents()
        self._log.debug( "\n\nTestConfig")
        valveCfg = getDictFromXmlString(digitalTimedCfg)
        valve = Valve(valveCfg['valve'],self.router)
        assert valve.move['TS'][1] == 1
        assert valve.move['CS'][1] == 2
        
        assert valve.move['TS'][0].onCmd == 'DO;1;N:'
        assert valve.move['CS'][0].onCmd == 'DO;2;N:'
        
    def publishDelayedEvent(self,event):
        time.sleep(0.5)
        self.router.publish(event.getSource() , event)
        
    def testAoTurn(self):
        """
            Test to make sure the correct events are being sent out when we request valvage
            We fake the return webbrick event to avoid having to set up a live webbrick
            The outgoing http request also never gets sent as we dont initialize twisted
        """            
        valveCfg = getDictFromXmlString(aCfg)
        self.valve = Valve(valveCfg['valve'],self.router)
        
        #turn the valve all the way to hot
        self.valve.doTurn("TS" , 100)
        time.sleep(0.2)
        TestEventLogger.logEvents()
        assert TestEventLogger._events[0].getType()  == 'internal/hvac/analogoutput'
        assert TestEventLogger._events[0].getSource() == 'hvac/valve/tv1/3'
        assert TestEventLogger._events[0].getPayload()['val'] == '30'
        TestEventLogger.clearEvents()
        
        #turn the valve all the way to cold
        self.valve.doTurn("CS" , 100)        
        time.sleep(0.2)
        TestEventLogger.logEvents()
        assert TestEventLogger._events[0].getType()  == 'internal/hvac/analogoutput'
        assert TestEventLogger._events[0].getSource() == 'hvac/valve/tv1/3'
        assert TestEventLogger._events[0].getPayload()['val'] == '0'        
        TestEventLogger.clearEvents()
        
        #turn the valve halfway to hot
        self.valve.doTurn("TS" , 50)
        time.sleep(0.2)
        TestEventLogger.logEvents()
        assert TestEventLogger._events[0].getType()  == 'internal/hvac/analogoutput'
        assert TestEventLogger._events[0].getSource() == 'hvac/valve/tv1/3'
        assert TestEventLogger._events[0].getPayload()['val'] == '15'        
        TestEventLogger.clearEvents()
        
        #turn the valve 25% further to hot, should end up getting rounded to 22
        self.valve.doTurn("TS" , 25)
        time.sleep(0.2)
        TestEventLogger.logEvents()
        assert TestEventLogger._events[0].getType()  == 'internal/hvac/analogoutput'
        assert TestEventLogger._events[0].getSource() == 'hvac/valve/tv1/3'
        assert TestEventLogger._events[0].getPayload()['val'] == '22'        
        TestEventLogger.clearEvents()
    
    def testDoTurn(self):
        valveCfg = getDictFromXmlString(digitalCfg)
        self.valve = Valve(valveCfg['valve'],self.router)
        
        #because of the way the digital valves work, any turn its 100% in either direction
        #turn the valve all the way to hot
        self.valve.doTurn("TS" , 100)
        time.sleep(0.2)
        TestEventLogger.logEvents()
        assert TestEventLogger._events[0].getType()  == 'internal/hvac/digitaloutput'
        assert TestEventLogger._events[0].getSource() == 'hvac/valve/tv1/1/on'
        TestEventLogger.clearEvents()
        
        #turn the valve all the way to cold
        self.valve.doTurn("CS" , 100)        
        time.sleep(0.2)
        TestEventLogger.logEvents()
        assert TestEventLogger._events[0].getType()  == 'internal/hvac/digitaloutput'
        assert TestEventLogger._events[0].getSource() == 'hvac/valve/tv1/1/off'
        TestEventLogger.clearEvents()
        
        #turn the valve halfway to hot 
        self.valve.doTurn("TS" , 50)
        time.sleep(0.2)
        TestEventLogger.logEvents()
        assert TestEventLogger._events[0].getType()  == 'internal/hvac/digitaloutput'
        assert TestEventLogger._events[0].getSource() == 'hvac/valve/tv1/1/on'
        TestEventLogger.clearEvents()
        
        #turn the valve 25% further to hot
        self.valve.doTurn("TS" , 25)
        time.sleep(0.2)
        TestEventLogger.logEvents()
        assert TestEventLogger._events[0].getType()  == 'internal/hvac/digitaloutput'
        assert TestEventLogger._events[0].getSource() == 'hvac/valve/tv1/1/on'     
        TestEventLogger.clearEvents()
    
    def testDoTTurn(self):
        valveCfg = getDictFromXmlString(digitalTimedCfg)
        self.valve = Valve(valveCfg['valve'],self.router)
        
        #turn the valve all the way to hot
        self.valve.doTurn("TS" , 100)
        time.sleep(0.2)
        TestEventLogger.logEvents()
        assert TestEventLogger._events[0].getType() == 'internal/hvac/digitalout'
        assert TestEventLogger._events[0].getSource() == 'hvac/valve/tv1/2/off'
        assert TestEventLogger._events[1].getType()  == 'internal/hvac/digitalout'
        assert TestEventLogger._events[1].getSource() == 'hvac/valve/tv1/1/dwell'
        assert TestEventLogger._events[1].getPayload()['val'] == '100'        
        TestEventLogger.clearEvents()
        
        #turn the valve all the way to cold
        self.valve.doTurn("CS" , 100)        
        time.sleep(0.2)
        TestEventLogger.logEvents()
        assert TestEventLogger._events[0].getType()  == 'internal/hvac/digitalout'
        assert TestEventLogger._events[0].getSource() == 'hvac/valve/tv1/1/off'
        assert TestEventLogger._events[1].getType()  == 'internal/hvac/digitalout'
        assert TestEventLogger._events[1].getSource() == 'hvac/valve/tv1/2/dwell'
        assert TestEventLogger._events[1].getPayload()['val'] == '200'        
        TestEventLogger.clearEvents()
        
        #turn the valve halfway to hot
        self.valve.doTurn("TS" , 50)
        time.sleep(0.2)
        TestEventLogger.logEvents()
        assert TestEventLogger._events[0].getType()  == 'internal/hvac/digitalout'
        assert TestEventLogger._events[0].getSource() == 'hvac/valve/tv1/2/off'  
        
        assert TestEventLogger._events[1].getType()  == 'internal/hvac/digitalout'
        assert TestEventLogger._events[1].getSource() == 'hvac/valve/tv1/1/dwell'
        assert TestEventLogger._events[1].getPayload()['val'] == '50'        
        TestEventLogger.clearEvents()
        
        #turn the valve 25% further to hot, should end up getting rounded to 22
        self.valve.doTurn("TS" , 25)
        time.sleep(0.2)
        TestEventLogger.logEvents()
        assert TestEventLogger._events[0].getType()  == 'internal/hvac/digitalout'
        assert TestEventLogger._events[0].getSource() == 'hvac/valve/tv1/2/off'  
        
        assert TestEventLogger._events[1].getType()  == 'internal/hvac/digitalout'
        assert TestEventLogger._events[1].getSource() == 'hvac/valve/tv1/1/dwell'
        assert TestEventLogger._events[1].getPayload()['val'] == '25'        
        TestEventLogger.clearEvents()
class TestRgbLedLighting(unittest.TestCase):

    def setUp(self):
        self._log = logging.getLogger( "TestRgbLedLighting" )
        self._log.debug( "\n\nsetUp" )

        self.router = None
        self.loader = None

    def tearDown(self):
        self._log.debug( "\n\ntearDown" )

        if self.loader:
            self.loader.stop()  # all tasks
            self.loader = None
        self.router = None

    def testLoadConfig(self):
        self._log.debug( "\ntestLoadConfig" )
        self.loader = EventRouterLoader()
        self.loader.loadHandlers( getDictFromXmlString(testConfigRgbLedLighting) )
        self.loader.start()  # all tasks
        self.router = self.loader.getEventRouter()

        time.sleep(1)

    def testOn(self):
        self._log.debug( "\ntestRed" )
        self.loader = EventRouterLoader()
        self.loader.loadHandlers( getDictFromXmlString(testConfigRgbLedLighting) )
        self.loader.start()  # all tasks
        self.router = self.loader.getEventRouter()

        self.router.publish( EventAgent("TestRgbLedLighting"), Events.evtSecond4 )
        time.sleep(1)

        oldLen = len(TestEventLogger._events)
        TestEventLogger.logEvents()

        self.assertEqual( oldLen, 1 )

    def testOff(self):
        self._log.debug( "\ntestOff" )
        self.loader = EventRouterLoader()
        self.loader.loadHandlers( getDictFromXmlString(testConfigRgbLedLighting) )
        self.loader.start()  # all tasks
        self.router = self.loader.getEventRouter()

        self.router.publish( EventAgent("TestRgbLedLighting"), Events.evtSecond5 )
        time.sleep(1)

        oldLen = len(TestEventLogger._events)
        TestEventLogger.logEvents()

        self.assertEqual( oldLen, 1 )

    def testCommand(self):
        self._log.debug( "\ntestCommand" )
        self.loader = EventRouterLoader()
        self.loader.loadHandlers( getDictFromXmlString(testConfigRgbLedLighting) )
        self.loader.start()  # all tasks
        self.router = self.loader.getEventRouter()

        self.router.publish( EventAgent("TestRgbLedLighting"), Events.evtSecond10 )
        time.sleep(1)

        oldLen = len(TestEventLogger._events)
        TestEventLogger.logEvents()

        self.assertEqual( oldLen, 1 )

    def testRed(self):
        self._log.debug( "\ntestRed" )
        self.loader = EventRouterLoader()
        self.loader.loadHandlers( getDictFromXmlString(testConfigRgbLedLighting) )
        self.loader.start()  # all tasks
        self.router = self.loader.getEventRouter()

        self.router.publish( EventAgent("TestRgbLedLighting"), Events.evtSecond1 )
        time.sleep(1)

        oldLen = len(TestEventLogger._events)
        TestEventLogger.logEvents()

        self.assertEqual( oldLen, 1 )

    def testGreen(self):
        self._log.debug( "\ntestGreen" )
        self.loader = EventRouterLoader()
        self.loader.loadHandlers( getDictFromXmlString(testConfigRgbLedLighting) )
        self.loader.start()  # all tasks
        self.router = self.loader.getEventRouter()

        self.router.publish( EventAgent("TestRgbLedLighting"), Events.evtSecond2 )
        time.sleep(1)

        oldLen = len(TestEventLogger._events)
        TestEventLogger.logEvents()

        self.assertEqual( oldLen, 1 )

    def testBlue(self):
        self._log.debug( "\ntestBlue" )
        self.loader = EventRouterLoader()
        self.loader.loadHandlers( getDictFromXmlString(testConfigRgbLedLighting) )
        self.loader.start()  # all tasks
        self.router = self.loader.getEventRouter()

        self.router.publish( EventAgent("TestRgbLedLighting"), Events.evtSecond3 )
        time.sleep(1)

        oldLen = len(TestEventLogger._events)
        TestEventLogger.logEvents()

        self.assertEqual( oldLen, 1 )

    def testBadCommand(self):
        self._log.debug( "\ntestBadCommand" )
        self.loader = EventRouterLoader()
        self.loader.loadHandlers( getDictFromXmlString(testConfigBadcommand) )
        self.loader.start()  # all tasks
        self.router = self.loader.getEventRouter()

        self.router.publish( EventAgent("TestRgbLedLighting"), Events.evtSecond5 )
        time.sleep(1)

        oldLen = len(TestEventLogger._events)
        TestEventLogger.logEvents()

        self.assertEqual( oldLen, 1 )

    def testDummy(self):
        return
Esempio n. 29
0
class TestTimerAction(unittest.TestCase):

    def setUp(self):
        self._log = logging.getLogger( "TestTimerAction" )
        self._log.debug( "\n\nsetUp" )

        self.router = None
        self.loader = None

    def tearDown(self):
        self._log.debug( "\n\ntearDown" )

        if self.loader:
            self.loader.stop()  # all tasks
            self.loader = None
        self.router = None
        time.sleep(2)

    def expectNevents(self, cnt ):
        idx = 20
        while (len(TestEventLogger._events) < cnt) and (idx > 0):
            time.sleep(0.05)
            idx = idx - 1

        if ( len(TestEventLogger._events) != cnt):
            TestEventLogger.logEvents()

        self.assertEqual( len(TestEventLogger._events), cnt)


    # Actual tests follow
    def testTimerEvent(self):
        self._log.debug( "\n\ntestTimerEvent" )

        self.loader = EventRouterLoader()
        self.loader.loadHandlers( getDictFromXmlString(testConfigTimer) )
        self.loader.start()  # all tasks
        self.router = self.loader.getEventRouter()
        self.router.publish( EventAgent("TestTimerAction"), Events.evtTimerConEnable )
        self.router.publish( EventAgent("TestTimerAction"), Events.evtTimerConDuration )
        self.router.publish( EventAgent("TestTimerAction"), Events.evtHome )
        self.router.publish( EventAgent("TestTimerAction"), Events.evtDark )
        self.router.publish( EventAgent("TestTimerAction"), Events.evtMorningDark )
        self.router.publish( EventAgent("TestTimerAction"), Events.evtDO_0_on )   # this should kick presence but not create an event
        self.router.publish( EventAgent("TestTimerAction"), Events.evtDO_0_off )  # this should kick presence because invert is true
        self.router.publish( EventAgent("TestTimerAction"), Events.evtDO_0_off )  # this should kick presence because invert is true (twice because this happens)
        self.router.publish( EventAgent("TestTimerAction"), Events.evtSecond0 )  # Create a 'second'
        self.router.publish( EventAgent("TestTimerAction"), Events.evtSecond1 )  # Create a 'second'
        self.router.publish( EventAgent("TestTimerAction"), Events.evtSecond2 )  # Create a 'second'
        self.router.publish( EventAgent("TestTimerAction"), Events.evtSecond3 )  # Create a 'second'
        time.sleep(1)
        self.expectNevents( 14 )
        
        self.assertEqual( TestEventLogger._events[12].getType(), u'http://id.webbrick.co.uk/events/timer' )
        self.assertEqual( TestEventLogger._events[12].getSource(), "testing/timer/1" )
        self.assertEqual( TestEventLogger._events[13].getType(), u'testing' )
        self.assertEqual( TestEventLogger._events[13].getSource(), "result/timertest" ) 


    def testTimerDisable(self):
        self._log.debug( "\n\ntestTimerDisable" )

        self.loader = EventRouterLoader()
        self.loader.loadHandlers( getDictFromXmlString(testConfigTimer) )
        self.loader.start()  # all tasks
        self.router = self.loader.getEventRouter()
        self.router.publish( EventAgent("TestTimerAction"), Events.evtTimerConDisable )
        self.router.publish( EventAgent("TestTimerAction"), Events.evtTimerConDuration )
        self.router.publish( EventAgent("TestTimerAction"), Events.evtHome )
        self.router.publish( EventAgent("TestTimerAction"), Events.evtDark )
        self.router.publish( EventAgent("TestTimerAction"), Events.evtMorningDark )
        self.router.publish( EventAgent("TestTimerAction"), Events.evtDO_0_off )  # this should kick presence
        self.router.publish( EventAgent("TestTimerAction"), Events.evtSecond0 )  # Create a 'second'
        self.router.publish( EventAgent("TestTimerAction"), Events.evtSecond1 )  # Create a 'second'
        self.router.publish( EventAgent("TestTimerAction"), Events.evtSecond2 )  # Create a 'second'
        self.router.publish( EventAgent("TestTimerAction"), Events.evtSecond3 )  # Create a 'second'
        self.expectNevents( 10 )
            
    def testTimerHold(self):
        self._log.debug( "\n\ntestTimerHold" )

        self.loader = EventRouterLoader()
        self.loader.loadHandlers( getDictFromXmlString(testConfigTimer) )
        self.loader.start()  # all tasks
        self.router = self.loader.getEventRouter()
        self.router.publish( EventAgent("TestTimerAction"), Events.evtTimerConEnable )
        self.router.publish( EventAgent("TestTimerAction"), Events.evtTimerConDuration )
        self.router.publish( EventAgent("TestTimerAction"), Events.evtHome )
        self.router.publish( EventAgent("TestTimerAction"), Events.evtDark )
        self.router.publish( EventAgent("TestTimerAction"), Events.evtMorningDark )
        self.router.publish( EventAgent("TestTimerAction"), Events.evtDO_1_off ) # this should create a hold state  (because invert is set)
        self.router.publish( EventAgent("TestTimerAction"), Events.evtDO_0_off )  # this should kick presence
        self.router.publish( EventAgent("TestTimerAction"), Events.evtSecond0 )  # Create a 'second'
        self.router.publish( EventAgent("TestTimerAction"), Events.evtSecond1 )  # Create a 'second'
        self.router.publish( EventAgent("TestTimerAction"), Events.evtSecond2 )  # Create a 'second'
        self.router.publish( EventAgent("TestTimerAction"), Events.evtSecond3 )  # Create a 'second'
        self.expectNevents( 11 )


    def testTimerHoldPI(self):
        self._log.debug( "\n\ntestTimerHoldPI" )

        self.loader = EventRouterLoader()
        self.loader.loadHandlers( getDictFromXmlString(testConfigTimer2) )
        self.loader.start()  # all tasks
        self.router = self.loader.getEventRouter()
        self.router.publish( EventAgent("TestTimerAction"), Events.evtTimerConEnable )
        self.router.publish( EventAgent("TestTimerAction"), Events.evtTimerConDuration )
        self.router.publish( EventAgent("TestTimerAction"), Events.evtHome )
        self.router.publish( EventAgent("TestTimerAction"), Events.evtDark )
        self.router.publish( EventAgent("TestTimerAction"), Events.evtMorningDark )
        self.router.publish( EventAgent("TestTimerAction"), Events.evtDO_1_on ) # this should NOT create a hold state  (because invert is set)
        self.router.publish( EventAgent("TestTimerAction"), Events.evtDO_0_on )  # this should kick presence
        self.router.publish( EventAgent("TestTimerAction"), Events.evtSecond0 )  # Create a 'second'
        self.router.publish( EventAgent("TestTimerAction"), Events.evtSecond1 )  # Create a 'second'
        self.router.publish( EventAgent("TestTimerAction"), Events.evtSecond2 )  # Create a 'second'
        self.router.publish( EventAgent("TestTimerAction"), Events.evtSecond3 )  # Create a 'second'
        self.expectNevents( 13 )


        self.assertEqual( TestEventLogger._events[11].getType(), u'http://id.webbrick.co.uk/events/timer' )
        self.assertEqual( TestEventLogger._events[11].getSource(), "testing/timer/1" )
        self.assertEqual( TestEventLogger._events[12].getType(), u'testing' )
        self.assertEqual( TestEventLogger._events[12].getSource(), "result/timertest" ) 



    def testTimerEventWithState(self):
        self._log.debug( "\n\ntestTimerEventWithState" )

        self.loader = EventRouterLoader()
        self.loader.loadHandlers( getDictFromXmlString(testConfigTimer3) )
        self.loader.start()  # all tasks
        self.router = self.loader.getEventRouter()
        self.router.publish( EventAgent("TestTimerAction"), Events.evtTimerConEnable )
        self.router.publish( EventAgent("TestTimerAction"), Events.evtTimerConDuration )
        self.router.publish( EventAgent("TestTimerAction"), Events.evtHome )
        self.router.publish( EventAgent("TestTimerAction"), Events.evtDark )
        self.router.publish( EventAgent("TestTimerAction"), Events.evtMorningDark )
        self.router.publish( EventAgent("TestTimerAction"), Events.evtDO_2_off )  # this should kick light on, but without presence
        self.router.publish( EventAgent("TestTimerAction"), Events.evtSecond0 )  # Create a 'second'
        self.router.publish( EventAgent("TestTimerAction"), Events.evtSecond1 )  # Create a 'second'
        self.router.publish( EventAgent("TestTimerAction"), Events.evtSecond2 )  # Create a 'second'
        self.router.publish( EventAgent("TestTimerAction"), Events.evtSecond3 )  # Create a 'second'
        self.expectNevents( 12 )
            
        self.assertEqual( TestEventLogger._events[10].getType(), u'http://id.webbrick.co.uk/events/timer' )
        self.assertEqual( TestEventLogger._events[10].getSource(), "testing/timer/1" )
        self.assertEqual( TestEventLogger._events[11].getType(), u'testing' )
        self.assertEqual( TestEventLogger._events[11].getSource(), "result/timertest" ) 


    def testTimerEventWithStateAndPresence(self):
        self._log.debug( "\n\ntestTimerEventWithStateAndPresence" )

        self.loader = EventRouterLoader()
        self.loader.loadHandlers( getDictFromXmlString(testConfigTimer3) )
        self.loader.start()  # all tasks
        self.router = self.loader.getEventRouter()
        self.router.publish( EventAgent("TestTimerAction"), Events.evtTimerConEnable )
        self.router.publish( EventAgent("TestTimerAction"), Events.evtTimerConDuration )
        self.router.publish( EventAgent("TestTimerAction"), Events.evtHome )
        self.router.publish( EventAgent("TestTimerAction"), Events.evtDark )
        self.router.publish( EventAgent("TestTimerAction"), Events.evtMorningDark )
        self.router.publish( EventAgent("TestTimerAction"), Events.evtDO_2_off )  # this should kick light on, 
        self.router.publish( EventAgent("TestTimerAction"), Events.evtDO_0_off )  # this should kick  presence
        self.router.publish( EventAgent("TestTimerAction"), Events.evtDO_0_off )  # this should kick  presence  (twice because this happens!)
        self.router.publish( EventAgent("TestTimerAction"), Events.evtSecond0 )  # Create a 'second'
        self.router.publish( EventAgent("TestTimerAction"), Events.evtSecond1 )  # Create a 'second'
        self.router.publish( EventAgent("TestTimerAction"), Events.evtSecond2 )  # Create a 'second'
        self.router.publish( EventAgent("TestTimerAction"), Events.evtSecond3 )  # Create a 'second'
        self.expectNevents( 14 )
            
        self.assertEqual( TestEventLogger._events[12].getType(), u'http://id.webbrick.co.uk/events/timer' )
        self.assertEqual( TestEventLogger._events[12].getSource(), "testing/timer/1" )
        self.assertEqual( TestEventLogger._events[13].getType(), u'testing' )
        self.assertEqual( TestEventLogger._events[13].getSource(), "result/timertest" ) 


    def testTimerEventWithAnalogue(self):
        self._log.debug( "\n\ntestTimerEventWithAnalogue" )

        self.loader = EventRouterLoader()
        self.loader.loadHandlers( getDictFromXmlString(testConfigTimer4) )
        self.loader.start()  # all tasks
        self.router = self.loader.getEventRouter()
        self.router.publish( EventAgent("TestTimerAction"), Events.evtTimerConEnable )
        self.router.publish( EventAgent("TestTimerAction"), Events.evtTimerConDuration )
        self.router.publish( EventAgent("TestTimerAction"), Events.evtHome )
        self.router.publish( EventAgent("TestTimerAction"), Events.evtDark )
        self.router.publish( EventAgent("TestTimerAction"), Events.evtMorningDark )
        self.router.publish( EventAgent("TestTimerAction"), Events.evtAI_0_10 )  # this should show light off, 
        self.router.publish( EventAgent("TestTimerAction"), Events.evtAI_0_90 )  # this should kick light on, 
        self.router.publish( EventAgent("TestTimerAction"), Events.evtAI_0_90 )  # this should kick light on, twice because it can happen 
        self.router.publish( EventAgent("TestTimerAction"), Events.evtDO_0_off )  # this should kick  presence
        self.router.publish( EventAgent("TestTimerAction"), Events.evtSecond0 )  # Create a 'second'
        self.router.publish( EventAgent("TestTimerAction"), Events.evtSecond1 )  # Create a 'second'
        self.router.publish( EventAgent("TestTimerAction"), Events.evtSecond2 )  # Create a 'second'
        self.router.publish( EventAgent("TestTimerAction"), Events.evtSecond3 )  # Create a 'second'
        self.expectNevents( 15 )
            
        self.assertEqual( TestEventLogger._events[13].getType(), u'http://id.webbrick.co.uk/events/timer' )
        self.assertEqual( TestEventLogger._events[13].getSource(), "testing/timer/1" )
        self.assertEqual( TestEventLogger._events[14].getType(), u'testing' )
        self.assertEqual( TestEventLogger._events[14].getSource(), "result/timertest" ) 
Esempio n. 30
0
class TestCompound(unittest.TestCase):

    def setUp(self):
        self._log = logging.getLogger( "TestCompound" )
        self._log.debug( "\n\nsetUp" )

        self.router = None
        self.loader = None

    def tearDown(self):
        self._log.debug( "\n\ntearDown" )

        if self.loader:
            self.loader.stop()  # all tasks
            self.loader = None
        self.router = None
            
    def expectNevents(self, cnt ):
        idx = 20
        while (len(TestEventLogger._events) < cnt) and (idx > 0):
            time.sleep(0.05)
            idx = idx - 1

        if ( len(TestEventLogger._events) != cnt):
            TestEventLogger.logEvents()

        self.assertEqual( len(TestEventLogger._events), cnt)

    # Actual tests follow
    def testCompoundEvent(self):
        self._log.debug( "\n\ntestCompoundEvent" )

        self.loader = EventRouterLoader()
        self.loader.loadHandlers( getDictFromXmlString(testConfigCompoundEvent) )
        self.loader.start()  # all tasks
        self.router = self.loader.getEventRouter()

        self.router.publish( EventAgent("TestCompound"), Events.evtDI_0_off )    # 0 Off
        self.router.publish( EventAgent("TestCompound"), Events.evtDI_1_off )    # 1 Off

        self.expectNevents( 3 )
        self.assertEqual( TestEventLogger._events[2].getType(), u'http://simple' )
        self.assertEqual( TestEventLogger._events[2].getSource(), "garage1/Error" )
        od = TestEventLogger._events[2].getPayload()
        self.assertEqual( od["Sensor1"], "0" )
        self.assertEqual( od["Sensor2"], "0" )

        self.router.publish( EventAgent("TestCompound"), Events.evtDI_1_on )    # 1 On
        self.expectNevents( 5 )
        self.assertEqual( TestEventLogger._events[4].getType(), u'http://simple' )
        self.assertEqual( TestEventLogger._events[4].getSource(), "garage1/Open" )
        od = TestEventLogger._events[4].getPayload()
        self.assertEqual( od["Sensor1"], "0" )
        self.assertEqual( od["Sensor2"], "1" )

        self.router.publish( EventAgent("TestCompound"), Events.evtDI_0_on )    # 0 On
        self.expectNevents( 7 )
        self.assertEqual( TestEventLogger._events[6].getType(), u'http://simple' )
        self.assertEqual( TestEventLogger._events[6].getSource(), "garage1/Ajar" )
        od = TestEventLogger._events[6].getPayload()
        self.assertEqual( od["aval"], "2" )
        self.assertEqual( od["Sensor1"], "1" )
        self.assertEqual( od["Sensor2"], "1" )

        self.router.publish( EventAgent("TestCompound"), Events.evtDI_1_off )    # 1 Off
        self.expectNevents( 9 )
        self.assertEqual( TestEventLogger._events[8].getType(), u'http://simple' )
        self.assertEqual( TestEventLogger._events[8].getSource(), "garage1/Closed" )
        od = TestEventLogger._events[8].getPayload()
        self.assertEqual( od["Sensor1"], "1" )
        self.assertEqual( od["Sensor2"], "0" )

    def testCompoundEvent2(self):
        # What happens if an updated updates multiple bits of local state
        # and gets repeated events
        self._log.debug( "\n\ntestCompoundEvent2" )

        self.loader = EventRouterLoader()
        self.loader.loadHandlers( getDictFromXmlString(testConfigCompoundEvent2) )
        self.loader.start()  # all tasks
        self.router = self.loader.getEventRouter()

        # initial state is all things off.
        self.router.publish( EventAgent("TestCompound"), Events.evtMinute1 )

        self.expectNevents( 1 )

        self.router.publish( EventAgent("TestCompound"), Events.evtMinute2 )
        self.expectNevents( 3 )
        self.assertEqual( TestEventLogger._events[2].getType(), u'http://simple' )
        self.assertEqual( TestEventLogger._events[2].getSource(), "garage1/Open" )

        self.router.publish( EventAgent("TestCompound"), Events.evtMinute3 )
        self.expectNevents( 5 )
        self.assertEqual( TestEventLogger._events[4].getType(), u'http://simple' )
        self.assertEqual( TestEventLogger._events[4].getSource(), "garage1/Closed" )

        self.router.publish( EventAgent("TestCompound"), Events.evtMinute2 )
        self.expectNevents( 7 )
        self.assertEqual( TestEventLogger._events[6].getType(), u'http://simple' )
        self.assertEqual( TestEventLogger._events[6].getSource(), "garage1/Open" )

    def testCompoundNewState(self):
        self._log.debug( "\ntestCompoundNewState" )

        self.loader = EventRouterLoader()
        self.loader.loadHandlers( getDictFromXmlString(testConfigCompoundEventNewState) )
        self.loader.start()  # all tasks
        self.router = self.loader.getEventRouter()

        # initial state is all things off.
        self.router.publish( EventAgent("TestCompound"), Events.evtMinute1 )

        TestEventLogger.logEvents()
        self.expectNevents( 1 )

        self.router.publish( EventAgent("TestCompound"), Events.evtMinute2 )
        self.expectNevents( 3 )
        self.assertEqual( TestEventLogger._events[2].getType(), u'internal' )
        self.assertEqual( TestEventLogger._events[2].getSource(), "testState" )
        od = TestEventLogger._events[2].getPayload()
        self.assertEqual( od["idx"], '1' )

        self.router.publish( EventAgent("TestCompound"), Events.evtMinute3 )
        self.expectNevents( 4 )

        self.router.publish( EventAgent("TestCompound"), Events.evtMinute4 )
        self.expectNevents( 6 )
        self.assertEqual( TestEventLogger._events[5].getType(), u'internal' )
        self.assertEqual( TestEventLogger._events[5].getSource(), "testState" )
        od = TestEventLogger._events[5].getPayload()
        self.assertEqual( od["idx"], 3 )  # previous minute