/[thuban]/branches/WIP-pyshapelib-bramz/test/support.py
ViewVC logotype

Diff of /branches/WIP-pyshapelib-bramz/test/support.py

Parent Directory Parent Directory | Revision Log Revision Log | View Patch Patch

revision 1397 by jonathan, Thu Jul 10 14:55:37 2003 UTC revision 2642 by bh, Fri Jul 1 20:49:04 2005 UTC
# Line 1  Line 1 
1  # Copyright (c) 2002, 2003 by Intevation GmbH  # Copyright (c) 2002, 2003, 2004, 2005 by Intevation GmbH
2  # Authors:  # Authors:
3  # Bernhard Herzog <[email protected]>  # Bernhard Herzog <[email protected]>
4  #  #
# Line 15  __version__ = "$Revision$" Line 15  __version__ = "$Revision$"
15    
16  import os, sys  import os, sys
17  import unittest  import unittest
18    import traceback
19    
20    import postgissupport
21    
22    
23  def thuban_dir():  def thuban_dir():
24      """Return the directory containing the Thuban package"""      """Return the directory containing the Thuban package"""
# Line 44  def initthuban(): Line 48  def initthuban():
48      """      """
49      global _initthuban_done      global _initthuban_done
50      if not _initthuban_done:      if not _initthuban_done:
51            # Thuban uses gettext to translate some strings. Some of these
52            # strings are tested for equality in some test cases. So we
53            # unset any LANG environment setting to make sure only the
54            # untranslated messages are used.
55            try:
56                del os.environ["LANG"]
57            except KeyError:
58                pass
59          add_thuban_dir_to_path()          add_thuban_dir_to_path()
60          import thubaninit          import thubaninit
61    
62            # Install a dummy translation function so that importing
63            # Thuban.UI doesn't install a wx specific one for which would
64            # need to import wxPython
65            import Thuban
66            Thuban.install_translation_function(lambda s: s)
67    
68            # For the time being the default encoding in the test suite is
69            # latin 1.  This is mostly for historical reasons.  Other
70            # encodings can be specified as an argument for runtests.py.
71            Thuban.set_internal_encoding("latin-1")
72    
73          _initthuban_done = 1          _initthuban_done = 1
74    
 def run_tests():  
     """Frontend for unittest.main that prints some additional debug information  
75    
76      After calling unittest.main, run the garbage collector and print  #
77      uncollected objects. Also print any un-unsubscribed messages.  # Special test runner and result that support skipping tests
78    #
79    
80    class SkipTest(Exception):
81        """Exception to raise in tests that are skipped for some reason
82    
83        For instance, since gdal support is optional, test cases that
84        require gdal raise this exception to indicate that they are skipped.
85        Skipped is different from failure or error in that it is expected
86        under certain circumstances.
87        """
88    
89    class ThubanTestResult(unittest._TextTestResult):
90    
91        def __init__(self, stream, descriptions, verbosity):
92            unittest._TextTestResult.__init__(self, stream, descriptions,
93                                              verbosity)
94            self.skipped_tests = {}
95    
96        def add_skipped_test(self, test, exc):
97            reason = str(exc)
98            self.skipped_tests.setdefault(reason, []).append(test)
99    
100        def count_skipped(self):
101            sum = 0
102            for tests in self.skipped_tests.values():
103                sum += len(tests)
104            return sum
105    
106        def addError(self, test, err):
107            """Extend inherited method to handle SkipTest exceptions specially
108            """
109            #print "addError", test, err
110            if isinstance(err[1], SkipTest):
111                self.add_skipped_test(test, err[1])
112                if self.showAll:
113                    self.stream.writeln("skipped")
114                elif self.dots:
115                    self.stream.write('S')
116            else:
117                unittest._TextTestResult.addError(self, test, err)
118    
119        def printErrors(self):
120            if self.skipped_tests:
121                if self.dots or self.showAll:
122                    self.stream.writeln()
123                self.stream.writeln("Skipped tests:")
124                for reason, tests in self.skipped_tests.items():
125                    self.stream.writeln("  %s:" % reason)
126                    for test in tests:
127                        self.stream.writeln("    " + test.id())
128            unittest._TextTestResult.printErrors(self)
129    
130        def getDescription(self, test):
131            return test.id()
132    
133    
134    class ThubanTestRunner(unittest.TextTestRunner):
135    
136        def _makeResult(self):
137            return ThubanTestResult(self.stream, self.descriptions, self.verbosity)
138    
139        def run(self, test):
140            result = unittest.TextTestRunner.run(self, test)
141            self.stream.writeln("skipped = %d" % result.count_skipped())
142            return result
143    
144    
145    class ThubanTestProgram(unittest.TestProgram):
146    
147        def runTests(self):
148            """Extend inherited method so that we use a ThubanTestRunner"""
149            self.testRunner = ThubanTestRunner(verbosity = self.verbosity)
150            unittest.TestProgram.runTests(self)
151    
152    
153    def execute_as_testsuite(callable, *args, **kw):
154        """Call callable  with args as if it were the entry point to the test suite
155    
156        Return watever callable returns.
157    
158        This is a helper function for run_tests and runtests.py. Call
159        callable in a try-finally block and run some cleanup and print some
160        additional information in the finally block.
161    
162        The additionaly information include:
163    
164         - A list of uncollected objects (after an explicit garbage
165           collector call)
166    
167         - any unsubscribed messages
168      """      """
169      try:      try:
170          unittest.main()          return callable(*args, **kw)
171      finally:      finally:
172          # This has to be in a finally clause because unittest.main()          # This has to be in a finally clause because unittest.main()
173          # ends with a sys.exit to make sure that the process exits with          # ends with a sys.exit to make sure that the process exits with
174          # an appropriate exit code          # an appropriate exit code
175    
176            # Shutdown the postgis server if it's running
177            try:
178                postgissupport.shutdown_test_server()
179            except:
180                traceback.print_exc()
181    
182            # Print additional information
183          print_additional_summary()          print_additional_summary()
184    
185    def run_tests():
186        """Frontend for unittest.main that prints some additional debug information
187    
188        After calling unittest.main, run the garbage collector and print
189        uncollected objects. Also print any un-unsubscribed messages.
190        """
191        execute_as_testsuite(ThubanTestProgram)
192    
193    
194  def print_additional_summary():  def print_additional_summary():
195      """Print some additional summary information after tests have been run"""      """Print some additional summary information after tests have been run"""
196      print_garbage_information()      print_garbage_information()
# Line 74  def print_garbage_information(): Line 203  def print_garbage_information():
203      Run the garbage collector and print uncollected objects. Also print      Run the garbage collector and print uncollected objects. Also print
204      any un-unsubscribed messages.      any un-unsubscribed messages.
205      """      """
206        # this function may be called indirectly from test cases that test
207        # test support modules which do not use anything from thuban itself,
208        # so we call initthuban so that we can import the connector module
209        initthuban()
210      import gc, Thuban.Lib.connector      import gc, Thuban.Lib.connector
211      gc.collect()      gc.collect()
212      if gc.garbage:      if gc.garbage:
# Line 82  def print_garbage_information(): Line 215  def print_garbage_information():
215          print gc.garbage          print gc.garbage
216      Thuban.Lib.connector._the_connector.print_connections()      Thuban.Lib.connector._the_connector.print_connections()
217    
218    #
219    
220  def create_temp_dir():  def create_temp_dir():
221      """Create a temporary directory and return its name.      """Create a temporary directory and return its name.
# Line 139  class FileLoadTestCase(unittest.TestCase Line 273  class FileLoadTestCase(unittest.TestCase
273      def filename(self):      def filename(self):
274          """Return the name of the test file to use.          """Return the name of the test file to use.
275    
276          The default implementation simply calls self.volatile_file_name          The default implementation simply calls self.temp_file_name with
277          with a basename derived from the class name by stripping off a          a basename derived from the class name by stripping off a
278          leading 'test_' and appending self.file_extension.          leading 'test_' and appending self.file_extension.
279          """          """
280          name = self.__class__.__name__          name = self.__class__.__name__
# Line 160  class FileLoadTestCase(unittest.TestCase Line 294  class FileLoadTestCase(unittest.TestCase
294          file.close()          file.close()
295    
296    
297  class FloatComparisonMixin(unittest.TestCase):  class FloatComparisonMixin:
298    
299      """      """
300      Mixin class for tests comparing floating point numbers.      Mixin class for tests comparing floating point numbers.
# Line 171  class FloatComparisonMixin(unittest.Test Line 305  class FloatComparisonMixin(unittest.Test
305    
306      fp_epsilon = 1e-6      fp_epsilon = 1e-6
307      fp_inf = float('1e1000')   # FIXME: hack for infinite      fp_inf = float('1e1000')   # FIXME: hack for infinite
308        
309      def assertFloatEqual(self, test, value, epsilon = None):      def assertFloatEqual(self, test, value, epsilon = None):
310          """Assert equality of test and value with some tolerance.          """Assert equality of test and value with some tolerance.
311    
# Line 193  class FloatComparisonMixin(unittest.Test Line 327  class FloatComparisonMixin(unittest.Test
327          value in test and value is less than the optional parameter          value in test and value is less than the optional parameter
328          epsilon. If epsilon is not given use self.fp_epsilon.          epsilon. If epsilon is not given use self.fp_epsilon.
329          """          """
330            self.assertEquals(len(test), len(value))
331          for i in range(len(test)):          for i in range(len(test)):
332              self.assertFloatEqual(test[i], value[i], epsilon)              self.assertFloatEqual(test[i], value[i], epsilon)
333    
334        def assertPointListEquals(self, test, value):
335            """Assert equality of two lists of lists of tuples of float
336    
337            This assertion is usually used to compare the geometry of shapes
338            as returned by a Shape object's Points() method, hence the name.
339            """
340            for i in range(len(test)):
341                self.assertEquals(len(test[i]), len(value[i]))
342                for j in range(len(test[i])):
343                    self.assertFloatSeqEqual(test[i][j], value[i][j])
344    
345    
346  class SubscriberMixin:  class SubscriberMixin:
347    
348      """Mixin class for tests for messages sent through the Connector      """Mixin class for tests for messages sent through the Connector

Legend:
Removed from v.1397  
changed lines
  Added in v.2642

[email protected]
ViewVC Help
Powered by ViewVC 1.1.26