File: test_postgis_db.py

package info (click to toggle)
thuban 1.2.2-2
  • links: PTS, VCS
  • area: main
  • in suites: squeeze
  • size: 7,596 kB
  • ctags: 5,301
  • sloc: python: 30,411; ansic: 6,181; xml: 4,127; cpp: 1,595; makefile: 166; sh: 101
file content (930 lines) | stat: -rw-r--r-- 38,990 bytes parent folder | download | duplicates (5)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
# Copyright (C) 2003, 2004, 2005, 2006 by Intevation GmbH
# Authors:
# Bernhard Herzog <bh@intevation.de>
#
# This program is free software under the GPL (>=v2)
# Read the file COPYING coming with the software for details.

"""Test for Thuban.Model.postgisdb"""

import os
import unittest


try:
    import psycopg2
except ImportError:
    # No psycopg available. Nothing to be done here because the
    # postgis.py support module determines this too and the tests will
    # be skipped completely.
    pass

import postgissupport

import support
support.initthuban()

from Thuban.Model.postgisdb import ConnectionError, PostGISConnection, \
     PostGISTable, PostGISShapeStore
from Thuban.Model.table import FIELDTYPE_INT, FIELDTYPE_STRING, \
     FIELDTYPE_DOUBLE
from Thuban.Model.data import SHAPETYPE_POINT, SHAPETYPE_POLYGON, \
     SHAPETYPE_ARC, RAW_WKT


class NonConnection(PostGISConnection):

    """Special connection class that doesn't actually connect"""

    def connect(self):
        pass



class TestPostGISSimple(unittest.TestCase):

    """Some simple PostGISConnection tests that don't need a real connection"""

    def test_brief_description(self):
        """Test PostGISConnection.BriefDescription()"""
        self.assertEquals(NonConnection("somedb").BriefDescription(),
                          "postgis://@:/somedb")
        self.assertEquals(NonConnection("db", host="here",
                                        port="123").BriefDescription(),
                          "postgis://@here:123/db")
        self.assertEquals(NonConnection("db", user="me",
                                        port="123").BriefDescription(),
                          "postgis://me@:123/db")

    def test_matches_parameters(self):
        """Test PostGISConnection.MatchesParameters()"""
        def do_test(testfn, conn, host = "", port="", dbname = "", user = ""):
            testfn(conn.MatchesParameters({"host": host, "port": port,
                                           "dbname": dbname, "user": user}))

        do_test(self.assert_, NonConnection("somedb"),
                dbname="somedb")
        do_test(self.assert_, NonConnection("somedb", host="here"),
                dbname="somedb", host="here")
        do_test(self.assert_, NonConnection("db", user="me", port="123"),
                dbname="db", port="123", user="me")

        do_test(self.failIf, NonConnection("somedb"),
                dbname="someotherdb")
        do_test(self.failIf, NonConnection("somedb", host="here"),
                dbname="somedb", host="here", port="765")
        do_test(self.failIf, NonConnection("db", user="me", port="123"),
                dbname="db", port="123", user="you")


class TestPostGISConnection(unittest.TestCase):

    def setUp(self):
        """Start the server and create a database.

        The database name will be stored in self.dbname, the server
        object in self.server and the db object in self.db.
        """
        postgissupport.skip_if_no_postgis()
        self.server = postgissupport.get_test_server()
        self.dbname = ".".join(self.id().split(".")[-2:])[-31:]
        self.db = self.server.new_postgis_db(self.dbname)

    def test_gis_tables_empty(self):
        """Test PostGISConnection.GISTables() on empty DB"""
        db = PostGISConnection(dbname = self.dbname,
                               **self.server.connection_params("user"))

        # An empty database doesn't have any GIS tables
        self.assertEquals(db.GeometryTables(), [])

    def test_gis_tables_with_views_and_tables(self):
        db = PostGISConnection(dbname = self.dbname,
                               **self.server.connection_params("user"))

        conn = psycopg2.connect("dbname=%s " % self.dbname
                               + self.server.connection_string("admin"))
        cursor = conn.cursor()
        # First a normal table, i.e. one without a geometry column
        # we need an explicit WITH OIDS for postgresql >= 8.0
        cursor.execute("CREATE TABLE normal (A INT, B VARCHAR) WITH OIDS;"
                       "GRANT SELECT ON normal TO PUBLIC;")

        # Then a table with a geometry column
        # we need an explicit WITH OIDS for postgresql >= 8.0
        cursor.execute("CREATE TABLE geo (A INT) WITH OIDS;"
                       "GRANT SELECT ON geo TO PUBLIC;")
        cursor.execute("SELECT AddGeometryColumn(%(dbname)s, 'geo',"
                       " 'the_geom', -1, 'POINT', 2);",
                       {"dbname": self.dbname})

        # And create a view containing a geometry column
        cursor.execute("CREATE VIEW my_view AS"
                       " (SELECT * FROM geo WHERE a > 100);"
                       "GRANT SELECT ON my_view TO PUBLIC;")
        conn.commit()
        self.assertEquals(db.GeometryTables(), ["geo", "my_view"])
        self.assertEquals(db.table_columns("geo"),
                          [("oid", FIELDTYPE_INT), ("a", FIELDTYPE_INT),
                           ("the_geom", "geometry")])
        self.assertEquals(db.table_columns("my_view"),
                          [("a", FIELDTYPE_INT), ("the_geom", "geometry")])
        self.assertEquals(db.table_columns("normal"),
                          [("oid", FIELDTYPE_INT), ("a", FIELDTYPE_INT),
                           ("b", FIELDTYPE_STRING)])


