소스 검색

gunittest: Support also Python3

git-svn-id: https://svn.osgeo.org/grass/grass/trunk@65782 15284696-431f-4ddb-bdfa-cd5b030d7da7
Pietro Zambelli 9 년 전
부모
커밋
4ac5ded26e

+ 17 - 10
lib/python/gunittest/case.py

@@ -8,10 +8,11 @@ for details.
 
 :authors: Vaclav Petras
 """
+from __future__ import print_function
 
 import os
 import subprocess
-import StringIO
+import sys
 import hashlib
 import uuid
 import unittest
@@ -27,6 +28,12 @@ from .utils import safe_repr
 from .gutils import is_map_in_mapset
 
 
+if sys.version_info[0] == 2:
+    import StringIO
+else:
+    from io import StringIO
+
+
 class TestCase(unittest.TestCase):
     # we dissable R0904 for all TestCase classes because their purpose is to
     # provide a lot of assert methods
@@ -624,7 +631,7 @@ class TestCase(unittest.TestCase):
         name and should be always provided.
         """
         # TODO: possible improvement is to require some descriptive name
-        # and ensure uniqueness by add UUID 
+        # and ensure uniqueness by add UUID
         if self.readable_names:
             return 'tmp_' + self.id().replace('.', '_') + '_' + name
         else:
@@ -1117,8 +1124,8 @@ class TestCase(unittest.TestCase):
             module.run()
             self.grass_modules.append(module.name)
         except CalledModuleError:
-            print module.outputs.stdout
-            print module.outputs.stderr
+            print(module.outputs.stdout)
+            print(module.outputs.stderr)
             # TODO: message format
             # TODO: stderr?
             stdmsg = ('Running <{m.name}> module ended'
@@ -1130,8 +1137,8 @@ class TestCase(unittest.TestCase):
                           errors=module.outputs.stderr
                       ))
             self.fail(self._formatMessage(msg, stdmsg))
-        print module.outputs.stdout
-        print module.outputs.stderr
+        print(module.outputs.stdout)
+        print(module.outputs.stderr)
         # log these to final report
         # TODO: always or only if the calling test method failed?
         # in any case, this must be done before self.fail()
@@ -1151,11 +1158,11 @@ class TestCase(unittest.TestCase):
             module.run()
             self.grass_modules.append(module.name)
         except CalledModuleError:
-            print module.outputs.stdout
-            print module.outputs.stderr
+            print(module.outputs.stdout)
+            print(module.outputs.stderr)
         else:
-            print module.outputs.stdout
-            print module.outputs.stderr
+            print(module.outputs.stdout)
+            print(module.outputs.stderr)
             stdmsg = ('Running <%s> ended with zero (successful) return code'
                       ' when expecting module to fail' % module.get_python())
             self.fail(self._formatMessage(msg, stdmsg))

+ 6 - 2
lib/python/gunittest/invoker.py

@@ -12,7 +12,6 @@ for details.
 import os
 import sys
 import shutil
-import string
 import subprocess
 
 from .checkers import text_to_keyvalue
@@ -25,6 +24,11 @@ from .reporters import (GrassTestFilesMultiReporter,
                         NoopFileAnonymizer, keyvalue_to_text)
 from .utils import silent_rmtree, ensure_dir
 
+try:
+    from string import maketrans
+except ImportError:
+    maketrans = str.maketrans
+
 # needed for write_gisrc
 # TODO: it would be good to find some way of writing rc without the need to
 # have GRASS proprly set (anything from grass.script requires translations to
@@ -104,7 +108,7 @@ class GrassTestFilesInvoker(object):
         # replace . to get rid of unclean path
         # TODO: clean paths
         # note that backslash cannot be at the end of raw string
-        dir_as_name = module.tested_dir.translate(string.maketrans(r'/\.', '___'))
+        dir_as_name = module.tested_dir.translate(maketrans(r'/\.', '___'))
         mapset = dir_as_name + '_' + module.name
         # TODO: use grass module to do this? but we are not in the right gisdbase
         mapset_dir = os.path.join(gisdbase, location, mapset)

+ 9 - 9
lib/python/gunittest/main.py

@@ -15,6 +15,7 @@ import argparse
 
 from unittest.main import TestProgram
 
+
 from .loader import GrassTestLoader
 from .runner import (GrassTestRunner, MultiTestResult,
                      TextTestResult, KeyValueTestResult)
