summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorSylvain <syt@logilab.fr>2009-03-04 11:54:23 +0100
committerSylvain <syt@logilab.fr>2009-03-04 11:54:23 +0100
commitb2a6afa68ec49734659ceeb7961218cf5f17b204 (patch)
treef810b5d258b2ee0defd451c26f2ef73ea9465dae
parent1f235a7313bba3369d109bc1eb9996a6963ef134 (diff)
downloadlogilab-common-b2a6afa68ec49734659ceeb7961218cf5f17b204.tar.gz
toward py3k
passing tests: unittest_shellutils, unittest_textutils, unittest_modutils, unittest_table, unittest_tree
-rw-r--r--adbh.py2
-rw-r--r--bind.py10
-rw-r--r--changelog.py2
-rw-r--r--cli.py4
-rw-r--r--compat.py6
-rw-r--r--configuration.py2
-rw-r--r--date.py2
-rw-r--r--debian/changelog2
-rw-r--r--debugger.py10
-rw-r--r--decorators.py15
-rw-r--r--deprecation.py2
-rw-r--r--fileutils.py54
-rw-r--r--logging_ext.py2
-rw-r--r--modutils.py46
-rw-r--r--shellutils.py44
-rw-r--r--table.py44
-rw-r--r--tasksqueue.py4
-rw-r--r--test/unittest_bind.py18
-rw-r--r--test/unittest_compat.py12
-rw-r--r--test/unittest_modutils.py8
-rw-r--r--test/unittest_shellutils.py15
-rw-r--r--test/unittest_table.py11
-rw-r--r--test/unittest_testlib.py18
-rw-r--r--test/unittest_textutils.py8
-rw-r--r--testlib.py155
-rw-r--r--textutils.py38
26 files changed, 230 insertions, 304 deletions
diff --git a/adbh.py b/adbh.py
index 5e25ebc..6e65c08 100644
--- a/adbh.py
+++ b/adbh.py
@@ -144,7 +144,7 @@ class _GenericAdvFuncHelper:
#@classmethod
def register_function(cls, funcdef):
- if isinstance(funcdef, basestring) :
+ if isinstance(funcdef, str) :
funcdef = FunctionDescr(funcdef.upper())
assert not funcdef.name in cls.FUNCTIONS, \
'%s is already registered' % funcdef.name
diff --git a/bind.py b/bind.py
index 275ab8b..2ec9900 100644
--- a/bind.py
+++ b/bind.py
@@ -78,9 +78,9 @@ def bind_code(co, globals):
def bind(f, globals):
"""Returns a new function whose code object has been
bound by bind_code()"""
- newcode = bind_code(f.func_code, globals)
+ newcode = bind_code(f.__code__, globals)
defaults = f.func_defaults or ()
- return make_function(newcode, f.func_globals, f.func_name, defaults)
+ return make_function(newcode, f.func_globals, f.__name__, defaults)
if type(__builtins__) == dict:
builtins = __builtins__
@@ -221,12 +221,12 @@ def optimize_module_2(m, globals_consts, bind_builtins=1):
for name, f in m.__dict__.items():
if inspect.isfunction(f):
functions[name] = f
- analyze_code(f.func_code, globals, consts_dict, consts_list)
+ analyze_code(f.__code__, globals, consts_dict, consts_list)
consts_list = tuple(consts_list)
for name, f in functions.items():
- newcode = rewrite_code(f.func_code, consts_dict, consts_list)
+ newcode = rewrite_code(f.__code__, consts_dict, consts_list)
defaults = f.func_defaults or ()
- m.__dict__[name] = make_function(newcode, f.func_globals, f.func_name,
+ m.__dict__[name] = make_function(newcode, f.func_globals, f.__name__,
defaults)
diff --git a/changelog.py b/changelog.py
index 45c4090..1175fa1 100644
--- a/changelog.py
+++ b/changelog.py
@@ -50,7 +50,7 @@ class Version(tuple):
correctly printing it as X.Y.Z
"""
def __new__(klass, versionstr):
- if isinstance(versionstr, basestring):
+ if isinstance(versionstr, str):
versionstr = versionstr.strip(' :')
try:
parsed = [int(i) for i in versionstr.split('.')]
diff --git a/cli.py b/cli.py
index 977ceca..6e1a726 100644
--- a/cli.py
+++ b/cli.py
@@ -173,7 +173,7 @@ class CLIHelper:
print
for command_help_method in self._topics[command]:
try:
- if callable(command_help_method):
+ if hasattr(command_help_method, '__call__'):
self._print_help(*command_help_method())
else:
self._print_help(*command_help_method)
@@ -181,7 +181,7 @@ class CLIHelper:
import traceback
traceback.print_exc()
print 'ERROR in help method %s'% (
- command_help_method.func_name)
+ command_help_method.__name__)
help_do_help = ("help", "help [topic|command]",
_("print help message for the given topic/command or \
diff --git a/compat.py b/compat.py
index 0ddf81c..e1ddba9 100644
--- a/compat.py
+++ b/compat.py
@@ -2,7 +2,7 @@
"""Wrappers around some builtins introduced in python 2.3, 2.4 and
2.5, making them available in for earlier versions of python.
-:copyright: 2000-2008 LOGILAB S.A. (Paris, FRANCE), all rights reserved.
+:copyright: 2000-2009 LOGILAB S.A. (Paris, FRANCE), all rights reserved.
:contact: http://www.logilab.fr/ -- mailto:contact@logilab.fr
:license: General Public License version 2 - http://www.gnu.org/licenses
"""
@@ -12,7 +12,7 @@ __docformat__ = "restructuredtext en"
import os
from warnings import warn
-import __builtin__
+import builtins
from logilab.common.deprecation import class_renamed
@@ -190,7 +190,7 @@ except TypeError:
key= kargs.pop("key", None)
#default implementation
if key is None:
- return __builtin__.max(*args,**kargs)
+ return builtins.max(*args,**kargs)
for karg in kargs:
raise TypeError("unexpected keyword argument %s for function max") % karg
diff --git a/configuration.py b/configuration.py
index 63dd32d..e7e764e 100644
--- a/configuration.py
+++ b/configuration.py
@@ -672,7 +672,7 @@ class OptionsProviderMixIn(object):
if opt_dict is None:
opt_dict = self.get_option_def(opt_name)
default = opt_dict.get('default')
- if callable(default):
+ if hasattr(default, '__call__'):
default = default()
return default
diff --git a/date.py b/date.py
index a49b2db..4f465b9 100644
--- a/date.py
+++ b/date.py
@@ -59,7 +59,7 @@ else:
end = Date(end.year, end.month, end.day)
holidays = [strptime(datestr, '%Y-%m-%d')
for datestr in FRENCH_MOBILE_HOLIDAYS.values()]
- for year in xrange(begin.year, end.year+1):
+ for year in range(begin.year, end.year+1):
for datestr in FRENCH_FIXED_HOLIDAYS.values():
date = strptime(datestr % year, '%Y-%m-%d')
if date not in holidays:
diff --git a/debian/changelog b/debian/changelog
index 3579ede..ccaf422 100644
--- a/debian/changelog
+++ b/debian/changelog
@@ -1,4 +1,4 @@
-logilab-common (0.38.1-1) UNRELEASED; urgency=low
+logilab-common (0.38.1-1) unstable; urgency=low
* new upstream release
* debian/watch
diff --git a/debugger.py b/debugger.py
index e401a0f..411258e 100644
--- a/debugger.py
+++ b/debugger.py
@@ -5,7 +5,7 @@
- overrides list command to search for current block instead
of using 5 lines of context
-:copyright: 2000-2008 LOGILAB S.A. (Paris, FRANCE), all rights reserved.
+:copyright: 2000-2009 LOGILAB S.A. (Paris, FRANCE), all rights reserved.
:contact: http://www.logilab.fr/ -- mailto:contact@logilab.fr
:license: General Public License version 2 - http://www.gnu.org/licenses
"""
@@ -18,9 +18,9 @@ except ImportError:
import os
import os.path as osp
import sys
-from pdb import Pdb
-from cStringIO import StringIO
import inspect
+from pdb import Pdb
+from io import StringIO
try:
from IPython import PyColorize
@@ -162,8 +162,8 @@ class Debugger(Pdb):
if not arg:
try:
source, start_lineno = getsource(self.curframe)
- print colorize(''.join(source), start_lineno,
- self.curframe.f_lineno)
+ print(colorize(''.join(source), start_lineno,
+ self.curframe.f_lineno))
except KeyboardInterrupt:
pass
except IOError:
diff --git a/decorators.py b/decorators.py
index 001563e..1088f80 100644
--- a/decorators.py
+++ b/decorators.py
@@ -1,6 +1,6 @@
"""A few useful function/method decorators.
-:copyright: 2006-2008 LOGILAB S.A. (Paris, FRANCE), all rights reserved.
+:copyright: 2006-2009 LOGILAB S.A. (Paris, FRANCE), all rights reserved.
:contact: http://www.logilab.fr/ -- mailto:contact@logilab.fr
:license: General Public License version 2 - http://www.gnu.org/licenses
"""
@@ -14,16 +14,13 @@ import sys, re
def cached(callableobj, keyarg=None):
"""Simple decorator to cache result of method call."""
- #print callableobj, keyarg, callableobj.func_code.co_argcount
- if callableobj.func_code.co_argcount == 1 or keyarg == 0:
+ if callableobj.__code__.co_argcount == 1 or keyarg == 0:
def cache_wrapper1(self, *args):
cache = '_%s_cache_' % callableobj.__name__
- #print 'cache1?', cache
try:
return self.__dict__[cache]
except KeyError:
- #print 'miss'
value = callableobj(self, *args)
setattr(self, cache, value)
return value
@@ -34,34 +31,28 @@ def cached(callableobj, keyarg=None):
def cache_wrapper2(self, *args, **kwargs):
cache = '_%s_cache_' % callableobj.__name__
key = args[keyarg-1]
- #print 'cache2?', cache, self, key
try:
_cache = self.__dict__[cache]
except KeyError:
- #print 'init'
_cache = {}
setattr(self, cache, _cache)
try:
return _cache[key]
except KeyError:
- #print 'miss', self, cache, key
_cache[key] = callableobj(self, *args, **kwargs)
return _cache[key]
return cache_wrapper2
def cache_wrapper3(self, *args):
cache = '_%s_cache_' % callableobj.__name__
- #print 'cache3?', cache, self, args
try:
_cache = self.__dict__[cache]
except KeyError:
- #print 'init'
_cache = {}
setattr(self, cache, _cache)
try:
return _cache[args]
except KeyError:
- #print 'miss'
_cache[args] = callableobj(self, *args)
return _cache[args]
return cache_wrapper3
@@ -124,7 +115,7 @@ def timed(f):
t = clock()
#for i in range(100):
res = f(*args, **kwargs)
- print '%s time: %.9f' % (f.__name__, clock() - t)
+ print('%s time: %.9f' % (f.__name__, clock() - t))
return res
return wrap
diff --git a/deprecation.py b/deprecation.py
index b103092..f9041ec 100644
--- a/deprecation.py
+++ b/deprecation.py
@@ -73,7 +73,7 @@ def deprecated_function(new_func, message=None):
"""
if message is None:
message = "this function is deprecated, use %s instead" % (
- new_func.func_name)
+ new_func.__name__)
def deprecated(*args, **kwargs):
warn(message, DeprecationWarning, stacklevel=2)
return new_func(*args, **kwargs)
diff --git a/fileutils.py b/fileutils.py
index 6f441ec..b98db52 100644
--- a/fileutils.py
+++ b/fileutils.py
@@ -6,7 +6,7 @@ get_by_ext, remove_dead_links
write_open_mode, ensure_fs_mode, export
:sort: path manipulation, file manipulation
-:copyright: 2000-2008 LOGILAB S.A. (Paris, FRANCE), all rights reserved.
+:copyright: 2000-2009 LOGILAB S.A. (Paris, FRANCE), all rights reserved.
:contact: http://www.logilab.fr/ -- mailto:contact@logilab.fr
:license: General Public License version 2 - http://www.gnu.org/licenses
"""
@@ -15,14 +15,14 @@ __docformat__ = "restructuredtext en"
import sys
import shutil
import mimetypes
-from os.path import isabs, isdir, islink, split, exists, walk, normpath, join
-from os.path import abspath
+from warnings import warn
from os import sep, mkdir, remove, listdir, stat, chmod
+from os.path import isabs, isdir, islink, split, exists, normpath, join, abspath
from stat import ST_MODE, S_IWRITE
-from cStringIO import StringIO
+from io import StringIO, FileIO
from logilab.common import STD_BLACKLIST as BASE_BLACKLIST, IGNORED_EXTENSIONS
-from logilab.common.shellutils import find
+from logilab.common.shellutils import find, blacklist_walk
def first_level_directory(path):
"""Return the first level directory of a path.
@@ -110,7 +110,7 @@ def ensure_fs_mode(filepath, desired_mode=S_IWRITE):
chmod(filepath, mode | desired_mode)
-class ProtectedFile(file):
+class ProtectedFile(FileIO):
"""A special file-object class that automatically that automatically
does a 'chmod +w' when needed.
@@ -137,7 +137,7 @@ class ProtectedFile(file):
if not self.original_mode & S_IWRITE:
chmod(filepath, self.original_mode | S_IWRITE)
self.mode_changed = True
- file.__init__(self, filepath, mode)
+ FileIO.__init__(self, filepath, mode)
def _restore_mode(self):
"""restores the original mode if needed"""
@@ -149,7 +149,7 @@ class ProtectedFile(file):
def close(self):
"""restore mode before closing"""
self._restore_mode()
- file.close(self)
+ FileIO.close(self)
def __del__(self):
if not self.closed:
@@ -343,13 +343,16 @@ def export(from_dir, to_dir,
flag indicating wether information about exported files should be
printed to stderr, default to False
"""
- def make_mirror(_, directory, fnames):
- """walk handler"""
- for norecurs in blacklist:
- try:
- fnames.remove(norecurs)
- except ValueError:
- continue
+ try:
+ mkdir(to_dir)
+ except OSError:
+ pass
+ for directory, dirnames, fnames in blacklist_walk(from_dir, blacklist):
+ for dirname in dirnames:
+ src = join(directory, dirname)
+ dest = to_dir + src[len(from_dir):]
+ if not exists(dest):
+ mkdir(dest)
for filename in fnames:
# don't include binary files
for ext in ignore_ext:
@@ -359,19 +362,10 @@ def export(from_dir, to_dir,
src = join(directory, filename)
dest = to_dir + src[len(from_dir):]
if verbose:
- print >> sys.stderr, src, '->', dest
- if isdir(src):
- if not exists(dest):
- mkdir(dest)
- else:
- if exists(dest):
- remove(dest)
- shutil.copy2(src, dest)
- try:
- mkdir(to_dir)
- except OSError:
- pass
- walk(from_dir, make_mirror, None)
+ print(src, '->', dest, file=sys.stderr)
+ if exists(dest):
+ remove(dest)
+ shutil.copy2(src, dest)
def remove_dead_links(directory, verbose=0):
@@ -391,13 +385,11 @@ def remove_dead_links(directory, verbose=0):
src = join(directory, filename)
if islink(src) and not exists(src):
if verbose:
- print 'remove dead link', src
+ print('remove dead link', src)
remove(src)
walk(directory, _remove_dead_link, None)
-from warnings import warn
-
def files_by_ext(directory, include_exts=None, exclude_exts=None,
exclude_dirs=BASE_BLACKLIST):
"""Return a list of files in a directory matching (or not) some
diff --git a/logging_ext.py b/logging_ext.py
index fe669ba..cf82c34 100644
--- a/logging_ext.py
+++ b/logging_ext.py
@@ -108,7 +108,7 @@ def init_log(debug=False, syslog=False, logthreshold=None, logfile=None,
handler = logging.StreamHandler()
if logthreshold is None:
logthreshold = logging.ERROR
- elif isinstance(logthreshold, basestring):
+ elif isinstance(logthreshold, str):
logthreshold = getattr(logging, THRESHOLD_MAP.get(logthreshold,
logthreshold))
# configure the root logger
diff --git a/modutils.py b/modutils.py
index a60ae7d..7a53634 100644
--- a/modutils.py
+++ b/modutils.py
@@ -2,7 +2,7 @@
"""Python modules manipulation utility functions.
:author: Logilab
-:copyright: 2000-2008 LOGILAB S.A. (Paris, FRANCE), all rights reserved.
+:copyright: 2000-2009 LOGILAB S.A. (Paris, FRANCE), all rights reserved.
:contact: http://www.logilab.fr/ -- mailto:contact@logilab.fr
:license: General Public License version 2 - http://www.gnu.org/licenses
@@ -19,10 +19,11 @@ __docformat__ = "restructuredtext en"
import sys
import os
-from os.path import walk, splitext, join, abspath, isdir, dirname, exists
+from os.path import splitext, join, abspath, isdir, dirname, exists
from imp import find_module, load_module, C_BUILTIN, PY_COMPILED, PKG_DIRECTORY
from logilab.common import STD_BLACKLIST
+from logilab.common.shellutils import blacklist_walk
if sys.platform.startswith('win'):
PY_SOURCE_EXTS = ('py', 'pyw')
@@ -57,7 +58,7 @@ class LazyObject(object):
def __getattribute__(self, attr):
try:
return super(LazyObject, self).__getattribute__(attr)
- except AttributeError, ex:
+ except AttributeError:
return getattr(self.__getobj(), attr)
def __call__(self, *args, **kwargs):
@@ -327,18 +328,11 @@ def get_modules(package, src_directory, blacklist=STD_BLACKLIST):
the list of all available python modules in the package and its
subpackages
"""
- def func(modules, directory, fnames):
- """walk handler"""
- # remove files/directories in the black list
- for norecurs in blacklist:
- try:
- fnames.remove(norecurs)
- except ValueError:
- continue
+ modules = []
+ for directory, dirnames, fnames in blacklist_walk(src_directory, blacklist):
# check for __init__.py
if not '__init__.py' in fnames:
- while fnames:
- fnames.pop()
+ fnames[:] = ()
elif directory != src_directory:
#src = join(directory, file)
dir_package = directory[len(src_directory):].replace(os.sep, '.')
@@ -350,12 +344,8 @@ def get_modules(package, src_directory, blacklist=STD_BLACKLIST):
if _is_python_file(filename) and filename != '__init__.py':
module = package + src[len(src_directory):-3]
modules.append(module.replace(os.sep, '.'))
- modules = []
- walk(src_directory, func, modules)
return modules
-
-
-
+
def get_module_files(src_directory, blacklist=STD_BLACKLIST):
"""given a package directory return a list of all available python
module's files in the package and its subpackages
@@ -374,14 +364,8 @@ def get_module_files(src_directory, blacklist=STD_BLACKLIST):
the list of all available python module's files in the package and
its subpackages
"""
- def func(files, directory, fnames):
- """walk handler"""
- # remove files/directories in the black list
- for norecurs in blacklist:
- try:
- fnames.remove(norecurs)
- except ValueError:
- continue
+ files = []
+ for directory, dirnames, fnames in blacklist_walk(src_directory, blacklist):
# check for __init__.py
if not '__init__.py' in fnames:
while fnames:
@@ -392,8 +376,6 @@ def get_module_files(src_directory, blacklist=STD_BLACKLIST):
continue
if _is_python_file(filename):
files.append(src)
- files = []
- walk(src_directory, func, files)
return files
@@ -455,19 +437,19 @@ def is_standard_module(modname, std_path=(STD_LIB_DIR,)):
except ImportError:
# import failed, i'm probably not so wrong by supposing it's
# not standard...
- return 0
+ return False
# modules which are not living in a file are considered standard
# (sys and __builtin__ for instance)
if filename is None:
- return 1
+ return True
filename = abspath(filename)
for path in std_path:
path = abspath(path)
if filename.startswith(path):
pfx_len = len(path)
if filename[pfx_len+1:pfx_len+14] != 'site-packages':
- return 1
- return 0
+ return True
+ return False
return False
diff --git a/shellutils.py b/shellutils.py
index 337a9dc..107a44e 100644
--- a/shellutils.py
+++ b/shellutils.py
@@ -2,7 +2,7 @@
scripts.
:author: Logilab
-:copyright: 2000-2008 LOGILAB S.A. (Paris, FRANCE), all rights reserved.
+:copyright: 2000-2009 LOGILAB S.A. (Paris, FRANCE), all rights reserved.
:contact: http://www.logilab.fr/ -- mailto:contact@logilab.fr
:license: General Public License version 2 - http://www.gnu.org/licenses
"""
@@ -17,7 +17,7 @@ import tempfile
import time
import fnmatch
import errno
-from os.path import exists, isdir, islink, basename, join, walk
+from os.path import exists, isdir, islink, basename, join
from logilab.common import STD_BLACKLIST
from logilab.common.proc import ProcInfo, NoSuchProcess
@@ -65,7 +65,7 @@ def mv(source, destination, _action=shutil.move):
destination = join(destination, basename(source))
try:
_action(source, destination)
- except OSError, ex:
+ except OSError as ex:
raise OSError('Unable to move %r to %r (%s)' % (
source, destination, ex))
@@ -87,6 +87,20 @@ def cp(source, destination):
mv(source, destination, _action=shutil.copy)
+def blacklist_walk(path, blacklist):
+ for directory, dirnames, fnames in os.walk(path):
+ # remove files/directories in the black list
+ for norecurs in blacklist:
+ try:
+ fnames.remove(norecurs)
+ except ValueError:
+ try:
+ dirnames.remove(norecurs)
+ except ValueError:
+ continue
+ yield directory, dirnames, fnames
+
+
def find(directory, exts, exclude=False, blacklist=STD_BLACKLIST):
"""Recursivly find files ending with the given extensions from the directory.
@@ -94,7 +108,7 @@ def find(directory, exts, exclude=False, blacklist=STD_BLACKLIST):
:param directory:
directory where the search should start
- :type exts: basestring or list or tuple
+ :type exts: str or list or tuple
:param exts:
extensions or lists or extensions to search
@@ -112,7 +126,7 @@ def find(directory, exts, exclude=False, blacklist=STD_BLACKLIST):
:return:
the list of all matching files
"""
- if isinstance(exts, basestring):
+ if isinstance(exts, str):
exts = (exts,)
if exclude:
def match(filename, exts):
@@ -126,22 +140,14 @@ def find(directory, exts, exclude=False, blacklist=STD_BLACKLIST):
if filename.endswith(ext):
return True
return False
- def func(files, directory, fnames):
- """walk handler"""
- # remove files/directories in the black list
- for norecurs in blacklist:
- try:
- fnames.remove(norecurs)
- except ValueError:
- continue
+ files = []
+ for directory, dirnames, fnames in blacklist_walk(directory, blacklist):
for filename in fnames:
src = join(directory, filename)
if isdir(src):
continue
if match(filename, exts):
files.append(src)
- files = []
- walk(directory, func, files)
return files
@@ -154,7 +160,7 @@ def globfind(directory, pattern, blacklist=STD_BLACKLIST):
:param directory:
directory where the search should start
- :type pattern: basestring
+ :type pattern: str
:param pattern:
the glob pattern (e.g *.py, foo*.py, etc.)
@@ -213,11 +219,11 @@ def acquire_lock(lock_file, max_try=10, delay=10, max_delay=3600):
while count:
try:
fd = os.open(lock_file, os.O_EXCL | os.O_RDWR | os.O_CREAT)
- os.write(fd, str(os.getpid()))
+ os.write(fd, bytes(str(os.getpid()), 'ascii'))
os.close(fd)
return True
- except OSError, e:
- if e.errno == errno.EEXIST:
+ except OSError as ex:
+ if ex.errno == errno.EEXIST:
try:
fd = open(lock_file, "r")
pid = int(fd.readline())
diff --git a/table.py b/table.py
index 7121bcb..e721d0f 100644
--- a/table.py
+++ b/table.py
@@ -179,7 +179,7 @@ class Table(object):
row_index = self.row_names.index(row_id)
self.set_row(row_index, row_data)
except ValueError:
- raise KeyError('Row (%s) not found in table' % (row_id))
+ raise KeyError('Row (%s) not found in table' % row_id)
def append_row(self, row_data, row_name=None):
@@ -478,7 +478,7 @@ class Table(object):
# The first cell <=> an empty one
col_names_line = [' '*col_start]
for col_name in self.col_names:
- col_names_line.append(col_name.encode('iso-8859-1') + ' '*5)
+ col_names_line.append(col_name + ' '*5)
lines.append('|' + '|'.join(col_names_line) + '|')
max_line_length = len(lines[0])
@@ -486,9 +486,8 @@ class Table(object):
for row_index, row in enumerate(self.data):
line = []
# First, build the row_name's cell
- row_name = self.row_names[row_index].encode('iso-8859-1')
+ row_name = self.row_names[row_index]
line.append(row_name + ' '*(col_start-len(row_name)))
-
# Then, build all the table's cell for this line.
for col_index, cell in enumerate(row):
col_name_length = len(self.col_names[col_index]) + 5
@@ -675,7 +674,6 @@ class TableStyleSheet:
for rule in rules:
self.add_rule(rule)
-
def add_rule(self, rule):
"""Adds a rule to the stylesheet rules
"""
@@ -686,8 +684,7 @@ class TableStyleSheet:
'table.py', 'exec'))
self.rules.append(rule)
except SyntaxError:
- print "Bad Stylesheet Rule : %s [skipped]"%rule
-
+ print("Bad Stylesheet Rule : %s [skipped]" % rule)
def add_rowsum_rule(self, dest_cell, row_index, start_col, end_col):
"""Creates and adds a rule to sum over the row at row_index from
@@ -703,7 +700,6 @@ class TableStyleSheet:
rule = '%d_%d=' % dest_cell + '+'.join(cell_list)
self.add_rule(rule)
-
def add_rowavg_rule(self, dest_cell, row_index, start_col, end_col):
"""Creates and adds a rule to make the row average (from start_col
to end_col)
@@ -718,7 +714,6 @@ class TableStyleSheet:
num = (end_col - start_col + 1)
rule = '%d_%d=' % dest_cell + '('+'+'.join(cell_list)+')/%f'%num
self.add_rule(rule)
-
def add_colsum_rule(self, dest_cell, col_index, start_row, end_row):
"""Creates and adds a rule to sum over the col at col_index from
@@ -733,7 +728,6 @@ class TableStyleSheet:
end_row + 1)]
rule = '%d_%d=' % dest_cell + '+'.join(cell_list)
self.add_rule(rule)
-
def add_colavg_rule(self, dest_cell, col_index, start_row, end_row):
"""Creates and adds a rule to make the col average (from start_row
@@ -766,7 +760,6 @@ class TableCellRenderer:
"""
self.properties = properties
-
def render_cell(self, cell_coord, table, table_style):
"""Renders the cell at 'cell_coord' in the table, using table_style
"""
@@ -777,22 +770,16 @@ class TableCellRenderer:
return self._render_cell_content(final_content,
table_style, col_index + 1)
-
def render_row_cell(self, row_name, table, table_style):
"""Renders the cell for 'row_id' row
"""
- cell_value = row_name.encode('iso-8859-1')
- return self._render_cell_content(cell_value, table_style, 0)
-
+ return self._render_cell_content(row_name, table_style, 0)
def render_col_cell(self, col_name, table, table_style):
"""Renders the cell for 'col_id' row
"""
- cell_value = col_name.encode('iso-8859-1')
col_index = table.col_names.index(col_name)
- return self._render_cell_content(cell_value, table_style, col_index +1)
-
-
+ return self._render_cell_content(col_name, table_style, col_index +1)
def _render_cell_content(self, content, table_style, col_index):
"""Makes the appropriate rendering for this cell content.
@@ -802,7 +789,6 @@ class TableCellRenderer:
**This method should be overridden in the derived renderer classes.**
"""
return content
-
def _make_cell_content(self, cell_content, table_style, col_index):
"""Makes the cell content (adds decoration data, like units for
@@ -815,7 +801,6 @@ class TableCellRenderer:
replacement_char = 0
if replacement_char and final_content == 0:
return replacement_char
-
try:
units_on = self.properties['units']
if units_on:
@@ -823,10 +808,8 @@ class TableCellRenderer:
cell_content, table_style, col_index)
except KeyError:
pass
-
return final_content
-
def _add_unit(self, cell_content, table_style, col_index):
"""Adds unit to the cell_content if needed
"""
@@ -845,7 +828,6 @@ class DocbookRenderer(TableCellRenderer):
size = table_style.get_size_by_index(col_index)
return '<colspec colname="c%d" colwidth="%s"/>\n' % \
(col_index, size)
-
def _render_cell_content(self, cell_content, table_style, col_index):
"""Makes the appropriate rendering for this cell content.
@@ -874,30 +856,25 @@ class TableWriter:
self.properties = properties
self.renderer = None
-
def set_style(self, style):
"""sets the table's associated style
"""
self.style = style
-
def set_renderer(self, renderer):
"""sets the way to render cell
"""
self.renderer = renderer
-
def update_properties(self, **properties):
"""Updates writer's properties (for cell rendering)
"""
self.properties.update(properties)
-
def write_table(self, title = ""):
"""Writes the table
"""
raise NotImplementedError("write_table must be implemented !")
-
class DocbookTableWriter(TableWriter):
@@ -911,7 +888,6 @@ class DocbookTableWriter(TableWriter):
for col_index in range(len(self._table.col_names)+1):
self._stream.write(self.renderer.define_col_header(col_index,
self.style))
-
self._stream.write("<thead>\n<row>\n")
# XXX FIXME : write an empty entry <=> the first (__row_column) column
self._stream.write('<entry></entry>\n')
@@ -919,15 +895,12 @@ class DocbookTableWriter(TableWriter):
self._stream.write(self.renderer.render_col_cell(
col_name, self._table,
self.style))
-
self._stream.write("</row>\n</thead>\n")
-
def _write_body(self):
"""Writes the table body
"""
self._stream.write('<tbody>\n')
-
for row_index, row in enumerate(self._table.data):
self._stream.write('<row>\n')
row_name = self._table.row_names[row_index]
@@ -935,17 +908,13 @@ class DocbookTableWriter(TableWriter):
self._stream.write(self.renderer.render_row_cell(row_name,
self._table,
self.style))
-
for col_index, cell in enumerate(row):
self._stream.write(self.renderer.render_cell(
(row_index, col_index),
self._table, self.style))
-
self._stream.write('</row>\n')
-
self._stream.write('</tbody>\n')
-
def write_table(self, title = ""):
"""Writes the table
"""
@@ -955,7 +924,6 @@ class DocbookTableWriter(TableWriter):
(len(self._table.col_names)+1))
self._write_headers()
self._write_body()
-
self._stream.write('</tgroup>\n</table>\n')
diff --git a/tasksqueue.py b/tasksqueue.py
index 75ade01..3aacf0f 100644
--- a/tasksqueue.py
+++ b/tasksqueue.py
@@ -1,13 +1,13 @@
"""Prioritized tasks queue
:organization: Logilab
-:copyright: 2008 LOGILAB S.A. (Paris, FRANCE), all rights reserved.
+:copyright: 2008-2009 LOGILAB S.A. (Paris, FRANCE), all rights reserved.
:contact: http://www.logilab.fr/ -- mailto:contact@logilab.fr
"""
__docformat__ = "restructuredtext en"
from bisect import insort_left
-from Queue import Queue
+from queue import Queue
LOW = 0
MEDIUM = 10
diff --git a/test/unittest_bind.py b/test/unittest_bind.py
index 0c3e2a3..c48db69 100644
--- a/test/unittest_bind.py
+++ b/test/unittest_bind.py
@@ -25,8 +25,8 @@ class BindTC(TestCase):
d = {'HELLO' : HELLO}
new_f = bind.bind(f, d)
self.assertEquals(new_f(), f())
- f_consts = f.func_code.co_consts
- newf_consts = new_f.func_code.co_consts
+ f_consts = f.__code__.co_consts
+ newf_consts = new_f.__code__.co_consts
self.assertEquals(f_consts, (None,))
self.assert_(newf_consts, (None, HELLO))
@@ -41,20 +41,20 @@ class BindTC(TestCase):
"""tests bind.analyze_code()"""
consts_dict, consts_list = {}, []
globs = {'HELLO' : "some global value"}
- modified = bind.analyze_code(modify_hello.func_code, globs,
+ modified = bind.analyze_code(modify_hello.__code__, globs,
consts_dict, consts_list)
self.assertEquals(consts_list, [None, 'hacked !'])
self.assertEquals(modified, ['HELLO'])
def test_optimize_module2(self):
"""test optimize_module_2()"""
- f1_consts = Set(foomod.f1.func_code.co_consts)
- f2_consts = Set(foomod.f2.func_code.co_consts)
- f3_consts = Set(foomod.f3.func_code.co_consts)
+ f1_consts = Set(foomod.f1.__code__.co_consts)
+ f2_consts = Set(foomod.f2.__code__.co_consts)
+ f3_consts = Set(foomod.f3.__code__.co_consts)
bind.optimize_module_2(foomod, ['f1', 'f2', 'f3'])
- newf1_consts = Set(foomod.f1.func_code.co_consts)
- newf2_consts = Set(foomod.f2.func_code.co_consts)
- newf3_consts = Set(foomod.f3.func_code.co_consts)
+ newf1_consts = Set(foomod.f1.__code__.co_consts)
+ newf2_consts = Set(foomod.f2.__code__.co_consts)
+ newf3_consts = Set(foomod.f3.__code__.co_consts)
self.assert_(newf1_consts == newf2_consts == newf3_consts)
self.assertEquals(newf1_consts, f1_consts | f2_consts | f3_consts)
diff --git a/test/unittest_compat.py b/test/unittest_compat.py
index eaa769b..0f66cc5 100644
--- a/test/unittest_compat.py
+++ b/test/unittest_compat.py
@@ -171,13 +171,13 @@ class Py25CompatTC(CompatTCMixIn, TestCase):
def test_any(self):
from logilab.common.compat import any
- testdata = ([], (), '', 'abc', xrange(0, 10), xrange(0, -10, -1))
+ testdata = ([], (), '', 'abc', range(0, 10), range(0, -10, -1))
self.assertEquals(any([]), False)
self.assertEquals(any(()), False)
self.assertEquals(any(''), False)
self.assertEquals(any('abc'), True)
- self.assertEquals(any(xrange(10)), True)
- self.assertEquals(any(xrange(0, -10, -1)), True)
+ self.assertEquals(any(range(10)), True)
+ self.assertEquals(any(range(0, -10, -1)), True)
# python2.5's any consumes iterables
irange = iter(range(10))
self.assertEquals(any(irange), True)
@@ -186,13 +186,13 @@ class Py25CompatTC(CompatTCMixIn, TestCase):
def test_all(self):
from logilab.common.compat import all
- testdata = ([], (), '', 'abc', xrange(0, 10), xrange(0, -10, -1))
+ testdata = ([], (), '', 'abc', range(0, 10), range(0, -10, -1))
self.assertEquals(all([]), True)
self.assertEquals(all(()), True)
self.assertEquals(all(''), True)
self.assertEquals(all('abc'), True)
- self.assertEquals(all(xrange(10)), False)
- self.assertEquals(all(xrange(0, -10, -1)), False)
+ self.assertEquals(all(range(10)), False)
+ self.assertEquals(all(range(0, -10, -1)), False)
# python2.5's all consumes iterables
irange = iter(range(10))
self.assertEquals(all(irange), False)
diff --git a/test/unittest_modutils.py b/test/unittest_modutils.py
index 09ec232..75582b2 100644
--- a/test/unittest_modutils.py
+++ b/test/unittest_modutils.py
@@ -143,7 +143,7 @@ class is_standard_module_tc(TestCase):
"""
def test_knownValues_is_standard_module_0(self):
- self.assertEqual(modutils.is_standard_module('__builtin__'), True)
+ self.assertEqual(modutils.is_standard_module('builtins'), True)
def test_knownValues_is_standard_module_1(self):
self.assertEqual(modutils.is_standard_module('sys'), True)
@@ -155,7 +155,7 @@ class is_standard_module_tc(TestCase):
self.assertEqual(modutils.is_standard_module('unknown'), False)
def test_knownValues_is_standard_module_4(self):
- self.assertEqual(modutils.is_standard_module('StringIO'), True)
+ self.assertEqual(modutils.is_standard_module('io'), True)
def test_knownValues_is_standard_module_5(self):
self.assertEqual(modutils.is_standard_module('data.module', (DATADIR,)), True)
@@ -186,8 +186,8 @@ class get_modules_tc(TestCase):
modules = modutils.get_modules(path.join(*mod_path), data.__path__[0])
modules.sort()
self.assertSetEquals(set(modules),
- set([ '.'.join(mod_path + (mod, )) for mod in 'module', 'module2',
- 'noendingnewline', 'nonregr']))
+ set([ '.'.join(mod_path + (mod, )) for mod in ('module', 'module2',
+ 'noendingnewline', 'nonregr')]))
class get_modules_files_tc(TestCase):
diff --git a/test/unittest_shellutils.py b/test/unittest_shellutils.py
index 17bc0e0..eec78d6 100644
--- a/test/unittest_shellutils.py
+++ b/test/unittest_shellutils.py
@@ -1,14 +1,14 @@
"""unit tests for logilab.common.shellutils"""
import sys, os, tempfile, shutil
-from os.path import join
import datetime, time
+from os.path import join
+from io import StringIO
from logilab.common.testlib import TestCase, unittest_main
-
from logilab.common.shellutils import globfind, find, ProgressBar, acquire_lock, release_lock
from logilab.common.proc import NoSuchProcess
-from StringIO import StringIO
+
DATA_DIR = join('data','find_test')
@@ -94,14 +94,15 @@ class ProgressBarTC(TestCase):
dots, update = round
else:
dots, update = round, None
+ dots = int(dots)
pgb.update()
if update or (update is None and dots != last):
last = dots
- expected_stream.write("\r["+('.'*dots)+(' '*(size-dots))+"]")
+ expected_stream.write('\r[' + ('.'*dots) + (' '*(size-dots)) + ']')
self.assertEquals(pgb_stream.getvalue(), expected_stream.getvalue())
def test_default(self):
- self._update_test(20, xrange(1,21))
+ self._update_test(20, range(1,21))
def test_nbops_gt_size(self):
"""Test the progress bar for nbops > size"""
@@ -145,14 +146,14 @@ class AcquireLockTC(TestCase):
def test_wrong_process(self):
fd = os.open(self.lock, os.O_EXCL | os.O_RDWR | os.O_CREAT)
- os.write(fd, '1111111111')
+ os.write(fd, b'1111111111')
os.close(fd)
self.assertTrue(os.path.exists(self.lock))
self.assertRaises(Exception, acquire_lock, self.lock, 1, 1)
def test_wrong_process_and_continue(self):
fd = os.open(self.lock, os.O_EXCL | os.O_RDWR | os.O_CREAT)
- os.write(fd, '1111111111')
+ os.write(fd, b'1111111111')
os.close(fd)
self.assertTrue(os.path.exists(self.lock))
self.assertTrue(acquire_lock(self.lock))
diff --git a/test/unittest_table.py b/test/unittest_table.py
index d41c646..cd2e9a5 100644
--- a/test/unittest_table.py
+++ b/test/unittest_table.py
@@ -2,11 +2,12 @@
Unittests for table management
"""
-__revision__ = '$Id: unittest_table.py,v 1.13 2006-04-09 22:30:53 nico Exp $'
-
import sys
import os
-from cStringIO import StringIO
+try:
+ from cStringIO import StringIO
+except ImportError:
+ from io import StringIO
from logilab.common.testlib import TestCase, unittest_main
from logilab.common.table import Table, TableStyleSheet, DocbookTableWriter, \
@@ -55,8 +56,8 @@ class TableTC(TestCase):
def test_iterable(self):
"""test iter(table)"""
it = iter(self.table)
- self.assert_(it.next() == self.table.data[0])
- self.assert_(it.next() == self.table.data[1])
+ self.assert_(next(it) == self.table.data[0])
+ self.assert_(next(it) == self.table.data[1])
def test_get_rows(self):
"""tests Table.get_rows()"""
diff --git a/test/unittest_testlib.py b/test/unittest_testlib.py
index 053ae05..260d0ef 100644
--- a/test/unittest_testlib.py
+++ b/test/unittest_testlib.py
@@ -151,8 +151,8 @@ class TestlibTC(TestCase):
self.tc.assertUnorderedIterableEquals({}, {})
def test_unordered_equality_for_iterables(self):
- self.assertRaises(AssertionError, self.tc.assertUnorderedIterableEquals, xrange(5), xrange(6))
- self.tc.assertUnorderedIterableEquals(xrange(5), range(5))
+ self.assertRaises(AssertionError, self.tc.assertUnorderedIterableEquals, range(5), range(6))
+ self.tc.assertUnorderedIterableEquals(range(5), range(5))
self.tc.assertUnorderedIterableEquals([], ())
def test_unordered_equality_for_dicts(self):
@@ -290,7 +290,7 @@ class GenerativeTestsTC(TestCase):
def test_generative_ok(self):
class FooTC(TestCase):
def test_generative(self):
- for i in xrange(10):
+ for i in range(10):
yield self.assertEquals, i, i
result = self.runner.run(FooTC('test_generative'))
self.assertEquals(result.testsRun, 10)
@@ -301,7 +301,7 @@ class GenerativeTestsTC(TestCase):
def test_generative_half_bad(self):
class FooTC(TestCase):
def test_generative(self):
- for i in xrange(10):
+ for i in range(10):
yield self.assertEquals, i%2, 0
result = self.runner.run(FooTC('test_generative'))
self.assertEquals(result.testsRun, 10)
@@ -312,7 +312,7 @@ class GenerativeTestsTC(TestCase):
def test_generative_error(self):
class FooTC(TestCase):
def test_generative(self):
- for i in xrange(10):
+ for i in range(10):
if i == 5:
raise ValueError('STOP !')
yield self.assertEquals, i, i
@@ -326,7 +326,7 @@ class GenerativeTestsTC(TestCase):
def test_generative_error2(self):
class FooTC(TestCase):
def test_generative(self):
- for i in xrange(10):
+ for i in range(10):
if i == 5:
yield self.ouch
yield self.assertEquals, i, i
@@ -342,7 +342,7 @@ class GenerativeTestsTC(TestCase):
def setUp(self):
raise ValueError('STOP !')
def test_generative(self):
- for i in xrange(10):
+ for i in range(10):
yield self.assertEquals, i, i
result = self.runner.run(FooTC('test_generative'))
@@ -382,7 +382,7 @@ class ExitFirstTC(TestCase):
def test_generative_exit_first(self):
class FooTC(TestCase):
def test_generative(self):
- for i in xrange(10):
+ for i in range(10):
yield self.assert_, False
result = self.runner.run(FooTC('test_generative'))
self.assertEquals(result.testsRun, 1)
@@ -501,7 +501,7 @@ class TestLoaderTC(TestCase):
class MyTestCase(TestCase):
def test_foo(self): pass
def test_foobar(self):
- for i in xrange(5):
+ for i in range(5):
if i%2 == 0:
yield InnerTest('even', lambda: None)
else:
diff --git a/test/unittest_textutils.py b/test/unittest_textutils.py
index c878c0f..4f065d8 100644
--- a/test/unittest_textutils.py
+++ b/test/unittest_textutils.py
@@ -208,10 +208,10 @@ class ColorizeAnsiTC(TestCase):
class UnormalizeTC(TestCase):
def test_unormalize(self):
- data = [(u'\u0153nologie', u'oenologie'),
- (u'\u0152nologie', u'OEnologie'),
- (u'l\xf8to', u'loto'),
- (u'été', u'ete'),
+ data = [('\u0153nologie', 'oenologie'),
+ ('\u0152nologie', 'OEnologie'),
+ ('l\xf8to', 'loto'),
+ ('été', 'ete'),
]
for input, output in data:
yield self.assertEquals, tu.unormalize(input), output
diff --git a/testlib.py b/testlib.py
index 76efcc5..fc9e60a 100644
--- a/testlib.py
+++ b/testlib.py
@@ -19,7 +19,7 @@ Command line options:
If no non-option arguments are present, prefixes used are 'test',
'regrtest', 'smoketest' and 'unittest'.
-:copyright: 2003-2008 LOGILAB S.A. (Paris, FRANCE), all rights reserved.
+:copyright: 2003-2009 LOGILAB S.A. (Paris, FRANCE), all rights reserved.
:contact: http://www.logilab.fr/ -- mailto:contact@logilab.fr
:license: General Public License version 2 - http://www.gnu.org/licenses
"""
@@ -40,11 +40,12 @@ import difflib
import types
import tempfile
import math
+from io import StringIO
from shutil import rmtree
from operator import itemgetter
from warnings import warn
-from compiler.consts import CO_GENERATOR
-from ConfigParser import ConfigParser
+from inspect import CO_GENERATOR
+from configparser import ConfigParser
try:
from test import test_support
@@ -118,9 +119,9 @@ def main(testdir=None, exitafter=True):
try:
opts, args = getopt.getopt(sys.argv[1:], 'hvqxr:t:pcd', ['help'])
- except getopt.error, msg:
- print msg
- print __doc__
+ except getopt.error as msg:
+ print(msg)
+ print(__doc__)
return 2
verbose = 0
quiet = False
@@ -145,7 +146,7 @@ def main(testdir=None, exitafter=True):
global ENABLE_DBC
ENABLE_DBC = True
elif o in ('-h', '--help'):
- print __doc__
+ print(__doc__)
sys.exit(0)
args = [item.rstrip('.py') for item in args]
@@ -158,7 +159,7 @@ def main(testdir=None, exitafter=True):
# Tell tests to be moderately quiet
test_support.verbose = verbose
if profile:
- print >> sys.stderr, '** profiled run'
+ print('** profiled run', file=sys.stderr)
from hotshot import Profile
prof = Profile('stones.prof')
start_time, start_ctime = time.time(), time.clock()
@@ -172,28 +173,28 @@ def main(testdir=None, exitafter=True):
capture)
end_time, end_ctime = time.time(), time.clock()
if not quiet:
- print '*'*80
+ print('*'*80)
if all_result:
- print 'Ran %s test cases in %0.2fs (%0.2fs CPU)' % (
+ print('Ran %s test cases in %0.2fs (%0.2fs CPU)' % (
all_result.testsRun, end_time - start_time,
- end_ctime - start_ctime),
+ end_ctime - start_ctime), )
if all_result.errors:
- print ', %s errors' % len(all_result.errors),
+ print(', %s errors' % len(all_result.errors), end='')
if all_result.failures:
- print ', %s failed' % len(all_result.failures),
+ print(', %s failed' % len(all_result.failures), end='')
if all_result.skipped:
- print ', %s skipped' % len(all_result.skipped),
+ print(', %s skipped' % len(all_result.skipped), end='')
print
if good:
if not bad and not skipped and len(good) > 1:
- print "All",
- print _count(len(good), "test"), "OK."
+ print("All", end='')
+ print(_count(len(good), "test"), "OK.")
if bad:
- print _count(len(bad), "test"), "failed:",
- print ', '.join(bad)
+ print(_count(len(bad), "test"), "failed:",)
+ print(', '.join(bad))
if skipped:
- print _count(len(skipped), "test"), "skipped:",
- print ', '.join(['%s (%s)' % (test, msg) for test, msg in skipped])
+ print(_count(len(skipped), "test"), "skipped:", end='')
+ print(', '.join(['%s (%s)' % (test, msg) for test, msg in skipped]))
if profile:
from hotshot import stats
stats = stats.load('stones.prof')
@@ -219,9 +220,9 @@ def run_tests(tests, quiet, verbose, runner=None, capture=0):
all_result = None
for test in tests:
if not quiet:
- print
- print '-'*80
- print "Executing", test
+ print()
+ print('-'*80)
+ print('Executing', test)
result = run_test(test, verbose, runner, capture)
if type(result) is type(''):
# an unexpected error occured
@@ -237,9 +238,9 @@ def run_tests(tests, quiet, verbose, runner=None, capture=0):
if result.errors or result.failures:
bad.append(test)
if verbose:
- print "test", test, \
+ print("test", test,
"failed -- %s errors, %s failures" % (
- len(result.errors), len(result.failures))
+ len(result.errors), len(result.failures)))
else:
good.append(test)
@@ -278,7 +279,7 @@ def run_test(test, verbose, runner=None, capture=0):
# m = __import__(test, globals(), locals(), sys.path)
try:
suite = m.suite
- if callable(suite):
+ if hasattr(suite, '__call__'):
suite = suite()
except AttributeError:
loader = unittest.TestLoader()
@@ -286,8 +287,8 @@ def run_test(test, verbose, runner=None, capture=0):
if runner is None:
runner = SkipAwareTextTestRunner(capture=capture) # verbosity=0)
return runner.run(suite)
- except KeyboardInterrupt, v:
- raise KeyboardInterrupt, v, sys.exc_info()[2]
+ except KeyboardInterrupt:
+ raise
except:
# raise
type, value = sys.exc_info()[:2]
@@ -318,12 +319,12 @@ def start_interactive_mode(result):
else:
while True:
testindex = 0
- print "Choose a test to debug:"
+ print('Choose a test to debug:')
# order debuggers in the same way than errors were printed
- print "\n".join(['\t%s : %s' % (i, descr) for i, (_, descr)
- in enumerate(descrs)])
- print "Type 'exit' (or ^D) to quit"
- print
+ print("\n".join(['\t%s : %s' % (i, descr) for i, (_, descr)
+ in enumerate(descrs)]))
+ print("Type 'exit' (or ^D) to quit")
+ print()
try:
todebug = raw_input('Enter a test name: ')
if todebug.strip().lower() == 'exit':
@@ -334,16 +335,15 @@ def start_interactive_mode(result):
testindex = int(todebug)
debugger = debuggers[descrs[testindex][0]]
except (ValueError, IndexError):
- print "ERROR: invalid test number %r" % (todebug, )
+ print("ERROR: invalid test number %r" % todebug)
else:
debugger.start()
except (EOFError, KeyboardInterrupt):
- print
+ print()
break
# test utils ##################################################################
-from cStringIO import StringIO
class SkipAwareTestResult(unittest._TextTestResult):
@@ -539,14 +539,14 @@ class SkipAwareTextTestRunner(unittest.TextTestRunner):
else:
if isinstance(test, TestCase):
meth = test._get_test_method()
- func = meth.im_func
- testname = '%s.%s' % (meth.im_class.__name__, func.__name__)
+ func = meth.__func__
+ testname = '%s.%s' % (meth.__self__.__class__.__name__, func.__name__)
elif isinstance(test, types.FunctionType):
func = test
testname = func.__name__
elif isinstance(test, types.MethodType):
- func = test.im_func
- testname = '%s.%s' % (test.im_class.__name__, func.__name__)
+ func = test.__func__
+ testname = '%s.%s' % (test.__self__.__class__.__name__, func.__name__)
else:
return True # Not sure when this happens
@@ -666,8 +666,7 @@ class NonStrictTestLoader(unittest.TestLoader):
def _collect_tests(self, module):
tests = {}
for obj in vars(module).values():
- if (issubclass(type(obj), (types.ClassType, type)) and
- issubclass(obj, unittest.TestCase)):
+ if issubclass(type(obj), type) and issubclass(obj, unittest.TestCase):
classname = obj.__name__
if classname[0] == '_' or self._this_is_skipped(classname):
continue
@@ -676,7 +675,7 @@ class NonStrictTestLoader(unittest.TestLoader):
for attrname in dir(obj):
if attrname.startswith(self.testMethodPrefix):
attr = getattr(obj, attrname)
- if callable(attr):
+ if hasattr(attr, '__call__'):
methodnames.append(attrname)
# keep track of class (obj) for convenience
tests[classname] = (obj, methodnames)
@@ -704,7 +703,7 @@ class NonStrictTestLoader(unittest.TestLoader):
collected = []
if len(parts) == 1:
pattern = parts[0]
- if callable(getattr(module, pattern, None)
+ if hasattr(getattr(module, pattern, None), '__call__'
) and pattern not in tests:
# consider it as a suite
return self.loadTestsFromSuite(module, pattern)
@@ -836,16 +835,16 @@ Examples:
else:
self.testNames = (self.defaultTest, )
self.createTests()
- except getopt.error, msg:
- self.usageExit(msg)
+ except getopt.error as ex:
+ self.usageExit(ex)
def runTests(self):
if hasattr(self.module, 'setup_module'):
try:
self.module.setup_module(self.options)
- except Exception, exc:
- print 'setup_module error:', exc
+ except Exception as ex:
+ print('setup_module error:', ex)
sys.exit(1)
self.testRunner = SkipAwareTextTestRunner(verbosity=self.verbosity,
stream=self.outstream,
@@ -881,24 +880,20 @@ Examples:
try:
restartfile = open(FILE_RESTART, 'r')
try:
- try:
- succeededtests = list(elem.rstrip('\n\r') for elem in
- restartfile.readlines())
- removeSucceededTests(self.test, succeededtests)
- except Exception, e:
- raise e
+ succeededtests = list(elem.rstrip('\n\r') for elem in
+ restartfile.readlines())
+ removeSucceededTests(self.test, succeededtests)
finally:
restartfile.close()
- except Exception ,e:
- raise "Error while reading \
-succeeded tests into", osp.join(os.getcwd(),FILE_RESTART)
-
+ except Exception:
+ raise Exception("Error while reading succeeded tests into %s"
+ % osp.join(os.getcwd(), FILE_RESTART))
result = self.testRunner.run(self.test)
if hasattr(self.module, 'teardown_module'):
try:
self.module.teardown_module(self.options, result)
- except Exception, exc:
- print 'teardown_module error:', exc
+ except Exception as ex:
+ print('teardown_module error:', ex)
sys.exit(1)
if os.environ.get('PYDEBUG'):
warn("PYDEBUG usage is deprecated, use -i / --pdb instead",
@@ -1009,7 +1004,7 @@ class TestSkipped(Exception):
"""raised when a test is skipped"""
def is_generator(function):
- flags = function.func_code.co_flags
+ flags = function.__code__.co_flags
return flags & CO_GENERATOR
@@ -1197,7 +1192,7 @@ class TestCase(unittest.TestCase):
if not self.quiet_run(result, self.setUp):
return
# generative tests
- if is_generator(testMethod.im_func):
+ if is_generator(testMethod.__func__):
success = self._proceed_generative(result, testMethod,
runcondition)
else:
@@ -1211,19 +1206,16 @@ class TestCase(unittest.TestCase):
try:
restartfile = open(FILE_RESTART, 'a')
try:
- try:
- descr = '.'.join((self.__class__.__module__,
- self.__class__.__name__,
- self._testMethodName))
- restartfile.write(descr+os.linesep)
- except Exception, e:
- raise e
+ descr = '.'.join((self.__class__.__module__,
+ self.__class__.__name__,
+ self._testMethodName))
+ restartfile.write(descr+os.linesep)
finally:
restartfile.close()
- except Exception, e:
- print >> sys.__stderr__, "Error while saving \
-succeeded test into", osp.join(os.getcwd(),FILE_RESTART)
- raise e
+ except Exception:
+ print('Error while saving succeeded test into',
+ osp.join(os.getcwd(), FILE_RESTART), file=sys.__stderr__)
+ raise
result.addSuccess(self)
finally:
# if result.cvg:
@@ -1371,7 +1363,7 @@ succeeded test into", osp.join(os.getcwd(),FILE_RESTART)
items={}
items['missing'] = expected - got
items['unexpected'] = got - expected
- if any(items.itervalues()):
+ if any(items.values()):
if msg is None:
msg = '\n'.join('%s:\n\t%s' % (key,"\n\t".join(str(value) for value in values))
for key, values in items.iteritems() if values)
@@ -1454,7 +1446,7 @@ succeeded test into", osp.join(os.getcwd(),FILE_RESTART)
self.fail( "tuple %s has %i children%s (%i expected)"%(tup,
len(tup[2]),
('', 's')[len(tup[2])>1], len(element)))
- for index in xrange(len(tup[2])):
+ for index in range(len(tup[2])):
self.assertXMLEqualsTuple(element[index], tup[2][index])
#check text
if element.text or len(tup)>3:
@@ -1484,9 +1476,9 @@ succeeded test into", osp.join(os.getcwd(),FILE_RESTART)
msg_prefix='Text differ'):
"""compare two multiline strings (using difflib and splitlines())"""
msg = []
- if not isinstance(text1, basestring):
+ if not isinstance(text1, str):
msg.append('text1 is not a string (%s)'%(type(text1)))
- if not isinstance(text2, basestring):
+ if not isinstance(text2, str):
msg.append('text2 is not a string (%s)'%(type(text2)))
if msg:
self.fail('\n'.join(msg))
@@ -1638,14 +1630,14 @@ succeeded test into", osp.join(os.getcwd(),FILE_RESTART)
"""
try:
callableObj(*args, **kwargs)
- except excClass, exc:
+ except excClass as exc:
return exc
else:
if hasattr(excClass, '__name__'):
excName = excClass.__name__
else:
excName = str(excClass)
- raise self.failureException, "%s not raised" % excName
+ raise self.failureException("%s not raised" % excName)
assertRaises = failUnlessRaises
@@ -1885,15 +1877,12 @@ def require_version(version):
except ValueError:
raise ValueError('%s is not a correct version : should be X.Y[.Z].' % version)
current = sys.version_info[:3]
- #print 'comp', current, compare
if current < compare:
- #print 'version too old'
def new_f(self, *args, **kwargs):
self.skip('Need at least %s version of python. Current version is %s.' % (version, '.'.join([str(element) for element in current])))
new_f.__name__ = f.__name__
return new_f
else:
- #print 'version young enough'
return f
return check_require_version
@@ -1903,10 +1892,8 @@ def require_module(module):
def check_require_module(f):
try:
__import__(module)
- #print module, 'imported'
return f
except ImportError:
- #print module, 'can not be imported'
def new_f(self, *args, **kwargs):
self.skip('%s can not be imported.' % module)
new_f.__name__ = f.__name__
diff --git a/textutils.py b/textutils.py
index fec946f..9d4a771 100644
--- a/textutils.py
+++ b/textutils.py
@@ -1,7 +1,7 @@
"""Some text manipulation utility functions.
:author: Logilab
-:copyright: 2003-2008 LOGILAB S.A. (Paris, FRANCE), all rights reserved.
+:copyright: 2003-2009 LOGILAB S.A. (Paris, FRANCE), all rights reserved.
:contact: http://www.logilab.fr/ -- mailto:contact@logilab.fr
:license: General Public License version 2 - http://www.gnu.org/licenses
@@ -39,20 +39,20 @@ except ImportError:
MANUAL_UNICODE_MAP = {
- u'\xa1': u'!', # INVERTED EXCLAMATION MARK
- u'\u0142': u'l', # LATIN SMALL LETTER L WITH STROKE
- u'\u2044': u'/', # FRACTION SLASH
- u'\xc6': u'AE', # LATIN CAPITAL LETTER AE
- u'\xa9': u'(c)', # COPYRIGHT SIGN
- u'\xab': u'"', # LEFT-POINTING DOUBLE ANGLE QUOTATION MARK
- u'\xe6': u'ae', # LATIN SMALL LETTER AE
- u'\xae': u'(r)', # REGISTERED SIGN
- u'\u0153': u'oe', # LATIN SMALL LIGATURE OE
- u'\u0152': u'OE', # LATIN CAPITAL LIGATURE OE
- u'\xd8': u'O', # LATIN CAPITAL LETTER O WITH STROKE
- u'\xf8': u'o', # LATIN SMALL LETTER O WITH STROKE
- u'\xbb': u'"', # RIGHT-POINTING DOUBLE ANGLE QUOTATION MARK
- u'\xdf': u'ss', # LATIN SMALL LETTER SHARP S
+ '\xa1': '!', # INVERTED EXCLAMATION MARK
+ '\u0142': 'l', # LATIN SMALL LETTER L WITH STROKE
+ '\u2044': '/', # FRACTION SLASH
+ '\xc6': 'AE', # LATIN CAPITAL LETTER AE
+ '\xa9': '(c)', # COPYRIGHT SIGN
+ '\xab': '"', # LEFT-POINTING DOUBLE ANGLE QUOTATION MARK
+ '\xe6': 'ae', # LATIN SMALL LETTER AE
+ '\xae': '(r)', # REGISTERED SIGN
+ '\u0153': 'oe', # LATIN SMALL LIGATURE OE
+ '\u0152': 'OE', # LATIN CAPITAL LIGATURE OE
+ '\xd8': 'O', # LATIN CAPITAL LETTER O WITH STROKE
+ '\xf8': 'o', # LATIN SMALL LETTER O WITH STROKE
+ '\xbb': '"', # RIGHT-POINTING DOUBLE ANGLE QUOTATION MARK
+ '\xdf': 'ss', # LATIN SMALL LETTER SHARP S
}
def unormalize(ustring, ignorenonascii=False):
@@ -69,7 +69,7 @@ def unormalize(ustring, ignorenonascii=False):
raise ValueError("can't deal with non-ascii based characters")
replacement = _uninormalize('NFD', letter)[0]
res.append(replacement)
- return u''.join(res)
+ return ''.join(res)
def unquote(string):
"""remove optional quotes (simple or double) from the string
@@ -261,7 +261,7 @@ def apply_units( string, units, inter=None, final=float, blank_reg=_BLANK_RE,
:type string: str or unicode
:param string: the string to parse
- :type units: dict (or any object with __getitem__ using basestring key)
+ :type units: dict (or any object with __getitem__ using str key)
:param units: a dict mapping a unit string repr to its value
:type inter: type
@@ -281,8 +281,6 @@ def apply_units( string, units, inter=None, final=float, blank_reg=_BLANK_RE,
values = []
for match in value_reg.finditer(string):
dic = match.groupdict()
- #import sys
- #print >> sys.stderr, dic
lit, unit = dic["value"], dic.get("unit")
value = inter(lit)
if unit is not None:
@@ -297,7 +295,7 @@ def pretty_match(match, string, underline_char='^'):
"""return a string with the match location underlined:
>>> import re
- >>> print pretty_match(re.search('mange', 'il mange du bacon'), 'il mange du bacon')
+ >>> print(pretty_match(re.search('mange', 'il mange du bacon'), 'il mange du bacon'))
il mange du bacon
^^^^^
>>>