class TestPostgisDBExceptions(unittest.TestCase):

    def setUp(self):
        """Start the postgis server and switch on authentication"""
        postgissupport.skip_if_no_postgis()
        self.server = postgissupport.get_test_server()
        self.postgisdb = self.server.get_default_static_data_db()
        self.server.require_authentication(True)

    def tearDown(self):
        """Extend the inherited method to switch off postgresql authentication
        """
        self.server.require_authentication(False)

    def test_no_password(self):
        """Test PostGISConnection with omitted but required password"""
        connection_params = self.server.connection_params("user")
        # remove the password deliberately
        del connection_params["password"]

        self.assertRaises(ConnectionError,
                          PostGISConnection, dbname = self.postgisdb.dbname,
                          **connection_params)


class TestPostGISSpecialCases(unittest.TestCase):

    """Tests for special cases of PostGIS table usage"""

    def setUp(self):
        """Start the server and create a database.

        The database name will be stored in self.dbname, the server
        object in self.server and the db object in self.db.
        """
        postgissupport.skip_if_no_postgis()
        self.server = postgissupport.get_test_server()
        self.dbname = ".".join(self.id().split(".")[-2:])[-31:]
        self.db = self.server.new_postgis_db(self.dbname)

    def test_unsupported_types(self):
        """test PostGISTable on a table with unsupported data types"""
        stmt = """CREATE TABLE foo (
                        gid integer,
                        ignored bigint,
                        length float);
                  GRANT SELECT ON foo TO PUBLIC;
                  """
        self.server.execute_sql(self.dbname, "admin", stmt)

        db = PostGISConnection(dbname = self.dbname,
                               **self.server.connection_params("user"))
        table = PostGISTable(db, "foo")

        # The bigint column will be ignored because it's not mapped to a
        # known integer type, so there are only two colunns
        self.assertEquals(table.NumColumns(), 2)
        self.assertEquals(table.Column(0).name, "gid")        
        self.assertEquals(table.Column(1).name, "length")

    def test_table_name_quoting(self):
        """Test whether PostGISTable quotes table names properly"""
        stmt = '''CREATE TABLE "name with ""quotes"" and spaces" (gid integer);
             GRANT SELECT ON "name with ""quotes"" and spaces" TO PUBLIC;'''
        self.server.execute_sql(self.dbname, "admin", stmt)

        db = PostGISConnection(dbname = self.dbname,
                               **self.server.connection_params("user"))
        table = PostGISTable(db, 'name with "quotes" and spaces')

        self.assertEquals(table.NumColumns(), 1)
        self.assertEquals(table.Column(0).name, "gid")

    def test_column_name_quoting(self):
        """Test whether PostGISTable quotes column names properly"""
        stmt = '''CREATE TABLE unusual_column_names (
                     gid integer,
                     "with space" float,
                     "with "" quote" integer);
             INSERT INTO unusual_column_names VALUES (1, 1.0, 0);
             INSERT INTO unusual_column_names VALUES (2, 2.0, 1);
             INSERT INTO unusual_column_names VALUES (3, 3.0, 1);
             GRANT SELECT ON unusual_column_names TO PUBLIC;'''
        self.server.execute_sql(self.dbname, "admin", stmt)

        db = PostGISConnection(dbname = self.dbname,
                               **self.server.connection_params("user"))
        table = PostGISTable(db, 'unusual_column_names')

        self.assertEquals(table.NumColumns(), 3)
        self.assertEquals(table.Column(0).name, "gid")
        self.assertEquals(table.Column(1).name, "with space")
        self.assertEquals(table.Column(2).name, "with \" quote")

        # do some queries where the names have to be quoted
        self.assertEquals(table.ReadRowAsDict(1),
                          {"gid": 1, "with space": 1.0, "with \" quote": 0})
        self.assertEquals(table.ReadValue(2, 1, row_is_ordinal = True), 3.0)
        self.assertEquals(table.ReadValue(2, 1, row_is_ordinal = False), 2.0)
        self.assertEquals(table.ValueRange("with space"), (1.0, 3.0))

        # The return value of UniqueValues is unsorted, so we need to
        # sort it for comparison.
        unique_values = table.UniqueValues("with \" quote")
        unique_values.sort()
        self.assertEquals(unique_values, [0, 1])
        self.assertEquals(table.SimpleQuery(table.Columns()[2], "==", 1),
                          [2, 3])
        self.assertEquals(table.SimpleQuery(table.Columns()[0], "==",
                                            table.Columns()[1]), [1, 2, 3])

    def test_shapestore_name_quoting(self):
        """Test whether PostGISShapeStore quotes table names properly"""
        postgissupport.skip_if_addgeometrycolumn_does_not_use_quote_ident()

        # Create a table with a name that needs quoting and a geometry
        # column whose name has to be quoted
        stmt = '''CREATE TABLE "table "" name" (gid integer);
             GRANT SELECT ON "table "" name" TO PUBLIC;'''
        self.server.execute_sql(self.dbname, "admin", stmt)
        stmt = """select AddGeometryColumn('%s', 'table \" name',
                                           'the \" geom', '-1', 'POINT', 2);"""
        self.server.execute_sql(self.dbname, "admin", stmt % self.dbname)
        stmt = '''INSERT INTO "table "" name" VALUES (0,
                GeometryFromText('POINT(0 0)', -1));'''
        self.server.execute_sql(self.dbname, "admin", stmt)

        # Instantiate the table
        db = PostGISConnection(dbname = self.dbname,
                               **self.server.connection_params("user"))
        store = PostGISShapeStore(db, "table \" name")

        # do some queries where the names have to be quoted
        self.assertEquals(store.NumShapes(), 1)
        self.assertEquals(store.ShapeType(), SHAPETYPE_POINT)
        self.assertEquals(store.BoundingBox(), (0, 0, 0, 0))
        self.assertEquals(store.Shape(0).ShapeID(), 0)
        self.assertEquals([s.ShapeID() for s in store.AllShapes()], [0])
        self.assertEquals([s.ShapeID()
                           for s in store.ShapesInRegion((-1, -1, 1, 1))], [0])

    def test_shapestore_empty_table(self):
        """Test PostGISShapeStore with emtpy table"""
        conn = psycopg2.connect("dbname=%s " % self.dbname
                               + self.server.connection_string("admin"))
        cursor = conn.cursor()
        cursor.execute("CREATE TABLE test (A INT);")
        cursor.execute("SELECT AddGeometryColumn(%(dbname)s, 'test',"
                       " 'geometry', -1, 'POINT', 2);",
                       {"dbname": self.dbname})
        cursor.execute("GRANT SELECT ON test TO PUBLIC;")
        conn.commit()

        db = PostGISConnection(dbname = self.dbname,
                               **self.server.connection_params("user"))
        store = PostGISShapeStore(db, "test")
        self.assertEquals(store.BoundingBox(), None)

    def test_shapestore_two_geom_cols(self):
        """Test PostGISShapeStore with two geometry columns"""
        conn = psycopg2.connect("dbname=%s " % self.dbname
                               + self.server.connection_string("admin"))
        cursor = conn.cursor()
        cursor.execute("INSERT INTO spatial_ref_sys VALUES"
                       " (1, '', 1, '', 'proj=longlat datum=WGS84')")
        cursor.execute("INSERT INTO spatial_ref_sys VALUES"
                       " (2, '', 2, '', 'proj=longlat datum=WGS84')")

        cursor.execute("CREATE TABLE two_geom_cols"
                       " (gid INTEGER PRIMARY KEY);")
        cursor.execute("SELECT AddGeometryColumn(%(dbname)s, 'two_geom_cols',"
                       " 'point', 1, 'POINT', 2);",
                       {"dbname": self.dbname})
        cursor.execute("SELECT AddGeometryColumn(%(dbname)s, 'two_geom_cols',"
                       " 'poly', 2, 'POLYGON', 2);",
                       {"dbname": self.dbname})
        cursor.execute("INSERT INTO two_geom_cols(gid, point, poly) VALUES (1,"
                       " GeometryFromText('POINT(1 1)', 1),"
                       " GeometryFromText('POLYGON((1 1, 1 2, 2 2,1 1))',2));")
        cursor.execute("GRANT SELECT ON two_geom_cols TO PUBLIC;")
        conn.commit()

        db = PostGISConnection(dbname = self.dbname,
                               **self.server.connection_params("user"))

        # The table has two geometry columns, and will raise a TypeError
        # when instantiated without specifying which one to use.
        self.assertRaises(TypeError,
                          PostGISShapeStore, db, "two_geom_cols")

        # If the geometry_column is not really a geometry column, we get
        # a TypeError
        self.assertRaises(TypeError,
                          PostGISShapeStore, db, "two_geom_cols",
                          geometry_column = "gid")

        # Instantiate two shape stores, one for each of the geometry
        # columns, and test whether they determine the right shape types
        # and srids (getting the srid wrong would lead to an exception
        # in ShapesInRegion).
        store = PostGISShapeStore(db, "two_geom_cols",
                                  geometry_column = "point")
        self.assertEquals(store.ShapeType(), SHAPETYPE_POINT)
        self.assertEquals([s.ShapeID()
                           for s in store.ShapesInRegion((0, 0, 100,100))],
                          [1])

        store = PostGISShapeStore(db, "two_geom_cols",
                                  geometry_column = "poly")
        self.assertEquals(store.ShapeType(), SHAPETYPE_POLYGON)
        self.assertEquals([s.ShapeID()
                           for s in store.ShapesInRegion((0, 0, 100,100))],
                          [1])


    def test_simple_error_handling(self):
        """Test some simple error handling.

        If an error happens in, say the SimpleQuery method, a subsequent
        ReadValue call should still succeed.
        """
        conn = psycopg2.connect("dbname=%s " % self.dbname
                               + self.server.connection_string("admin"))
        cursor = conn.cursor()
        cursor.execute("CREATE TABLE some_table"
                       " (gid INTEGER PRIMARY KEY, length float);"
                       "INSERT INTO some_table VALUES (1, 3.5);")
        cursor.execute("GRANT SELECT ON some_table TO PUBLIC;")
        conn.commit()
        conn.close()

        db = PostGISConnection(dbname = self.dbname,
                               **self.server.connection_params("user"))
        table = PostGISTable(db, "some_table", id_column = "gid")

        # trying to compare the length to a string should fail with an
        # exception.
        self.assertRaises(psycopg2.ProgrammingError,
                          table.SimpleQuery,
                          table.Column("length"), "<=", "abc")

        # After the exception, doing a query on the same table should
        # work. Since it's the same database connection as before, it
        # can fail if no rollback has been done or the connection isn't
        # in autocommit mode.  Typical error message is
        #
        #     ERROR: current transaction is aborted, commands ignored
        #     until end of transaction block
        try:
            self.assertEquals(table.ReadValue(1, "length"), 3.5)
        except psycopg2.ProgrammingError, val:
            self.fail("table didn't handle exception properly (%s)" % val)


