[GRASS-SVN] r64637 - in grass/trunk/lib/python/gunittest: . testsuite

svn_grass at osgeo.org svn_grass at osgeo.org
Sat Feb 14 20:54:48 PST 2015


Author: wenzeslaus
Date: 2015-02-14 20:54:48 -0800 (Sat, 14 Feb 2015)
New Revision: 64637

Modified:
   grass/trunk/lib/python/gunittest/case.py
   grass/trunk/lib/python/gunittest/gutils.py
   grass/trunk/lib/python/gunittest/testsuite/test_assertions.py
Log:
gunittest: functions to test existence of raster, 3D raster and vector

Using g.findfile because it is faster than g.list but translating the g.list names to g.findfile names. Including tests of basic functionality of the assert functions.


Modified: grass/trunk/lib/python/gunittest/case.py
===================================================================
--- grass/trunk/lib/python/gunittest/case.py	2015-02-15 03:56:24 UTC (rev 64636)
+++ grass/trunk/lib/python/gunittest/case.py	2015-02-15 04:54:48 UTC (rev 64637)
@@ -23,6 +23,7 @@
                        text_to_keyvalue, keyvalue_equals, diff_keyvalue,
                        file_md5, files_equal_md5)
 from .utils import safe_repr
+from .gutils import is_map_in_mapset
 
 
 class TestCase(unittest.TestCase):
@@ -189,7 +190,7 @@
             if mismatch:
                 stdMsg = "%s difference:\n" % module
                 stdMsg += "mismatch values"
-                stdMsg += "(key, reference, actual): %s\n" % mismatch
+                stdMsg += " (key, reference, actual): %s\n" % mismatch
                 stdMsg += 'command: %s %s' % (module, parameters)
             else:
                 # we can probably remove this once we have more tests
@@ -451,14 +452,45 @@
                           a=actual['max'], r=refmax, m=map, o=actual['min']))
             self.fail(self._formatMessage(msg, stdmsg))
 
+    def _get_detailed_message_about_no_map(self, name, type):
+        msg = ("There is no map <{n}> of type <{t}>"
+               " in the current mapset".format(n=name, t=type))
+        related = call_module('g.list', type='raster,raster3d,vector',
+                              flags='imt', pattern='*' + name + '*')
+        if related:
+            msg += "\nSee available maps:\n"
+            msg += related
+        else:
+            msg += "\nAnd there are no maps containing the name anywhere\n"
+        return msg
+
+    def assertRasterExists(self, name, msg=None):
+        """Checks if the raster map exists in current mapset"""
+        if not is_map_in_mapset(name, type='raster'):
+            stdmsg = self._get_detailed_message_about_no_map(name, 'raster')
+            self.fail(self._formatMessage(msg, stdmsg))
+
+    def assertRaster3dExists(self, name, msg=None):
+        """Checks if the 3D raster map exists in current mapset"""
+        if not is_map_in_mapset(name, type='raster3d'):
+            stdmsg = self._get_detailed_message_about_no_map(name, 'raster3d')
+            self.fail(self._formatMessage(msg, stdmsg))
+
+    def assertVectorExists(self, name, msg=None):
+        """Checks if the vector map exists in current mapset"""
+        if not is_map_in_mapset(name, type='vector'):
+            stdmsg = self._get_detailed_message_about_no_map(name, 'vector')
+            self.fail(self._formatMessage(msg, stdmsg))
+
     def assertFileExists(self, filename, msg=None,
                          skip_size_check=False, skip_access_check=False):
         """Test the existence of a file.
 
         .. note:
             By default this also checks if the file size is greater than 0
-            since we rarely want a file to be empty. And it also checks
-            if the file is access for reading.
+            since we rarely want a file to be empty. It also checks
+            if the file is accessible for reading since we expect that user
+            wants to look at created files.
         """
         if not os.path.isfile(filename):
             stdmsg = 'File %s does not exist' % filename

