diff options
author | Arusekk <arek_koz@o2.pl> | 2020-10-26 18:04:14 +0100 |
---|---|---|
committer | Alexander Akulich <akulichalexander@gmail.com> | 2020-11-10 00:48:37 +0300 |
commit | 6fcaa04e2211f2dda2e4498239360380261b646c (patch) | |
tree | 07ee2a241386a0b5211b0950127ec167142fbd66 | |
parent | 0818764401dc33c5f58a892e5c9880ce84bbe645 (diff) | |
download | telepathy-haze-6fcaa04e2211f2dda2e4498239360380261b646c.tar.gz |
Port tests to python 3
glib2reactor is deprecated in favor of gireactor
-rw-r--r-- | tests/twisted/cm/protocols.py | 2 | ||||
-rw-r--r-- | tests/twisted/connect/twice-to-same-account.py | 2 | ||||
-rw-r--r-- | tests/twisted/gabbletest.py | 49 | ||||
-rw-r--r-- | tests/twisted/roster/groups.py | 20 | ||||
-rw-r--r-- | tests/twisted/sasl/telepathy-password.py | 2 | ||||
-rw-r--r-- | tests/twisted/servicetest.py | 45 | ||||
-rw-r--r-- | tools/c-constants-gen.py | 2 | ||||
-rw-r--r-- | tools/glib-ginterface-gen.py | 9 | ||||
-rw-r--r-- | tools/glib-gtypes-generator.py | 4 | ||||
-rw-r--r-- | tools/glib-interfaces-gen.py | 4 | ||||
-rw-r--r-- | tools/glib-signals-marshal-gen.py | 7 | ||||
-rw-r--r-- | tools/libglibcodegen.py | 6 | ||||
-rw-r--r-- | tools/libtpcodegen.py | 8 | ||||
-rw-r--r-- | tools/make-release-mail.py | 10 |
14 files changed, 83 insertions, 87 deletions
diff --git a/tests/twisted/cm/protocols.py b/tests/twisted/cm/protocols.py index 4dc3f19..1d851d6 100644 --- a/tests/twisted/cm/protocols.py +++ b/tests/twisted/cm/protocols.py @@ -18,7 +18,7 @@ def test(q, bus, conn, stream): protocols = cm_props.Get(cs.CM, 'Protocols') protocol_names = cm_iface.ListProtocols() - assertEquals(set(protocols.iterkeys()), set(protocol_names)) + assertEquals(set(protocols.keys()), set(protocol_names)) for name in protocol_names: props = protocols[name] diff --git a/tests/twisted/connect/twice-to-same-account.py b/tests/twisted/connect/twice-to-same-account.py index 8fe3db2..419e1a3 100644 --- a/tests/twisted/connect/twice-to-same-account.py +++ b/tests/twisted/connect/twice-to-same-account.py @@ -28,7 +28,7 @@ def test(q, bus, conn, stream): # You might think that this is the test... try: cm_iface.RequestConnection('jabber', params) - except dbus.DBusException, e: + except dbus.DBusException as e: assertEquals(cs.NOT_AVAILABLE, e.get_dbus_name()) # but you'd be wrong: we now test that Haze is still alive. diff --git a/tests/twisted/gabbletest.py b/tests/twisted/gabbletest.py index 82db618..efed50a 100644 --- a/tests/twisted/gabbletest.py +++ b/tests/twisted/gabbletest.py @@ -75,7 +75,7 @@ def make_muc_presence(affiliation, role, muc_jid, alias, jid=None, photo=None): if photo is not None: presence.addChild( elem(ns.VCARD_TEMP_UPDATE, 'x')( - elem('photo')(unicode(photo)) + elem('photo')(str(photo)) )) return presence @@ -129,7 +129,7 @@ class JabberAuthenticator(GabbleAuthenticator): def streamStarted(self, root=None): if root: - self.xmlstream.sid = '%x' % random.randint(1, sys.maxint) + self.xmlstream.sid = '%x' % random.randint(1, sys.maxsize) self.xmlstream.domain = root.getAttribute('to') self.xmlstream.sendHeader() @@ -165,11 +165,11 @@ class JabberAuthenticator(GabbleAuthenticator): def respondToSecondIq(self, iq): username = xpath.queryForNodes('/iq/query/username', iq) - assert map(str, username) == [self.username] + assert list(map(str, username)) == [self.username] digest = xpath.queryForNodes('/iq/query/digest', iq) expect = hashlib.sha1(self.xmlstream.sid + self.password).hexdigest() - assert map(str, digest) == [expect] + assert list(map(str, digest)) == [expect] resource = xpath.queryForNodes('/iq/query/resource', iq) assertLength(1, resource) @@ -197,7 +197,7 @@ class XmppAuthenticator(GabbleAuthenticator): self.xmlstream.domain = root.getAttribute('to') if self.xmlstream.sid is None: - self.xmlstream.sid = '%x' % random.randint(1, sys.maxint) + self.xmlstream.sid = '%x' % random.randint(1, sys.maxsize) self.xmlstream.sendHeader() @@ -232,8 +232,8 @@ class XmppAuthenticator(GabbleAuthenticator): self.streamSASL() def auth(self, auth): - assert (base64.b64decode(str(auth)) == - '\x00%s\x00%s' % (self.username, self.password)) + assert (base64.b64decode(bytes(auth)) == + b'\x00%s\x00%s' % (self.username.encode(), self.password.encode())) success = domish.Element((ns.NS_XMPP_SASL, 'success')) self.xmlstream.send(success) @@ -304,8 +304,7 @@ class StreamFactory(twisted.internet.protocol.Factory): self.streams = streams self.jids = jids self.presences = {} - self.mappings = dict(map (lambda jid, stream: (jid, stream), - jids, streams)) + self.mappings = dict(zip(jids, streams)) # Make a copy of the streams self.factory_streams = list(streams) @@ -347,7 +346,7 @@ class StreamFactory(twisted.internet.protocol.Factory): stream.send(presence) def lost_presence(self, stream, jid): - if self.presences.has_key(jid): + if jid in self.presences: del self.presences[jid] for dest_jid in self.presences.keys(): presence = domish.Element(('jabber:client', 'presence')) @@ -556,7 +555,7 @@ def disconnect_conn(q, conn, stream, expected_before=[], expected_after=[]): return before_events[:-2], after_events[:-1] def element_repr(element): - """__repr__ cannot safely return non-ASCII: see + r"""__repr__ cannot safely return non-ASCII: see <http://bugs.python.org/issue5876>. So we print non-ASCII characters as \uXXXX escapes in debug output @@ -568,7 +567,7 @@ def expect_connected(queue): args=[cs.CONN_STATUS_CONNECTING, cs.CSR_REQUESTED]) queue.expect('stream-authenticated') queue.expect('dbus-signal', signal='PresencesChanged', - args=[{1L: (cs.PRESENCE_AVAILABLE, u'available', '')}]) + args=[{1: (cs.PRESENCE_AVAILABLE, u'available', '')}]) queue.expect('dbus-signal', signal='StatusChanged', args=[cs.CONN_STATUS_CONNECTED, cs.CSR_REQUESTED]) @@ -587,7 +586,7 @@ def exec_test_deferred(fun, params, protocol=None, timeout=None, try: bus = dbus.SessionBus() except dbus.exceptions.DBusException as e: - print e + print(e) os._exit(1) queue = servicetest.IteratingEventQueue(timeout) @@ -607,11 +606,11 @@ def exec_test_deferred(fun, params, protocol=None, timeout=None, try: (conn, jid) = make_connection_func(bus, queue.append, params, suffix) - except Exception, e: + 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 + print(e) for conn in conns: conn.Disconnect() @@ -640,7 +639,7 @@ def exec_test_deferred(fun, params, protocol=None, timeout=None, break queue.append(Event('dbus-signal', path=unwrap(kw['path']), - signal=kw['member'], args=map(unwrap, args), + signal=kw['member'], args=list(map(unwrap, args)), interface=kw['interface'])) match_all_signals = bus.add_signal_receiver( @@ -666,7 +665,7 @@ def exec_test_deferred(fun, params, protocol=None, timeout=None, fun(queue, bus, conns[0], streams[0]) else: fun(queue, bus, conns, streams) - except Exception, e: + except Exception as e: traceback.print_exc() error = e queue.verbose = False @@ -688,9 +687,9 @@ def exec_test_deferred(fun, params, protocol=None, timeout=None, else: # Connection is not connected, call Disconnect() to destroy it conn.Disconnect() - except dbus.DBusException, e: + except dbus.DBusException as e: pass - except Exception, e: + except Exception as e: traceback.print_exc() error = e @@ -698,9 +697,9 @@ def exec_test_deferred(fun, params, protocol=None, timeout=None, conn.Disconnect() raise AssertionError("Connection didn't disappear; " "all subsequent tests will probably fail") - except dbus.DBusException, e: + except dbus.DBusException as e: pass - except Exception, e: + except Exception as e: traceback.print_exc() error = e @@ -756,7 +755,7 @@ def _elem_add(elem, *children): for child in children: if isinstance(child, domish.Element): elem.addChild(child) - elif isinstance(child, unicode): + elif isinstance(child, str): elem.addContent(child) else: raise ValueError( @@ -797,14 +796,14 @@ def elem(a, b=None, attrs={}, **kw): # First, let's pull namespaces out realattrs = {} - for k, v in allattrs.iteritems(): + for k, v in allattrs.items(): if k.startswith('xmlns:'): abbr = k[len('xmlns:'):] elem.localPrefixes[abbr] = v else: realattrs[k] = v - for k, v in realattrs.iteritems(): + for k, v in realattrs.items(): if k == 'from_': elem['from'] = v else: @@ -820,7 +819,7 @@ def elem_iq(server, type, **kw): iq = _iq(server, type) - for k, v in kw.iteritems(): + for k, v in kw.items(): if k == 'from_': iq['from'] = v else: diff --git a/tests/twisted/roster/groups.py b/tests/twisted/roster/groups.py index 8f8f2c9..48790cf 100644 --- a/tests/twisted/roster/groups.py +++ b/tests/twisted/roster/groups.py @@ -137,8 +137,8 @@ def test(q, bus, conn, stream): EventPattern('dbus-return', method='AddMembers'), ) assertEquals('duncan@scotland.lit', iq.stanza.query.item['jid']) - groups = set([str(x) for x in xpath.queryForNodes('/iq/query/item/group', - iq.stanza)]) + groups = {str(x) for x in xpath.queryForNodes('/iq/query/item/group', + iq.stanza)} assertLength(2, groups) assertContains(default_group_name, groups) assertContains('Scots', groups) @@ -154,8 +154,8 @@ def test(q, bus, conn, stream): EventPattern('dbus-return', method='RemoveMembers'), ) assertEquals('duncan@scotland.lit', iq.stanza.query.item['jid']) - groups = set([str(x) for x in xpath.queryForNodes('/iq/query/item/group', - iq.stanza)]) + groups = {str(x) for x in xpath.queryForNodes('/iq/query/item/group', + iq.stanza)} assertLength(1, groups) assertContains('Scots', groups) @@ -178,15 +178,15 @@ def test(q, bus, conn, stream): ) assertEquals('romeo@montague.lit', iq1.stanza.query.item['jid']) - groups = set([str(x) for x in xpath.queryForNodes('/iq/query/item/group', - iq1.stanza)]) + groups = {str(x) for x in xpath.queryForNodes('/iq/query/item/group', + iq1.stanza)} assertLength(2, groups) assertContains('Still alive', groups) assertContains(default_group_name, groups) assertEquals('romeo@montague.lit', iq2.stanza.query.item['jid']) - groups = set([str(x) for x in xpath.queryForNodes('/iq/query/item/group', - iq2.stanza)]) + groups = {str(x) for x in xpath.queryForNodes('/iq/query/item/group', + iq2.stanza)} assertLength(1, groups) assertContains(default_group_name, groups) @@ -202,8 +202,8 @@ def test(q, bus, conn, stream): EventPattern('dbus-return', method='RemoveMembers'), ) assertEquals('juliet@capulet.lit', iq.stanza.query.item['jid']) - groups = set([str(x) for x in xpath.queryForNodes('/iq/query/item/group', - iq.stanza)]) + groups = {str(x) for x in xpath.queryForNodes('/iq/query/item/group', + iq.stanza)} assertLength(1, groups) assertContains('Capulets', groups) diff --git a/tests/twisted/sasl/telepathy-password.py b/tests/twisted/sasl/telepathy-password.py index f95a3d0..3051eef 100644 --- a/tests/twisted/sasl/telepathy-password.py +++ b/tests/twisted/sasl/telepathy-password.py @@ -7,7 +7,7 @@ from hazetest import exec_test import constants as cs from saslutil import connect_and_get_sasl_channel -PASSWORD = "pass" +PASSWORD = b"pass" def test_close_straight_after_accept(q, bus, conn, stream): chan, props = connect_and_get_sasl_channel(q, bus, conn) diff --git a/tests/twisted/servicetest.py b/tests/twisted/servicetest.py index 31c00f4..c9736b0 100644 --- a/tests/twisted/servicetest.py +++ b/tests/twisted/servicetest.py @@ -2,10 +2,11 @@ """ Infrastructure code for testing connection managers. """ +from __future__ import print_function -from twisted.internet import glib2reactor +from twisted.internet import gireactor from twisted.internet.protocol import Protocol, Factory, ClientFactory -glib2reactor.install() +gireactor.install() import sys import time import os @@ -86,7 +87,7 @@ class EventPattern: if event.type != self.type: return False - for key, value in self.properties.iteritems(): + for key, value in self.properties.items(): try: if getattr(event, key) != value: return False @@ -128,7 +129,7 @@ class BaseEventQueue: def log(self, s): if self.verbose: - print s + print(s) def log_queues(self, queues): self.log ("Waiting for event on: %s" % ", ".join(queues)) @@ -137,7 +138,7 @@ class BaseEventQueue: self.log('got event:') if self.verbose: - map(self.log, format_event(event)) + list(map(self.log, format_event(event))) def forbid_events(self, patterns): """ @@ -265,10 +266,10 @@ class BaseEventQueue: def queues_available(self, queues): if queues == None: - return self.event_queues.keys() + return list(self.event_queues.keys()) else: available = self.event_queues.keys() - return filter(lambda x: x in available, queues) + return [x for x in queues if x in available] def pop_next(self, queue): @@ -362,7 +363,7 @@ class EventQueueTest(unittest.TestCase): queue.append(Event('baz-test', x=1)) queue.append(Event('baz-test', x=2)) - for x in xrange(1,2): + for x in range(1,2): e = queue.expect ('baz-test') assertEquals (x, e.x) @@ -390,18 +391,18 @@ def unwrap(x): printed.""" if isinstance(x, list): - return map(unwrap, x) + return list(map(unwrap, x)) if isinstance(x, tuple): return tuple(map(unwrap, x)) if isinstance(x, dict): - return dict([(unwrap(k), unwrap(v)) for k, v in x.iteritems()]) + return {unwrap(k): unwrap(v) for k, v in x.items()} if isinstance(x, dbus.Boolean): return bool(x) - for t in [unicode, str, long, int, float]: + for t in [str, bytes, int, int, float]: if isinstance(x, t): return t(x) @@ -444,9 +445,9 @@ class ProxyWrapper: self.Properties = dbus.Interface(object, dbus.PROPERTIES_IFACE) self.TpProperties = \ dbus.Interface(object, tp_name_prefix + '.Properties') - self.interfaces = dict([ - (name, dbus.Interface(object, iface)) - for name, iface in others.iteritems()]) + self.interfaces = { + name: dbus.Interface(object, iface) + for name, iface in others.items()} def __getattr__(self, name): if name in self.interfaces: @@ -482,9 +483,9 @@ def wrap_channel(chan, type_, extra=None): } if extra: - interfaces.update(dict([ - (name, tp_name_prefix + '.Channel.Interface.' + name) - for name in extra])) + interfaces.update({ + name: tp_name_prefix + '.Channel.Interface.' + name + for name in extra}) return ProxyWrapper(chan, tp_name_prefix + '.Channel', interfaces) @@ -493,9 +494,9 @@ def wrap_content(chan, extra=None): interfaces = { } if extra: - interfaces.update(dict([ - (name, tp_name_prefix + '.Call1.Content.Interface.' + name) - for name in extra])) + interfaces.update({ + name: tp_name_prefix + '.Call1.Content.Interface.' + name + for name in extra}) return ProxyWrapper(chan, tp_name_prefix + '.Call1.Content', interfaces) @@ -562,7 +563,7 @@ def watch_tube_signals(q, tube): q.append(Event('tube-signal', path=kwargs['path'], signal=kwargs['member'], - args=map(unwrap, args), + args=list(map(unwrap, args)), tube=tube)) tube.add_signal_receiver(got_signal_cb, @@ -658,7 +659,7 @@ def install_colourer(): class DummyStream(object): def write(self, s): if 'CHECK_TWISTED_VERBOSE' in os.environ: - print s, + print(s, end=' ') def flush(self): pass diff --git a/tools/c-constants-gen.py b/tools/c-constants-gen.py index 8969ffd..1a039f7 100644 --- a/tools/c-constants-gen.py +++ b/tools/c-constants-gen.py @@ -17,7 +17,7 @@ class Generator(object): self.do_footer() def write(self, code): - stdout.write(code.encode('utf-8')) + stdout.write(code) # Header def do_header(self): diff --git a/tools/glib-ginterface-gen.py b/tools/glib-ginterface-gen.py index 13f7f69..7e117f2 100644 --- a/tools/glib-ginterface-gen.py +++ b/tools/glib-ginterface-gen.py @@ -26,7 +26,7 @@ import sys import os.path import xml.dom.minidom -from libglibcodegen import Signature, type_to_gtype, cmp_by_name, \ +from libglibcodegen import Signature, type_to_gtype, key_by_name, \ NS_TP, dbus_gutils_wincaps_to_uscore, \ signal_to_marshal_name, method_to_glue_marshal_name @@ -694,8 +694,7 @@ class Generator(object): return False def __call__(self): - nodes = self.dom.getElementsByTagName('node') - nodes.sort(cmp_by_name) + nodes = sorted(self.dom.getElementsByTagName('node'), key=key_by_name) self.h('#include <glib-object.h>') self.h('#include <dbus/dbus-glib.h>') @@ -730,7 +729,7 @@ class Generator(object): def cmdline_error(): - print """\ + print("""\ usage: gen-ginterface [OPTIONS] xmlfile Prefix_ options: @@ -750,7 +749,7 @@ options: void symbol (DBusGMethodInvocation *context) and return some sort of "not implemented" error via dbus_g_method_return_error (context, ...) -""" +""") sys.exit(1) diff --git a/tools/glib-gtypes-generator.py b/tools/glib-gtypes-generator.py index ebc2ad4..946bf54 100644 --- a/tools/glib-gtypes-generator.py +++ b/tools/glib-gtypes-generator.py @@ -65,10 +65,10 @@ class GTypesGenerator(object): self.need_other_arrays = {} def h(self, code): - self.header.write(code.encode("utf-8")) + self.header.write(code) def c(self, code): - self.body.write(code.encode("utf-8")) + self.body.write(code) def do_mapping_header(self, mapping): members = mapping.getElementsByTagNameNS(NS_TP, 'member') diff --git a/tools/glib-interfaces-gen.py b/tools/glib-interfaces-gen.py index 9543968..19af6df 100644 --- a/tools/glib-interfaces-gen.py +++ b/tools/glib-interfaces-gen.py @@ -14,10 +14,10 @@ class Generator(object): self.spec = get_by_path(dom, "spec")[0] def h(self, code): - self.decls.write(code.encode('utf-8')) + self.decls.write(code) def c(self, code): - self.impls.write(code.encode('utf-8')) + self.impls.write(code) def __call__(self): for f in self.h, self.c: diff --git a/tools/glib-signals-marshal-gen.py b/tools/glib-signals-marshal-gen.py index 0d02c13..896a61b 100644 --- a/tools/glib-signals-marshal-gen.py +++ b/tools/glib-signals-marshal-gen.py @@ -41,12 +41,9 @@ class Generator(object): for signal in signals: self.do_signal(signal) - all = self.marshallers.keys() - all.sort() - for marshaller in all: - rhs = self.marshallers[marshaller] + for marshaller, rhs in sorted(self.marshallers.items()): if not marshaller.startswith('g_cclosure'): - print 'VOID:' + ','.join(rhs) + print('VOID:' + ','.join(rhs)) if __name__ == '__main__': argv = sys.argv[1:] diff --git a/tools/libglibcodegen.py b/tools/libglibcodegen.py index 6a9d214..0f72748 100644 --- a/tools/libglibcodegen.py +++ b/tools/libglibcodegen.py @@ -23,7 +23,7 @@ please make any changes there. from libtpcodegen import NS_TP, \ Signature, \ - cmp_by_name, \ + key_by_name, \ escape_as_identifier, \ get_by_path, \ get_descendant_text, \ @@ -154,7 +154,7 @@ def type_to_gtype(s): return ("GHashTable *", "DBUS_TYPE_G_STRING_STRING_HASHTABLE", "BOXED", False) elif s[:2] == 'a{': #some arbitrary hash tables if s[2] not in ('y', 'b', 'n', 'q', 'i', 'u', 's', 'o', 'g'): - raise Exception, "can't index a hashtable off non-basic type " + s + raise Exception("can't index a hashtable off non-basic type " + s) first = type_to_gtype(s[2]) second = type_to_gtype(s[3:-1]) return ("GHashTable *", "(dbus_g_type_get_map (\"GHashTable\", " + first[1] + ", " + second[1] + "))", "BOXED", False) @@ -169,4 +169,4 @@ def type_to_gtype(s): return ("GValueArray *", gtype, "BOXED", True) # we just don't know .. - raise Exception, "don't know the GType for " + s + raise Exception("don't know the GType for " + s) diff --git a/tools/libtpcodegen.py b/tools/libtpcodegen.py index 837ff2f..93b2f30 100644 --- a/tools/libtpcodegen.py +++ b/tools/libtpcodegen.py @@ -29,9 +29,8 @@ NS_TP = "http://telepathy.freedesktop.org/wiki/DbusSpec#extensions-v0" _ASCII_ALNUM = ascii_letters + digits -def cmp_by_name(node1, node2): - return cmp(node1.getAttributeNode("name").nodeValue, - node2.getAttributeNode("name").nodeValue) +def key_by_name(node): + return node.getAttributeNode("name").nodeValue def escape_as_identifier(identifier): @@ -155,7 +154,7 @@ class _SignatureIter: def __init__(self, string): self.remaining = string - def next(self): + def __next__(self): if self.remaining == '': raise StopIteration @@ -200,6 +199,7 @@ class _SignatureIter: end = end + 1 self.remaining = signature[end:] return Signature(signature[0:end]) + next = __next__ class Signature(str): diff --git a/tools/make-release-mail.py b/tools/make-release-mail.py index 5c42b47..3783cc3 100644 --- a/tools/make-release-mail.py +++ b/tools/make-release-mail.py @@ -19,8 +19,8 @@ def extract_description(package, version, news_path): break # Skip the ====== line, and the first blank line - lines.next() - lines.next() + next(lines) + next(lines) got_release_name = False @@ -50,7 +50,7 @@ GIT_URL = 'http://cgit.freedesktop.org/telepathy' def main(package, version, news_path): release_name, details = extract_description(package, version, news_path) - print """ + print(""" %(release_name)s tarball: %(base_url)s/%(package)s/%(package)s-%(version)s.tar.gz @@ -64,14 +64,14 @@ git: %(git_url)s/%(package)s 'version': version, 'release_name': release_name, 'details': details, - } + }) if __name__ == '__main__': try: package, version, news_path = sys.argv[1:] main(package, version, news_path) - except ValueError, e: + except ValueError as e: sys.stderr.write( 'Usage: %s package-name package.version.number path/to/NEWS\n' % sys.argv[0]) |