class PostGISStaticTests(unittest.TestCase, support.FloatComparisonMixin):

    """Base class for PostGIS tests with static data."""

    def setUp(self):
        """Start the server and create a database with static data

        This method sets the following instance attributes:

           dbname -- the name of the database

           server -- The server object

           db -- the PostGISConnection object
        """
        postgissupport.skip_if_no_postgis()
        self.server = postgissupport.get_test_server()
        self.postgisdb = self.server.get_default_static_data_db()
        self.db = PostGISConnection(dbname = self.postgisdb.dbname,
                                    **self.server.connection_params("user"))

    def tearDown(self):
        """Close the database connection"""
        self.db.Close()


class TableTests:

    """Mix-in class for the PostGISTable tests

    The tests defined here make some assumptions about the table and the
    data in it:

        self.table should be the PostGISTable instance to test.  Derived
        classes should set this up in setUp.

        self.db should be the DB connection object used by self.table.

        self.table_name should be the name of the table in the database.
        The tests assume that e.g. the title of self.table can be
        derived from this.

        self.gid_column should be the name of the gid column used when
        self.table was instantiated.

        The data in the table should be the data of the
        cultural_landmark-point shapefile with the shape ids used to get
        the contents of the gid column by adding 1000.
    """

    def test_dbconn(self):
        """Test PostGISTable.DBConnection()"""
        self.failUnless(self.table.DBConnection() is self.db)

    def test_dbname(self):
        """Test PostGISTable.TableName()"""
        self.assertEquals(self.table.TableName(), self.table_name)

    def test_title(self):
        """test PostGISTable.Title()"""
        # The title is currently equal to the tablename
        self.assertEquals(self.table.Title(), self.table_name)

    def test_dependencies(self):
        """Test PostGISTable.Dependencies()"""
        # A PostGISTable depends on no other data container
        self.assertEquals(self.table.Dependencies(), ())

    def test_num_rows(self):
        """Test PostGISTable.NumRows()"""
        self.assertEquals(self.table.NumRows(), 34)

    def test_num_columns(self):
        """Test PostGISTable.NumColumns()"""
        # The table in the postgis db has one additional column, "gid",
        # so there's one more column in the PostGISTable than in the DBF
        self.assertEquals(self.table.NumColumns(), 7)

    def test_columns(self):
        """Test PostGISTable.Columns()"""
        self.assertEquals(len(self.table.Columns()), 7)
        self.assertEquals(self.table.Columns()[0].name, self.gid_column)
        self.assertEquals(self.table.Columns()[0].type, FIELDTYPE_INT)
        self.assertEquals(self.table.Columns()[0].index, 0)
        self.assertEquals(self.table.Columns()[1].name, "area")
        self.assertEquals(self.table.Columns()[1].type, FIELDTYPE_DOUBLE)
        self.assertEquals(self.table.Columns()[1].index, 1)
        self.assertEquals(self.table.Columns()[5].name, "clptlabel")
        self.assertEquals(self.table.Columns()[5].type, FIELDTYPE_STRING)
        self.assertEquals(self.table.Columns()[5].index, 5)

    def test_column(self):
        """Test PostGISTable.Column()"""
        self.assertEquals(self.table.Column("area").name, "area")
        self.assertEquals(self.table.Column("area").type, FIELDTYPE_DOUBLE)
        self.assertEquals(self.table.Column("area").index, 1)

    def test_has_column(self):
        """Test PostGISTable.HasColumn()"""
        self.assert_(self.table.HasColumn("area"))
        self.failIf(self.table.HasColumn("foo"))

    def test_read_row_as_dict(self):
        """Test PostGISTable.ReadRowAsDict()"""
        self.assertEquals(self.table.ReadRowAsDict(1003),
                          {self.gid_column: 1003,
                           "area": 0.0,
                           "perimeter": 0.0,
                           "clpoint_": 4,
                           "clpoint_id": 24,
                           "clptlabel": "RUINS",
                           "clptflag": 0})

    def test_read_row_as_dict_row_count_mode(self):
        """Test PostGISTable.ReadRowAsDict() row count address mode"""
        self.assertEquals(self.table.ReadRowAsDict(3, row_is_ordinal = 1),
                          {self.gid_column: 1003,
                           "area": 0.0,
                           "perimeter": 0.0,
                           "clpoint_": 4,
                           "clpoint_id": 24,
                           "clptlabel": "RUINS",
                           "clptflag": 0})

    def test_read_value(self):
        """Test PostGISTable.ReadValue()"""
        self.assertEquals(self.table.ReadValue(1003, 4), 24)
        self.assertEquals(self.table.ReadValue(1003, "clpoint_id"), 24)

    def test_read_value_row_count_mode(self):
        """Test PostGISTable.ReadValue() row count address mode"""
        self.assertEquals(self.table.ReadValue(3, 4, row_is_ordinal = 1), 24)
        self.assertEquals(self.table.ReadValue(3, "clpoint_id",
                                               row_is_ordinal = 1),
                          24)

    def test_row_id_to_ordinal(self):
        """Test PostGISTable.RowIdToOrdinal()"""
        self.assertEquals(self.table.RowIdToOrdinal(1005), 5)

    def test_row_oridnal_to_id(self):
        """Test PostGISTable.RowOrdinalToId()"""
        self.assertEquals(self.table.RowOrdinalToId(5), 1005)

    def test_value_range(self):
        """Test PostGISTable.ValueRange()"""
        self.assertEquals(self.table.ValueRange("clpoint_id"), (21, 74))

    def test_unique_values(self):
        """Test PostGISTable.UniqueValues()"""
        values = self.table.UniqueValues("clptlabel")
        values.sort()
        self.assertEquals(values, ["BUILDING", "FARM", "HUT","LIGHTHOUSE",
                                   "OTHER/UNKNOWN", "RUINS"])

    def test_simple_query(self):
        """Test PostGISTable.SimpleQuery()"""
        table = self.table
        self.assertEquals(table.SimpleQuery(table.Column("clptlabel"),
                                            "==", "FARM"),
                          [1006])
        self.assertEquals(table.SimpleQuery(table.Column("clpoint_id"),
                                            ">", 70),
                          [1024, 1025, 1026])
        self.assertEquals(table.SimpleQuery(table.Column("clpoint_id"),
                                            "<", table.Column("clpoint_")),
                          [1028, 1029, 1030, 1031, 1032, 1033])


