def _add_child_pobj(pobj): """Add the given popen4 object to the list of child processes we are tracking. Return an event object that can be used to get the process' exit code. """ CHILD_POBJS.append(pobj) event = coros.event() CHILD_EVENTS[pobj] = event return event
def test_multiple_waiters(self): evt = coros.event() value = 'some stuff' results = [] def wait_on_event(i_am_done): evt.wait() results.append(True) i_am_done.send() waiters = [] count = 5 for i in range(count): waiters.append(coros.event()) api.spawn(wait_on_event, waiters[-1]) evt.send() for w in waiters: w.wait() self.assertEqual(len(results), count)
def test_returns_immediately(self): self.pool = self.create_pool() conn = self.pool.get() self.set_up_test_table(conn) self.fill_test_table(conn) curs = conn.cursor() results = [] SHORT_QUERY = "select * from test_table" evt = coros.event() def a_query(): self.assert_cursor_works(curs) curs.execute(SHORT_QUERY) results.append(2) evt.send() evt2 = coros.event() api.spawn(a_query) results.append(1) self.assertEqual([1], results) evt.wait() self.assertEqual([1, 2], results)
def test_two_simultaneous_connections(self): """ This test is timing-sensitive. """ self.pool = self.create_pool(2) conn = self.pool.get() self.set_up_test_table(conn) self.fill_test_table(conn) curs = conn.cursor() conn2 = self.pool.get() self.set_up_test_table(conn2) self.fill_test_table(conn2) curs2 = conn2.cursor() results = [] LONG_QUERY = "select * from test_table" SHORT_QUERY = "select * from test_table where row_id <= 20" evt = coros.event() def long_running_query(): self.assert_cursor_works(curs) curs.execute(LONG_QUERY) results.append(1) evt.send() evt2 = coros.event() def short_running_query(): self.assert_cursor_works(curs2) curs2.execute(SHORT_QUERY) results.append(2) evt2.send() api.spawn(long_running_query) api.spawn(short_running_query) evt.wait() evt2.wait() results.sort() self.assertEqual([1, 2], results)
def complete(self, full_remote_path): """Wait until one of the incoming connections binds using provided full_remote_path. Return connected and bound MSRPTransport instance. If no such binding was made within MSRPBindSessionTimeout.seconds, raise MSRPBindSessionTimeout. """ full_remote_path = tuple(full_remote_path) event = coros.event() self.expected_remote_paths[full_remote_path] = event try: self.new_full_remote_path_notifier.send() with MSRPBindSessionTimeout.timeout(): return event.wait() finally: self.expected_remote_paths.pop(full_remote_path, None)
def test_waiting(self): def do_wait(q, evt): result = q.wait() evt.send(result) q = coros.queue() e1 = coros.event() api.spawn(do_wait, q, e1) api.sleep(0) self.assertEqual(1, waiting(q)) q.send('hi') api.sleep(0) self.assertEqual(0, waiting(q)) self.assertEqual('hi', e1.wait()) self.assertEqual(0, waiting(q))
def wrapper(*args, **kw): event = coros.event() def wrapped_func(): try: result = func(*args, **kw) except: event.send_exception(*sys.exc_info()) else: event.send(result) if threadable.isInIOThread(): callInGreenThread(wrapped_func) else: from twisted.internet import reactor reactor.callFromThread(callInGreenThread, wrapped_func) return event
def deliver_chunk(self, chunk, event=None): """Send chunk, wait for the transaction response (if Failure-Report header is not 'no'). Return the transaction response if it's a success, raise MSRPTransactionError if it's not. If chunk's Failure-Report is 'no', return None immediately. """ if chunk.failure_report!='no' and event is None: event = coros.event() self.send_chunk(chunk, event.send) if event is not None: response = event.wait() if isinstance(response, Exception): raise response elif 200 <= response.code <= 299: return response raise MSRPTransactionError(comment=response.comment, code=response.code)
def test_waiters_that_cancel(self): q = coros.queue() def do_receive(q, evt): api.exc_after(0, RuntimeError()) try: result = q.wait() evt.send(result) except RuntimeError: evt.send('timed out') evt = coros.event() api.spawn(do_receive, q, evt) self.assertEqual(evt.wait(), 'timed out') q.send('hi') self.assertEqual(q.wait(), 'hi')
def test_send_exc(self): log = [] e = event() def waiter(): try: result = e.wait() log.append(('received', result)) except Exception as ex: log.append(('catched', ex)) spawn(waiter) sleep(0) # let waiter to block on e.wait() obj = Exception() e.send(exc=obj) sleep(0) assert log == [('catched', obj)], log
def set_links_timeout(self, link): # stuff that won't be touched event = coros.event() link(event) proc_finished_flag = [] def myproc(): sleep(10) proc_finished_flag.append('finished') return 555 myproc = proc.spawn(myproc) link(myproc) queue = coros.queue(0) link(queue) return event, myproc, proc_finished_flag, queue
def test_reentrant(self): pool = self.klass(0, 1) def reenter(): waiter = pool.execute(lambda a: a, 'reenter') self.assertEqual('reenter', waiter.wait()) outer_waiter = pool.execute(reenter) outer_waiter.wait() evt = coros.event() def reenter_async(): pool.execute_async(lambda a: a, 'reenter') evt.send('done') pool.execute_async(reenter_async) evt.wait()
def test_multiple_coros(self): evt = coros.event() results = [] def producer(): results.append('prod') evt.send() def consumer(): results.append('cons1') evt.wait() results.append('cons2') pool = self.klass(0, 2) done = pool.execute(consumer) pool.execute_async(producer) done.wait() self.assertEquals(['cons1', 'prod', 'cons2'], results)
def prepare(self, local_uri=None): """Start listening for an incoming MSRP connection using port and use_tls from local_uri if provided. Return full local path, suitable to put in SDP a:path attribute. Note, that `local_uri' may be updated in place. """ local_uri = local_uri or protocol.URI(port=0) self.transport_event = coros.event() local_uri.host = gethostbyname(local_uri.host) factory = SpawnFactory(self.transport_event, MSRPTransport, local_uri, logger=self.logger, use_sessmatch=self.use_sessmatch) self.listening_port = self._listen(local_uri, factory) self.local_uri = local_uri return [local_uri]
def test_killing_unlinked(self): e = coros.event() def func(): try: 1 / 0 except: e.send_exception(*sys.exc_info()) p = proc.spawn_link(func) try: try: e.wait() except ZeroDivisionError: pass finally: p.unlink( ) # this disables LinkedCompleted that otherwise would be raised by the next line sleep(DELAY)
def test_raising_received(self): msgs = [] def received((message, evt)): evt.send() if message == 'fail': raise RuntimeError() else: msgs.append(message) self.actor.received = received evt = coros.event() self.actor.cast(('fail', evt)) evt.wait() evt.reset() self.actor.cast(('should_appear', evt)) evt.wait() self.assertEqual(['should_appear'], msgs)
def test_server_connectionMade_never_called(self): # trigger case when protocol instance is created, # but it's connectionMade is never called from gnutls.interfaces.twisted import TLSContext, X509Credentials from gnutls.errors import GNUTLSError cred = X509Credentials(None, None) ctx = TLSContext(cred) ev = event() def handle(conn): ev.send("handle must not be called") s = reactor.listenTLS( 0, pr.SpawnFactory(handle, LineOnlyReceiverTransport), ctx) creator = pr.GreenClientCreator(reactor, LineOnlyReceiverTransport) try: conn = creator.connectTLS('127.0.0.1', s.getHost().port, ctx) except GNUTLSError: pass assert ev.poll() is None, repr(ev.poll())
def __init__(self, _func, *args, **kw): self.func = _func self.args = args self.kw = kw self.event = coros.event() self._started = False
def __init__(self, name, event=None, timestamp=None, **kw): self.name = name self.event = event or coros.event() self.timestamp = timestamp or datetime.utcnow() self.__dict__.update(self.__defaults__.get(name, {})) self.__dict__.update(kw)
def __init__(self): super(ExternalVNCServerHandler, self).__init__() self.vnc_starter_thread = None self.vnc_socket = None self._reconnect_event = event()
def esend(meth,*args, **kwargs): global _reqq, _rspq e = coros.event() _reqq.put((e,meth,args,kwargs)) return e
def __init__(self): self._event = event()
def esend(meth, *args, **kwargs): global _reqq, _rspq e = coros.event() _reqq.put((e, meth, args, kwargs)) return e