don't raise string exception in testlib (closes #35331)

authorSylvain Th?nault <sylvain.thenault@logilab.fr>
changesetcc01389a0dbc
branchstable
phasepublic
hiddenno
parent revision#e24a3ef78e52 tests: fix some configuration tests (python2.4)
child revision#6939a1eb1edf [configuration] include lgc version in deprecation message
files modified by this revision
ChangeLog
daemon.py
graph.py
logging_ext.py
modutils.py
testlib.py
# HG changeset patch
# User Sylvain Thénault <sylvain.thenault@logilab.fr>
# Date 1278002257 -7200
# Thu Jul 01 18:37:37 2010 +0200
# Branch stable
# Node ID cc01389a0dbc3c0a6bc5ef54318c899561e55a63
# Parent e24a3ef78e52ecf55d8fb4c6b493c608cc8cb138
don't raise string exception in testlib (closes #35331)

diff --git a/ChangeLog b/ChangeLog
@@ -1,8 +1,11 @@
1  ChangeLog for logilab.common
2  ============================
3 
4 +--
5 +    * don't raise string exception in testlib (closes #35331)
6 +
7  2010-06-04  --  0.50.3
8      * logging: added new optional kw argument to init_log rotating_parameters
9 
10      * date: fix nb_open_days() codomain, positive natural numbers are expected
11 
diff --git a/daemon.py b/daemon.py
@@ -25,11 +25,11 @@
12  import sys
13  import time
14  import warnings
15 
16 
17 -def daemonize(pidfile):
18 +def daemonize(pidfile=None, uid=None):
19      # See http://www.erlenstar.demon.co.uk/unix/faq_toc.html#TOC16
20      # XXX unix specific
21      #
22      # fork so the parent can exit
23      if os.fork():   # launch child and...
@@ -64,10 +64,18 @@
24          if not os.path.exists(piddir):
25              os.makedirs(piddir)
26          f = file(pidfile, 'w')
27          f.write(str(os.getpid()))
28          f.close()
29 +    # change process uid
30 +    if uid:
31 +        try:
32 +            uid = int(uid)
33 +        except ValueError:
34 +            from pwd import getpwnam
35 +            uid = getpwnam(uid).pw_uid
36 +        os.setuid(uid)
37      return None
38 
39 
40  class DaemonMixIn:
41      """Mixin to make a daemon from watchers/queriers.
diff --git a/graph.py b/graph.py
@@ -16,15 +16,12 @@
42  # You should have received a copy of the GNU Lesser General Public License along
43  # with logilab-common.  If not, see <http://www.gnu.org/licenses/>.
44  """Graph manipulation utilities.
45 
46  (dot generation adapted from pypy/translator/tool/make_dot.py)
47 -
48 +"""
49 
50 -
51 -
52 -"""
53  __docformat__ = "restructuredtext en"
54 
55  __metaclass__ = type
56 
57  import os.path as osp
@@ -114,10 +111,12 @@
58          else:
59              pdot.write(self.source)
60          pdot.close()
61          if target != 'dot':
62              if mapfile:
63 +                print '%s -Tcmapx -o%s -T%s %s -o%s' % (self.renderer, mapfile,
64 +                                                        target, dot_sourcepath, outputfile)
65                  subprocess.call('%s -Tcmapx -o%s -T%s %s -o%s' % (self.renderer, mapfile,
66                             target, dot_sourcepath, outputfile), shell=True)
67              else:
68                  subprocess.call('%s -T%s %s -o%s' % (self.renderer, target,
69                              dot_sourcepath, outputfile), shell=True)
@@ -150,10 +149,11 @@
70  class GraphGenerator:
71      def __init__(self, backend):
72          # the backend is responsible to output the graph in a particular format
73          self.backend = backend
74 
75 +    # XXX doesn't like space in outpufile / mapfile
76      def generate(self, visitor, propshdlr, outputfile=None, mapfile=None):
77          # the visitor
78          # the property handler is used to get node and edge properties
79          # according to the graph and to the backend
80          self.propshdlr = propshdlr
diff --git a/logging_ext.py b/logging_ext.py
@@ -14,17 +14,12 @@
81  # FOR A PARTICULAR PURPOSE.  See the GNU Lesser General Public License for more
82  # details.
83  #
84  # You should have received a copy of the GNU Lesser General Public License along
85  # with logilab-common.  If not, see <http://www.gnu.org/licenses/>.
86 -
87 -"""Extends the logging module from the standard library.
88 +"""Extends the logging module from the standard library."""
89 
90 -
91 -
92 -
93 -"""
94  __docformat__ = "restructuredtext en"
95 
96  import os
97  import sys
98  import logging
diff --git a/modutils.py b/modutils.py
@@ -16,15 +16,10 @@
99  #
100  # You should have received a copy of the GNU Lesser General Public License along
101  # with logilab-common.  If not, see <http://www.gnu.org/licenses/>.
102  """Python modules manipulation utility functions.
103 
104 -
105 -
106 -
107 -
108 -
109  :type PY_SOURCE_EXTS: tuple(str)
110  :var PY_SOURCE_EXTS: list of possible python source file extension
111 
112  :type STD_LIB_DIR: str
113  :var STD_LIB_DIR: directory where standard modules are located
@@ -159,11 +154,11 @@
114          path = [dirname( _file )]
115          prevmodule = module
116      return module
117 
118 
119 -def load_module_from_file(filepath, path=None, use_sys=1):
120 +def load_module_from_file(filepath, path=None, use_sys=1, extrapath=None):
121      """Load a Python module from it's path.
122 
123      :type filepath: str
124      :param filepath: path to the python module or package
125 
@@ -181,11 +176,12 @@
126      :raise ImportError: if the module or package is not found
127 
128      :rtype: module
129      :return: the loaded module
130      """
131 -    return load_module_from_modpath(modpath_from_file(filepath), path, use_sys)
132 +    modpath = modpath_from_file(filepath, extrapath)
133 +    return load_module_from_modpath(modpath, path, use_sys)
134 
135 
136  def _check_init(path, mod_path):
137      """check there are some __init__.py all along the way"""
138      for part in mod_path:
diff --git a/testlib.py b/testlib.py
@@ -215,12 +215,12 @@
139              loader = unittest.TestLoader()
140              suite = loader.loadTestsFromModule(m)
141          if runner is None:
142              runner = SkipAwareTextTestRunner(capture=capture) # verbosity=0)
143          return runner.run(suite)
144 -    except KeyboardInterrupt, v:
145 -        raise KeyboardInterrupt, v, sys.exc_info()[2]
146 +    except KeyboardInterrupt:
147 +        raise
148      except:
149          # raise
150          type, value = sys.exc_info()[:2]
151          msg = "test %s crashed -- %s : %s" % (test, type, value)
152          if verbose:
@@ -835,21 +835,18 @@
153          if getattr(self.options, 'restart', False):
154              # retrieve succeeded tests from FILE_RESTART
155              try:
156                  restartfile = open(FILE_RESTART, 'r')
157                  try:
158 -                    try:
159 -                        succeededtests = list(elem.rstrip('\n\r') for elem in
160 -                            restartfile.readlines())
161 -                        removeSucceededTests(self.test, succeededtests)
162 -                    except Exception, e:
163 -                        raise e
164 +                    succeededtests = list(elem.rstrip('\n\r') for elem in
165 +                                          restartfile.readlines())
166 +                    removeSucceededTests(self.test, succeededtests)
167                  finally:
168                      restartfile.close()
169 -            except Exception ,e:
170 -                raise "Error while reading \
171 -succeeded tests into", osp.join(os.getcwd(),FILE_RESTART)
172 +            except Exception, ex:
173 +                raise Exception("Error while reading succeeded tests into %s: %s"
174 +                                % (osp.join(os.getcwd(), FILE_RESTART), ex))
175 
176          result = self.testRunner.run(self.test)
177          # help garbage collection: we want TestSuite, which hold refs to every
178          # executed TestCase, to be gc'ed
179          del self.test
@@ -1158,23 +1155,20 @@
180                  if hasattr(options, "exitfirst") and options.exitfirst:
181                      # add this test to restart file
182                      try:
183                          restartfile = open(FILE_RESTART, 'a')
184                          try:
185 -                            try:
186 -                                descr = '.'.join((self.__class__.__module__,
187 -                                    self.__class__.__name__,
188 -                                    self._testMethodName))
189 -                                restartfile.write(descr+os.linesep)
190 -                            except Exception, e:
191 -                                raise e
192 +                            descr = '.'.join((self.__class__.__module__,
193 +                                              self.__class__.__name__,
194 +                                              self._testMethodName))
195 +                            restartfile.write(descr+os.linesep)
196                          finally:
197                              restartfile.close()
198 -                    except Exception, e:
199 +                    except Exception, ex:
200                          print >> sys.__stderr__, "Error while saving \
201  succeeded test into", osp.join(os.getcwd(),FILE_RESTART)
202 -                        raise e
203 +                        raise ex
204                  result.addSuccess(self)
205          finally:
206              # if result.cvg:
207              #     result.cvg.stop()
208              result.stopTest(self)
@@ -1661,11 +1655,11 @@
209          else:
210              if hasattr(excClass, '__name__'):
211                  excName = excClass.__name__
212              else:
213                  excName = str(excClass)
214 -            raise self.failureException, "%s not raised" % excName
215 +            raise self.failureException("%s not raised" % excName)
216 
217      assertRaises = failUnlessRaises
218 
219  import doctest
220