class TestPostGISTable(TableTests, PostGISStaticTests):

    def setUp(self):
        """Extend inherited method to set self.table to a PostGISTable"""
        PostGISStaticTests.setUp(self)
        self.table_name = "landmarks"
        self.gid_column = "gid"

        # Note that omit the gid column here to the backwards compatible
        # interface of the constructor where the gid_column defaults to
        # "gid"
        self.table = PostGISTable(self.db, self.table_name)


class TestPostGISTableExplicitGIDColumn(TableTests, PostGISStaticTests):

    def setUp(self):
        """Extend inherited method to set self.table to a PostGISTable"""
        PostGISStaticTests.setUp(self)
        self.table_name = "landmarks_point_id"
        self.gid_column = "point_id"
        self.table = PostGISTable(self.db, self.table_name,
                                  id_column = self.gid_column)


class PointTests:

    """Mix-in class for the tests on POINT tables

    The methods in this class expect self.store to be the shapestore
    used for testing.  Derived classes should initialize self.store with
    PostGISShapeStore in setUp.  Another assumption is that the data in
    self.store is effectively the cultural_landmark-point shapefile with
    shape ids increased by 1000.
    """

    #
    # First, some tests that should be independend of the shapetype, so
    # it shouldn't be necessary to repeat them for other shapetypes
    #

    def test_dependencies(self):
        """Test PostGISShapeStore.Dependencies()"""
        # A PostGISShapeStore depends on no other data container
        self.assertEquals(self.store.Dependencies(), ())

    def test_table(self):
        """Test PostGISShapeStore.Table() with POINT shapes"""
        # A PostGISShapeStore is its own table
        self.assert_(self.store.Table() is self.store)

    def test_orig_shapestore(self):
        """Test PostGISShapeStore.OrigShapeStore() with POINT shapes"""
        # A PostGISShapeStore is not derived from another shape store
        self.assert_(self.store.OrigShapeStore() is None)

    def test_raw_format(self):
        """Test PostGISShapeStore.RawShapeFormat() with POINT shapes"""
        self.assertEquals(self.store.RawShapeFormat(), RAW_WKT)

    def test_all_shapes(self):
        """Test PostGISShapeStore.AllShapes()"""
        self.assertEquals([s.ShapeID() for s in self.store.AllShapes()],
                          range(1000, 1000 + self.store.NumShapes()))

    def test_id_column(self):
        self.assertEquals(self.store.IDColumn().name, self.id_column)

    def test_geometry_column(self):
        self.assertEquals(self.store.GeometryColumn().name,
                          self.geometry_column)

    #
    # Shapetype specific tests
    #

    def test_shape_type(self):
        """Test PostGISShapeStore.ShapeType() with POINT shapes"""
        self.assertEquals(self.store.ShapeType(), SHAPETYPE_POINT)

    def test_num_shapes(self):
        """Test PostGISShapeStore.NumShapes() with POINT shapes"""
        self.assertEquals(self.store.NumShapes(), 34)

    def test_bounding_box(self):
        """Test PostGISShapeStore.BoundingBox() with POINT shapes"""
        self.assertFloatSeqEqual(self.store.BoundingBox(),
                                 [-23.806047439575195, 63.405960083007812,
                                  -15.12291431427002, 66.36572265625])

    def test_shape_shapeid(self):
        """Test PostGISShapeStore.Shape(i).ShapeID() with POINT shapes"""
        self.assertEquals(self.store.Shape(1005).ShapeID(), 1005)

    def test_shape_points(self):
        """Test PostGISShapeStore.Shape(i).Points() with POINT shapes"""
        self.assertPointListEquals(self.store.Shape(1000).Points(),
                                   [[(-22.711074829101562, 66.36572265625)]])

    def test_shape_raw_data(self):
        """Test PostGISShapeStore.Shape(i).RawData() with POINT shapes"""
        self.assertEquals(self.store.Shape(1000).RawData(),
                          'POINT(-22.7110748291016 66.36572265625)')

    def test_shapes_in_region(self):
        """Test PostGISShapeStore:ShapesInRegion() with POINT shapes"""
        shapes = self.store.ShapesInRegion((-20.0, 64.0, -24.0, 67))
        self.assertEquals([s.ShapeID() for s in shapes],
                          [1000, 1001, 1002, 1003, 1004, 1005, 1027])


