[GRASS-SVN] r60993 - in sandbox/wenzeslaus/gunittest: . testsuite

svn_grass at osgeo.org svn_grass at osgeo.org
Thu Jun 26 13:30:21 PDT 2014


Author: wenzeslaus
Date: 2014-06-26 13:30:21 -0700 (Thu, 26 Jun 2014)
New Revision: 60993

Added:
   sandbox/wenzeslaus/gunittest/testsuite/test_gmodules.py
Modified:
   sandbox/wenzeslaus/gunittest/case.py
   sandbox/wenzeslaus/gunittest/gmodules.py
Log:
gunittest: add more parameters to call_module() function and use it

Modified: sandbox/wenzeslaus/gunittest/case.py
===================================================================
--- sandbox/wenzeslaus/gunittest/case.py	2014-06-26 20:28:04 UTC (rev 60992)
+++ sandbox/wenzeslaus/gunittest/case.py	2014-06-26 20:30:21 UTC (rev 60993)
@@ -16,8 +16,7 @@
 import unittest
 from unittest.util import safe_repr
 
-import grass.script.core as gcore
-
+from .gmodules import call_module
 from .checkers import (check_text_ellipsis,
                        text_to_keyvalue, compare_keyvalue, diff_keyvalue)
 
@@ -43,15 +42,16 @@
         self.assert_(isinstance(reference, basestring), (
                      'reference argument is not a string'))
         if not check_text_ellipsis(actual=actual, reference=reference):
-            standardMsg = '"%s" does not correspond with "%s"' % (safe_repr(actual),
-                                                                  safe_repr(reference))
+            # TODO: add support for multiline (first line general, others with details)
+            standardMsg = '"%s" does not correspond with "%s"' % (actual,
+                                                                  reference)
             self.fail(self._formatMessage(msg, standardMsg))
 
     def assertCommandKeyValue(self, module, parameters, reference, sep,
                               msg=None):
         if isinstance(reference, basestring):
             reference = text_to_keyvalue(reference, sep=sep)
-        stdout = gcore.read_command(module, **parameters)
+        stdout = call_module(module, **parameters)
         raster_univar = text_to_keyvalue(stdout, sep=sep)
         if not compare_keyvalue(dict_a=reference, dict_b=raster_univar,
                                 a_is_subset=True):

Modified: sandbox/wenzeslaus/gunittest/gmodules.py
===================================================================
--- sandbox/wenzeslaus/gunittest/gmodules.py	2014-06-26 20:28:04 UTC (rev 60992)
+++ sandbox/wenzeslaus/gunittest/gmodules.py	2014-06-26 20:30:21 UTC (rev 60993)
@@ -81,51 +81,71 @@
         raise CalledModuleError(returncode, module, kwargs)
 
 
-def call_module(module, stdin=None, merge_stderr=False, **kwargs):
+def call_module(module, stdin=None,
+                merge_stderr=False, capture_stdout=True, capture_stderr=True,
+                **kwargs):
     r"""Run module with parameters given in `kwargs` and return its output.
 
     >>> print call_module('g.region', flags='pg')  # doctest: +ELLIPSIS
     n=...
     s=...
     w=...
+    >>> call_module('m.proj', flags='i', input='-', stdin="50.0 41.5")
+    '8642890.65|6965155.61|0.00\n'
     >>> call_module('g.region', aabbbccc='notexist')  # doctest: +IGNORE_EXCEPTION_DETAIL
     Traceback (most recent call last):
         ...
     CalledModuleError: Module run g.region ... ended with error
-    >>> call_module('m.proj', flags='i', input='-', stdin="50.0 41.5")
-    '8642890.65|6965155.61|0.00\n'
 
     If `stdin` is not set and `kwargs` contains ``input`` with value set
     to ``-`` (dash), the function raises an error.
 
+    Note that ``input`` nor ``output`` parameters are used by this
+    function itself, these are usually module parameters which this
+    function just passes to it. However, when ``input`` is in parameters
+    the function checks if its values is correct considering value of
+    ``stdin`` parameter.
+
     :param str module: module name
     :param stdin: string to be used as module standard input (stdin) or `None`
     :param merge_stderr: if the standard error output should be merged with stdout
     :param kwargs: module parameters
 
-    :returns: module standard output (stdout)
+    :returns: module standard output (stdout) as string or None if apture_stdout is False
 
     :raises CalledModuleError: if module return code is non-zero
     :raises ValueError: if the parameters are not correct
     """
+    # TODO: remove this:
+    do_doctest_gettext_workaround()
     # implemenation inspired by subprocess.check_output() function
     if stdin:
+        if 'input' in kwargs and kwargs['input'] != '-':
+            raise ValueError(_("input='-' must be used when stdin is specified"))
+        if stdin == subprocess.PIPE:
+            raise ValueError(_("stdin must be string or buffer, not PIPE"))
         kwargs['stdin'] = subprocess.PIPE  # to be able to send data to stdin
-    elif 'input' in kwargs and kwargs['input'] != '-':
-        raise ValueError(_("stdin must be set when input='-'"))
+    elif 'input' in kwargs and kwargs['input'] == '-':
+        raise ValueError(_("stdin must be used when input='-'"))
+    if merge_stderr and not (capture_stdout and capture_stderr):
+        raise ValueError(_("You cannot merge stdout and stderr and not capture them"))
     if 'stdout' in kwargs:
