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

Annotation of /branches/WIP-pyshapelib-bramz/test/test_postgis_db.py

Parent Directory Parent Directory | Revision Log Revision Log


Revision 2096 - (hide annotations)
Thu Mar 11 13:50:53 2004 UTC (20 years, 11 months ago) by bh
Original Path: trunk/thuban/test/test_postgis_db.py
File MIME type: text/x-python
File size: 34017 byte(s)
* Thuban/Model/postgisdb.py (PostGISTable.__init__): New parameter
id_column to specify which column to use to identify rows.  Also
new instance variables id_column and quoted_id_column
(PostGISTable.RowIdToOrdinal, PostGISTable.RowOrdinalToId)
(PostGISTable.ReadRowAsDict, PostGISTable.ReadValue)
(PostGISTable.SimpleQuery): Use the id column name provided to the
constructor instead of "gid"
(PostGISShapeStore.__init__): New parameter id_column analogously
to PostGISTable.__init__.  This parameter is simply passed through
to the base class constructor
(PostGISShapeStore._create_col_from_description): Fix typo in
doc-string
(PostGISShapeStore.Shape, PostGISShapeStore.AllShapes)
(PostGISShapeStore.ShapesInRegion): Use the id column name
provided to the constructor instead of "gid"

* test/postgissupport.py
(PostgreSQLServer.get_default_static_data_db): New static table
landmarks_point_id with an id column != "gid.  Update the comments
a bit.
(skip_if_addgeometrycolumn_does_not_use_quote_ident): Fix typo in
doc-
(upload_shapefile): New parameter gid_column to use a name other
than "gid" for the column to store the shape ids

* test/test_postgis_db.py (TableTests): New.  Mixin-class
containing all tests previously in TestPostGISTable.  The actual
tests are the same but the code is a bit more configurable to
allow for different id columns etc.
(TestPostGISTable): Derive from TableTests now for the actual
tests.
(TestPostGISTableExplicitGIDColumn): New. Like TestPostGISTable
except that it the landmarks_point_id table to test the id_column
parameter
(PointTests): Extend the doc-string
(TestPostGISShapestorePointExplicitGIDColumn)
(TestPostGISShapestorePointOIDAsGIDColumn): New classes derived
from PointTests to test the explicit id_column parameter.  One
tests with the name of the column holding the shape ids, the other
uses PostgreSQL's OID column.  For the latter a number of methods
have to be overwritten to make them independent of the actual id
values.