class TestPostGISShapestorePoint(PointTests, PostGISStaticTests):

    """Tests for PostGISShapeStore objects with POINT data an no SRID"""

    def setUp(self):
        """Extend inherited method to set self.table to a PostGISShapeStore"""
        PostGISStaticTests.setUp(self)
        self.id_column = "gid"
        self.geometry_column = "the_geom"
        self.store = PostGISShapeStore(self.db, "landmarks")



class TestPostGISShapestorePointSRID(PointTests, PostGISStaticTests):

    """Tests for PostGISShapeStore objects with POINT data and an SRID"""

    def setUp(self):
        """Extend inherited method to set self.table to a PostGISShapeStore"""
        PostGISStaticTests.setUp(self)
        self.id_column = "gid"
        self.geometry_column = "the_geom"
        self.store = PostGISShapeStore(self.db, "landmarks_srid")


class TestPostGISShapestorePointExplicitGIDColumn(PointTests,
                                                  PostGISStaticTests):

    """Tests for PostGISShapeStores with POINT data and explicit gid column"""

    def setUp(self):
        """Extend inherited method to set self.table to a PostGISShapeStore"""
        PostGISStaticTests.setUp(self)
        self.id_column = "point_id"
        self.geometry_column = "the_geom"
        self.store = PostGISShapeStore(self.db, "landmarks_point_id",
                                       id_column = "point_id")


