1"""
2This module contains fixups for using nose under different versions of Python.
3"""
4import sys
5import os
6import traceback
7import types
8import inspect
9import nose.util
10
11__all__ = ['make_instancemethod', 'cmp_to_key', 'sort_list', 'ClassType',
12           'TypeType', 'UNICODE_STRINGS', 'unbound_method', 'ismethod',
13           'bytes_', 'is_base_exception', 'force_unicode', 'exc_to_unicode',
14           'format_exception']
15
16# In Python 3.x, all strings are unicode (the call to 'unicode()' in the 2.x
17# source will be replaced with 'str()' when running 2to3, so this test will
18# then become true)
19UNICODE_STRINGS = (type(str()) == type(str()))
20
21if sys.version_info[:2] < (3, 0):
22    def force_unicode(s, encoding='UTF-8'):
23        try:
24            s = str(s)
25        except UnicodeDecodeError:
26            s = str(s).decode(encoding, 'replace')
27
28        return s
29else:
30    def force_unicode(s, encoding='UTF-8'):
31        return str(s)
32
33# new.instancemethod() is obsolete for new-style classes (Python 3.x)
34# We need to use descriptor methods instead.
35try:
36    import new
37    def make_instancemethod(function, instance):
38        return new.instancemethod(function.__func__, instance,
39                                  instance.__class__)
40except ImportError:
41    def make_instancemethod(function, instance):
42        return function.__get__(instance, instance.__class__)
43
44# To be forward-compatible, we do all list sorts using keys instead of cmp
45# functions.  However, part of the unittest.TestLoader API involves a
46# user-provideable cmp function, so we need some way to convert that.
47def cmp_to_key(mycmp):
48    'Convert a cmp= function into a key= function'
49    class Key(object):
50        def __init__(self, obj):
51            self.obj = obj
52        def __lt__(self, other):
53            return mycmp(self.obj, other.obj) < 0
54        def __gt__(self, other):
55            return mycmp(self.obj, other.obj) > 0
56        def __eq__(self, other):
57            return mycmp(self.obj, other.obj) == 0
58    return Key
59
60# Python 2.3 also does not support list-sorting by key, so we need to convert
61# keys to cmp functions if we're running on old Python..
62if sys.version_info < (2, 4):
63    def sort_list(l, key, reverse=False):
64        if reverse:
65            return l.sort(lambda a, b: cmp(key(b), key(a)))
66        else:
67            return l.sort(lambda a, b: cmp(key(a), key(b)))
68else:
69    def sort_list(l, key, reverse=False):
70        return l.sort(key=key, reverse=reverse)
71
72# In Python 3.x, all objects are "new style" objects descended from 'type', and
73# thus types.ClassType and types.TypeType don't exist anymore.  For
74# compatibility, we make sure they still work.
75if hasattr(types, 'ClassType'):
76    ClassType = type
77    TypeType = type
78else:
79    ClassType = type
80    TypeType = type
81
82# The following emulates the behavior (we need) of an 'unbound method' under
83# Python 3.x (namely, the ability to have a class associated with a function
84# definition so that things can do stuff based on its associated class)
85class UnboundMethod:
86    def __init__(self, cls, func):
87        # Make sure we have all the same attributes as the original function,
88        # so that the AttributeSelector plugin will work correctly...
89        self.__dict__ = func.__dict__.copy()
90        self._func = func
91        self.__self__ = UnboundSelf(cls)
92        if sys.version_info < (3, 0):
93            self.__self__.__class__ = cls
94
95    def address(self):
96        cls = self.__self__.cls
97        modname = cls.__module__
98        module = sys.modules[modname]
99        filename = getattr(module, '__file__', None)
100        if filename is not None:
101            filename = os.path.abspath(filename)
102        return (nose.util.src(filename), modname, "%s.%s" % (cls.__name__,
103                                                        self._func.__name__))
104
105    def __call__(self, *args, **kwargs):
106        return self._func(*args, **kwargs)
107
108    def __getattr__(self, attr):
109        return getattr(self._func, attr)
110
111    def __repr__(self):
112        return '<unbound method %s.%s>' % (self.__self__.cls.__name__,
113                                           self._func.__name__)
114
115class UnboundSelf:
116    def __init__(self, cls):
117        self.cls = cls
118
119    # We have to do this hackery because Python won't let us override the
120    # __class__ attribute...
121    def __getattribute__(self, attr):
122        if attr == '__class__':
123            return self.cls
124        else:
125            return object.__getattribute__(self, attr)
126
127def unbound_method(cls, func):
128    if inspect.ismethod(func):
129        return func
130    if not inspect.isfunction(func):
131        raise TypeError('%s is not a function' % (repr(func),))
132    return UnboundMethod(cls, func)
133
134def ismethod(obj):
135    return inspect.ismethod(obj) or isinstance(obj, UnboundMethod)
136
137
138# Make a pseudo-bytes function that can be called without the encoding arg:
139if sys.version_info >= (3, 0):
140    def bytes_(s, encoding='utf8'):
141        if isinstance(s, bytes):
142            return s
143        return bytes(s, encoding)
144else:
145    def bytes_(s, encoding=None):
146        return str(s)
147
148
149if sys.version_info[:2] >= (2, 6):
150    def isgenerator(o):
151        if isinstance(o, UnboundMethod):
152            o = o._func
153        return inspect.isgeneratorfunction(o) or inspect.isgenerator(o)
154else:
155    try:
156        from compiler.consts import CO_GENERATOR
157    except ImportError:
158        # IronPython doesn't have a complier module
159        CO_GENERATOR=0x20
160
161    def isgenerator(func):
162        try:
163            return func.__code__.co_flags & CO_GENERATOR != 0
164        except AttributeError:
165            return False
166
167# Make a function to help check if an exception is derived from BaseException.
168# In Python 2.4, we just use Exception instead.
169if sys.version_info[:2] < (2, 5):
170    def is_base_exception(exc):
171        return isinstance(exc, Exception)
172else:
173    def is_base_exception(exc):
174        return isinstance(exc, BaseException)
175
176if sys.version_info[:2] < (3, 0):
177    def exc_to_unicode(ev, encoding='utf-8'):
178        if is_base_exception(ev):
179            if not hasattr(ev, '__unicode__'):
180                # 2.5-
181                if not hasattr(ev, 'message'):
182                    # 2.4
183                    msg = len(ev.args) and ev.args[0] or ''
184                else:
185                    msg = ev.message
186                msg = force_unicode(msg, encoding=encoding)
187                clsname = force_unicode(ev.__class__.__name__,
188                        encoding=encoding)
189                ev = '%s: %s' % (clsname, msg)
190        elif not isinstance(ev, str):
191            ev = repr(ev)
192
193        return force_unicode(ev, encoding=encoding)
194else:
195    def exc_to_unicode(ev, encoding='utf-8'):
196        return str(ev)
197
198def format_exception(exc_info, encoding='UTF-8'):
199    ec, ev, tb = exc_info
200
201    # Our exception object may have been turned into a string, and Python 3's
202    # traceback.format_exception() doesn't take kindly to that (it expects an
203    # actual exception object).  So we work around it, by doing the work
204    # ourselves if ev is not an exception object.
205    if not is_base_exception(ev):
206        tb_data = force_unicode(
207                ''.join(traceback.format_tb(tb)),
208                encoding)
209        ev = exc_to_unicode(ev)
210        return tb_data + ev
211    else:
212        return force_unicode(
213                ''.join(traceback.format_exception(*exc_info)),
214                encoding)
215