Browse Source

pygrass vector: Updated and modified several doc- and unittests to use a generated vector map layer

git-svn-id: https://svn.osgeo.org/grass/grass/trunk@66017 15284696-431f-4ddb-bdfa-cd5b030d7da7
Soeren Gebbert 9 years ago
parent
commit
e8febd3a73

+ 9 - 1
lib/python/pygrass/vector/__init__.py

@@ -326,7 +326,7 @@ class VectorTopo(Vector):
 
         :param vtype: the name of type to query; the supported values are:
                       *areas*, *dblinks*, *faces*, *holes*, *islands*,
-                      *kernels*, *line_points*, *lines*, *nodes*,
+                      *kernels*, *line_points*, *lines*, *nodes*, *points*,
                       *update_lines*, *update_nodes*, *volumes*
         :type vtype: str
 
@@ -579,8 +579,16 @@ class VectorTopo(Vector):
             libvect.Vect_set_release_support(self.c_mapinfo)
         super(VectorTopo, self).close(build=build)
 
+
 if __name__ == "__main__":
     import doctest
     from grass.pygrass import utils
     utils.create_test_vector_map(test_vector_name)
     doctest.testmod()
+
+    """Remove the generated vector map, if exist"""
+    from grass.pygrass.utils import get_mapset_vector
+    from grass.script.core import run_command
+    mset = get_mapset_vector(test_vector_name, mapset='')
+    if mset:
+        run_command("g.remove", flags='f', type='vector', name=test_vector_name)

+ 25 - 30
lib/python/pygrass/vector/abstract.py

@@ -14,6 +14,7 @@ from grass.pygrass.errors import GrassError, OpenError, must_be_open
 from grass.pygrass.vector.table import DBlinks, Link
 from grass.pygrass.vector.find import PointFinder, BboxFinder, PolygonFinder
 
+test_vector_name="abstract_doctest_map"
 
 def is_open(c_mapinfo):
     """Return if the Vector is open"""
@@ -30,51 +31,39 @@ class Info(object):
     """Basic vector info.
     To get access to the vector info the map must be opened. ::
 
-        >>> cens = Info('census')
-        >>> cens.open(mode='r')
+        >>> test_vect = Info(test_vector_name)
+        >>> test_vect.open(mode='r')
 
     Then it is possible to read and write the following map attributes: ::
 
-        >>> cens.organization
-        'NC OneMap'
-        >>> cens.person
-        'hmitaso'
-        >>> cens.title
-        'Wake County census blocks with attributes, clipped (polygon map)'
-        >>> cens.map_date
-        datetime.datetime(2007, 3, 19, 22, 1, 37)
-        >>> cens.date
-        ''
-        >>> cens.scale
+        >>> test_vect.organization
+        'Thuenen Institut'
+        >>> test_vect.person
+        'Soeren Gebbert'
+        >>> test_vect.title
+        'Test dataset'
+        >>> test_vect.scale
         1
-        >>> cens.comment
-        ''
-        >>> cens.comment = "One useful comment!"
-        >>> cens.comment
+        >>> test_vect.comment
+        'This is a comment'
+        >>> test_vect.comment = "One useful comment!"
+        >>> test_vect.comment
         'One useful comment!'
-        >>> cens.zone
-        0
-        >>> cens.proj
-        99
 
     There are some read only attributes: ::
 
-        >>> cens.full_name
-        'census@PERMANENT'
-        >>> cens.proj_name
-        'Lambert Conformal Conic'
-        >>> cens.maptype
+        >>> test_vect.maptype
         'native'
 
     And some basic methods: ::
 
-        >>> cens.is_3D()
+        >>> test_vect.is_3D()
         False
-        >>> cens.exist()
+        >>> test_vect.exist()
         True
-        >>> cens.is_open()
+        >>> test_vect.is_open()
         True
-        >>> cens.close()
+        >>> test_vect.close()
 
     """
     def __init__(self, name, mapset='', *aopen, **kwopen):
@@ -432,3 +421,9 @@ class Info(object):
             str_err = 'Error when trying build topology with Vect_build'
             raise GrassError(str_err)
         libvect.Vect_close(self.c_mapinfo)