class TestPostGISShapestorePointOIDAsGIDColumn(PointTests, PostGISStaticTests):

    """Tests for PostGISShapeStores with POINT data using OID as gid column"""

    def setUp(self):
        """Extend inherited method to set self.table to a PostGISShapeStore"""
        PostGISStaticTests.setUp(self)
        self.id_column = "oid"
        self.geometry_column = "the_geom"
        self.store = PostGISShapeStore(self.db, "landmarks_point_id",
                                       id_column = self.id_column,
                                       geometry_column = self.geometry_column)

    def find_test_shape_id(self):
        """Return the id of an interesting shape for some test cases.

        This test uses OIDs so we can't easily hard wire ids in the test
        cases
        """
        # get the id of an interesting shape
        shapes = self.store.ShapesInRegion((-20.0, 64.0, -24.0, 67))
        return list(shapes)[0].ShapeID()


    # Override a few tests that won't work with this table because they
    # require knowledge of specific IDs

    def test_shape_shapeid(self):
        """Test PostGISShapeStore.Shape(i).ShapeID() with POINT shapes"""
        gid = self.find_test_shape_id()
        self.assertEquals(self.store.Shape(gid).ShapeID(), gid)

    def test_shape_points(self):
        """Test PostGISShapeStore.Shape(i).Points() with POINT shapes"""
        gid = self.find_test_shape_id()
        self.assertPointListEquals(self.store.Shape(gid).Points(),
                                   [[(-22.711074829101562, 66.36572265625)]])

    def test_shape_raw_data(self):
        """Test PostGISShapeStore.Shape(i).RawData() with POINT shapes"""
        gid = self.find_test_shape_id()
        self.assertEquals(self.store.Shape(gid).RawData(),
                          'POINT(-22.7110748291016 66.36572265625)')

    def test_shapes_in_region(self):
        """Test PostGISShapeStore:ShapesInRegion() with POINT shapes"""
        shapes = self.store.ShapesInRegion((-20.0, 64.0, -24.0, 67))
        self.assertEquals(len(list(shapes)), 7)

    def test_all_shapes(self):
        """Test PostGISShapeStore.AllShapes()"""
        self.assertEquals(len(list(self.store.AllShapes())), 34)


