def run_test(): q = servicetest.IteratingEventQueue() # Set verboseness if needed for debugging #q.verbose = True (listener, port) = setup_stream_listener(q, "incoming") outbound = connect_to_stream(q, "outgoing", "incoming", "localhost", port) inbound = q.expect('incoming-connection', listener=listener).connection # inbound stream is opened first, then outbounds stream is opened and # receive features q.expect('stream-opened', connection=inbound) q.expect('stream-opened', connection=outbound) q.expect('stream-features', connection=outbound) message = domish.Element(('', 'message')) message.addElement('body', content="test123") outbound.send(message) e = q.expect('stream-message', connection=inbound) # twisting twisted reactor.stop()
def exec_test_deferred(fun, params, protocol=None, timeout=None, make_conn=True): colourer = None if 'SALUT_TEST_REAL_AVAHI' not in os.environ: ensure_avahi_is_running() if sys.stdout.isatty() or 'CHECK_FORCE_COLOR' in os.environ: colourer = servicetest.install_colourer() bus = dbus.SessionBus() queue = servicetest.IteratingEventQueue(timeout) queue.verbose = (os.environ.get('CHECK_TWISTED_VERBOSE', '') != '' or '-v' in sys.argv) if make_conn: try: conn = make_connection(bus, queue.append, params) except Exception, e: # This is normally because the connection's still kicking around # on the bus from a previous test. Let's bail out unceremoniously. print e os._exit(1)
def exec_test_deferred(fun, params, protocol=None, timeout=None, authenticator=None, num_instances=1, do_connect=True, make_connection_func=make_connection, expect_connected_func=expect_connected): # hack to ease debugging domish.Element.__repr__ = element_repr colourer = None if sys.stdout.isatty() or 'CHECK_FORCE_COLOR' in os.environ: colourer = servicetest.install_colourer() try: bus = dbus.SessionBus() except dbus.exceptions.DBusException as e: print e os._exit(1) queue = servicetest.IteratingEventQueue(timeout) queue.verbose = (os.environ.get('CHECK_TWISTED_VERBOSE', '') != '' or '-v' in sys.argv) conns = [] jids = [] streams = [] resource = params.get('resource') if params is not None else None for i in range(0, num_instances): if i == 0: suffix = '' else: suffix = str(i) try: (conn, jid) = make_connection_func(bus, queue.append, params, suffix) except Exception, e: # Crap. This is normally because the connection's still kicking # around on the bus. Let's bin any connections we *did* manage to # get going and then bail out unceremoniously. print e for conn in conns: conn.Disconnect() os._exit(1) conns.append(conn) jids.append(jid) streams.append( make_stream(queue.append, protocol=protocol, authenticator=authenticator, resource=resource, suffix=suffix))
def exec_test_deferred(funs, params, protocol=None, timeout=None): colourer = None if sys.stdout.isatty(): colourer = install_colourer() queue = servicetest.IteratingEventQueue(timeout) queue.verbose = (os.environ.get('CHECK_TWISTED_VERBOSE', '') != '' or '-v' in sys.argv) bus = dbus.SessionBus() sim = Simulator() bus.add_signal_receiver( lambda *args, **kw: queue.append( Event('dbus-signal', path=unwrap(kw['path']), signal=kw['member'], args=map(unwrap, args), interface=kw['interface'])), None, # signal name None, # interface None, path_keyword='path', member_keyword='member', interface_keyword='interface', byte_arrays=True) try: for f in funs: conn = make_connection(bus, queue.append, params) f(queue, bus, conn) except Exception: import traceback traceback.print_exc() try: if colourer: sys.stdout = colourer.fh reactor.crash() # force Disconnect in case the test crashed and didn't disconnect # properly. We need to call this async because the BaseIRCServer # class must do something in response to the Disconnect call and if we # call it synchronously, we're blocking ourself from responding to the # quit method. servicetest.call_async(queue, conn, 'Disconnect') if 'RING_TEST_REFDBG' in os.environ: # we have to wait for the timeout so the process is properly # exited and refdbg can generate its report time.sleep(5.5) except dbus.DBusException: pass
def exec_test(fun, params=None, register_cb=default_register_cb, timeout=None): queue = servicetest.IteratingEventQueue(timeout) queue.verbose = (os.environ.get('CHECK_TWISTED_VERBOSE', '') != '') if '-v' in sys.argv: queue.verbose = True bus, conn, sip = prepare_test(queue.append, params=params, register_cb=register_cb) if sys.stdout.isatty(): def red(s): return '\x1b[31m%s\x1b[0m' % s def green(s): return '\x1b[32m%s\x1b[0m' % s patterns = { 'handled,': green, 'not hand': red, } class Colourer: def __init__(self, fh, patterns): self.fh = fh self.patterns = patterns def write(self, s): f = self.patterns.get(s[:len('handled,')], lambda x: x) self.fh.write(f(s)) def isatty(self): return False sys.stdout = Colourer(sys.stdout, patterns) try: fun(queue, bus, conn, sip) finally: try: conn.Disconnect() # second call destroys object conn.Disconnect() except dbus.DBusException, e: pass
def exec_test_deferred (funs, params, protocol=None, timeout=None): colourer = None if sys.stdout.isatty(): colourer = install_colourer() queue = servicetest.IteratingEventQueue(timeout) queue.verbose = ( os.environ.get('CHECK_TWISTED_VERBOSE', '') != '' or '-v' in sys.argv) bus = dbus.SessionBus() # conn = make_connection(bus, queue.append, params) (server, port) = start_server(queue.append, protocol=protocol) bus.add_signal_receiver( lambda *args, **kw: queue.append( Event('dbus-signal', path=unwrap(kw['path']), signal=kw['member'], args=map(unwrap, args), interface=kw['interface'])), None, # signal name None, # interface None, path_keyword='path', member_keyword='member', interface_keyword='interface', byte_arrays=True ) error = None try: for f in funs: conn = make_connection(bus, queue.append, params) f(queue, bus, conn, server) except Exception, e: import traceback traceback.print_exc() error = e
def has_another_llxmpp(): if 'SALUT_TEST_REAL_AVAHI' not in os.environ: return False q = servicetest.IteratingEventQueue() l = AvahiListener(q) l.listen_for_service('_presence._tcp') has = False while True: e = q.wait(['service']) if (e.type == 'service-added' and e.flags & (avahi.LOOKUP_RESULT_LOCAL | avahi.LOOKUP_RESULT_OUR_OWN)): has = True elif e.type == 'service-all-for-now': break return has
def skip_if_another_llxmpp(): if has_another_llxmpp(): print("SKIP: This test fails if there is another LL XMPP instance " "running on the machine.") # exiting 77 causes automake to consider the test to have been skipped raise SystemExit(77) if __name__ == '__main__': from twisted.internet import reactor txtdict = {"test0": "0", "test1": "1"} a = AvahiAnnouncer("test", "_test._tcp", 1234, txtdict) q = servicetest.IteratingEventQueue() # Set verboseness if needed for debugging # q.verbose = True l = AvahiListener(q) l.listen_for_service("_test._tcp") while True: e = q.expect('service-added', stype='_test._tcp') # Only care about services we announced ourselves if e.flags & (avahi.LOOKUP_RESULT_LOCAL | avahi.LOOKUP_RESULT_OUR_OWN): break assert "test" == e.name[0:len("test")] s = e.service
def exec_test_deferred(fun, params, protocol=None, timeout=None, authenticator=None, num_instances=1, do_connect=True, make_connection_func=make_connection, expect_connected_func=expect_connected): # hack to ease debugging domish.Element.__repr__ = element_repr colourer = None if sys.stdout.isatty() or 'CHECK_FORCE_COLOR' in os.environ: colourer = servicetest.install_colourer() try: bus = dbus.SessionBus() except dbus.exceptions.DBusException as e: print(e) os._exit(1) queue = servicetest.IteratingEventQueue(timeout) queue.verbose = (os.environ.get('CHECK_TWISTED_VERBOSE', '') != '' or '-v' in sys.argv) port = os.environ.get('CHECK_TWISTED_PORT', '') if port != '': port = dbus.UInt32(port) else: port = dbus.UInt32(4242) if params: params = dict(params) # This means caller wants server to use non-standard port and hence # connection to fail. Let's move the client by large margin off to # prevent it hitting one of the instances spawned by meson if 'port' in params and params['port'] != 4242: params['port'] = port port = port - 1000 else: params['port'] = port else: params = {'port': port} conns = [] jids = [] streams = [] resource = params.get('resource') if params is not None else None for i in range(0, num_instances): if i == 0: suffix = '' else: suffix = str(i) try: (conn, jid) = make_connection_func(bus, queue.append, params, suffix) except Exception as e: # Crap. This is normally because the connection's still kicking # around on the bus. Let's bin any connections we *did* manage to # get going and then bail out unceremoniously. print(e) for conn in conns: conn.Disconnect() os._exit(1) conns.append(conn) jids.append(jid) streams.append( make_stream(queue.append, protocol=protocol, authenticator=authenticator, resource=resource, suffix=suffix)) factory = StreamFactory(streams, jids) port = reactor.listenTCP(port, factory, interface='localhost') def signal_receiver(*args, **kw): if kw['path'] == '/org/freedesktop/DBus' and \ kw['member'] == 'NameOwnerChanged': bus_name, old_name, new_name = args if new_name == '': for i, conn in enumerate(conns): stream = streams[i] jid = jids[i] if conn._requested_bus_name == bus_name: factory.lost_presence(stream, jid) break queue.append( Event('dbus-signal', path=unwrap(kw['path']), signal=kw['member'], args=[unwrap(arg) for arg in args], interface=kw['interface'])) match_all_signals = bus.add_signal_receiver( signal_receiver, None, # signal name None, # interface None, path_keyword='path', member_keyword='member', interface_keyword='interface', byte_arrays=True) error = None try: if do_connect: for conn in conns: conn.Connect() expect_connected_func(queue) if len(conns) == 1: fun(queue, bus, conns[0], streams[0]) else: fun(queue, bus, conns, streams) except Exception as e: traceback.print_exc() error = e queue.verbose = False if colourer: sys.stdout = colourer.fh d = port.stopListening() # Does the Connection object still exist? for i, conn in enumerate(conns): if not bus.name_has_owner(conn.object.bus_name): # Connection has already been disconnected and destroyed continue try: if conn.Properties.Get(cs.CONN, 'Status') == cs.CONN_STATUS_CONNECTED: # Connection is connected, properly disconnect it disconnect_conn(queue, conn, streams[i]) else: # Connection is not connected, call Disconnect() to destroy it conn.Disconnect() except dbus.DBusException as e: pass except Exception as e: traceback.print_exc() error = e try: conn.Disconnect() raise AssertionError("Connection didn't disappear; " "all subsequent tests will probably fail") except dbus.DBusException as e: pass except Exception as e: traceback.print_exc() error = e match_all_signals.remove() if error is None: d.addBoth((lambda *args: reactor.crash())) else: # please ignore the POSIX behind the curtain d.addBoth((lambda *args: os._exit(1)))
q.expect('stream-authenticated') q.expect('dbus-signal', signal='PresencesChanged', args=[{ 1: (cs.PRESENCE_AVAILABLE, 'available', '') }]) q.expect('dbus-signal', signal='StatusChanged', args=[cs.CONN_STATUS_CONNECTED, cs.CSR_REQUESTED]) # Disconnection 2 disconnect_conn(q, conn2, stream2) if __name__ == '__main__': queue = servicetest.IteratingEventQueue(None) queue.verbose = (os.environ.get('CHECK_TWISTED_VERBOSE', '') != '' or '-v' in sys.argv) bus = dbus.SessionBus() params = { 'account': 'test1@localhost/Resource', 'password': '******', 'resource': 'Resource', 'server': 'localhost', 'port': dbus.UInt32(4242), } conn1, jid1 = make_connection(bus, queue.append, params) authenticator = BlockForeverTlsAuthenticator('test1', 'pass') stream1 = make_stream(queue.append, authenticator, protocol=XmppXmlStream)