def __init__(self): self.process = None self.available = False self.loop = mainloop.MainLoop() self.bus = Gio.bus_get_sync(Gio.BusType.SESSION, None)
def testFileBackedTrigger(self): loop = mainloop.MainLoop() notifier = tr.filenotifier.FileNotifier(loop) tr.cwmptypes.SetFileBackedNotifier(notifier) self.assertEqual(len(notifier.watches), 0) tr.helpers.Unlink(TEST3_FILE) obj = TriggerObject() obj_ref = weakref.ref(obj) self.assertEqual(len(notifier.watches), 0) # file monitoring doesn't kick in until we read/write the value once. # See cwmptypes.FileBacked._RegisterNotifier() for an explanation. _ = obj.file3 self.assertEqual(len(notifier.watches), 1) loop.RunOnce() self.assertEqual(obj.triggers, 0) open(TEST3_FILE, 'w').write('boo') loop.RunOnce() self.assertEqual(obj.triggers, 1) loop.RunOnce() self.assertEqual(obj.triggers, 1) open(TEST3_FILE, 'w').write('doo') loop.RunOnce() self.assertEqual(obj.triggers, 2) obj.file3 = 'wonk' loop.RunOnce() self.assertEqual(obj.triggers, 3) loop.RunOnce() self.assertEqual(obj.triggers, 3) self.assertEqual(obj.file3, 'wonk') self.assertTrue(obj_ref()) _ = obj.file4 del obj self.assertFalse(obj_ref())
def Main(): # Initialise PyGame os.environ["SDL_VIDEO_CENTERED"] = "1" pygame.init() options = ParseCommandLineOptions(sys.argv[1:]) # Figure out the speed if options.speed is 0: delay = 0 else: delay = 1000 / options.speed # Set up a function to create a new snake logic. if options.maze_filename: new_sl_function = lambda: snake_game.snake_logic.SnakeLogic( snake_game.maze_conf_reader. GetNewStateAccordingToConfigurationFile(options.maze_filename)) else: new_sl_function = lambda: snake_game.snake_logic.SnakeLogic( snake_game.maze_conf_reader. GetNewStateAccordingToDefaultConfiguration()) # Set up an aritst if options.no_graphics: artist = snake_game.artist.Artist(new_sl_function().state.size) else: artist = snake_game.pygame_artist.PyGameArtist( new_sl_function().state.size) # If fps, start the gui mainloop if options.fps: interact = keyb_interact.KeyBInteract() return mainloop.MainLoop(interact, artist, new_sl_function, delay) else: interact = agent_interact.AgentInteract(options.agent, options.state_mapper, options.trained_filename, options.dump_filename, options.epsilon, options.rewards, backup_num_moves=1000) return mainloop.MainLoop(interact, artist, new_sl_function, delay)
def testFileBackedNotDeleted(self): obj = TestObject() open(TEST2_FILE, 'w').write('0') self.assertEquals(obj.file2, False) obj.file2 = '' loop = mainloop.MainLoop() loop.RunOnce() self.assertTrue(os.path.exists(TEST2_FILE)) obj.file2 = None loop.RunOnce() self.assertTrue(os.path.exists(TEST2_FILE)) os.unlink(TEST2_FILE)
def testPeriodicEnable(self): ms.PERIODIC_CALLBACK = MockPeriodicCallback cpe_ms = ms.CpeManagementServer( acs_config=FakeAcsConfig(), port=0, ping_path='/', start_periodic_session=self.start_session) cpe_ms.PeriodicInformEnable = 'true' cpe_ms.PeriodicInformInterval = '15' loop = mainloop.MainLoop() loop.RunOnce() # cpe_ms should schedule the callbacks when Enable and Interval both set self.assertEqual(len(periodic_callbacks), 1) cb = periodic_callbacks[0] self.assertTrue(cb.callback) self.assertGreater(cb.callback_time, 0)
def testAcsDisable(self): http.CWMP_TMPDIR = tempfile.mkdtemp() self.removedirs.append(http.CWMP_TMPDIR) cpe_machine = self.getCpe() loop = mainloop.MainLoop() http.ACS_DISABLE_EXPIRY_SECS = 60 * 10 # pylint: disable=protected-access acs_disabled_filename = cpe_machine._AcsDisabledFilename() # Disable the ACS. Make sure we logged an access attempt anyway. before = cpe_machine._acs_config.acs_access_attempt_count open(acs_disabled_filename, 'w') loop.RunOnce() cpe_machine.NewPeriodicSession() cpe_machine.PingReceived() self.assertEqual(len(cpe_machine.event_queue), 0) after = cpe_machine._acs_config.acs_access_attempt_count self.assertNotEqual(before, after) # Now test that the file age has expired. We have to open the file again # to trigger _UpdateAcsDisabled. http.ACS_DISABLE_EXPIRY_SECS = 0.1 open(acs_disabled_filename, 'w') time.sleep(0.1) loop.RunOnce() cpe_machine.NewPeriodicSession() cpe_machine.PingReceived() self.assertEqual(len(cpe_machine.event_queue), 1) # Clear the event queue and session, go back a step to the ACS being # disabled again, then delete the file and make sure that re-enables it. cpe_machine.InformResponseReceived() cpe_machine.session = None self.assertEqual(len(cpe_machine.event_queue), 0) http.ACS_DISABLE_EXPIRY_SECS = 60 * 10 open(acs_disabled_filename, 'w') loop.RunOnce() cpe_machine.NewPeriodicSession() cpe_machine.PingReceived() self.assertEqual(len(cpe_machine.event_queue), 0) os.unlink(acs_disabled_filename) loop.RunOnce() cpe_machine.NewPeriodicSession() cpe_machine.PingReceived() self.assertEqual(len(cpe_machine.event_queue), 1)
def run(filename_function, layout=None): global ml import qtdisplay import mainloop try: ml = mainloop.MainLoop(filename_function) display = qtdisplay.QTDisplay(ml, layout) ml.setdisplay(display) display.init() except KeyboardInterrupt: pass except Exception, e: print traceback.format_exc(e)
def __init__(self, ip, cpe, listenport, acs_config, ping_path, acs_url=None, fetch_args=None, ioloop=None, restrict_acs_hosts=None): tornado.httpclient.AsyncHTTPClient.configure( 'tornado.curl_httpclient.CurlAsyncHTTPClient') # pylint:disable=protected-access oldcreate = tornado.curl_httpclient._curl_create tornado.curl_httpclient._curl_create = ( lambda *args, **kwargs: CurlCreator(oldcreate, *args, **kwargs)) # pylint:enable=protected-access self.cpe = cpe self.cpe_soap = api_soap.CPE(self.cpe) self.encode = api_soap.Encode() self.cwmplogger = cwmplog.Logger(full_logs=10) self.outstanding = None self.response_queue = [] self.request_queue = [] self.event_queue = LimitDeque(MAX_EVENT_QUEUE_SIZE, self.EventQueueHandler) self.ioloop = ioloop or tornado.ioloop.IOLoop.instance() self.retry_count = 0 # for Inform.RetryCount self.start_session_timeout = None # timer for CWMPRetryInterval self.session = None self.my_configured_ip = ip self.fetch_args = fetch_args or dict() self.ping_rate_limit_seconds = 2 self.previous_ping_time = 0 self.ping_timeout_pending = None self._changed_parameters = set() self._changed_parameters_sent = set() self._acs_config = acs_config self.cpe_management_server = cpe_management_server.CpeManagementServer( acs_url=acs_url, acs_config=acs_config, port=listenport, ping_path=ping_path, get_parameter_key=cpe.getParameterKey, start_periodic_session=self.NewPeriodicSession, ioloop=self.ioloop, restrict_acs_hosts=restrict_acs_hosts) self.last_success_response = 0 # used by DiagUI self.num_599_responses = 0 self._acs_disabled_until = None try: notifier = filenotifier.FileNotifier(mainloop.MainLoop()) self.watch_acs_disabled = notifier.WatchObj(self._AcsDisabledFilename(), self._UpdateAcsDisabled) self._UpdateAcsDisabled() except pyinotify.WatchManagerError: print 'cwmp temp dir (%s) does not exist' % CWMP_TMPDIR
def testFileBackedTransactions(self): loop = mainloop.MainLoop() obj = TestObject() saved = obj.file obj.file = '1' self.assertEqual(obj.file, saved) obj.file = saved self.assertEqual(obj.file, saved) # Simulates an abandoned transaction loop.RunOnce() self.assertEqual(obj.file, saved) saved = obj.file obj.file = '1' self.assertEqual(obj.file, saved) # Simulates a successful transaction loop.RunOnce() self.assertTrue(obj.file)
def main(): def MeCall(): print 'mecall' def MeCall2(): print 'mecall2' def MeCall22(): print 'mecall22' loop = mainloop.MainLoop() n = FileNotifier(loop) n.Add('/tmp/whatzit', MeCall) n.Add('/tmp/whatzit2', MeCall2) if not os.path.isdir('/tmp/d'): os.makedirs('/tmp/d') n.Add('/tmp/d/whatzit2', MeCall22) loop.Start()
def main(): loop = mainloop.MainLoop() class Sub(core.Exporter): def __init__(self): core.Exporter.__init__(self) self.Export(params=['Value']) self.Value = 0 root = core.Exporter() root.Sub = Sub root.SubList = {} root.Test = 'this is a test string' root.Export(params=['Test'], lists=['Sub']) loop.ListenInet(('', 12999), MakeRemoteCommandStreamer(root)) loop.ListenUnix('/tmp/cwmpd.sock', MakeRemoteCommandStreamer(root)) loop.Start()
def testMainLoop(self): self.got = '' loop = mainloop.MainLoop() listener = loop.ListenInet(('', 0), self._MakeHandler) stream = loop.Connect(listener.family, listener.address, self._SendRequest) loop.Start(timeout=5) print 'after loop 1' self.assertEqual(self.got, REQUEST_STRING) stream.close() print 'after close' loop.RunOnce(timeout=5) print 'after loop 2' # This slightly weird test ensures that the LineReader object actually # gets destroyed after its client closes. If it didn't, we would have # a memory leak. self.handler is itself a weakref so that its own # existence doesn't prevent the object from being destroyed, thus # defeating our test. self.assertEqual(self.handler(), None)
def testIdler(self): print print 'testIdler' loop = mainloop.MainLoop() loop.RunOnce() idler[0] = 0 idler[1] = 0 IdleFunc() IdleFunc() loop.RunOnce() self.assertEquals(idler, [1, 0]) loop.RunOnce() self.assertEquals(idler, [1, 0]) i1 = IdleClass() i2 = IdleClass() i1.ClassIdleFunc() i1.ClassIdleFunc() i2.ClassIdleFunc() i2.ClassIdleFunc() loop.RunOnce() self.assertEquals(idler, [1, 2])
def __init__(self, roothandle): super(Experiments, self).__init__() self.force_values = {} self.saved_values = {} self.roothandle = roothandle assert hasattr(roothandle, 'inner') self.active = [] self.loop = mainloop.MainLoop() # Read initial value of requested system experiments from the filesystem try: # This will trigger Triggered(), but can't be allowed to throw an # exception at startup time, so catch it if something goes wrong. req = ((_GetSystemExperiments(ACTIVEDIR, '.active') | _GetSystemExperiments(ACTIVEDIR, '.requested')) - _GetSystemExperiments(ACTIVEDIR, '.unrequested') - set(registered.keys())) self.Requested = ','.join(sorted(req)) except (IOError, OSError) as e: traceback.print_exc() print "Experiments: can't init self.Requested: %r" % e self._Periodic()
def testFileBackedDeleteRace(self): obj = TestObject() open(TEST3_FILE, 'w').write('0') self.assertEquals(obj.file3, '0') obj.file3 = '' # should cause deletion loop = mainloop.MainLoop() loop.RunOnce() self.assertFalse(os.path.exists(TEST3_FILE)) obj.file2 = None loop.RunOnce() self.assertTrue(os.path.exists(TEST2_FILE)) self.assertEqual(open(TEST2_FILE).read(), '') obj.file3 = '' # schedule a deletion obj.file3 = 'string' # schedule a file replacement loop.RunOnce() self.assertTrue(os.path.exists(TEST3_FILE)) self.assertEqual(open(TEST3_FILE).read(), 'string\n') obj.file3 = 'string' # schedule a file replacement obj.file3 = '' # schedule a deletion loop.RunOnce() self.assertFalse(os.path.exists(TEST3_FILE))
def IsSystemBusNameAuthorized(self, system_bus_name, action_id, challenge=True, details={}): """Don't call this inside a D-Bus method or signal handler.""" import warnings warnings.warn( "This method is not safe to use in all circumstances. Use IsSystemBusNameAuthorizedAsync() instead.", DeprecationWarning, stacklevel=2) ml = mainloop.MainLoop() reply = {} def reply_cb(is_auth): reply["reply"] = is_auth ml.quit() def error_cb(error): reply["error"] = error ml.quit() self.IsSystemBusNameAuthorizedAsync(system_bus_name, action_id, reply_handler=reply_cb, error_handler=error_cb, challenge=challenge, details=details) ml.run() if "error" in reply: raise reply["error"] return reply["reply"]
def testFileBackedNotifier(self): loop = mainloop.MainLoop() notifier = tr.filenotifier.FileNotifier(loop) tr.cwmptypes.SetFileBackedNotifier(notifier) tr.helpers.Unlink(TEST3_FILE) obj = TestObject() count = [0] def CallMe(obj): print 'callme: %r' % obj count[0] += 1 # file monitoring doesn't kick in until we read/write the value once. # See cwmptypes.FileBacked._RegisterNotifier() for an explanation. _ = obj.file3 tr.cwmptypes.AddNotifier(type(obj), 'file3', CallMe) loop.RunOnce() self.assertEqual(count, [0]) open(TEST3_FILE, 'w').write('boo') loop.RunOnce() self.assertEqual(count, [1]) loop.RunOnce() self.assertEqual(count, [1]) open(TEST3_FILE, 'w').write('doo') loop.RunOnce() self.assertEqual(count, [2])
def testMainLoop2(self): loop = mainloop.MainLoop() loop.RunOnce() del loop loop = mainloop.MainLoop() loop.RunOnce()
def main(): loop = mainloop.MainLoop() loop.ListenInet6(('', 12999), QuotedBlockStreamer) loop.ListenUnix('/tmp/cwmpd.sock', QuotedBlockStreamer) print 'hello' loop.Start()
def testFileBackedNotExist(self): obj = TestObject() with self.assertRaises(IOError): obj.file_bad = 'this should assert!' loop = mainloop.MainLoop() loop.RunOnce()
def testTypes(self): obj = TestObject() self.assertEquals(obj.a, None) self.assertEquals(obj.b, None) self.assertEquals(obj.s, 'defaultstring') self.assertEquals(obj.i, None) self.assertEquals(obj.e, None) self.assertEquals(obj.e2, None) self.assertEquals(obj.d, None) self.assertEquals(obj.m, None) self.assertEquals(obj.ip4, None) self.assertEquals(obj.ip6, None) o1 = object() obj.a = o1 self.assertEquals(obj.a, o1) obj.a = None self.assertEquals(obj.a, None) obj.b = 0 self.assertEquals(obj.b, 0) self.assertNotEqual(obj.b, None) obj.b = False self.assertEquals(obj.b, 0) obj.b = 'FaLSe' self.assertEquals(obj.b, 0) self.assertTrue(obj.b is False) self.assertTrue(obj.b is not 0) obj.b = '' self.assertEquals(obj.b, 0) obj.b = 'tRuE' self.assertEquals(obj.b, 1) self.assertTrue(obj.b is True) self.assertTrue(obj.b is not 1) obj.b = '5' self.assertTrue(obj.b is True) self.assertRaises(ValueError, setattr, obj, 'b', object()) self.assertRaises(ValueError, setattr, obj, 'b', []) self.assertFalse(hasattr(obj.b, 'xsitype')) self.assertEquals(obj.s, 'defaultstring') obj.s = 1 self.assertEquals(obj.s, '1') obj.s = o1 self.assertEquals(obj.s, str(o1)) obj.s = None self.assertEquals(obj.s, None) self.assertNotEqual(obj.s, str(None)) obj.s = '' self.assertEquals(obj.s, '') self.assertNotEqual(obj.s, None) obj.i = 7 self.assertEquals(obj.i, 7) obj.i = '8' self.assertEquals(obj.i, 8) self.assertEquals(obj.i.xsitype, 'xsd:int') self.assertRaises(ValueError, setattr, obj, 'i', '') obj.u = '5' self.assertEquals(obj.u, 5) self.assertEquals(obj.u.xsitype, 'xsd:unsignedInt') obj.u = 0 self.assertEquals(obj.u, 0) self.assertRaises(ValueError, setattr, obj, 'u', '-5') self.assertRaises(ValueError, setattr, obj, 'u', -5) obj.f = '5' self.assertEquals(obj.f, 5.0) obj.f = 0 self.assertEquals(obj.f, 0) obj.f = 5e60 self.assertEquals(obj.f, 5e60) obj.e = 'one' self.assertEquals(obj.e, 'one') obj.e = 7 self.assertEquals(obj.e, 7) self.assertRaises(ValueError, setattr, obj, 'e', '7') obj.e = None obj.e2 = 'thing' self.assertRaises(ValueError, setattr, obj, 'e2', None) obj.f = 11.5 self.assertEquals(tr.cwmptypes.tryattr(obj, 'v', 3.4), int(int(3.4) * 11.5)) self.assertRaises(ValueError, setattr, obj, 'v', -1) obj.v = 7.3 self.assertEquals(obj.v, int(int(7.3) * 11.5)) obj.vv = 5 # validator chain is: -((-5) + 1) self.assertEquals(obj.vv, 4) obj.d = 0 self.assertEquals(obj.d, datetime.datetime.utcfromtimestamp(0)) now = time.time() obj.d = now self.assertEquals(obj.d, datetime.datetime.utcfromtimestamp(now)) obj.d = '' self.assertEquals(obj.d, None) obj.d = '2013-02-27T12:17:37Z' self.assertEquals(obj.d, datetime.datetime.utcfromtimestamp(1361967457)) obj.m = '00:11:22:33:44:55' self.assertEquals(obj.m, '00:11:22:33:44:55') obj.m = '00-11-22-33-44-55' self.assertEquals(obj.m, '00-11-22-33-44-55') self.assertRaises(ValueError, setattr, obj, 'm', 1) obj.ip4 = '2.3.4.5' self.assertEquals(obj.ip4, '2.3.4.5') self.assertRaises(ValueError, setattr, obj, 'ip4', 1) obj.ip6 = '2222::' self.assertEquals(obj.ip6, '2222::') self.assertRaises(ValueError, setattr, obj, 'ip6', 1) open(TEST_FILE, 'w').write('5') self.assertEquals(obj.file, 1) open(TEST_FILE, 'w').write('0') self.assertEquals(obj.file, 0) obj.file = '' # file is Bool, so converts to False, which is NOT empty loop = mainloop.MainLoop() loop.RunOnce() self.assertTrue(os.path.exists(TEST_FILE)) self.assertEquals(open(TEST_FILE).read(), 'False\n') obj.file = None loop.RunOnce() self.assertFalse(os.path.exists(TEST_FILE)) obj.file = -900 loop.RunOnce() self.assertEquals(open(TEST_FILE).read(), 'True\n') os.unlink(TEST_FILE)