class TestPostGISShapestorePointFromViews(PointTests, PostGISStaticTests):

    """Tests for PostGISShapeStores with POINT data in a view"""

    def setUp(self):
        """Extend inherited method to set self.table to a PostGISShapeStore"""
        PostGISStaticTests.setUp(self)
        self.id_column = "point_id"
        self.geometry_column = "the_geom"
        self.store = PostGISShapeStore(self.db, "v_landmarks",
                                       id_column = "point_id")


class LineStringTests:

    """Tests shared by the LINESTRING and MULTILINESTRING tests.

    The tests are the same because they are based on the same data.
    """

    def test_shape_type(self):
        """Test PostGISShapeStore.ShapeType() with ARC shapes"""
        self.assertEquals(self.store.ShapeType(), SHAPETYPE_ARC)

    def test_num_shapes(self):
        """Test PostGISShapeStore.NumShapes() with ARC shapes"""
        self.assertEquals(self.store.NumShapes(), 839)

    def test_bounding_box(self):
        """Test PostGISShapeStore.BoundingBox() with ARC shapes"""
        self.assertFloatSeqEqual(self.store.BoundingBox(),
                                 [-24.450359344482422, 63.426830291748047,
                                  -13.55668830871582, 66.520111083984375])

    def test_shape_shapeid(self):
        """Test PostGISShapeStore.Shape(i).ShapeID() with ARC shapes"""
        self.assertEquals(self.store.Shape(5).ShapeID(), 5)

    def test_shape_points(self):
        """Test PostGISShapeStore.Shape(i).Points() with ARC shapes"""
        self.assertPointListEquals(self.store.Shape(32).Points(),
                                   [[(-15.0821743011474, 66.2773818969726),
                                     (-15.0263500213623, 66.2733917236328)]])

    def test_shapes_in_region(self):
        """Test PostGISShapeStore.ShapesInRegion() with ARC shapes"""
        shapes = self.store.ShapesInRegion((-24.0, 64.5, -23.5, 65.0))
        self.assertEquals([s.ShapeID() for s in shapes], [573, 581, 613])


