Python2 -> Python3

Originally developed by Milan Crha for Fedora, copied from there
by Patrick Ohly.
This commit is contained in:
Milan Crha 2020-08-09 16:14:40 +02:00 committed by Patrick Ohly
parent 3bd97cc795
commit 75dff12823
9 changed files with 349 additions and 348 deletions

View File

@ -1,4 +1,4 @@
#!/usr/bin/python #!/usr/bin/python3
""" """
Converts source code (first parameter, can be - for stdin) to HTML Converts source code (first parameter, can be - for stdin) to HTML
@ -29,8 +29,8 @@ try:
pygments.highlight(code, lexer, formatter, out) pygments.highlight(code, lexer, formatter, out)
except: except:
import cgi import cgi
print >>sys.stderr, "source2html.py failed with pygments:", sys.exc_info() print("source2html.py failed with pygments:", sys.exc_info(), file=sys.stderr)
print >>sys.stderr, "falling back to internal code" print("falling back to internal code", file=sys.stderr)
out.write('''<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd"> out.write('''<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html> <html>

View File

@ -62,6 +62,11 @@ dnl check for programs.
AC_PROG_CXX AC_PROG_CXX
AC_PROG_MAKE_SET AC_PROG_MAKE_SET
AC_PATH_PROGS(PYTHON, python3 python, "")
if test "x$PYTHON" = "x" ; then
AC_ERROR([python3 not found])
fi
dnl Use the most recent C++ standard that is supported by the code. dnl Use the most recent C++ standard that is supported by the code.
dnl We can fall back to older versions, but not below C++11. dnl We can fall back to older versions, but not below C++11.
dnl Akonadi/Qt don't work with C++17 yet, so we can't enable that. dnl Akonadi/Qt don't work with C++17 yet, so we can't enable that.

View File

@ -1,4 +1,4 @@
#! /usr/bin/python -u #!/usr/bin/python3 -u
# -*- coding: utf-8 -*- # -*- coding: utf-8 -*-
# vim: set fileencoding=utf-8 :# # vim: set fileencoding=utf-8 :#
# #
@ -140,21 +140,21 @@ dbus_type_mapping = {
dbus.Double: float, dbus.Double: float,
dbus.Int16: int, dbus.Int16: int,
dbus.Int32: int, dbus.Int32: int,
dbus.Int64: long, dbus.Int64: int,
dbus.ObjectPath: str, dbus.ObjectPath: str,
dbus.Signature: str, dbus.Signature: str,
dbus.String: unicode, dbus.String: str,
dbus.Struct: tuple, dbus.Struct: tuple,
dbus.UInt16: int, dbus.UInt16: int,
dbus.UInt32: int, dbus.UInt32: int,
dbus.UInt64: long, dbus.UInt64: int,
dbus.UTF8String: unicode dbus.UTF8String: str
} }
def strip_dbus(instance): def strip_dbus(instance):
base = dbus_type_mapping.get(type(instance), None) base = dbus_type_mapping.get(type(instance), None)
if base == dict or isinstance(instance, dict): if base == dict or isinstance(instance, dict):
return dict([(strip_dbus(k), strip_dbus(v)) for k, v in instance.iteritems()]) return dict([(strip_dbus(k), strip_dbus(v)) for k, v in instance.items()])
if base == list or isinstance(instance, list): if base == list or isinstance(instance, list):
l = [strip_dbus(v) for v in instance] l = [strip_dbus(v) for v in instance]
l.sort() l.sort()
@ -163,7 +163,7 @@ def strip_dbus(instance):
return tuple([strip_dbus(v) for v in instance]) return tuple([strip_dbus(v) for v in instance])
if base == None: if base == None:
return instance return instance
if base == unicode: if base == str:
# try conversion to normal string # try conversion to normal string
try: try:
return str(instance) return str(instance)
@ -178,7 +178,7 @@ def checkpoint(operation):
global starttime, running global starttime, running
if running: if running:
now = time.time() now = time.time()
print "+%04.3fs %s stopping '%s', duration %fs" % (now - begin, time.ctime(now), running, now - starttime) print("+%04.3fs %s stopping '%s', duration %fs" % (now - begin, time.ctime(now), running, now - starttime))
if options.end_operation: if options.end_operation:
subprocess.check_call(options.end_operation % {'operation': running}, subprocess.check_call(options.end_operation % {'operation': running},
shell=True) shell=True)
@ -188,7 +188,7 @@ def checkpoint(operation):
subprocess.check_call(options.start_operation % {'operation': operation}, subprocess.check_call(options.start_operation % {'operation': operation},
shell=True) shell=True)
now = time.time() now = time.time()
print "+%04.3fs %s starting '%s'" % (now - begin, time.ctime(now), operation) print("+%04.3fs %s starting '%s'" % (now - begin, time.ctime(now), operation))
starttime = now starttime = now
running = operation running = operation
@ -200,7 +200,7 @@ def nothrow(fn):
try: try:
fn(*a, **b) fn(*a, **b)
except: except:
print traceback.format_exc() print(traceback.format_exc())
return wrapper return wrapper
@ -224,7 +224,7 @@ class ContactsView(dbus.service.Object):
def search(self, filter): def search(self, filter):
'''Start a search.''' '''Start a search.'''
print 'searching: %s' % filter print('searching: %s' % filter)
self.viewPath = manager.Search(filter, self.path, self.viewPath = manager.Search(filter, self.path,
timeout=100000) timeout=100000)
# This example uses the ViewControl to read contact data. # This example uses the ViewControl to read contact data.
@ -254,19 +254,19 @@ class ContactsView(dbus.service.Object):
for index, contact in enumerate(self.contacts): for index, contact in enumerate(self.contacts):
if start == index: if start == index:
# empty line with marker where range starts # empty line with marker where range starts
print '=> ' print('=> ')
print '%s %03d %s' % \ print('%s %03d %s' % \
(start != None and index >= start and index < start + count and '*' or ' ', (start != None and index >= start and index < start + count and '*' or ' ',
index, index,
isinstance(contact, dict) and contact.get('full-name', '<<unnamed>>') or '<<reading...>>') isinstance(contact, dict) and contact.get('full-name', '<<unnamed>>') or '<<reading...>>'))
if options.verbosity >= VERBOSITY_DATA_FULL: if options.verbosity >= VERBOSITY_DATA_FULL:
print ' ', strip_dbus(contact) print(' ', strip_dbus(contact))
print print()
@nothrow @nothrow
def ContactsRead(self, ids, contacts): def ContactsRead(self, ids, contacts):
if options.verbosity >= VERBOSITY_DATA_FULL: if options.verbosity >= VERBOSITY_DATA_FULL:
print 'got contact data %s => %s ' % (ids, strip_dbus(contacts)) print('got contact data %s => %s ' % (ids, strip_dbus(contacts)))
min = len(contacts) min = len(contacts)
max = -1 max = -1
for index, contact in contacts: for index, contact in contacts:
@ -283,17 +283,17 @@ class ContactsView(dbus.service.Object):
@nothrow @nothrow
def ReadFailed(self, ids, error): def ReadFailed(self, ids, error):
print 'request for contact data %s failed: %s' % \ print('request for contact data %s failed: %s' % \
(ids, error) (ids, error))
@nothrow @nothrow
@dbus.service.method(dbus_interface='org._01.pim.contacts.ViewAgent', @dbus.service.method(dbus_interface='org._01.pim.contacts.ViewAgent',
in_signature='oias', out_signature='') in_signature='oias', out_signature='')
def ContactsModified(self, view, start, ids): def ContactsModified(self, view, start, ids):
if options.verbosity >= VERBOSITY_NOTIFICATIONS: if options.verbosity >= VERBOSITY_NOTIFICATIONS:
print 'contacts modified: %s, start %d, count %d, ids %s' % \ print('contacts modified: %s, start %d, count %d, ids %s' % \
(view, start, len(ids), (view, start, len(ids),
options.verbosity >= VERBOSITY_DATA_SUMMARY and strip_dbus(ids) or '<...>') options.verbosity >= VERBOSITY_DATA_SUMMARY and strip_dbus(ids) or '<...>'))
self.contacts[start:start + len(ids)] = ids self.contacts[start:start + len(ids)] = ids
self.dump(start, len(ids)) self.dump(start, len(ids))
if not options.read_all: if not options.read_all:
@ -304,9 +304,9 @@ class ContactsView(dbus.service.Object):
in_signature='oias', out_signature='') in_signature='oias', out_signature='')
def ContactsAdded(self, view, start, ids): def ContactsAdded(self, view, start, ids):
if options.verbosity >= VERBOSITY_NOTIFICATIONS: if options.verbosity >= VERBOSITY_NOTIFICATIONS:
print 'contacts added: %s, start %d, count %d, ids %s' % \ print('contacts added: %s, start %d, count %d, ids %s' % \
(view, start, len(ids), (view, start, len(ids),
options.verbosity >= VERBOSITY_DATA_SUMMARY and strip_dbus(ids) or '<...>') options.verbosity >= VERBOSITY_DATA_SUMMARY and strip_dbus(ids) or '<...>'))
self.contacts[start:start] = ids self.contacts[start:start] = ids
self.dump(start, len(ids)) self.dump(start, len(ids))
if not options.read_all: if not options.read_all:
@ -317,9 +317,9 @@ class ContactsView(dbus.service.Object):
in_signature='oii', out_signature='') in_signature='oii', out_signature='')
def ContactsRemoved(self, view, start, count): def ContactsRemoved(self, view, start, count):
if options.verbosity >= VERBOSITY_NOTIFICATIONS: if options.verbosity >= VERBOSITY_NOTIFICATIONS:
print 'contacts removed: %s, start %d, count %d, ids %s' % \ print('contacts removed: %s, start %d, count %d, ids %s' % \
(view, start, len(ids), (view, start, len(ids),
options.verbosity >= VERBOSITY_DATA_SUMMARY and strip_dbus(ids) or '<...>') options.verbosity >= VERBOSITY_DATA_SUMMARY and strip_dbus(ids) or '<...>'))
# Remove obsolete entries. # Remove obsolete entries.
del self.contacts[start:start + len(ids)] del self.contacts[start:start + len(ids)]
self.dump(start, 0) self.dump(start, 0)
@ -329,7 +329,7 @@ class ContactsView(dbus.service.Object):
in_signature='o', out_signature='') in_signature='o', out_signature='')
def Quiescent(self, view): def Quiescent(self, view):
if options.verbosity >= VERBOSITY_NOTIFICATIONS: if options.verbosity >= VERBOSITY_NOTIFICATIONS:
print 'view is stable' print('view is stable')
if options.read_all: if options.read_all:
# Avoid reading in parallel, if quiescence signal repeats. # Avoid reading in parallel, if quiescence signal repeats.
if running != 'read': if running != 'read':
@ -340,26 +340,26 @@ class ContactsView(dbus.service.Object):
checkpoint('getallpeers') checkpoint('getallpeers')
peers = strip_dbus(manager.GetAllPeers()) peers = strip_dbus(manager.GetAllPeers())
print 'peers: %s' % peers print('peers: %s' % peers)
print 'available databases: %s' % ([''] + ['peer-' + uid for uid in peers.keys()]) print('available databases: %s' % ([''] + ['peer-' + uid for uid in list(peers.keys())]))
checkpoint('getactiveaddressbooks') checkpoint('getactiveaddressbooks')
address_books = strip_dbus(manager.GetActiveAddressBooks()) address_books = strip_dbus(manager.GetActiveAddressBooks())
if options.address_books: if options.address_books:
print 'active address books %s -> %s' % (address_books, options.address_books) print('active address books %s -> %s' % (address_books, options.address_books))
checkpoint('setactiveaddressbooks') checkpoint('setactiveaddressbooks')
manager.SetActiveAddressBooks(options.address_books) manager.SetActiveAddressBooks(options.address_books)
else: else:
print 'active address books: %s' % options.address_books print('active address books: %s' % options.address_books)
checkpoint('getsortorder') checkpoint('getsortorder')
order = strip_dbus(manager.GetSortOrder()) order = strip_dbus(manager.GetSortOrder())
if options.order: if options.order:
print 'active sort order %s -> %s' % (order, options.order) print('active sort order %s -> %s' % (order, options.order))
checkpoint('setsortorder') checkpoint('setsortorder')
manager.SetSortOrder(options.order) manager.SetSortOrder(options.order)
else: else:
print 'active sort order: %s' % order print('active sort order: %s' % order)
if options.search != None: if options.search != None:
checkpoint('search') checkpoint('search')
@ -367,6 +367,6 @@ if options.search != None:
view.search(eval(options.search)) view.search(eval(options.search))
loop.run() loop.run()
else: else:
print 'no search expression given, quitting' print('no search expression given, quitting')
checkpoint(None) checkpoint(None)