Modified: grass/trunk/lib/python/gunittest/gutils.py
===================================================================
--- grass/trunk/lib/python/gunittest/gutils.py	2015-02-15 03:56:24 UTC (rev 64636)
+++ grass/trunk/lib/python/gunittest/gutils.py	2015-02-15 04:54:48 UTC (rev 64637)
@@ -9,8 +9,50 @@
 :authors: Vaclav Petras
 """
 
+from grass.script.core import start_command, PIPE
+
 from .gmodules import call_module
+from .checkers import text_to_keyvalue
 
+
 def get_current_mapset():
     """Get curret mapset name as a string"""
     return call_module('g.mapset', flags='p').strip()
+
+def is_map_in_mapset(name, type, mapset=None):
+    """Check is map is present in the mapset (current mapset by default)
+
+    This function is different from what we would expect in GRASS
+    because it cares only about specific mapset, the current one by default,
+    and it does not care that the map is accessible in other mapset.
+
+    :param name: name of the map
+    :param type: data type ('raster', 'raster3d', and 'vector') 
+    """
+    if not mapset:
+        mapset = get_current_mapset()
+
+    # change type to element used by find file
+    # otherwise, we are not checking the input,
+    # so anything accepted by g.findfile will work but this can change in the
+    # future (the documentation is clear about what's legal)
+    # supporting both short and full names
+    if type == 'rast' or  type == 'raster':
+        type = 'cell'
+    elif type == 'rast3d' or type == 'raster3d':
+        type = 'grid3'
+    elif type == 'vect':
+        type = 'vector'
+    # g.findfile returns non-zero when file was not found
+    # se we ignore return code and just focus on stdout
+    process = start_command('g.findfile', flags='n',
+                            element=type, file=name, mapset=mapset,
+                            stdout=PIPE, stderr=PIPE)
+    output, errors = process.communicate()
+    info = text_to_keyvalue(output, sep='=')
+    # file is the key questioned in grass.script.core find_file()
+    # return code should be equivalent to checking the output
+    if info['file']:
+        return True
+    else:
+        return False

Modified: grass/trunk/lib/python/gunittest/testsuite/test_assertions.py
===================================================================
--- grass/trunk/lib/python/gunittest/testsuite/test_assertions.py	2015-02-15 03:56:24 UTC (rev 64636)
+++ grass/trunk/lib/python/gunittest/testsuite/test_assertions.py	2015-02-15 04:54:48 UTC (rev 64637)
@@ -189,6 +189,68 @@
                           msg="The difference of different maps should have huge mean")
 
 
+class TestMapExistsAssertions(grass.gunittest.TestCase):
+    # pylint: disable=R0904
+
+    raster_cell = 'TestMapExistsAssertions_raster_cell'
+    raster_dcell = 'TestMapExistsAssertions_raster_dcell'
+    raster3d = 'TestMapExistsAssertions_raster3D'
+    vector = 'TestMapExistsAssertions_vector'
+
+    @classmethod
+    def setUpClass(cls):
+        cls.use_temp_region()
+        cls.runModule('g.region', n=10, e=10, s=0, w=0, t=10, b=0, res=1)
+        cls.runModule('r.mapcalc', expression=cls.raster_cell + ' = 1')
+        cls.runModule('r.mapcalc', expression=cls.raster_dcell + ' = 1.0')
+        cls.runModule('r3.mapcalc', expression=cls.raster3d + ' = 1.0')
+        cls.runModule('v.edit', map=cls.vector, tool='create')
+
+    @classmethod
+    def tearDownClass(cls):
+        cls.runModule('g.remove', flags='f',
+                      type=['raster', 'raster3d', 'vector'],
+                      name=[cls.raster_cell, cls.raster_dcell,
+                            cls.raster3d, cls.vector])
+        cls.del_temp_region()
+
+    def test_rast_cell_exists(self):
+        self.assertRasterExists(self.raster_cell)
+
+    def test_rast_dcell_exists(self):
+        self.assertRasterExists(self.raster_dcell)
+
+    def test_rast_does_not_exist(self):
+        self.assertRaises(self.failureException,
+                          self.assertRasterExists,
+                          'does_not_exists')
+
+    def test_rast3d_exists(self):
+        self.assertRaster3dExists(self.raster3d)
+
+    def test_rast3d_does_not_exist(self):
+        self.assertRaises(self.failureException,
+                          self.assertRaster3dExists,
+                          'does_not_exists')
+
+    def test_vect_exists(self):
+        self.assertVectorExists(self.vector)
+
+    def test_vect_does_not_exist(self):
+        self.assertRaises(self.failureException,
+                          self.assertVectorExists,
+                          'does_not_exists')
+
+    def test_rast_does_not_exist_in_current_mapset(self):
+		# expecting that there is elevation in PERMANENT
+		# TODO: use skip decorator
+		# TODO: add the same tests but for vect and rast3d
+        self.assertRaises(self.failureException,
+                          self.assertRasterExists,
+                          'elevation',
+                          msg="Rasters from different mapsets should be ignored")
+
+
 class TestFileAssertions(grass.gunittest.TestCase):
     # pylint: disable=R0904
 



More information about the grass-commit mailing list