class TestPostGISShapestoreLineString(LineStringTests, PostGISStaticTests):

    """Tests for PostGISShapeStore objects with LINESTRING data"""

    def setUp(self):
        """Extend inherited method to set self.table to a PostGISShapeStore"""
        PostGISStaticTests.setUp(self)
        self.store = PostGISShapeStore(self.db, "roads")

    def test_shape_raw_data(self):
        """Test PostGISShapeStore.Shape(i).RawData() with ARC shapes"""
        self.assertEquals(self.store.Shape(32).RawData(),
                     "LINESTRING(-15.0821743011475 66.2773818969727,"
                                "-15.0263500213623 66.2733917236328)")


class TestPostGISShapestoreMultiLineString(LineStringTests,
                                           PostGISStaticTests):

    """Tests for PostGISShapeStore objects with MULTILINESTRING data"""

    def setUp(self):
        """Extend inherited method to set self.table to a PostGISShapeStore"""
        PostGISStaticTests.setUp(self)
        self.store = PostGISShapeStore(self.db, "roads_multi")

    def test_shape_raw_data(self):
        """Test PostGISShapeStore.Shape(i).RawData() with ARC shapes"""
        self.assertEquals(self.store.Shape(32).RawData(),
                     "MULTILINESTRING((-15.0821743011475 66.2773818969727,"
                                      "-15.0263500213623 66.2733917236328))")


class PolygonTests:

    """Test shared by the POLYGON and MULTIPOLYGON tests

    The tests are the same because they are based on the same data.
    """

    def test_shape_type(self):
        """Test PostGISShapeStore.ShapeType() with POLYGON shapes"""
        self.assertEquals(self.store.ShapeType(), SHAPETYPE_POLYGON)

    def test_num_shapes(self):
        """Test PostGISShapeStore.NumShapes() with POLYGON shapes"""
        self.assertEquals(self.store.NumShapes(), 156)

    def test_bounding_box(self):
        """Test PostGISShapeStore.BoundingBox() with POLYGON shapes"""
        self.assertFloatSeqEqual(self.store.BoundingBox(),
                                 [-24.546524047851562, 63.286754608154297,
                                  -13.495815277099609, 66.563774108886719])

    def test_shape_shapeid(self):
        """Test PostGISShapeStore.Shape(i).ShapeID() with POLYGON shapes"""
        self.assertEquals(self.store.Shape(5).ShapeID(), 5)

    def test_shape_points(self):
        """Test PostGISShapeStore.Shape(i).Points() with POLYGON shapes"""
        self.assertPointListEquals(self.store.Shape(4).Points(),
                                   [[(-22.40639114379882, 64.714111328125),
                                     (-22.41621208190918, 64.716003417968),
                                     (-22.40605163574218, 64.719200134277),
                                     (-22.40639114379882, 64.714111328125)]])

    def test_shapes_in_region(self):
        """Test PostGISShapeStore.ShapesInRegion() with POLYGON shapes"""
        shapes = self.store.ShapesInRegion((-23.0, 65.5, -22.8, 65.25))
        self.assertEquals([s.ShapeID() for s in shapes],
                          [47, 56, 59, 61, 62, 71, 144])


class TestPostGISShapestorePolygon(PolygonTests, PostGISStaticTests):

    """Tests for PostGISShapeStore objects with POLYGON data"""

    def setUp(self):
        """Extend inherited method to set self.table to a PostGISShapeStore"""
        PostGISStaticTests.setUp(self)
        self.store = PostGISShapeStore(self.db, "political")

    def test_shape_type(self):
        """Test PostGISShapeStore.ShapeType() with POLYGON shapes"""
        self.assertEquals(self.store.ShapeType(), SHAPETYPE_POLYGON)


    def test_shape_raw_data(self):
        """Test PostGISShapeStore.Shape(i).RawData() with POLYGON shapes"""
        self.assertEquals(self.store.Shape(4).RawData(),
                          "POLYGON((-22.4063911437988 64.714111328125,"
                                   "-22.4162120819092 64.7160034179688,"
                                   "-22.4060516357422 64.7192001342773,"
                                   "-22.4063911437988 64.714111328125))")


class TestPostGISShapestoreMultiPolygon(PolygonTests, PostGISStaticTests):

    """Tests for PostGISShapeStore objects with MUTLIPOLYGON data"""

    def setUp(self):
        """Extend inherited method to set self.table to a PostGISShapeStore"""
        PostGISStaticTests.setUp(self)
        self.store = PostGISShapeStore(self.db, "political_multi")

    def test_shape_raw_data(self):
        """Test PostGISShapeStore.Shape(i).RawData() with POLYGON shapes"""
        self.assertEquals(self.store.Shape(4).RawData(),
                          "MULTIPOLYGON(((-22.4063911437988 64.714111328125,"
                                         "-22.4162120819092 64.7160034179688,"
                                         "-22.4060516357422 64.7192001342773,"
                                        "-22.4063911437988 64.714111328125)))")



if __name__ == "__main__":
    support.run_tests()