@@ -55,16 +56,15 @@ class GrassTestProgram(TestProgram):
                                        failfast=failfast,
                                        buffer=buffer_stdout_stderr,
                                        result=result)
-
         super(GrassTestProgram, self).__init__(module=module,
-                                               argv=unittest_argv,
-                                               testLoader=grass_loader,
-                                               testRunner=grass_runner,
-                                               exit=exit_at_end,
-                                               verbosity=verbosity,
-                                               failfast=failfast,
-                                               catchbreak=catchbreak,
-                                               buffer=buffer_stdout_stderr)
+                                                   argv=unittest_argv,
+                                                   testLoader=grass_loader,
+                                                   testRunner=grass_runner,
+                                                   exit=exit_at_end,
+                                                   verbosity=verbosity,
+                                                   failfast=failfast,
+                                                   catchbreak=catchbreak,
+                                                   buffer=buffer_stdout_stderr)
         keyval_file.close()
 
 

+ 14 - 8
lib/python/gunittest/reporters.py

@@ -14,15 +14,21 @@ import datetime
 import xml.sax.saxutils as saxutils
 import xml.etree.ElementTree as et
 import subprocess
-import StringIO
+import sys
 import collections
-import types
 import re
 
 from .utils import ensure_dir
 from .checkers import text_to_keyvalue
 
 
+if sys.version_info[0] == 2:
+    from StringIO import StringIO
+else:
+    from io import StringIO
+    basestring = str
+
+
 # TODO: change text_to_keyvalue to same sep as here
 # TODO: create keyvalue file and move it there together with things from checkers
 def keyvalue_to_text(keyvalue, sep='=', vsep='\n', isep=',',
@@ -30,9 +36,9 @@ def keyvalue_to_text(keyvalue, sep='=', vsep='\n', isep=',',
     if not last_vertical:
         last_vertical = vsep == '\n'
     items = []
-    for key, value in keyvalue.iteritems():
+    for key, value in keyvalue.items():
         # TODO: use isep for iterables other than strings
-        if (not isinstance(value, types.StringTypes)
+        if (not isinstance(value, basestring)
                 and isinstance(value, collections.Iterable)):
             # TODO: this does not work for list of non-strings
             value = isep.join(value)
@@ -444,7 +450,7 @@ def html_file_preview(filename):
     if not size:
         return '<p style="color: red>File %s is empty<p>' % filename
     max_size = 10000
-    html = StringIO.StringIO()
+    html = StringIO()
     html.write(before)
     if size < max_size:
         with open(filename) as text:
@@ -582,7 +588,7 @@ class GrassTestFilesHtmlReporter(GrassTestFilesCountingReporter):
                      st=self.successes, ft=self.failures + self.errors,
                      total=self.total, pt=pass_per
                      ))
-        
+
         # this is the second place with this function
         # TODO: provide one implementation
         def format_percentage(percentage):
@@ -835,7 +841,7 @@ class GrassTestFilesKeyValueReporter(GrassTestFilesCountingReporter):
         # TODO: add some general metadata here (passed in constructor)
 
         # add additional information
-        for key, value in self._info.iteritems():
+        for key, value in self._info.items():
             summary[key] = value
 
         summary_filename = os.path.join(self.result_dir,
@@ -1150,7 +1156,7 @@ class TestsuiteDirReporter(object):
         page.write(head)
         page.write(tests_table_head)
 
-        for directory, test_files in directories.iteritems():
+        for directory, test_files in directories.items():
             row = self.report_for_dir(root=root, directory=directory,
                                       test_files=test_files)
             page.write(row)

+ 3 - 2
lib/python/gunittest/runner.py

@@ -43,8 +43,9 @@ class TestResult(unittest.TestResult):
     # where are also unused, so perhaps we can remove them
     # stream set to None and not included in interface, it would not make sense
     def __init__(self, stream=None, descriptions=None, verbosity=None):
-        super(TestResult, self).__init__(
-            stream=stream, descriptions=descriptions, verbosity=verbosity)
+        super(TestResult, self).__init__(stream=stream,
+                                         descriptions=descriptions,
+                                         verbosity=verbosity)
         self.successes = []
 
     def addSuccess(self, test):

+ 4 - 1
lib/python/gunittest/utils.py

@@ -54,7 +54,10 @@ def do_doctest_gettext_workaround():
 
     sys.displayhook = new_displayhook
 
-    import __builtin__
+    try:
+        import __builtin__
+    except ImportError:
+        import builtins as __builtin__
     __builtin__._ = new_translator