py/tests/dcerpc_integer: remove dup tests
[amitay/samba.git] / python / samba / compat.py
1 # module which helps with porting to Python 3
2 #
3 # Copyright (C) Lumir Balhar <lbalhar@redhat.com> 2017
4 #
5 # This program is free software; you can redistribute it and/or modify
6 # it under the terms of the GNU General Public License as published by
7 # the Free Software Foundation; either version 3 of the License, or
8 # (at your option) any later version.
9 #
10 # This program is distributed in the hope that it will be useful,
11 # but WITHOUT ANY WARRANTY; without even the implied warranty of
12 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13 # GNU General Public License for more details.
14 #
15 # You should have received a copy of the GNU General Public License
16 # along with this program.  If not, see <http://www.gnu.org/licenses/>.
17
18 """module which helps with porting to Python 3"""
19
20 import sys
21
22 PY3 = sys.version_info[0] == 3
23
24 if PY3:
25     # Sometimes in PY3 we have variables whose content can be 'bytes' or
26     # 'str' and we can't be sure which. Generally this is because the
27     # code variable can be initialised (or reassigned) a value from different
28     # api(s) or functions depending on complex conditions or logic. Or another
29     # common case is in PY2 the variable is 'type <str>' and in PY3 it is
30     # 'class <str>' and the function to use e.g. b64encode requires 'bytes'
31     # in PY3. In such cases it would be nice to avoid excessive testing in
32     # the client code. Calling such a helper function should be avoided
33     # if possible but sometimes this just isn't possible.
34     # If a 'str' object is passed in it is encoded using 'utf8' or if 'bytes'
35     # is passed in it is returned unchanged.
36     # Using this function is PY2/PY3 code should ensure in most cases
37     # the PY2 code runs unchanged in PY2 whereas the code in PY3 possibly
38     # encodes the variable (see PY2 implementation of this function below)
39     def get_bytes(bytesorstring):
40         tmp = bytesorstring
41         if isinstance(bytesorstring, str):
42             tmp = bytesorstring.encode('utf8')
43         elif not isinstance(bytesorstring, bytes):
44             raise ValueError('Expected byte or string for %s:%s' % (type(bytesorstring), bytesorstring))
45         return tmp
46
47     # helper function to get a string from a variable that maybe 'str' or
48     # 'bytes' if 'bytes' then it is decoded using 'utf8'. If 'str' is passed
49     # it is returned unchanged
50     # Using this function is PY2/PY3 code should ensure in most cases
51     # the PY2 code runs unchanged in PY2 whereas the code in PY3 possibly
52     # decodes the variable (see PY2 implementation of this function below)
53     def get_string(bytesorstring):
54         tmp = bytesorstring
55         if isinstance(bytesorstring, bytes):
56             tmp = bytesorstring.decode('utf8')
57         elif not isinstance(bytesorstring, str):
58             raise ValueError('Expected byte of string for %s:%s' % (type(bytesorstring), bytesorstring))
59         return tmp
60
61     def cmp_fn(x, y):
62         """
63         Replacement for built-in function cmp that was removed in Python 3
64
65         Compare the two objects x and y and return an integer according to
66         the outcome. The return value is negative if x < y, zero if x == y
67         and strictly positive if x > y.
68         """
69
70         return (x > y) - (x < y)
71     # compat functions
72     from urllib.parse import quote as urllib_quote
73     from urllib.parse import urljoin as urllib_join
74     from urllib.request import urlopen as urllib_urlopen
75     from functools import cmp_to_key as cmp_to_key_fn
76
77     # compat types
78     integer_types = int,
79     string_types = str
80     text_type = str
81     binary_type = bytes
82
83     # alias
84     import io
85     StringIO = io.StringIO
86     def ConfigParser(defaults=None, dict_type=None, allow_no_value=None):
87         from configparser import ConfigParser
88         return ConfigParser(defaults, dict_type, allow_no_value, interpolation=None)
89 else:
90     # Helper function to return bytes.
91     # if 'unicode' is passed in then it is decoded using 'utf8' and
92     # the result returned. If 'str' is passed then it is returned unchanged.
93     # Using this function is PY2/PY3 code should ensure in most cases
94     # the PY2 code runs unchanged in PY2 whereas the code in PY3 possibly
95     # encodes the variable (see PY3 implementation of this function above)
96     def get_bytes(bytesorstring):
97         tmp = bytesorstring
98         if isinstance(bytesorstring, unicode):
99             tmp = bytesorstring.encode('utf8')
100         elif not isinstance(bytesorstring, str):
101             raise ValueError('Expected string for %s:%s' % (type(bytesorstring), bytesorstring))
102         return tmp
103
104     # Helper function to return string.
105     # if 'str' or 'unicode' passed in they are returned unchanged
106     # otherwise an exception is generated
107     # Using this function is PY2/PY3 code should ensure in most cases
108     # the PY2 code runs unchanged in PY2 whereas the code in PY3 possibly
109     # decodes the variable (see PY3 implementation of this function above)
110     def get_string(bytesorstring):
111         tmp = bytesorstring
112         if not(isinstance(bytesorstring, str) or isinstance(bytesorstring, unicode)):
113             raise ValueError('Expected str or unicode for %s:%s' % (type(bytesorstring), bytesorstring))
114         return tmp
115
116
117     if sys.version_info < (2, 7):
118         def cmp_to_key_fn(mycmp):
119
120             """Convert a cmp= function into a key= function"""
121             class K(object):
122                 __slots__ = ['obj']
123
124                 def __init__(self, obj, *args):
125                     self.obj = obj
126
127                 def __lt__(self, other):
128                     return mycmp(self.obj, other.obj) < 0
129
130                 def __gt__(self, other):
131                     return mycmp(self.obj, other.obj) > 0
132
133                 def __eq__(self, other):
134                     return mycmp(self.obj, other.obj) == 0
135
136                 def __le__(self, other):
137                     return mycmp(self.obj, other.obj) <= 0
138
139                 def __ge__(self, other):
140                     return mycmp(self.obj, other.obj) >= 0
141
142                 def __ne__(self, other):
143                     return mycmp(self.obj, other.obj) != 0
144
145                 def __hash__(self):
146                     raise TypeError('hash not implemented')
147             return K
148     else:
149         from functools import cmp_to_key as cmp_to_key_fn
150     # compat functions
151     from urllib import quote as urllib_quote
152     from urllib import urlopen as urllib_urlopen
153     from urlparse import urljoin as urllib_join
154
155     # compat types
156     integer_types = (int, long)
157     string_types = basestring
158     text_type = unicode
159     binary_type = str
160
161     # alias
162     import cStringIO
163     StringIO = cStringIO.StringIO
164     from ConfigParser import ConfigParser
165     cmp_fn = cmp