-        raise ValueError(_("stdout argument not allowed, it would be overridden"))
+        raise ValueError(_("stdout argument not allowed, it could be overridden"))
     if 'stderr' in kwargs:
-        raise ValueError(_("stderr argument not allowed, it would be overridden"))
+        raise ValueError(_("stderr argument not allowed, it could be overridden"))
 
-    kwargs['stdout'] = subprocess.PIPE
-    if merge_stderr:
-        kwargs['stderr'] = subprocess.STDOUT
-    else:
-        kwargs['stderr'] = subprocess.PIPE
+    if capture_stdout:
+        kwargs['stdout'] = subprocess.PIPE
+    if capture_stderr:
+        if merge_stderr:
+            kwargs['stderr'] = subprocess.STDOUT
+        else:
+            kwargs['stderr'] = subprocess.PIPE
     process = start_command(module, **kwargs)
     # input=None means no stdin (our default)
-    # for stderr=STDOUT errors in None which is fine for CalledModuleError
+    # for no stdout, output is None which is out interface
+    # for stderr=STDOUT or no stderr, errors is None
+    # which is fine for CalledModuleError
     output, errors = process.communicate(input=stdin)
     returncode = process.poll()
     if returncode:

Added: sandbox/wenzeslaus/gunittest/testsuite/test_gmodules.py
===================================================================
--- sandbox/wenzeslaus/gunittest/testsuite/test_gmodules.py	                        (rev 0)
+++ sandbox/wenzeslaus/gunittest/testsuite/test_gmodules.py	2014-06-26 20:30:21 UTC (rev 60993)
@@ -0,0 +1,93 @@
+# -*- coding: utf-8 -*-
+
+import os
+import sys
+import subprocess
+
+# this should be solved on the level of the testing framework
+sys.path.insert(0, os.path.split(os.path.split((os.path.dirname(__file__)))[0])[0])
+
+from gunittest.case import GrassTestCase
+from gunittest.gmodules import call_module, CalledModuleError
+
+G_REGION_OUTPUT = """n=...
+s=...
+w=...
+e=...
+nsres=...
+ewres=...
+rows=...
+cols=...
+cells=...
+"""
+
+
+class TestCallModuleFunction(GrassTestCase):
+
+    def test_output(self):
+        output = call_module('g.region', flags='pg')
+        self.assertLooksLike(output, G_REGION_OUTPUT)
+
+    def test_input_output(self):
+        output = call_module('m.proj', flags='i', input='-', stdin="50.0 41.5")
+        self.assertLooksLike(output, '...|...\n')
+
+    def test_no_output(self):
+        output = call_module('m.proj', flags='i', input='-', stdin="50.0 41.5",
+                             capture_stdout=False)
+        self.assertIsNone(output)
+
+    def test_merge_stderr(self):
+        output = call_module('m.proj', flags='i', input='-', stdin="50.0 41.5",
+                             verbose=True,
+                             merge_stderr=True)
+        self.assertLooksLike(output, '...+proj=longlat +datum=WGS84...')
+        self.assertLooksLike(output, '...|...\n')
+
+    def test_merge_stderr_with_wrong_stdin_stderr(self):
+        self.assertRaises(ValueError,
+                          call_module,
+                          'm.proj', flags='i', input='-', stdin="50.0 41.5",
+                          verbose=True,
+                          merge_stderr=True, capture_stdout=False)
+        self.assertRaises(ValueError,
+                          call_module,
+                          'm.proj', flags='i', input='-', stdin="50.0 41.5",
+                          verbose=True,
+                          merge_stderr=True, capture_stderr=False)
+        self.assertRaises(ValueError,
+                          call_module,
+                          'm.proj', flags='i', input='-', stdin="50.0 41.5",
+                          verbose=True,
+                          merge_stderr=True,
+                          capture_stdout=False, capture_stderr=False)
+
+    def test_wrong_module_params(self):
+        self.assertRaises(CalledModuleError,
+                          call_module,
+                          'g.region', aabbbccc='notexist')
+
+    def test_module_input_param_wrong(self):
+        self.assertRaises(ValueError,
+                          call_module,
+                          'm.proj', flags='i', input='does_not_exist',
+                          stdin="50.0 41.5")
+
+    def test_missing_stdin_with_input_param(self):
+        self.assertRaises(ValueError,
+                          call_module,
+                          'm.proj', flags='i', input='-')
+
+    def test_wrong_usage_of_popen_like_interface(self):
+        self.assertRaises(ValueError,
+                          call_module,
+                          'm.proj', flags='i', input='-',
+                          stdin=subprocess.PIPE)
+        self.assertRaises(ValueError,
+                          call_module,
+                          'm.proj', flags='i', input='-',
+                          stdout='any_value_or_type_here')
+        self.assertRaises(ValueError,
+                          call_module,
+                          'm.proj', flags='i', input='-',
+                          stderr='any_value_or_type_here')


Property changes on: sandbox/wenzeslaus/gunittest/testsuite/test_gmodules.py
___________________________________________________________________
Added: svn:mime-type
   + text/x-python
Added: svn:eol-style
   + native



More information about the grass-commit mailing list