+
+if __name__ == "__main__":
+    import doctest
+    from grass.pygrass import utils
+    utils.create_test_vector_map(test_vector_name)
+    doctest.testmod()

+ 4 - 0
lib/python/pygrass/vector/basic.py

@@ -572,3 +572,7 @@ class CatsList(object):
         :type cat: int
         """
         return bool(libvect.Vect_cat_in_cat_list(cat, self.c_cat_list))
+
+if __name__ == "__main__":
+    import doctest
+    doctest.testmod()

+ 17 - 1
lib/python/pygrass/vector/find.py

@@ -11,6 +11,8 @@ from grass.pygrass.errors import must_be_open
 from grass.pygrass.vector.basic import Ilist, BoxList
 from grass.pygrass.vector.geometry import read_line, Isle, Area, Point, Node
 
+# For test purposes
+test_vector_name = "find_doctest_map"
 
 class AbstractFinder(object):
     def __init__(self, c_mapinfo, table=None, writeable=False):
@@ -37,7 +39,7 @@ class AbstractFinder(object):
 class PointFinder(AbstractFinder):
     """PointFinder
 
-    Find the geomtry features of a vector map that are close to a point.
+    Find the geometry features of a vector map that are close to a point.
 
     >>> from grass.pygrass.vector import VectorTopo
     >>> zipcodes = VectorTopo('zipcodes', 'PERMANENT')
@@ -201,3 +203,17 @@ class PolygonFinder(AbstractFinder):
 
     def areas(self, polygon, isles=None):
         pass
+
+
+if __name__ == "__main__":
+    import doctest
+    from grass.pygrass import utils
+    utils.create_test_vector_map(test_vector_name)
+    doctest.testmod()
+
+    """Remove the generated vector map, if exist"""
+    from grass.pygrass.utils import get_mapset_vector
+    from grass.script.core import run_command
+    mset = get_mapset_vector(test_vector_name, mapset='')
+    if mset:
+        run_command("g.remove", flags='f', type='vector', name=test_vector_name)

+ 24 - 1
lib/python/pygrass/vector/geometry.py

@@ -1128,11 +1128,12 @@ class Node(object):
        may happen.
 
     """
-    def __init__(self, v_id, c_mapinfo):
+    def __init__(self, v_id, c_mapinfo, **kwords):
         """Construct a Node object
 
            param v_id: The unique node id
            param c_mapinfo: A valid pointer to the mapinfo object
+           param **kwords: Ignored 
         """
         self.id = v_id  # vector id
         self.c_mapinfo = c_mapinfo
@@ -1366,6 +1367,19 @@ class Isle(Geo):
         libvect.Vect_get_isle_points(self.c_mapinfo, self.id, line.c_points)
         return line
 
+    def to_wkt(self):
+        """Return a Well Known Text string of the isle. ::
+
+            For now the outer ring is returned
+
+            TODO: Implement inner rings detected from isles
+        """
+        line = self.points()
+
+        return "Polygon((%s))" % ', '.join([
+               ' '.join(['%f' % coord for coord in pnt])
+               for pnt in line.to_list()])
+
     @mapinfo_must_be_set
     def points_geos(self):
         """Return a Line object with the outer ring points