1 bh 2057 # Copyright (C) 2003, 2004 by Intevation GmbH
2 bh 1605 # Authors:
3     # Bernhard Herzog <[email protected]>
4     #
5     # This program is free software under the GPL (>=v2)
6     # Read the file COPYING coming with the software for details.
7    
8     """Test for Thuban.Model.postgisdb"""
9    
10     import os
11     import unittest
12    
13    
14     try:
15     import psycopg
16     except ImportError:
17     # No psycopg available. Nothing to be done here because the
18     # postgis.py support module determines this too and the tests will
19     # be skipped completely.
20     pass
21    
22     import postgissupport
23    
24     import support
25     support.initthuban()
26    
27 bh 1636 from Thuban.Model.postgisdb import ConnectionError, PostGISConnection, \
28     PostGISTable, PostGISShapeStore
29 bh 1605 from Thuban.Model.table import FIELDTYPE_INT, FIELDTYPE_STRING, \
30     FIELDTYPE_DOUBLE
31     from Thuban.Model.data import SHAPETYPE_POINT, SHAPETYPE_POLYGON, \
32     SHAPETYPE_ARC, RAW_WKT
33    
34    
35 bh 1620 class NonConnection(PostGISConnection):
36    
37     """Special connection class that doesn't actually connect"""
38    
39     def connect(self):
40     pass
41    
42    
43    
44 bh 1957 class TestPostGISSimple(unittest.TestCase):
45 bh 1620
46 bh 1957 """Some simple PostGISConnection tests that don't need a real connection"""
47    
48     def test_brief_description(self):
49 bh 1620 """Test PostGISConnection.BriefDescription()"""
50     self.assertEquals(NonConnection("somedb").BriefDescription(),
51     "postgis://@:/somedb")
52     self.assertEquals(NonConnection("db", host="here",
53     port="123").BriefDescription(),
54     "postgis://@here:123/db")
55     self.assertEquals(NonConnection("db", user="me",
56     port="123").BriefDescription(),
57     "postgis://me@:123/db")
58    
59 bh 1957 def test_matches_parameters(self):
60     """Test PostGISConnection.MatchesParameters()"""
61     def do_test(testfn, conn, host = "", port="", dbname = "", user = ""):
62     testfn(conn.MatchesParameters({"host": host, "port": port,
63     "dbname": dbname, "user": user}))
64 bh 1620
65 bh 1957 do_test(self.assert_, NonConnection("somedb"),
66     dbname="somedb")
67     do_test(self.assert_, NonConnection("somedb", host="here"),
68     dbname="somedb", host="here")
69     do_test(self.assert_, NonConnection("db", user="me", port="123"),
70     dbname="db", port="123", user="me")
71    
72     do_test(self.failIf, NonConnection("somedb"),
73     dbname="someotherdb")
74     do_test(self.failIf, NonConnection("somedb", host="here"),
75     dbname="somedb", host="here", port="765")
76     do_test(self.failIf, NonConnection("db", user="me", port="123"),
77     dbname="db", port="123", user="you")
78    
79    
80 bh 1605 class TestPostGISConnection(unittest.TestCase):
81    
82     def setUp(self):
83     """Start the server and create a database.
84    
85     The database name will be stored in self.dbname, the server
86     object in self.server and the db object in self.db.
87     """
88     postgissupport.skip_if_no_postgis()
89     self.server = postgissupport.get_test_server()
90     self.dbname = ".".join(self.id().split(".")[-2:])[-31:]
91     self.db = self.server.new_postgis_db(self.dbname)
92    
93     def test_gis_tables_empty(self):
94     """Test PostGISConnection.GISTables() on empty DB"""
95 bh 1634 db = PostGISConnection(dbname = self.dbname,
96     **self.server.connection_params("user"))
97 bh 1605
98     # An empty database doesn't have any GIS tables
99     self.assertEquals(db.GeometryTables(), [])
100    
101     def test_gis_tables_non_empty(self):
102     """Test PostGISConnection.GISTables() on non-empty DB"""
103 bh 1634 db = PostGISConnection(dbname = self.dbname,
104     **self.server.connection_params("user"))
105 bh 1605
106 bh 1634 conn = psycopg.connect("dbname=%s " % self.dbname
107     + self.server.connection_string("admin"))
108 bh 1605 cursor = conn.cursor()
109     cursor.execute("CREATE TABLE test (A INT);")
110     cursor.execute("SELECT AddGeometryColumn(%(dbname)s, 'test',"
111     " 'geometry', -1, 'POINT', 2);",
112     {"dbname": self.dbname})
113     conn.commit()
114    
115     # An empty database doesn't have any GIS tables
116     self.assertEquals(db.GeometryTables(), ["test"])
117    
118    
119 bh 1636 class TestPostgisDBExceptions(unittest.TestCase):
120    
121     def setUp(self):
122     """Start the postgis server and switch on authentication"""
123     postgissupport.skip_if_no_postgis()
124     self.server = postgissupport.get_test_server()
125     self.postgisdb = self.server.get_default_static_data_db()
126     self.server.require_authentication(True)
127    
128     def tearDown(self):
129     """Extend the inherited method to switch off postgresql authentication
130     """
131     self.server.require_authentication(False)
132    
133     def test_no_password(self):
134     """Test PostGISConnection with omitted but required password"""
135     connection_params = self.server.connection_params("user")
136     # remove the password deliberately
137     del connection_params["password"]
138    
139     self.assertRaises(ConnectionError,
140     PostGISConnection, dbname = self.postgisdb.dbname,
141     **connection_params)
142    
143    
144 bh 1948 class TestPostGISSpecialCases(unittest.TestCase):
145 bh 1693
146 bh 1948 """Tests for special cases of PostGIS table usage"""
147    
148 bh 1693 def setUp(self):
149     """Start the server and create a database.
150    
151     The database name will be stored in self.dbname, the server
152     object in self.server and the db object in self.db.
153     """
154     postgissupport.skip_if_no_postgis()
155     self.server = postgissupport.get_test_server()
156     self.dbname = ".".join(self.id().split(".")[-2:])[-31:]
157     self.db = self.server.new_postgis_db(self.dbname)
158    
159 bh 1948 def test_unsupported_types(self):
160 bh 1693 """test PostGISTable on a table with unsupported data types"""
161     stmt = """CREATE TABLE foo (
162     gid integer,
163     ignored bigint,
164     length float);
165     GRANT SELECT ON foo TO PUBLIC;
166     """
167     self.server.execute_sql(self.dbname, "admin", stmt)
168    
169     db = PostGISConnection(dbname = self.dbname,
170     **self.server.connection_params("user"))
171     table = PostGISTable(db, "foo")
172    
173     # The bigint column will be ignored because it's not mapped to a
174     # known integer type, so there are only two colunns
175     self.assertEquals(table.NumColumns(), 2)
176     self.assertEquals(table.Column(0).name, "gid")
177     self.assertEquals(table.Column(1).name, "length")
178    
179 bh 1948 def test_table_name_quoting(self):
180     """Test whether PostGISTable quotes table names properly"""
181     stmt = '''CREATE TABLE "name with ""quotes"" and spaces" (gid integer);
182     GRANT SELECT ON "name with ""quotes"" and spaces" TO PUBLIC;'''
183     self.server.execute_sql(self.dbname, "admin", stmt)
184 bh 1693
185 bh 1948 db = PostGISConnection(dbname = self.dbname,
186     **self.server.connection_params("user"))
187     table = PostGISTable(db, 'name with "quotes" and spaces')
188    
189     self.assertEquals(table.NumColumns(), 1)
190     self.assertEquals(table.Column(0).name, "gid")
191    
192     def test_column_name_quoting(self):
193     """Test whether PostGISTable quotes column names properly"""
194     stmt = '''CREATE TABLE unusual_column_names (
195     gid integer,
196     "with space" float,
197     "with "" quote" integer);
198     INSERT INTO unusual_column_names VALUES (1, 1.0, 0);
199     INSERT INTO unusual_column_names VALUES (2, 2.0, 1);
200     INSERT INTO unusual_column_names VALUES (3, 3.0, 1);
201     GRANT SELECT ON unusual_column_names TO PUBLIC;'''
202     self.server.execute_sql(self.dbname, "admin", stmt)
203    
204     db = PostGISConnection(dbname = self.dbname,
205     **self.server.connection_params("user"))
206     table = PostGISTable(db, 'unusual_column_names')
207    
208     self.assertEquals(table.NumColumns(), 3)
209     self.assertEquals(table.Column(0).name, "gid")
210     self.assertEquals(table.Column(1).name, "with space")
211     self.assertEquals(table.Column(2).name, "with \" quote")
212    
213     # do some queries where the names have to be quoted
214     self.assertEquals(table.ReadRowAsDict(1),
215     {"gid": 1, "with space": 1.0, "with \" quote": 0})
216     self.assertEquals(table.ReadValue(2, 1, row_is_ordinal = True), 3.0)
217     self.assertEquals(table.ReadValue(2, 1, row_is_ordinal = False), 2.0)
218     self.assertEquals(table.ValueRange("with space"), (1.0, 3.0))
219     self.assertEquals(table.UniqueValues("with \" quote"), [0, 1])
220     self.assertEquals(table.SimpleQuery(table.Columns()[2], "==", 1),
221     [2, 3])
222     self.assertEquals(table.SimpleQuery(table.Columns()[0], "==",
223     table.Columns()[1]), [1, 2, 3])
224    
225     def test_shapestore_name_quoting(self):
226     """Test whether PostGISShapeStore quotes table names properly"""
227     postgissupport.skip_if_addgeometrycolumn_does_not_use_quote_ident()
228    
229     # Create a table with a name that needs quoting and a geometry
230     # column whose name has to be quoted
231     stmt = '''CREATE TABLE "table "" name" (gid integer);
232     GRANT SELECT ON "table "" name" TO PUBLIC;'''
233     self.server.execute_sql(self.dbname, "admin", stmt)
234     stmt = """select AddGeometryColumn('%s', 'table \" name',
235     'the \" geom', '-1', 'POINT', 2);"""
236     self.server.execute_sql(self.dbname, "admin", stmt % self.dbname)
237     stmt = '''INSERT INTO "table "" name" VALUES (0,
238     GeometryFromText('POINT(0 0)', -1));'''
239     self.server.execute_sql(self.dbname, "admin", stmt)
240    
241     # Instantiate the table
242     db = PostGISConnection(dbname = self.dbname,
243     **self.server.connection_params("user"))
244     store = PostGISShapeStore(db, "table \" name")
245    
246     # do some queries where the names have to be quoted
247     self.assertEquals(store.NumShapes(), 1)
248     self.assertEquals(store.ShapeType(), SHAPETYPE_POINT)
249     self.assertEquals(store.BoundingBox(), (0, 0, 0, 0))
250     self.assertEquals(store.Shape(0).ShapeID(), 0)
251     self.assertEquals([s.ShapeID() for s in store.AllShapes()], [0])
252     self.assertEquals([s.ShapeID()
253     for s in store.ShapesInRegion((-1, -1, 1, 1))], [0])
254    
255 bh 2057 def test_shapestore_empty_table(self):
256     """Test PostGISShapeStore with emtpy table"""
257     conn = psycopg.connect("dbname=%s " % self.dbname
258     + self.server.connection_string("admin"))
259     cursor = conn.cursor()
260     cursor.execute("CREATE TABLE test (A INT);")
261     cursor.execute("SELECT AddGeometryColumn(%(dbname)s, 'test',"
262     " 'geometry', -1, 'POINT', 2);",
263     {"dbname": self.dbname})
264     cursor.execute("GRANT SELECT ON test TO PUBLIC;")
265     conn.commit()
266    
267     db = PostGISConnection(dbname = self.dbname,
268     **self.server.connection_params("user"))
269     store = PostGISShapeStore(db, "test")
270     self.assertEquals(store.BoundingBox(), None)
271    
272 bh 2059 def test_shapestore_two_geom_cols(self):
273     """Test PostGISShapeStore with two geometry columns"""
274     conn = psycopg.connect("dbname=%s " % self.dbname
275     + self.server.connection_string("admin"))
276     cursor = conn.cursor()
277     cursor.execute("INSERT INTO spatial_ref_sys VALUES"
278     " (1, '', 1, '', 'proj=longlat datum=WGS84')")
279     cursor.execute("INSERT INTO spatial_ref_sys VALUES"
280     " (2, '', 2, '', 'proj=longlat datum=WGS84')")
281 bh 2057
282 bh 2059 cursor.execute("CREATE TABLE two_geom_cols"
283     " (gid INTEGER PRIMARY KEY);")
284     cursor.execute("SELECT AddGeometryColumn(%(dbname)s, 'two_geom_cols',"
285     " 'point', 1, 'POINT', 2);",
286     {"dbname": self.dbname})
287     cursor.execute("SELECT AddGeometryColumn(%(dbname)s, 'two_geom_cols',"
288     " 'poly', 2, 'POLYGON', 2);",
289     {"dbname": self.dbname})
290     cursor.execute("INSERT INTO two_geom_cols(gid, point, poly) VALUES (1,"
291     " GeometryFromText('POINT(1 1)', 1),"
292     " GeometryFromText('POLYGON((1 1, 1 2, 2 2,1 1))',2));")
293     cursor.execute("GRANT SELECT ON two_geom_cols TO PUBLIC;")
294     conn.commit()
295    
296     db = PostGISConnection(dbname = self.dbname,
297     **self.server.connection_params("user"))
298    
299     # The table has two geometry columns, and will raise a TypeError
300     # when instantiated without specifying which one to use.
301     self.assertRaises(TypeError,
302     PostGISShapeStore, db, "two_geom_cols")
303    
304     # If the geometry_column is not really a geometry column, we get
305     # a TypeError
306     self.assertRaises(TypeError,
307     PostGISShapeStore, db, "two_geom_cols",
308     geometry_column = "gid")
309    
310     # Instantiate two shape stores, one for each of the geometry
311     # columns, and test whether they determine the right shape types
312     # and srids (getting the srid wrong would lead to an exception
313     # in ShapesInRegion).
314     store = PostGISShapeStore(db, "two_geom_cols",
315     geometry_column = "point")
316     self.assertEquals(store.ShapeType(), SHAPETYPE_POINT)
317     self.assertEquals([s.ShapeID()
318     for s in store.ShapesInRegion((0, 0, 100,100))],
319     [1])
320    
321     store = PostGISShapeStore(db, "two_geom_cols",
322     geometry_column = "poly")
323     self.assertEquals(store.ShapeType(), SHAPETYPE_POLYGON)
324     self.assertEquals([s.ShapeID()
325     for s in store.ShapesInRegion((0, 0, 100,100))],
326     [1])
327    
328    
329 bh 1605 class PostGISStaticTests(unittest.TestCase, support.FloatComparisonMixin):
330    
331     """Base class for PostGIS tests with static data."""
332    
333     def setUp(self):
334     """Start the server and create a database with static data
335    
336     This method sets the following instance attributes:
337    
338     dbname -- the name of the database
339    
340     server -- The server object
341    
342     db -- the PostGISConnection object
343     """
344     postgissupport.skip_if_no_postgis()
345     self.server = postgissupport.get_test_server()
346     self.postgisdb = self.server.get_default_static_data_db()
347     self.db = PostGISConnection(dbname = self.postgisdb.dbname,
348 bh 1634 **self.server.connection_params("user"))
349 bh 1605
350     def tearDown(self):
351     """Close the database connection"""
352     self.db.Close()
353    
354    
355 bh 2096 class TableTests:
356 bh 1605
357 bh 2096 """Mix-in class for the PostGISTable tests
358 bh 1605
359 bh 2096 The tests defined here make some assumptions about the table and the
360     data in it:
361    
362     self.table should be the PostGISTable instance to test. Derived
363     classes should set this up in setUp.
364    
365     self.db should be the DB connection object used by self.table.
366    
367     self.table_name should be the name of the table in the database.
368     The tests assume that e.g. the title of self.table can be
369     derived from this.
370    
371     self.gid_column should be the name of the gid column used when
372     self.table was instantiated.
373    
374     The data in the table should be the data of the
375     cultural_landmark-point shapefile with the shape ids used to get
376     the contents of the gid column by adding 1000.
377     """
378    
379 bh 1638 def test_dbconn(self):
380     """Test PostGISTable.DBConnection()"""
381     self.failUnless(self.table.DBConnection() is self.db)
382    
383     def test_dbname(self):
384     """Test PostGISTable.TableName()"""
385 bh 2096 self.assertEquals(self.table.TableName(), self.table_name)
386 bh 1638
387 bh 1658 def test_title(self):
388     """test PostGISTable.Title()"""
389     # The title is currently equal to the tablename
390 bh 2096 self.assertEquals(self.table.Title(), self.table_name)
391 bh 1658
392 bh 1605 def test_dependencies(self):
393     """Test PostGISTable.Dependencies()"""
394     # A PostGISTable depends on no other data container
395     self.assertEquals(self.table.Dependencies(), ())
396    
397     def test_num_rows(self):
398     """Test PostGISTable.NumRows()"""
399     self.assertEquals(self.table.NumRows(), 34)
400    
401     def test_num_columns(self):
402     """Test PostGISTable.NumColumns()"""
403     # The table in the postgis db has one additional column, "gid",
404     # so there's one more column in the PostGISTable than in the DBF
405     self.assertEquals(self.table.NumColumns(), 7)
406    
407     def test_columns(self):
408     """Test PostGISTable.Columns()"""
409     self.assertEquals(len(self.table.Columns()), 7)
410 bh 2096 self.assertEquals(self.table.Columns()[0].name, self.gid_column)
411 bh 1605 self.assertEquals(self.table.Columns()[0].type, FIELDTYPE_INT)
412     self.assertEquals(self.table.Columns()[0].index, 0)
413     self.assertEquals(self.table.Columns()[1].name, "area")
414     self.assertEquals(self.table.Columns()[1].type, FIELDTYPE_DOUBLE)
415     self.assertEquals(self.table.Columns()[1].index, 1)
416     self.assertEquals(self.table.Columns()[5].name, "clptlabel")
417     self.assertEquals(self.table.Columns()[5].type, FIELDTYPE_STRING)
418     self.assertEquals(self.table.Columns()[5].index, 5)
419    
420     def test_column(self):
421     """Test PostGISTable.Column()"""
422     self.assertEquals(self.table.Column("area").name, "area")
423     self.assertEquals(self.table.Column("area").type, FIELDTYPE_DOUBLE)
424     self.assertEquals(self.table.Column("area").index, 1)
425    
426     def test_has_column(self):
427     """Test PostGISTable.HasColumn()"""
428     self.assert_(self.table.HasColumn("area"))
429     self.failIf(self.table.HasColumn("foo"))
430    
431     def test_read_row_as_dict(self):
432     """Test PostGISTable.ReadRowAsDict()"""
433 bh 1662 self.assertEquals(self.table.ReadRowAsDict(1003),
434 bh 2096 {self.gid_column: 1003,
435 bh 1605 "area": 0.0,
436     "perimeter": 0.0,
437     "clpoint_": 4,
438     "clpoint_id": 24,
439     "clptlabel": "RUINS",
440     "clptflag": 0})
441    
442 bh 1662 def test_read_row_as_dict_row_count_mode(self):
443     """Test PostGISTable.ReadRowAsDict() row count address mode"""
444     self.assertEquals(self.table.ReadRowAsDict(3, row_is_ordinal = 1),
445 bh 2096 {self.gid_column: 1003,
446 bh 1662 "area": 0.0,
447     "perimeter": 0.0,
448     "clpoint_": 4,
449     "clpoint_id": 24,
450     "clptlabel": "RUINS",
451     "clptflag": 0})
452    
453 bh 1605 def test_read_value(self):
454     """Test PostGISTable.ReadValue()"""
455 bh 1662 self.assertEquals(self.table.ReadValue(1003, 4), 24)
456     self.assertEquals(self.table.ReadValue(1003, "clpoint_id"), 24)
457 bh 1605
458 bh 1662 def test_read_value_row_count_mode(self):
459     """Test PostGISTable.ReadValue() row count address mode"""
460     self.assertEquals(self.table.ReadValue(3, 4, row_is_ordinal = 1), 24)
461     self.assertEquals(self.table.ReadValue(3, "clpoint_id",
462     row_is_ordinal = 1),
463     24)
464    
465     def test_row_id_to_ordinal(self):
466     """Test PostGISTable.RowIdToOrdinal()"""
467     self.assertEquals(self.table.RowIdToOrdinal(1005), 5)
468    
469     def test_row_oridnal_to_id(self):
470     """Test PostGISTable.RowOrdinalToId()"""
471     self.assertEquals(self.table.RowOrdinalToId(5), 1005)
472    
473 bh 1605 def test_value_range(self):
474     """Test PostGISTable.ValueRange()"""
475     self.assertEquals(self.table.ValueRange("clpoint_id"), (21, 74))
476    
477     def test_unique_values(self):
478     """Test PostGISTable.UniqueValues()"""
479     values = self.table.UniqueValues("clptlabel")
480     values.sort()
481     self.assertEquals(values, ["BUILDING", "FARM", "HUT","LIGHTHOUSE",
482     "OTHER/UNKNOWN", "RUINS"])
483    
484     def test_simple_query(self):
485     """Test PostGISTable.SimpleQuery()"""
486     table = self.table
487     self.assertEquals(table.SimpleQuery(table.Column("clptlabel"),
488     "==", "FARM"),
489 bh 1662 [1006])
490 bh 1605 self.assertEquals(table.SimpleQuery(table.Column("clpoint_id"),
491     ">", 70),
492 bh 1662 [1024, 1025, 1026])
493 bh 1605 self.assertEquals(table.SimpleQuery(table.Column("clpoint_id"),
494     "<", table.Column("clpoint_")),
495 bh 1662 [1028, 1029, 1030, 1031, 1032, 1033])
496 bh 1605
497    
498 bh 2096 class TestPostGISTable(TableTests, PostGISStaticTests):
499    
500     def setUp(self):
501     """Extend inherited method to set self.table to a PostGISTable"""
502     PostGISStaticTests.setUp(self)
503     self.table_name = "landmarks"
504     self.gid_column = "gid"
505    
506     # Note that omit the gid column here to the backwards compatible
507     # interface of the constructor where the gid_column defaults to
508     # "gid"
509     self.table = PostGISTable(self.db, self.table_name)
510    
511    
512     class TestPostGISTableExplicitGIDColumn(TableTests, PostGISStaticTests):
513    
514     def setUp(self):
515     """Extend inherited method to set self.table to a PostGISTable"""
516     PostGISStaticTests.setUp(self)
517     self.table_name = "landmarks_point_id"
518     self.gid_column = "point_id"
519     self.table = PostGISTable(self.db, self.table_name,
520     id_column = self.gid_column)
521    
522    
523 bh 2057 class PointTests:
524 bh 1605
525 bh 2096 """Mix-in class for the tests on POINT tables
526 bh 1605
527 bh 2096 The methods in this class expect self.store to be the shapestore
528     used for testing. Derived classes should initialize self.store with
529     PostGISShapeStore in setUp. Another assumption is that the data in
530     self.store is effectively the cultural_landmark-point shapefile with
531     shape ids increased by 1000.
532     """
533    
534 bh 1605 #
535     # First, some tests that should be independend of the shapetype, so
536     # it shouldn't be necessary to repeat them for other shapetypes
537     #
538    
539     def test_dependencies(self):
540     """Test PostGISShapeStore.Dependencies()"""
541     # A PostGISShapeStore depends on no other data container
542     self.assertEquals(self.store.Dependencies(), ())
543    
544     def test_table(self):
545     """Test PostGISShapeStore.Table() with POINT shapes"""
546     # A PostGISShapeStore is its own table
547     self.assert_(self.store.Table() is self.store)
548    
549     def test_orig_shapestore(self):
550     """Test PostGISShapeStore.OrigShapeStore() with POINT shapes"""
551     # A PostGISShapeStore is not derived from another shape store
552     self.assert_(self.store.OrigShapeStore() is None)
553    
554     def test_raw_format(self):
555     """Test PostGISShapeStore.RawShapeFormat() with POINT shapes"""
556     self.assertEquals(self.store.RawShapeFormat(), RAW_WKT)
557    
558 bh 1658 def test_all_shapes(self):
559     """Test PostGISShapeStore.AllShapes()"""
560     self.assertEquals([s.ShapeID() for s in self.store.AllShapes()],
561 bh 1662 range(1000, 1000 + self.store.NumShapes()))
562 bh 1658
563 bh 1605 #
564     # Shapetype specific tests
565     #
566    
567     def test_shape_type(self):
568     """Test PostGISShapeStore.ShapeType() with POINT shapes"""
569     self.assertEquals(self.store.ShapeType(), SHAPETYPE_POINT)
570    
571     def test_num_shapes(self):
572     """Test PostGISShapeStore.NumShapes() with POINT shapes"""
573     self.assertEquals(self.store.NumShapes(), 34)
574    
575     def test_bounding_box(self):
576     """Test PostGISShapeStore.BoundingBox() with POINT shapes"""
577     self.assertFloatSeqEqual(self.store.BoundingBox(),
578     [-23.806047439575195, 63.405960083007812,
579     -15.12291431427002, 66.36572265625])
580    
581     def test_shape_shapeid(self):
582     """Test PostGISShapeStore.Shape(i).ShapeID() with POINT shapes"""
583 bh 1662 self.assertEquals(self.store.Shape(1005).ShapeID(), 1005)
584 bh 1605
585     def test_shape_points(self):
586     """Test PostGISShapeStore.Shape(i).Points() with POINT shapes"""
587 bh 1662 self.assertPointListEquals(self.store.Shape(1000).Points(),
588 bh 1605 [[(-22.711074829101562, 66.36572265625)]])
589    
590     def test_shape_raw_data(self):
591     """Test PostGISShapeStore.Shape(i).RawData() with POINT shapes"""
592 bh 1662 self.assertEquals(self.store.Shape(1000).RawData(),
593 bh 1605 'POINT(-22.7110748291016 66.36572265625)')
594    
595     def test_shapes_in_region(self):
596     """Test PostGISShapeStore:ShapesInRegion() with POINT shapes"""
597     shapes = self.store.ShapesInRegion((-20.0, 64.0, -24.0, 67))
598     self.assertEquals([s.ShapeID() for s in shapes],
599 bh 1662 [1000, 1001, 1002, 1003, 1004, 1005, 1027])
600 bh 1605
601    
602 bh 2057 class TestPostGISShapestorePoint(PointTests, PostGISStaticTests):
603    
604     """Tests for PostGISShapeStore objects with POINT data an no SRID"""
605    
606     def setUp(self):
607     """Extend inherited method to set self.table to a PostGISShapeStore"""
608     PostGISStaticTests.setUp(self)
609     self.store = PostGISShapeStore(self.db, "landmarks")
610    
611    
612    
613     class TestPostGISShapestorePointSRID(PointTests, PostGISStaticTests):
614    
615     """Tests for PostGISShapeStore objects with POINT data and an SRID"""
616    
617     def setUp(self):
618     """Extend inherited method to set self.table to a PostGISShapeStore"""
619     PostGISStaticTests.setUp(self)
620     self.store = PostGISShapeStore(self.db, "landmarks_srid")
621    
622    
623 bh 2096 class TestPostGISShapestorePointExplicitGIDColumn(PointTests,
624     PostGISStaticTests):
625 bh 2057
626 bh 2096 """Tests for PostGISShapeStores with POINT data and explicit gid column"""
627    
628     def setUp(self):
629     """Extend inherited method to set self.table to a PostGISShapeStore"""
630     PostGISStaticTests.setUp(self)
631     self.store = PostGISShapeStore(self.db, "landmarks_point_id",
632     id_column = "point_id")
633    
634    
635     class TestPostGISShapestorePointOIDAsGIDColumn(PointTests, PostGISStaticTests):
636    
637     """Tests for PostGISShapeStores with POINT data using OID as gid column"""
638    
639     def setUp(self):
640     """Extend inherited method to set self.table to a PostGISShapeStore"""
641     PostGISStaticTests.setUp(self)
642     self.store = PostGISShapeStore(self.db, "landmarks_point_id",
643     id_column = "oid")
644    
645     def find_test_shape_id(self):
646     """Return the id of an interesting shape for some test cases.
647    
648     This test uses OIDs so we can't easily hard wire ids in the test
649     cases
650     """
651     # get the id of an interesting shape
652     shapes = self.store.ShapesInRegion((-20.0, 64.0, -24.0, 67))
653     return list(shapes)[0].ShapeID()
654    
655    
656     # Override a few tests that won't work with this table because they
657     # require knowledge of specific IDs
658    
659     def test_shape_shapeid(self):
660     """Test PostGISShapeStore.Shape(i).ShapeID() with POINT shapes"""
661     gid = self.find_test_shape_id()
662     self.assertEquals(self.store.Shape(gid).ShapeID(), gid)
663    
664     def test_shape_points(self):
665     """Test PostGISShapeStore.Shape(i).Points() with POINT shapes"""
666     gid = self.find_test_shape_id()
667     self.assertPointListEquals(self.store.Shape(gid).Points(),
668     [[(-22.711074829101562, 66.36572265625)]])
669    
670     def test_shape_raw_data(self):
671     """Test PostGISShapeStore.Shape(i).RawData() with POINT shapes"""
672     gid = self.find_test_shape_id()
673     self.assertEquals(self.store.Shape(gid).RawData(),
674     'POINT(-22.7110748291016 66.36572265625)')
675    
676     def test_shapes_in_region(self):
677     """Test PostGISShapeStore:ShapesInRegion() with POINT shapes"""
678     shapes = self.store.ShapesInRegion((-20.0, 64.0, -24.0, 67))
679     self.assertEquals(len(list(shapes)), 7)
680    
681     def test_all_shapes(self):
682     """Test PostGISShapeStore.AllShapes()"""
683     self.assertEquals(len(list(self.store.AllShapes())), 34)
684    
685    
686    
687 bh 1605 class TestPostGISShapestoreArc(PostGISStaticTests):
688    
689     """Tests for PostGISShapeStore objects with MULTILINESTRING data"""
690    
691     def setUp(self):
692     """Extend inherited method to set self.table to a PostGISShapeStore"""
693     PostGISStaticTests.setUp(self)
694     self.store = PostGISShapeStore(self.db, "roads")
695    
696     def test_shape_type(self):
697     """Test PostGISShapeStore.ShapeType() with ARC shapes"""
698     self.assertEquals(self.store.ShapeType(), SHAPETYPE_ARC)
699    
700     def test_num_shapes(self):
701     """Test PostGISShapeStore.NumShapes() with ARC shapes"""
702     self.assertEquals(self.store.NumShapes(), 839)
703    
704     def test_bounding_box(self):
705     """Test PostGISShapeStore.BoundingBox() with ARC shapes"""
706     self.assertFloatSeqEqual(self.store.BoundingBox(),
707     [-24.450359344482422, 63.426830291748047,
708     -13.55668830871582, 66.520111083984375])
709    
710     def test_shape_shapeid(self):
711     """Test PostGISShapeStore.Shape(i).ShapeID() with ARC shapes"""
712     self.assertEquals(self.store.Shape(5).ShapeID(), 5)
713    
714     def test_shape_points(self):
715     """Test PostGISShapeStore.Shape(i).Points() with ARC shapes"""
716     self.assertPointListEquals(self.store.Shape(32).Points(),
717     [[(-15.0821743011474, 66.2773818969726),
718     (-15.0263500213623, 66.2733917236328)]])
719    
720     def test_shape_raw_data(self):
721     """Test PostGISShapeStore.Shape(i).RawData() with ARC shapes"""
722     self.assertEquals(self.store.Shape(32).RawData(),
723     "MULTILINESTRING((-15.0821743011475 66.2773818969727,"
724     "-15.0263500213623 66.2733917236328))")
725    
726     def test_shapes_in_region(self):
727     """Test PostGISShapeStore.ShapesInRegion() with ARC shapes"""
728     shapes = self.store.ShapesInRegion((-24.0, 64.5, -23.5, 65.0))
729     self.assertEquals([s.ShapeID() for s in shapes], [573, 581, 613])
730    
731    
732    
733 bh 1656 class PolygonTests:
734 bh 1605
735 bh 2057 """Test shared by the POLYGON and MULTIPOLYGON tests
736 bh 1605
737 bh 1656 The tests are the same because they are based on the same data.
738     """
739    
740 bh 1605 def test_shape_type(self):
741     """Test PostGISShapeStore.ShapeType() with POLYGON shapes"""
742     self.assertEquals(self.store.ShapeType(), SHAPETYPE_POLYGON)
743    
744     def test_num_shapes(self):
745     """Test PostGISShapeStore.NumShapes() with POLYGON shapes"""
746     self.assertEquals(self.store.NumShapes(), 156)
747    
748     def test_bounding_box(self):
749     """Test PostGISShapeStore.BoundingBox() with POLYGON shapes"""
750     self.assertFloatSeqEqual(self.store.BoundingBox(),
751     [-24.546524047851562, 63.286754608154297,
752     -13.495815277099609, 66.563774108886719])
753    
754     def test_shape_shapeid(self):
755     """Test PostGISShapeStore.Shape(i).ShapeID() with POLYGON shapes"""
756     self.assertEquals(self.store.Shape(5).ShapeID(), 5)
757    
758     def test_shape_points(self):
759     """Test PostGISShapeStore.Shape(i).Points() with POLYGON shapes"""
760     self.assertPointListEquals(self.store.Shape(4).Points(),
761     [[(-22.40639114379882, 64.714111328125),
762     (-22.41621208190918, 64.716003417968),
763     (-22.40605163574218, 64.719200134277),
764     (-22.40639114379882, 64.714111328125)]])
765    
766 bh 1656 def test_shapes_in_region(self):
767     """Test PostGISShapeStore.ShapesInRegion() with POLYGON shapes"""
768     shapes = self.store.ShapesInRegion((-23.0, 65.5, -22.8, 65.25))
769     self.assertEquals([s.ShapeID() for s in shapes],
770     [47, 56, 59, 61, 62, 71, 144])
771    
772    
773     class TestPostGISShapestorePolygon(PolygonTests, PostGISStaticTests):
774    
775     """Tests for PostGISShapeStore objects with POLYGON data"""
776    
777     def setUp(self):
778     """Extend inherited method to set self.table to a PostGISShapeStore"""
779     PostGISStaticTests.setUp(self)
780     self.store = PostGISShapeStore(self.db, "political")
781    
782     def test_shape_type(self):
783     """Test PostGISShapeStore.ShapeType() with POLYGON shapes"""
784     self.assertEquals(self.store.ShapeType(), SHAPETYPE_POLYGON)
785    
786    
787 bh 1605 def test_shape_raw_data(self):
788     """Test PostGISShapeStore.Shape(i).RawData() with POLYGON shapes"""
789     self.assertEquals(self.store.Shape(4).RawData(),
790     "POLYGON((-22.4063911437988 64.714111328125,"
791     "-22.4162120819092 64.7160034179688,"
792     "-22.4060516357422 64.7192001342773,"
793     "-22.4063911437988 64.714111328125))")
794    
795    
796 bh 1656 class TestPostGISShapestoreMultiPolygon(PolygonTests, PostGISStaticTests):
797 bh 1605
798 bh 1656 """Tests for PostGISShapeStore objects with MUTLIPOLYGON data"""
799    
800     def setUp(self):
801     """Extend inherited method to set self.table to a PostGISShapeStore"""
802     PostGISStaticTests.setUp(self)
803     self.store = PostGISShapeStore(self.db, "political_multi")
804    
805     def test_shape_raw_data(self):
806     """Test PostGISShapeStore.Shape(i).RawData() with POLYGON shapes"""
807     self.assertEquals(self.store.Shape(4).RawData(),
808     "MULTIPOLYGON(((-22.4063911437988 64.714111328125,"
809     "-22.4162120819092 64.7160034179688,"
810     "-22.4060516357422 64.7192001342773,"
811     "-22.4063911437988 64.714111328125)))")
812    
813 bh 1693
814    
815 bh 1605 if __name__ == "__main__":
816     support.run_tests()

Properties

Name Value
svn:eol-style native
svn:keywords Author Date Id Revision

[email protected]
ViewVC Help
Powered by ViewVC 1.1.26