View File

@ -1,4 +1,4 @@
#! /usr/bin/python -u #!/usr/bin/python3 -u
# -*- coding: utf-8 -*- # -*- coding: utf-8 -*-
# vim: set fileencoding=utf-8 :# # vim: set fileencoding=utf-8 :#
# #
@ -112,7 +112,7 @@ manager = dbus.Interface(bus.get_object('org._01.pim.contacts',
# Capture and print debug output. # Capture and print debug output.
def log_output(path, level, output, component): def log_output(path, level, output, component):
print '%s %s: %s' % (level, (component or 'sync'), output) print('%s %s: %s' % (level, (component or 'sync'), output))
# Format seconds as mm:ss[.mmm]. # Format seconds as mm:ss[.mmm].
def format_seconds(seconds, with_milli): def format_seconds(seconds, with_milli):
@ -137,9 +137,9 @@ def log_progress(uid, event, data):
bar = int(percent * BAR_LENGTH) * '-' bar = int(percent * BAR_LENGTH) * '-'
if len(bar) > 0 and len(bar) < BAR_LENGTH: if len(bar) > 0 and len(bar) < BAR_LENGTH:
bar = bar[0:-1] + '>' bar = bar[0:-1] + '>'
print prefix, '|%s%s| %.1f%% %s' % (bar, (BAR_LENGTH - len(bar)) * ' ', percent * 100, strip_dbus(data)) print(prefix, '|%s%s| %.1f%% %s' % (bar, (BAR_LENGTH - len(bar)) * ' ', percent * 100, strip_dbus(data)))
else: else:
print prefix, '%s = %s' % (event, strip_dbus(data)) print(prefix, '%s = %s' % (event, strip_dbus(data)))
last = now last = now
if options.debug: if options.debug:
@ -167,21 +167,21 @@ dbus_type_mapping = {
dbus.Double: float, dbus.Double: float,
dbus.Int16: int, dbus.Int16: int,
dbus.Int32: int, dbus.Int32: int,
dbus.Int64: long, dbus.Int64: int,
dbus.ObjectPath: str, dbus.ObjectPath: str,
dbus.Signature: str, dbus.Signature: str,
dbus.String: unicode, dbus.String: str,
dbus.Struct: tuple, dbus.Struct: tuple,
dbus.UInt16: int, dbus.UInt16: int,
dbus.UInt32: int, dbus.UInt32: int,
dbus.UInt64: long, dbus.UInt64: int,
dbus.UTF8String: unicode dbus.UTF8String: str
} }
def strip_dbus(instance): def strip_dbus(instance):
base = dbus_type_mapping.get(type(instance), None) base = dbus_type_mapping.get(type(instance), None)
if base == dict or isinstance(instance, dict): if base == dict or isinstance(instance, dict):
return dict([(strip_dbus(k), strip_dbus(v)) for k, v in instance.iteritems()]) return dict([(strip_dbus(k), strip_dbus(v)) for k, v in instance.items()])
if base == list or isinstance(instance, list): if base == list or isinstance(instance, list):
l = [strip_dbus(v) for v in instance] l = [strip_dbus(v) for v in instance]
l.sort() l.sort()
@ -190,7 +190,7 @@ def strip_dbus(instance):
return tuple([strip_dbus(v) for v in instance]) return tuple([strip_dbus(v) for v in instance])
if base == None: if base == None:
return instance return instance
if base == unicode: if base == str:
# try conversion to normal string # try conversion to normal string
try: try:
return str(instance) return str(instance)
@ -217,13 +217,13 @@ def run(syncing=False):
global result global result
result = None result = None
if syncing: if syncing:
print 'Running a sync, press CTRL-C to control it interactively.' print('Running a sync, press CTRL-C to control it interactively.')
while result is None and error is None: while result is None and error is None:
try: try:
loop.run() loop.run()
except KeyboardInterrupt: except KeyboardInterrupt:
while True: while True:
print '[a]bort, [s]uspend, [r]esume, continue? ', print('[a]bort, [s]uspend, [r]esume, continue? ', end=' ')
response = sys.stdin.readline() response = sys.stdin.readline()
try: try:
if response == 'a\n': if response == 'a\n':
@ -238,16 +238,16 @@ def run(syncing=False):
elif response == '\n': elif response == '\n':
break break
else: else:
print 'Unknown response, try again.' print('Unknown response, try again.')
except dbus.exceptions.DBusException, ex: except dbus.exceptions.DBusException as ex:
print 'operation %s failed: %s' % (response, ex) print('operation %s failed: %s' % (response, ex))
else: else:
loop.run() loop.run()
if error: if error:
print print()
print error print(error)
print print()
return result return result
async_args = { async_args = {
'reply_handler': done, 'reply_handler': done,
@ -257,8 +257,8 @@ async_args = {
manager.GetAllPeers(**async_args) manager.GetAllPeers(**async_args)
peers = strip_dbus(run()) peers = strip_dbus(run())
print 'peers: %s' % peers print('peers: %s' % peers)
print 'available databases: %s' % ([''] + ['peer-' + uid for uid in peers.keys()]) print('available databases: %s' % ([''] + ['peer-' + uid for uid in list(peers.keys())]))
if not error and options.configure: if not error and options.configure:
peer = json.loads(options.peer_config) peer = json.loads(options.peer_config)
@ -267,13 +267,13 @@ if not error and options.configure:
peer['protocol'] = 'PBAP' peer['protocol'] = 'PBAP'
if not 'address' in peer: if not 'address' in peer:
peer['address'] = options.mac peer['address'] = options.mac
print 'adding peer config %s = %s' % (peername, peer) print('adding peer config %s = %s' % (peername, peer))
manager.SetPeer(peername, peer, **async_args) manager.SetPeer(peername, peer, **async_args)
run() run()
def pull_progress(): def pull_progress():
status = manager.GetPeerStatus(peername) status = manager.GetPeerStatus(peername)
print 'Poll status:', strip_dbus(status) print('Poll status:', strip_dbus(status))
return True return True
if not error and options.sync: if not error and options.sync:
@ -281,7 +281,7 @@ if not error and options.sync:
if options.poll_progress is not None: if options.poll_progress is not None:
pull_progress() pull_progress()
print 'syncing peer %s' % peername print('syncing peer %s' % peername)
flags = json.loads(options.sync_flags) flags = json.loads(options.sync_flags)
if options.progress_frequency != 0.0: if options.progress_frequency != 0.0:
flags['progress-frequency'] = options.progress_frequency flags['progress-frequency'] = options.progress_frequency
@ -307,10 +307,10 @@ if not error and options.sync:
timeout.destroy() timeout.destroy()
if not error and options.remove: if not error and options.remove:
print 'removing peer %s' % peername print('removing peer %s' % peername)
manager.RemovePeer(peername, **async_args) manager.RemovePeer(peername, **async_args)
run() run()
if options.debug: if options.debug:
print "waiting for further debug output, press CTRL-C to stop" print("waiting for further debug output, press CTRL-C to stop")
loop.run() loop.run()

File diff suppressed because it is too large Load Diff

View File

@ -42,12 +42,12 @@ if COND_DBUS
nodist_bin_SCRIPTS += src/syncevo-http-server nodist_bin_SCRIPTS += src/syncevo-http-server
endif endif
src/syncevo-http-server: $(top_srcdir)/test/syncevo-http-server.py src/syncevo-http-server: $(top_srcdir)/test/syncevo-http-server.py
$(AM_V_GEN)cp $< $@ $(AM_V_GEN)sed -e 's|\@PYTHON\@|$(PYTHON)|' $< > $@
CLEANFILES += src/syncevo-http-server CLEANFILES += src/syncevo-http-server
nodist_bin_SCRIPTS += src/syncevo-phone-config nodist_bin_SCRIPTS += src/syncevo-phone-config
src/syncevo-phone-config: $(top_srcdir)/test/syncevo-phone-config.py src/syncevo-phone-config: $(top_srcdir)/test/syncevo-phone-config.py
$(AM_V_GEN)cp $< $@ $(AM_V_GEN)sed -e 's|\@PYTHON\@|$(PYTHON)|' $< > $@
CLEANFILES += src/syncevo-phone-config CLEANFILES += src/syncevo-phone-config
SYNCEVOLUTION_DEP = SYNCEVOLUTION_DEP =
@ -72,7 +72,7 @@ src/synccompare : $(top_srcdir)/test/Algorithm/Diff.pm $(top_srcdir)/test/syncco
bin_SCRIPTS += src/synclog2html bin_SCRIPTS += src/synclog2html
CLEANFILES += src/synclog2html CLEANFILES += src/synclog2html
src/synclog2html: $(top_srcdir)/test/log2html.py src/synclog2html: $(top_srcdir)/test/log2html.py
$(AM_V_GEN)cp $< $@ && chmod u+x $@ $(AM_V_GEN)sed -e 's|\@PYTHON\@|$(PYTHON)|' $< > $@ && chmod u+x $@
CORE_SOURCES = CORE_SOURCES =
@ -367,7 +367,7 @@ testcase2patch: $(TEST_FILES_GENERATED)
nodist_noinst_DATA += src/ClientTest.cpp.html nodist_noinst_DATA += src/ClientTest.cpp.html
CLEANFILES += src/ClientTest.cpp.html CLEANFILES += src/ClientTest.cpp.html
src/ClientTest.cpp.html: build/source2html.py test/ClientTest.cpp src/ClientTest.cpp.html: build/source2html.py test/ClientTest.cpp
$(AM_V_GEN)python $+ >$@ $(AM_V_GEN)$(PYTHON) $+ >$@
# copy base test files # copy base test files
$(filter-out %.tem, $(filter src/testcases/%, $(subst $(top_srcdir)/test/,src/,$(CLIENT_LIB_TEST_FILES)))) : src/% : $(top_srcdir)/test/% $(filter-out %.tem, $(filter src/testcases/%, $(subst $(top_srcdir)/test/,src/,$(CLIENT_LIB_TEST_FILES)))) : src/% : $(top_srcdir)/test/%

View File

@ -1,4 +1,4 @@
#!/usr/bin/python #!@PYTHON@
""" """
Converts the .log output for a client-test test into HTML, with Converts the .log output for a client-test test into HTML, with

View File

@ -1,4 +1,4 @@
#! /usr/bin/python #!@PYTHON@
'''Usage: syncevo-http-server.py <URL> '''Usage: syncevo-http-server.py <URL>
Runs a SyncML HTTP server under the given base URL.''' Runs a SyncML HTTP server under the given base URL.'''
@ -10,9 +10,8 @@ DBusGMainLoop(set_as_default=True)
glib2reactor.install() glib2reactor.install()
import dbus import dbus
import gobject
import sys import sys
import urlparse import urllib.parse
import optparse import optparse
import os import os
import atexit import atexit
@ -132,13 +131,13 @@ class SyncMLSession:
then remove the session''' then remove the session'''
logger.debug("destructing connection %s with code %s message %s", self.conpath, code, message) logger.debug("destructing connection %s with code %s message %s", self.conpath, code, message)
if self.request: if self.request:
self.request.setResponseCode(code, message) self.request.setResponseCode(code, message.encode())
self.request.finish() self.request.finish()
self.request = None self.request = None
if self.connection: if self.connection:
try: try:
self.connection.Close(False, message, timeout=timeout) self.connection.Close(False, message, timeout=timeout)
except dbus.exceptions.DBusException, ex: except dbus.exceptions.DBusException as ex:
if ex.get_dbus_name() == "org.freedesktop.DBus.Error.UnknownMethod": if ex.get_dbus_name() == "org.freedesktop.DBus.Error.UnknownMethod":
# triggered if connection instance is already gone, hide from user # triggered if connection instance is already gone, hide from user
logger.debug("self.connection.Close() failed, connection probably already gone: %s", ex) logger.debug("self.connection.Close() failed, connection probably already gone: %s", ex)
@ -180,7 +179,7 @@ class SyncMLSession:
OldRequest.type = type OldRequest.type = type
if request: if request:
request.setHeader('Content-Type', type) request.setHeader('Content-Type', type)
request.setHeader('Content-Length', len(data)) request.setHeader('Content-Length', str(len(data)))
request.setResponseCode(http.OK) request.setResponseCode(http.OK)
request.write(data) request.write(data)
request.finish() request.finish()
@ -244,7 +243,6 @@ class SyncMLSession:
'org.syncevolution', 'org.syncevolution',
self.conpath, self.conpath,
path_keyword='conpath', path_keyword='conpath',
utf8_strings=True,
byte_arrays=True) byte_arrays=True)
self.reply_match = \ self.reply_match = \
Context.bus.add_signal_receiver(self.reply, Context.bus.add_signal_receiver(self.reply,
@ -253,7 +251,6 @@ class SyncMLSession:
'org.syncevolution', 'org.syncevolution',
self.conpath, self.conpath,
path_keyword='conpath', path_keyword='conpath',
utf8_strings=True,
byte_arrays=True) byte_arrays=True)
# feed new data into SyncEvolution and wait for reply # feed new data into SyncEvolution and wait for reply
@ -320,16 +317,16 @@ class SyncMLPost(resource.Resource):
config = "" config = ""
type = request.getHeader('content-type') type = request.getHeader('content-type')
len = request.getHeader('content-length') len = request.getHeader('content-length')
sessionid = request.args.get('sessionid') sessionid = request.args.get(b'sessionid')
if sessionid: if sessionid:
sessionid = sessionid[0] sessionid = sessionid[0].decode()
logger.debug("POST from %s config %s type %s session %s args %s length %s", logger.debug("POST from %s config %s type %s session %s args %s length %s",
request.getClientIP(), config, type, sessionid, request.args, len) request.getClientIP(), config, type, sessionid, request.args, len)
if not sessionid: if not sessionid:
logger.info("new SyncML session for %s", request.getClientIP()) logger.info("new SyncML session for %s", request.getClientIP())
session = SyncMLSession() session = SyncMLSession()
session.start(request, config, session.start(request, config,
urlparse.urljoin(self.url.geturl(), request.path)) urllib.parse.urljoin(self.url.geturl(), request.path.decode()))
return server.NOT_DONE_YET return server.NOT_DONE_YET
else: else:
data = request.content.read() data = request.content.read()
@ -536,7 +533,7 @@ syncevo-http-server itself is installed""")
# use this X11 session to find D-Bus session bus # use this X11 session to find D-Bus session bus
os.environ["DISPLAY"] = dpy os.environ["DISPLAY"] = dpy
havedbus = True havedbus = True
except dbus.exceptions.DBusException, ex: except dbus.exceptions.DBusException as ex:
if ex.get_dbus_name() == "org.freedesktop.DBus.Error.ServiceUnknown": if ex.get_dbus_name() == "org.freedesktop.DBus.Error.ServiceUnknown":
logger.debug("org.freedesktop.ConsoleKit service not available") logger.debug("org.freedesktop.ConsoleKit service not available")
else: else:
@ -586,9 +583,9 @@ syncevo-http-server itself is installed""")
logger.error("need exactly on URL as command line parameter") logger.error("need exactly on URL as command line parameter")
exit(1) exit(1)
url = urlparse.urlparse(args[0]) url = urllib.parse.urlparse(args[0])
root = resource.Resource() root = resource.Resource()
root.putChild(url.path[1:], SyncMLPost(url)) root.putChild(url.path[1:].encode(), SyncMLPost(url))
site = server.Site(root) site = server.Site(root)
if url.scheme == "https": if url.scheme == "https":
if not options.cert: if not options.cert:

View File

@ -1,4 +1,4 @@
#!/usr/bin/python #!@PYTHON@
# #
# Copyright (C) 2010 Intel Corporation # Copyright (C) 2010 Intel Corporation
# #
@ -23,7 +23,7 @@ SyncEvolution.
''' '''
import sys, optparse, os, time, tempfile import sys, optparse, os, time, tempfile
import shutil import shutil
import ConfigParser import configparser
import glob import glob
import os.path import os.path
@ -94,13 +94,13 @@ class ConfigurationParameter:
self.identifier = identifier self.identifier = identifier
def printMe(self): def printMe(self):
print "Test parameter: " print("Test parameter: ")
print "With CTCap: %s" %(self.ctcap,) print("With CTCap: %s" %(self.ctcap,))
print "Identifier: %s" %(self.identifier,) print("Identifier: %s" %(self.identifier,))
print "SyncML version: %s" %(self.version,) print("SyncML version: %s" %(self.version,))
print "Sync Source: %s" %(self.source,) print("Sync Source: %s" %(self.source,))
print "URI: %s" %(self.uri,) print("URI: %s" %(self.uri,))
print "Content Type: %s" %(self.type,) print("Content Type: %s" %(self.type,))
def __str__(self): def __str__(self):
res = [] res = []
@ -249,10 +249,10 @@ def compareSyncData(sources, type):
except: except:
return False return False
if (options.verbose > 1): if (options.verbose > 1):
print "comparing received file:" print("comparing received file:")
print received print(received)
print "with built in keywords in test case:" print("with built in keywords in test case:")
print keys print(keys)
for key in keys: for key in keys:
if (received.find(key) <0): if (received.find(key) <0):
return False return False
@ -262,7 +262,7 @@ def compareSyncData(sources, type):
def runCommand(cmd, exception = True): def runCommand(cmd, exception = True):
"""Log and run the given command, throwing an exception if it fails.""" """Log and run the given command, throwing an exception if it fails."""
if (options.verbose > 1): if (options.verbose > 1):
print "%s: %s" % (os.getcwd(), cmd) print("%s: %s" % (os.getcwd(), cmd))
else: else:
cmd += ' >/dev/null' cmd += ' >/dev/null'
sys.stdout.flush() sys.stdout.flush()
@ -298,7 +298,7 @@ def runSync(sync):
else: else:
return self.fp.readline() return self.fp.readline()
ini = ConfigParser.ConfigParser({"status": "0", "error": ""}) ini = configparser.ConfigParser({"status": "0", "error": ""})
ini.readfp(IniFile(resultFile)) ini.readfp(IniFile(resultFile))
statuscode = ini.get("main", "status") statuscode = ini.get("main", "status")
if statuscode == "20015": if statuscode == "20015":
@ -307,7 +307,7 @@ def runSync(sync):
interrupt = True interrupt = True
if statuscode == "22002": if statuscode == "22002":
# syncevolution failed (for example, kill -9), warn and abort # syncevolution failed (for example, kill -9), warn and abort
print "\nSyncEvolution binary died prematurely, aborting testing." print("\nSyncEvolution binary died prematurely, aborting testing.")
status = False status = False
interrupt = True interrupt = True
return (status, interrupt) return (status, interrupt)
@ -320,7 +320,7 @@ def rm_r(dirname):
def hash2ini(hash): def hash2ini(hash):
"""convert key/value pairs into .ini file without sections""" """convert key/value pairs into .ini file without sections"""
res = [] res = []
for key, value in hash.items(): for key, value in list(hash.items()):
res.append("%s = %s" % (key, value)) res.append("%s = %s" % (key, value))
return "\n".join(res) return "\n".join(res)
@ -399,29 +399,29 @@ class TestingConfiguration():
# 3) we already found a working configuration for combined calendar and # 3) we already found a working configuration for combined calendar and
# task, thus seperate testing for calendar and task is not needed. # task, thus seperate testing for calendar and task is not needed.
skip = False skip = False
for source, config in self.wConfigs.items(): for source, config in list(self.wConfigs.items()):
if (config): if (config):
if ( (config.source == self.source) or (config.identifier != self.identifier ) or (config.ctcap != self.ctcap) or (config.version != self.version)): if ( (config.source == self.source) or (config.identifier != self.identifier ) or (config.ctcap != self.ctcap) or (config.version != self.version)):
skip = True skip = True
if (skip): if (skip):
if (options.verbose > 1): if (options.verbose > 1):
print "Test %d/%d skipped because already found a working configuration" % (curconfig, allconfigs) print("Test %d/%d skipped because already found a working configuration" % (curconfig, allconfigs))
elif options.verbose > 0: elif options.verbose > 0:
print "Test %d/%d skipped" %(curconfig, allconfigs), \ print("Test %d/%d skipped" %(curconfig, allconfigs), \
ConfigurationParameter(self.version, self.source, self.uri, self.type, self.ctcap, self.identifier) ConfigurationParameter(self.version, self.source, self.uri, self.type, self.ctcap, self.identifier))
else: else:
print "Test %d/%d skipped" %(curconfig, allconfigs) print("Test %d/%d skipped" %(curconfig, allconfigs))
else: else:
print ("Start %d/%d test" % (curconfig, allconfigs)), print(("Start %d/%d test" % (curconfig, allconfigs)), end=' ')
if (options.verbose > 0): if (options.verbose > 0):
config = ConfigurationParameter(self.version, self.source, self.uri, self.type, self.ctcap, self.identifier) config = ConfigurationParameter(self.version, self.source, self.uri, self.type, self.ctcap, self.identifier)
if (options.verbose > 1): if (options.verbose > 1):
print print()
config.printMe() config.printMe()
else: else:
print config print(config)
else: else:
print print()
return skip return skip
@ -526,7 +526,7 @@ class TestingConfiguration():
for self.uri in self.uris[self.source]: for self.uri in self.uris[self.source]:
for self.type in self.types[self.source]: for self.type in self.types[self.source]:
allconfigs +=1 allconfigs +=1
print "Starting test for %d configurations..." %(allconfigs,) print("Starting test for %d configurations..." %(allconfigs,))
curconfig = 0 curconfig = 0
self.wConfigs = {} self.wConfigs = {}
@ -557,33 +557,33 @@ class TestingConfiguration():
(status, interrupt) = self.testWithCurrentConfiguration () (status, interrupt) = self.testWithCurrentConfiguration ()
if (status and not interrupt): if (status and not interrupt):
self.wConfigs[self.source] = ConfigurationParameter (self.version, self.source, self.uri, self.type, self.ctcap, self.identifier) self.wConfigs[self.source] = ConfigurationParameter (self.version, self.source, self.uri, self.type, self.ctcap, self.identifier)
print "Found a working configuration for %s" % (self.source,) print("Found a working configuration for %s" % (self.source,))
if (options.verbose > 0): if (options.verbose > 0):
self.wConfigs[self.source].printMe() self.wConfigs[self.source].printMe()
if (interrupt): if (interrupt):
break; break;
if(interrupt): if(interrupt):
print "Test Interrupted" print("Test Interrupted")
return 1 return 1
print "Test Ended" print("Test Ended")
#Test finished, print summary and generating configurations #Test finished, print summary and generating configurations
print "****************SUMMARY****************" print("****************SUMMARY****************")
found = False found = False
for source,config in self.wConfigs.items(): for source,config in list(self.wConfigs.items()):
if (config): if (config):
found = True found = True
print "------------------------------------------" print("------------------------------------------")
print "Configuration parameter for %s:" % (source,) print("Configuration parameter for %s:" % (source,))
config.printMe() config.printMe()
if (not found): if (not found):
print "No working configuration found" print("No working configuration found")
else: else:
have_combined = \ have_combined = \
self.wConfigs.has_key('calendar') and \ 'calendar' in self.wConfigs and \
self.wConfigs.has_key('todo') and \ 'todo' in self.wConfigs and \
self.wConfigs['calendar'] and \ self.wConfigs['calendar'] and \
self.wConfigs['todo'] and \ self.wConfigs['todo'] and \
self.wConfigs['calendar'].uri == self.wConfigs['todo'].uri self.wConfigs['calendar'].uri == self.wConfigs['todo'].uri
@ -606,7 +606,7 @@ class TestingConfiguration():
runCommand(cmd) runCommand(cmd)
syncCreated = False syncCreated = False
for source,config in self.wConfigs.items(): for source,config in list(self.wConfigs.items()):
if (config): if (config):
if (not syncCreated): if (not syncCreated):
#set the sync parameter #set the sync parameter
@ -628,17 +628,17 @@ class TestingConfiguration():
if (options.advanced): if (options.advanced):
print "" print("")
print "We have conducted basic test by sending and receiving" print("We have conducted basic test by sending and receiving")
print "data to the phone. You can help the SyncEvolution project" print("data to the phone. You can help the SyncEvolution project")
print "and other users by submitting the following configuration" print("and other users by submitting the following configuration")
print "template at http://syncevolution.org/wiki/phone-compatibility-template" print("template at http://syncevolution.org/wiki/phone-compatibility-template")
print "" print("")
configini = { "peerIsClient": "1" } configini = { "peerIsClient": "1" }
sourceConfigInis = {} sourceConfigInis = {}
for source,config in self.wConfigs.items(): for source,config in list(self.wConfigs.items()):
if(config): if(config):
sourceini = {} sourceini = {}
if (config.identifier): if (config.identifier):
@ -667,27 +667,27 @@ class TestingConfiguration():
# print template to stdout # print template to stdout
sep = "--------------------> snip <--------------------" sep = "--------------------> snip <--------------------"
print sep print(sep)
print "=== template.ini ===" print("=== template.ini ===")
print "fingerprint = <Model> <Manufacturer>" print("fingerprint = <Model> <Manufacturer>")
print "=== config.ini ===" print("=== config.ini ===")
print hash2ini(configini) print(hash2ini(configini))
print "consumerReady = 1" print("consumerReady = 1")
for source, configini in sourceConfigInis.items(): for source, configini in list(sourceConfigInis.items()):
print "=== sources/%s/config.ini ===" % source print("=== sources/%s/config.ini ===" % source)
print hash2ini(configini) print(hash2ini(configini))
print sep print(sep)
else: else:
print "" print("")
print "We just conducted minimum test by syncing with the phone" print("We just conducted minimum test by syncing with the phone")
print "without checking received data. For more reliable result," print("without checking received data. For more reliable result,")
print "use the --advanced option, but beware that it will overwrite" print("use the --advanced option, but beware that it will overwrite")
print "contacts, events, tasks and memos on the phone." print("contacts, events, tasks and memos on the phone.")
if (options.create): if (options.create):
print "" print("")
print "Created configuration: %s" %(options.create) print("Created configuration: %s" %(options.create))
print "You may start syncing with: syncevolution %s" %(options.create) print("You may start syncing with: syncevolution %s" %(options.create))
def main(): def main():
versions = [] versions = []
@ -721,7 +721,7 @@ def main():
testFolder = tmpdir+'/data' testFolder = tmpdir+'/data'
testResult = tmpdir+'/cache' testResult = tmpdir+'/cache'
testConfig = tmpdir+'/config' testConfig = tmpdir+'/config'
print "Running test with test data inside %s and test results inside %s" %(testFolder, testResult) print("Running test with test data inside %s and test results inside %s" %(testFolder, testResult))
config.run() config.run()
if __name__ == "__main__": if __name__ == "__main__":