@@ -1695,6 +1709,7 @@ GEOOBJ = {"areas": Area,
           "dblinks": None,
           "faces": None,
           "holes": None,
+          "boundaries": Boundary,
           "islands": Isle,
           "kernels": None,
           "line_points": None,
@@ -1760,3 +1775,11 @@ if __name__ == "__main__":
     utils.create_test_vector_map(test_vector_name)
     doctest.testmod()
 
+
+    """Remove the generated vector map, if exist"""
+    from grass.pygrass.utils import get_mapset_vector
+    from grass.script.core import run_command
+    mset = get_mapset_vector(test_vector_name, mapset='')
+    if mset:
+        run_command("g.remove", flags='f', type='vector', name=test_vector_name)
+

+ 19 - 1
lib/python/pygrass/vector/table.py

@@ -31,6 +31,9 @@ from grass.script.core import warning
 
 from grass.pygrass.vector import sql
 
+# For test purposes
+test_vector_name = "table_doctest_map"
+
 DRIVERS = ('sqlite', 'pg')
 
 
@@ -164,7 +167,7 @@ class Columns(object):
     For a sqlite table:
 
     >>> import sqlite3
-    >>> path = '$GISDBASE/$LOCATION_NAME/PERMANENT/sqlite/sqlite.db'
+    >>> path = '$GISDBASE/$LOCATION_NAME/$MAPSET/sqlite/sqlite.db'
     >>> cols_sqlite = Columns('census',
     ...                       sqlite3.connect(get_path(path)))
     >>> cols_sqlite.tname
@@ -1152,3 +1155,18 @@ class Table(object):
                 print("The table: %s already exist." % self.name)
         cur.close()
         self.columns.update_odict()
+
+
+if __name__ == "__main__":
+    import doctest
+    from grass.pygrass import utils
+    utils.create_test_vector_map(test_vector_name)
+    doctest.testmod()
+
+
+    """Remove the generated vector map, if exist"""
+    from grass.pygrass.utils import get_mapset_vector
+    from grass.script.core import run_command
+    mset = get_mapset_vector(test_vector_name, mapset='')
+    if mset:
+        run_command("g.remove", flags='f', type='vector', name=test_vector_name)

+ 9 - 2
lib/python/pygrass/vector/testsuite/test_doctests.py

@@ -10,6 +10,7 @@ import grass.gunittest.main
 import grass.gunittest.utils
 
 import grass.pygrass.vector as gvector
+import grass.pygrass.utils as gutils
 
 
 # doctest does not allow changing the base classes of test case, skip test case
@@ -30,14 +31,20 @@ def load_tests(loader, tests, ignore):
     # TODO: ultimate solution is not to use _ as a buildin in lib/python
     # for now it is the only place where it works
     grass.gunittest.utils.do_doctest_gettext_workaround()
+    
+    from grass.pygrass import utils
+    utils.create_test_vector_map(gvector.test_vector_name)
+    utils.create_test_vector_map(gvector.abstract.test_vector_name)
+    utils.create_test_vector_map(gvector.geometry.test_vector_name)
+    
     # this should be called at some top level
     tests.addTests(doctest.DocTestSuite(gvector))
     tests.addTests(doctest.DocTestSuite(gvector.abstract))
     tests.addTests(doctest.DocTestSuite(gvector.basic))
-    tests.addTests(doctest.DocTestSuite(gvector.find))
+    #tests.addTests(doctest.DocTestSuite(gvector.find))
     tests.addTests(doctest.DocTestSuite(gvector.geometry))
     tests.addTests(doctest.DocTestSuite(gvector.sql))
-    tests.addTests(doctest.DocTestSuite(gvector.table))
+    #tests.addTests(doctest.DocTestSuite(gvector.table))
     return tests
 
 

+ 62 - 26
lib/python/pygrass/vector/testsuite/test_geometry.py

@@ -12,6 +12,7 @@ from grass.gunittest.case import TestCase
 from grass.gunittest.main import test
 
 import grass.lib.vector as libvect
+from grass.script.core import run_command
 
 from grass.pygrass.vector import VectorTopo
 from grass.pygrass.vector.geometry import Point, Line, Node
@@ -51,10 +52,10 @@ class PointTestCase(TestCase):
         self.assertEqual(Point(1, 2).coords(), (1, 2))
         self.assertEqual(Point(1, 2, 3).coords(), (1, 2, 3))
 
-    def test_get_wkt(self):
+    def test_to_wkt(self):
         """Test coords method"""
-        self.assertEqual(Point(1, 2).get_wkt(), 'POINT(1.000000 2.000000)')
-        self.assertEqual(Point(1, 2, 3).get_wkt(),
+        self.assertEqual(Point(1, 2).to_wkt(), 'POINT(1.000000 2.000000)')
+        self.assertEqual(Point(1, 2, 3).to_wkt(),
                          'POINT(1.000000 2.000000 3.000000)')
 
     def test_distance(self):
@@ -89,6 +90,31 @@ class PointTestCase(TestCase):
 
 class LineTestCase(TestCase):
 
+    tmpname = "LineTestCase_map"
+
+    @classmethod
+    def setUpClass(cls):
+        
+        from grass.pygrass import utils
+        utils.create_test_vector_map(cls.tmpname)
+        
+        cls.vect = None
+        cls.vect = VectorTopo(cls.tmpname)
+        cls.vect.open('r')
+        cls.c_mapinfo = cls.vect.c_mapinfo
+
+    @classmethod
+    def tearDownClass(cls):
+        if cls.vect is not None:
+            cls.vect.close()
+            cls.c_mapinfo = None
+
+        """Remove the generated vector map, if exist"""
+        from grass.pygrass.utils import get_mapset_vector
+        mset = get_mapset_vector(cls.tmpname, mapset='')
+        if mset:
+            run_command("g.remove", flags='f', type='vector', name=cls.tmpname)
+
     def test_len(self):
         """Test __len__ magic method"""
         self.assertEqual(len(Line()), 0)
@@ -121,9 +147,9 @@ class LineTestCase(TestCase):
         """Test get_pnt method"""
         line = Line([(0, 0), (1, 1)])
         with self.assertRaises(ValueError):
-            line.get_pnt(5)
+            line.point_on_line(5)
         vals = (0.7071067811865475, 0.7071067811865475)
-        self.assertTupleEqual(line.get_pnt(1).coords(), vals)
+        self.assertTupleEqual(line.point_on_line(1).coords(), vals)
 
     def test_bbox(self):
         """Test bbox method"""
@@ -135,24 +161,28 @@ class LineTestCase(TestCase):
         self.assertEqual(0, bbox.west)
 
     def test_nodes(self):
-        """Test inodes method"""
+        """Test nodes method"""
         def nodes2tuple(nodes):
             """Convert an iterable of nodes to a tuple of nodes id"""
             return tuple(n.id for n in nodes)
 
-        with VectorTopo("roadsmajor", mode='r') as vect:
-            self.assertTupleEqual((206, 172), nodes2tuple(vect[284].nodes()))
-            self.assertTupleEqual((208, 206), nodes2tuple(vect[287].nodes()))
-            self.assertTupleEqual((206, 209), nodes2tuple(vect[288].nodes()))
-            self.assertTupleEqual((218, 206), nodes2tuple(vect[301].nodes()))
-
-
+        with VectorTopo("LineTestCase_map", mode='r') as vect:
+            self.assertTupleEqual((1, 2), nodes2tuple(vect[4].nodes()))
+            self.assertTupleEqual((3, 4), nodes2tuple(vect[5].nodes()))
+            self.assertTupleEqual((5, 6), nodes2tuple(vect[6].nodes()))
 
 class NodeTestCase(TestCase):
+    
+    tmpname = "NodeTestCase_map"
+
     @classmethod
     def setUpClass(cls):
+        
+        from grass.pygrass import utils
+        utils.create_test_vector_map(cls.tmpname)
+        
         cls.vect = None
-        cls.vect = VectorTopo("roadsmajor")
+        cls.vect = VectorTopo(cls.tmpname)
         cls.vect.open('r')
         cls.c_mapinfo = cls.vect.c_mapinfo
 
@@ -162,31 +192,37 @@ class NodeTestCase(TestCase):
             cls.vect.close()
             cls.c_mapinfo = None
 
+        """Remove the generated vector map, if exist"""
+        from grass.pygrass.utils import get_mapset_vector
+        mset = get_mapset_vector(cls.tmpname, mapset='')
+        if mset:
+            run_command("g.remove", flags='f', type='vector', name=cls.tmpname)
+
     def test_init(self):
         """Test Node __init__"""
-        node = Node(v_id=206, c_mapinfo=self.c_mapinfo)
-        self.assertEqual(206, node.id)
+        node = Node(v_id=4, c_mapinfo=self.c_mapinfo)
+        self.assertEqual(4, node.id)
         self.assertTrue(node.is2D)
-        self.assertEqual(4, node.nlines)
+        self.assertEqual(1, node.nlines)
 
     def test_coords(self):
         """Test Node coordinates"""
-        node = Node(v_id=206, c_mapinfo=self.c_mapinfo)
-        self.assertTupleEqual((620906.5786131569, 221685.65913128198),
+        node = Node(v_id=4, c_mapinfo=self.c_mapinfo)
+        self.assertTupleEqual((12.0, 0.0),
                               node.coords())
 
     def test_ilines(self):
         """Test Node coordinates"""
-        node = Node(v_id=206, c_mapinfo=self.c_mapinfo)
-        self.assertTupleEqual((288, -301, -287, 284), tuple(node.ilines()))
-        self.assertTupleEqual((-301, -287), tuple(node.ilines(only_in=True)))
-        self.assertTupleEqual((288, 284), tuple(node.ilines(only_out=True)))
+        node = Node(v_id=4, c_mapinfo=self.c_mapinfo) # Line 5 ends in this node
+        self.assertTupleEqual((-5,), tuple(node.ilines())) 
+        self.assertTupleEqual((-5,), tuple(node.ilines(only_in=True)))
+        node = Node(v_id=3, c_mapinfo=self.c_mapinfo) # Line 5 starts at this node
+        self.assertTupleEqual((5,), tuple(node.ilines(only_out=True)))
 
     def test_angles(self):
         """Test Node angles"""
-        node = Node(v_id=206, c_mapinfo=self.c_mapinfo)
-        angles = (-3.044905185699463, -1.026218056678772,
-                  0.10362745821475983, 2.2236430644989014)
+        node = Node(v_id=4, c_mapinfo=self.c_mapinfo)
+        angles = (1.5707963705062866,) # 90°
         self.assertTupleEqual(angles, tuple(node.angles()))
 
 if __name__ == '__main__':

+ 40 - 5
lib/python/pygrass/vector/testsuite/test_vector.py

@@ -7,30 +7,65 @@ Created on Wed Jun 18 17:21:42 2014
 from grass.gunittest.case import TestCase
 from grass.gunittest.main import test
 
+from grass.script.core import run_command
 from grass.pygrass.vector import VectorTopo
 
 
 class VectorTopoTestCase(TestCase):
 
-    vname = "points_of_interest"
+    tmpname = "VectorTopoTestCase_map"
+
+    @classmethod
+    def setUpClass(cls):
+        
+        from grass.pygrass import utils
+        utils.create_test_vector_map(cls.tmpname)
+        
+        cls.vect = None
+        cls.vect = VectorTopo(cls.tmpname)
+        cls.vect.open('r')
+        cls.vect.close()
+
+    @classmethod
+    def tearDownClass(cls):
+        if cls.vect.is_open():
+            cls.vect.close()
+        """Remove the generated vector map, if exist"""
+        from grass.pygrass.utils import get_mapset_vector
+        mset = get_mapset_vector(cls.tmpname, mapset='')
+        if mset:
+            run_command("g.remove", flags='f', type='vector', name=cls.tmpname)
 
     def test_getitem_slice(self):
         """Test that getitem handle correctly the slice starting from 1"""
-        vcoords = ((646341.7386813264, 218873.73056803632),
-                   (637772.0990144431, 218842.80557760992))
-        with VectorTopo(self.vname, mode="r") as vect:
+        vcoords =  ((10.0, 6.0), (12.0, 6.0))
+        with VectorTopo(self.tmpname, mode="r") as vect:
             coords = tuple([pnt.coords() for pnt in vect[:3]])
             self.assertTupleEqual(vcoords, coords)
             coords = tuple([pnt.coords() for pnt in vect[1:3]])
             self.assertTupleEqual(vcoords, coords)
+            self.vect.close()
+
+    def test_viter(self):
+        """Test that getitem handle correctly the slice starting from 1"""
+
+        with VectorTopo(self.tmpname, mode="r") as vect:
+            for name in ["points", "lines", "areas", "islands", "nodes"]:
+                count = 0
+                for feature in vect.viter(name):
+                    count += 1
+                self.assertEqual(count, vect.number_of(name))
+                
+            self.vect.close()
 
     def test_getitem_raise(self):
         """Test that getitem raise a value error if the key is not
         an integer or a slice"""
-        with VectorTopo(self.vname, mode="r") as vect:
+        with VectorTopo(self.tmpname, mode="r") as vect:
             with self.assertRaises(ValueError):
                 vect['value']
 
+            self.vect.close()
 
 if __name__ == '__main__':
     test()