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

Diff of /branches/WIP-pyshapelib-bramz/test/test_load.py

Parent Directory Parent Directory | Revision Log Revision Log | View Patch Patch

revision 1642 by bh, Mon Aug 25 10:54:31 2003 UTC revision 1976 by bh, Tue Nov 25 14:26:08 2003 UTC
# Line 34  import unittest Line 34  import unittest
34  import support  import support
35  support.initthuban()  support.initthuban()
36    
37    import postgissupport
38  from xmlsupport import sax_eventlist  from xmlsupport import sax_eventlist
39    
40  import dbflib  import dbflib
41    import shapelib
42    
43  from Thuban.Model.save import save_session  from Thuban.Model.save import save_session
44  from Thuban.Model.load import load_session, parse_color, LoadError  from Thuban.Model.load import load_session, parse_color, LoadError, \
45         LoadCancelled
46  from Thuban.Model.color import Transparent  from Thuban.Model.color import Transparent
47  from Thuban.Model.classification import ClassGroupProperties, ClassGroupRange,\  from Thuban.Model.classification import ClassGroupProperties, ClassGroupRange,\
48      ClassGroupSingleton, ClassGroupDefault      ClassGroupSingleton, ClassGroupDefault
49    from Thuban.Model.postgisdb import ConnectionError
50    from Thuban.Model.table import DBFTable, MemoryTable, \
51         FIELDTYPE_DOUBLE, FIELDTYPE_INT, FIELDTYPE_STRING, \
52         table_to_dbf
53    
54    
55  def filenames_equal(name1, name2):  def filenames_equal(name1, name2):
# Line 80  class LoadSessionTest(support.FileLoadTe Line 87  class LoadSessionTest(support.FileLoadTe
87          self.session = None          self.session = None
88    
89    
90      dtd = "http://thuban.intevation.org/dtds/thuban-0.9-dev.dtd"      dtd = "http://thuban.intevation.org/dtds/thuban-1.0-dev.dtd"
91      thubanids = [((dtd, n), (None, "id")) for n in      thubanids = [((dtd, n), (None, "id")) for n in
92                   ["fileshapesource", "filetable", "jointable",                   ["fileshapesource", "filetable", "jointable",
93                    "derivedshapesource"]]                    "derivedshapesource"]]
# Line 90  class LoadSessionTest(support.FileLoadTe Line 97  class LoadSessionTest(support.FileLoadTe
97                       ("jointable", "right"),                       ("jointable", "right"),
98                       ("derivedshapesource", "table"),                       ("derivedshapesource", "table"),
99                       ("derivedshapesource", "shapesource")]]                       ("derivedshapesource", "shapesource")]]
100        filenames = [((dtd, n), (None, m)) for n, m in
101                     [("fileshapesource", "filename"),
102                      ("rasterlayer", "filename"),
103                      ("filetable", "filename")]]
104      del n, m, dtd      del n, m, dtd
105    
106      def check_format(self):      def check_format(self):
# Line 100  class LoadSessionTest(support.FileLoadTe Line 111  class LoadSessionTest(support.FileLoadTe
111          filename = self.temp_file_name(self.id() + ".roundtrip.thuban")          filename = self.temp_file_name(self.id() + ".roundtrip.thuban")
112          save_session(self.session, filename)          save_session(self.session, filename)
113          el1 = sax_eventlist(filename = filename, ids = self.thubanids,          el1 = sax_eventlist(filename = filename, ids = self.thubanids,
114                              idrefs = self.thubanidrefs)                              idrefs = self.thubanidrefs,
115                                filenames = self.filenames)
116          el2 = sax_eventlist(filename = self.filename(), ids = self.thubanids,          el2 = sax_eventlist(filename = self.filename(), ids = self.thubanids,
117                              idrefs = self.thubanidrefs)                              idrefs = self.thubanidrefs,
118                                filenames = self.filenames)
119          if 0:          if 0:
120              for a, b in zip(el1, el2):              for a, b in zip(el1, el2):
121                  print a != b and "***************" or ""                  print a != b and "***************" or ""
# Line 165  class ClassificationTest(LoadSessionTest Line 178  class ClassificationTest(LoadSessionTest
178    
179  class TestSingleLayer(LoadSessionTest):  class TestSingleLayer(LoadSessionTest):
180    
181        # Note: The use of & and non-ascii characters is deliberate. We
182        # want to test whether the loading code handles that correctly.
183      file_contents = '''\      file_contents = '''\
184  <?xml version="1.0" encoding="UTF-8"?>  <?xml version="1.0" encoding="UTF-8"?>
185  <!DOCTYPE session SYSTEM "thuban-0.9.dtd">  <!DOCTYPE session SYSTEM "thuban-1.0.dtd">
186  <session xmlns="http://thuban.intevation.org/dtds/thuban-0.9-dev.dtd"  <session xmlns="http://thuban.intevation.org/dtds/thuban-1.0-dev.dtd"
187          title="single map&amp;layer">          title="Stra\xc3\x9fen &amp; Landmarken">
188      <fileshapesource filetype="shapefile" id="D1"      <fileshapesource filetype="shapefile" id="D1"
189          filename="../../Data/iceland/political.shp"/>          filename="../../Data/iceland/political.shp"/>
190      <map title="Test Map">      <map title="\xc3\x9cbersicht">
191          <projection name="Unknown">          <projection epsg="32627" name="WGS 84 / UTM zone 27N">
192              <parameter value="zone=26"/>              <parameter value="datum=WGS84"/>
193                <parameter value="ellps=WGS84"/>
194              <parameter value="proj=utm"/>              <parameter value="proj=utm"/>
195              <parameter value="ellps=clrk66"/>              <parameter value="units=m"/>
196                <parameter value="zone=27"/>
197          </projection>          </projection>
198          <layer shapestore="D1" visible="true"          <layer shapestore="D1" visible="true"
199                  stroke="#000000" title="My Layer" stroke_width="1"                  stroke="#000000" title="K\xc3\xbcste" stroke_width="1"
200                  fill="None"/>                  fill="None"/>
201      </map>      </map>
202  </session>  </session>
# Line 192  class TestSingleLayer(LoadSessionTest): Line 209  class TestSingleLayer(LoadSessionTest):
209          self.session = session          self.session = session
210    
211          # Check the title          # Check the title
212          eq(session.Title(), "single map&layer")          eq(session.Title(), "Stra\xdfen & Landmarken")
213    
214          # the session has one map.          # the session has one map.
215          maps = session.Maps()          maps = session.Maps()
# Line 200  class TestSingleLayer(LoadSessionTest): Line 217  class TestSingleLayer(LoadSessionTest):
217    
218          # Check the map's attributes          # Check the map's attributes
219          map = maps[0]          map = maps[0]
220          eq(map.Title(), "Test Map")          eq(map.Title(), "\xdcbersicht")
221            proj = map.GetProjection()
222            eq(proj.GetName(), "WGS 84 / UTM zone 27N")
223            eq(proj.EPSGCode(), "32627")
224            params = proj.GetAllParameters()
225            params.sort()
226            eq(params, ["datum=WGS84", "ellps=WGS84", "proj=utm", "units=m",
227                        "zone=27"])
228    
229          # the map has a single layer          # the map has a single layer
230          layers = map.Layers()          layers = map.Layers()
# Line 208  class TestSingleLayer(LoadSessionTest): Line 232  class TestSingleLayer(LoadSessionTest):
232    
233          # Check the layer attributes          # Check the layer attributes
234          layer = layers[0]          layer = layers[0]
235          eq(layer.Title(), "My Layer")          eq(layer.Title(), "K\xfcste")
236          self.failUnless(filenames_equal(layer.ShapeStore().FileName(),          self.failUnless(filenames_equal(layer.ShapeStore().FileName(),
237                                          os.path.join(self.temp_dir(),                                          os.path.join(self.temp_dir(),
238                                                       os.pardir, os.pardir,                                                       os.pardir, os.pardir,
# Line 223  class TestSingleLayer(LoadSessionTest): Line 247  class TestSingleLayer(LoadSessionTest):
247          self.session.Destroy()          self.session.Destroy()
248          self.session = None          self.session = None
249    
250        def test_leak(self):
251            """Test load_session for resource leaks
252    
253            The load_session function had a resource leak in that it created
254            cyclic references. The objects would have been eventually
255            collected by the garbage collector but too late. One symptom is
256            that when layers are removed so that the last normal reference
257            owned indirectly by the session to a shape store goes away, the
258            shape store is not actually removed from the session even though
259            the session only keeps weak references because there are still
260            references owned by the cyclic garbage.
261            """
262            session = load_session(self.filename())
263            self.session = session
264    
265            # sanity check
266            self.assertEquals(len(session.ShapeStores()), 1)
267    
268            # remove the map. The shapestore should go away too
269            session.RemoveMap(session.Maps()[0])
270            self.assertEquals(len(session.ShapeStores()), 0)
271    
272    
273    class TestNonAsciiColumnName(LoadSessionTest):
274    
275        file_contents = '''\
276    <?xml version="1.0" encoding="UTF-8"?>
277    <!DOCTYPE session SYSTEM "thuban-1.0.dtd">
278    <session xmlns="http://thuban.intevation.org/dtds/thuban-1.0-dev.dtd"
279            title="Non ASCII column name test">
280        <fileshapesource filetype="shapefile" id="D1"
281            filename="TestNonAsciiColumnName.shp"/>
282        <map title="map">
283            <projection name="Some Projection">
284                <parameter value="datum=WGS84"/>
285                <parameter value="ellps=WGS84"/>
286                <parameter value="proj=utm"/>
287                <parameter value="units=m"/>
288                <parameter value="zone=27"/>
289            </projection>
290            <layer shapestore="D1" visible="true"
291                    stroke="#000000" title="layer" stroke_width="1"
292                    fill="None">
293                <classification field="Fl\xc3\xa4che" field_type="double">
294                    <clnull label="">
295                        <cldata stroke="#000000" stroke_width="1" fill="None"/>
296                    </clnull>
297                </classification>
298            </layer>
299        </map>
300    </session>
301    '''
302    
303        def test(self):
304            """Load a session with a single map with a single layer"""
305    
306            # Create a shapefile and a dbffile with a non-ascii column name
307            dbffile = self.temp_file_name("TestNonAsciiColumnName.dbf")
308            shpfile = self.temp_file_name("TestNonAsciiColumnName.shp")
309            dbf = dbflib.create(dbffile)
310            dbf.add_field('Fl\xe4che', dbflib.FTDouble, 10, 5)
311            dbf.write_record(0, (0.0,))
312            dbf.close()
313            shp = shapelib.create(shpfile, shapelib.SHPT_POLYGON)
314            shp.write_object(-1, shapelib.SHPObject(shapelib.SHPT_POLYGON, 1,
315                                                    [[(0,0), (10, 10), (10, 0),
316                                                      (0, 0)]]))
317            shp.close()
318    
319            try:
320                session = load_session(self.filename())
321            except ValueError, v:
322                # Usually if the field name is not decoded properly the
323                # loading fails because the field type mentioned in the file
324                # is not None as returned from the layer for a non-existing
325                # column name so we check for that and report it as failure.
326                # Other exceptions are errors in the test case.
327                if str(v) == "xml field type differs from database!":
328                    self.fail("Cannot load file with non-ascii column names")
329                else:
330                    raise
331            self.session = session
332    
333            # In case Thuban could load the file anyway (i.e. no ValueError
334            # exception in load_session()), check explicitly whether the
335            # field name was decoded properly. The test will probably lead
336            # to a UnicodeError instead of a test failure so we check that
337            # too
338            layer = session.Maps()[0].Layers()[0]
339            try:
340                self.assertEquals(layer.GetClassificationColumn(), 'Fl\xe4che')
341            except UnicodeError:
342                # FIXME: Obviously this will have to change if Thuban ever
343                # supports unicode properly.
344                self.fail("Column name was not converted to a bytestring")
345    
346            # roundtrip check
347            self.check_format()
348    
349    
350  class TestLayerVisibility(LoadSessionTest):  class TestLayerVisibility(LoadSessionTest):
351    
352      file_contents = '''\      file_contents = '''\
353  <?xml version="1.0" encoding="UTF-8"?>  <?xml version="1.0" encoding="UTF-8"?>
354  <!DOCTYPE session SYSTEM "thuban-0.9.dtd">  <!DOCTYPE session SYSTEM "thuban-1.0.dtd">
355  <session xmlns="http://thuban.intevation.org/dtds/thuban-0.9-dev.dtd"  <session xmlns="http://thuban.intevation.org/dtds/thuban-1.0-dev.dtd"
356          title="single map&amp;layer">          title="single map&amp;layer">
357      <fileshapesource filetype="shapefile" id="D1"      <fileshapesource filetype="shapefile" id="D1"
358          filename="../../Data/iceland/political.shp"/>          filename="../../Data/iceland/political.shp"/>
# Line 266  class TestClassification(ClassificationT Line 389  class TestClassification(ClassificationT
389    
390      file_contents = '''\      file_contents = '''\
391  <?xml version="1.0" encoding="UTF-8"?>  <?xml version="1.0" encoding="UTF-8"?>
392  <!DOCTYPE session SYSTEM "thuban.dtd">  <!DOCTYPE session SYSTEM "thuban-1.0.dtd">
393  <session title="single map&amp;layer">  <session xmlns="http://thuban.intevation.org/dtds/thuban-1.0-dev.dtd"
394          <map title="Test Map">          title="single map&amp;layer">
395                  <projection>      <fileshapesource filetype="shapefile" id="D138389860"
396                          <parameter value="zone=26"/>          filename="../../Data/iceland/political.shp"/>
397                          <parameter value="proj=utm"/>      <fileshapesource filetype="shapefile" id="D138504492"
398                          <parameter value="ellps=clrk66"/>          filename="../../Data/iceland/political.shp"/>
399                  </projection>      <map title="Test Map">
400                  <layer title="My Layer" stroke_width="1" fill="None"          <projection name="">
401                      filename="../../Data/iceland/political.shp"              <parameter value="zone=26"/>
402                      stroke="#000000">              <parameter value="proj=utm"/>
403                <parameter value="ellps=clrk66"/>
404            </projection>
405            <layer shapestore="D138389860" visible="true" stroke="#000000"
406                    title="My Layer" stroke_width="1" fill="None">
407              <classification field="POPYREG" field_type="string">              <classification field="POPYREG" field_type="string">
408                  <clnull>                  <clnull label="">
409                      <cldata stroke="#000000" stroke_width="1" fill="None"/>                      <cldata stroke="#000000" stroke_width="1" fill="None"/>
410                  </clnull>                  </clnull>
411                  <clpoint value="1">                  <clpoint label="" value="1">
412                      <cldata stroke="#000000" stroke_width="2" fill="None"/>                      <cldata stroke="#000000" stroke_width="2" fill="None"/>
413                  </clpoint>                  </clpoint>
414                  <clpoint value="1">                  <clpoint label="" value="1">
415                      <cldata stroke="#000000" stroke_width="10" fill="None"/>                      <cldata stroke="#000000" stroke_width="10" fill="None"/>
416                  </clpoint>                  </clpoint>
417                  <clpoint value="\xc3\xa4\xc3\xb6\xc3\xbc"                  <clpoint label="\xc3\x9cml\xc3\xa4uts"
418                           label="\xc3\x9cml\xc3\xa4uts">                          value="\xc3\xa4\xc3\xb6\xc3\xbc">
419                      <cldata fill="None" stroke="#000000" stroke_width="1"/>                      <cldata stroke="#000000" stroke_width="1" fill="None"/>
420                  </clpoint>                  </clpoint>
421              </classification>              </classification>
422          </layer>          </layer>
423                  <layer title="My Layer 2" stroke_width="1" fill="None"          <layer shapestore="D138504492" visible="true" stroke="#000000"
424                      filename="../../Data/iceland/political.shp"                  title="My Layer 2" stroke_width="2" fill="None">
                     stroke="#000000">  
425              <classification field="AREA" field_type="double">              <classification field="AREA" field_type="double">
426                  <clnull>                  <clnull label="">
427                      <cldata stroke="#000000" stroke_width="2" fill="None"/>                      <cldata stroke="#000000" stroke_width="2" fill="None"/>
428                  </clnull>                  </clnull>
429                  <clrange min="0" max="1">                  <clrange label="" range="[0;1[">
430                      <cldata stroke="#111111" stroke_width="1" fill="None"/>                      <cldata stroke="#111111" stroke_width="1" fill="None"/>
431                  </clrange>                  </clrange>
432                  <clpoint value=".5">                  <clpoint label="" value="0.5">
433                      <cldata stroke="#000000" stroke_width="1" fill="#111111"/>                      <cldata stroke="#000000" stroke_width="1" fill="#111111"/>
434                  </clpoint>                  </clpoint>
435                  <clrange min="-1" max="0">                  <clrange label="" range="[-1;0[">
436                      <cldata stroke="#000000" stroke_width="1" fill="None"/>                      <cldata stroke="#000000" stroke_width="1" fill="None"/>
437                  </clrange>                  </clrange>
438                  <clpoint value="-.5">                  <clpoint label="" value="-0.5">
439                      <cldata stroke="#000000" stroke_width="1" fill="None"/>                      <cldata stroke="#000000" stroke_width="1" fill="None"/>
440                  </clpoint>                  </clpoint>
441              </classification>              </classification>
442          </layer>          </layer>
443          </map>      </map>
444  </session>  </session>
445  '''  '''
446    
# Line 348  class TestClassification(ClassificationT Line 474  class TestClassification(ClassificationT
474    
475          self.TestLayers(map.Layers(), expected)          self.TestLayers(map.Layers(), expected)
476    
477            self.check_format()
478    
479    
480  class TestLabels(ClassificationTest):  class TestLabels(ClassificationTest):
481    
482      file_contents = '''\      file_contents = '''\
483  <?xml version="1.0" encoding="UTF-8"?>  <?xml version="1.0" encoding="UTF-8"?>
484  <!DOCTYPE session SYSTEM "thuban-0.9.dtd">  <!DOCTYPE session SYSTEM "thuban-1.0.dtd">
485  <session xmlns="http://thuban.intevation.org/dtds/thuban-0.9-dev.dtd"  <session xmlns="http://thuban.intevation.org/dtds/thuban-1.0-dev.dtd"
486          title="single map&amp;layer">          title="single map&amp;layer">
487      <fileshapesource filetype="shapefile" id="D1"      <fileshapesource filetype="shapefile" id="D1"
488          filename="../../Data/iceland/political.shp"/>          filename="../../Data/iceland/political.shp"/>
# Line 401  class TestLayerProjection(LoadSessionTes Line 529  class TestLayerProjection(LoadSessionTes
529    
530      file_contents = '''\      file_contents = '''\
531  <?xml version="1.0" encoding="UTF-8"?>  <?xml version="1.0" encoding="UTF-8"?>
532  <!DOCTYPE session SYSTEM "thuban-0.9.dtd">  <!DOCTYPE session SYSTEM "thuban-1.0.dtd">
533  <session xmlns="http://thuban.intevation.org/dtds/thuban-0.9-dev.dtd"  <session xmlns="http://thuban.intevation.org/dtds/thuban-1.0-dev.dtd"
534          title="single map&amp;layer">          title="single map&amp;layer">
535      <fileshapesource filetype="shapefile" id="D2"      <fileshapesource filetype="shapefile" id="D2"
536          filename="../../Data/iceland/roads-line.shp"/>          filename="../../Data/iceland/roads-line.shp"/>
# Line 434  class TestLayerProjection(LoadSessionTes Line 562  class TestLayerProjection(LoadSessionTes
562                  title="My Layer" stroke_width="1" fill="None">                  title="My Layer" stroke_width="1" fill="None">
563              <projection name="Unknown">              <projection name="Unknown">
564                  <parameter value="proj=lcc"/>                  <parameter value="proj=lcc"/>
565                    <parameter value="lat_1=10"/>
566                    <parameter value="lat_2=20"/>
567                  <parameter value="ellps=clrk66"/>                  <parameter value="ellps=clrk66"/>
568              </projection>              </projection>
569          </layer>          </layer>
# Line 466  class TestLayerProjection(LoadSessionTes Line 596  class TestLayerProjection(LoadSessionTes
596          neq(proj, None)          neq(proj, None)
597          eq(proj.GetName(), "Unknown")          eq(proj.GetName(), "Unknown")
598          eq(proj.GetParameter("proj"), "lcc")          eq(proj.GetParameter("proj"), "lcc")
599            eq(proj.GetParameter("lat_1"), "10")
600            eq(proj.GetParameter("lat_2"), "20")
601          eq(proj.GetParameter("ellps"), "clrk66")          eq(proj.GetParameter("ellps"), "clrk66")
602    
603          self.check_format()          self.check_format()
# Line 475  class TestRasterLayer(LoadSessionTest): Line 607  class TestRasterLayer(LoadSessionTest):
607    
608      file_contents = '''\      file_contents = '''\
609  <?xml version="1.0" encoding="UTF-8"?>  <?xml version="1.0" encoding="UTF-8"?>
610  <!DOCTYPE session SYSTEM "thuban-0.9.dtd">  <!DOCTYPE session SYSTEM "thuban-1.0.dtd">
611  <session xmlns="http://thuban.intevation.org/dtds/thuban-0.9-dev.dtd"  <session xmlns="http://thuban.intevation.org/dtds/thuban-1.0-dev.dtd"
612          title="single map&amp;layer">          title="single map&amp;layer">
613      <map title="Test Map">      <map title="Test Map">
614          <rasterlayer visible="false" filename="../../Data/iceland/island.tif"          <rasterlayer visible="false" filename="../../Data/iceland/island.tif"
# Line 509  class TestRasterLayer(LoadSessionTest): Line 641  class TestRasterLayer(LoadSessionTest):
641  class TestJoinedTable(LoadSessionTest):  class TestJoinedTable(LoadSessionTest):
642    
643      file_contents = '''<?xml version="1.0" encoding="UTF-8"?>      file_contents = '''<?xml version="1.0" encoding="UTF-8"?>
644  <!DOCTYPE session SYSTEM "thuban-0.9.dtd">  <!DOCTYPE session SYSTEM "thuban-1.0.dtd">
645  <session xmlns="http://thuban.intevation.org/dtds/thuban-0.9-dev.dtd" title="A Joined Table session">  <session xmlns="http://thuban.intevation.org/dtds/thuban-1.0-dev.dtd" title="A Joined Table session">
646      <fileshapesource filetype="shapefile" id="D137227612"      <fileshapesource filetype="shapefile" id="D137227612"
647          filename="../../Data/iceland/roads-line.shp"/>          filename="../../Data/iceland/roads-line.shp"/>
648      <filetable filetype="DBF" filename="load_joinedtable.dbf" id="D136171140"      <filetable filetype="DBF" filename="load_joinedtable.dbf" id="D136171140"
# Line 554  class TestJoinedTable(LoadSessionTest): Line 686  class TestJoinedTable(LoadSessionTest):
686          self.check_format()          self.check_format()
687    
688    
689    
690    class TestPostGISLayer(LoadSessionTest):
691    
692        file_contents = '''<?xml version="1.0" encoding="UTF-8"?>
693    <!DOCTYPE session SYSTEM "thuban-1.0.dtd">
694    <session xmlns="http://thuban.intevation.org/dtds/thuban-1.0-dev.dtd"
695            title="unnamed session">
696        <dbconnection port="%(port)s" host="%(host)s" user="%(user)s"
697            dbtype="postgis" id="D142684948" dbname="%(dbname)s"/>
698        <dbshapesource tablename="landmarks" id="D143149420" dbconn="D142684948"/>
699        <map title="unnamed map">
700            <layer shapestore="D143149420" visible="true" stroke="#000000"
701                    title="landmarks" stroke_width="1" fill="None"/>
702        </map>
703    </session>
704    '''
705    
706        def setUp(self):
707            """Extend the inherited method to start the postgis server
708    
709            Furthermore, patch the file contents with the real postgis db
710            information
711            """
712            postgissupport.skip_if_no_postgis()
713            self.server = postgissupport.get_test_server()
714            self.postgisdb = self.server.get_default_static_data_db()
715    
716            self.file_contents = self.__class__.file_contents % {
717                "dbname": self.postgisdb.dbname,
718                "user": self.server.user_name,
719                "port": self.server.port,
720                "host": self.server.host}
721            LoadSessionTest.setUp(self)
722    
723        def test(self):
724            """Test loading a session containing a postgis shapestore"""
725            session = load_session(self.filename())
726            self.session = session
727            connections = session.DBConnections()
728            self.assertEquals(len(connections), 1)
729            conn = connections[0]
730            for attr, value in [("host", self.server.host),
731                                ("port", str(self.server.port)),
732                                ("user", self.server.user_name),
733                                ("dbname", self.postgisdb.dbname)]:
734                self.assertEquals(getattr(conn, attr), value)
735            layer = session.Maps()[0].Layers()[0]
736            self.failUnless(layer.ShapeStore().DBConnection() is conn)
737    
738    
739    class TestPostGISLayerPassword(LoadSessionTest):
740    
741        file_contents = '''<?xml version="1.0" encoding="UTF-8"?>
742    <!DOCTYPE session SYSTEM "thuban-1.0.dtd">
743    <session xmlns="http://thuban.intevation.org/dtds/thuban-1.0-dev.dtd"
744            title="unnamed session">
745        <dbconnection port="%(port)s" host="%(host)s" user="%(user)s"
746            dbtype="postgis" id="D142684948" dbname="%(dbname)s"/>
747        <dbshapesource tablename="landmarks" id="D143149420" dbconn="D142684948"/>
748        <map title="unnamed map">
749            <layer shapestore="D143149420" visible="true" stroke="#000000"
750                    title="landmarks" stroke_width="1" fill="None"/>
751        </map>
752    </session>
753    '''
754    
755        def setUp(self):
756            """Extend the inherited method to start the postgis server
757    
758            Furthermore, patch the file contents with the real postgis db
759            information
760            """
761            postgissupport.skip_if_no_postgis()
762            self.server = postgissupport.get_test_server()
763            self.postgisdb = self.server.get_default_static_data_db()
764    
765            self.file_contents = self.__class__.file_contents % {
766                "dbname": self.postgisdb.dbname,
767                "user": self.server.user_name,
768                "port": self.server.port,
769                "host": self.server.host}
770            LoadSessionTest.setUp(self)
771    
772            self.db_connection_callback_called = False
773            self.server.require_authentication(True)
774    
775        def tearDown(self):
776            """Extend the inherited method to switch off postgresql authentication
777            """
778            self.server.require_authentication(False)
779            LoadSessionTest.tearDown(self)
780    
781        def db_connection_callback(self, params, message):
782            """Implementation of Thuban.Model.hooks.query_db_connection_parameters
783            """
784            self.assertEquals(params,
785                              {"dbname": self.postgisdb.dbname,
786                               "user": self.server.user_name,
787                               "port": str(self.server.port),
788                               "host": self.server.host})
789            self.db_connection_callback_called = True
790            params = params.copy()
791            params["password"] = self.server.user_password
792            return params
793    
794        def test_with_callback(self):
795            """Test loading a session with postgis, authentication and a callback
796            """
797            session = load_session(self.filename(),
798                          db_connection_callback = self.db_connection_callback)
799            self.session = session
800            connections = session.DBConnections()
801            self.assertEquals(len(connections), 1)
802            conn = connections[0]
803            for attr, value in [("host", self.server.host),
804                                ("port", str(self.server.port)),
805                                ("user", self.server.user_name),
806                                ("dbname", self.postgisdb.dbname)]:
807                self.assertEquals(getattr(conn, attr), value)
808            layer = session.Maps()[0].Layers()[0]
809            self.failUnless(layer.ShapeStore().DBConnection() is conn)
810            self.failUnless(self.db_connection_callback_called)
811    
812        def test_without_callback(self):
813            """Test loading a session with postgis, authentication and no callback
814            """
815            # A password is required and there's no callback, so we should
816            # get a ConnectionError
817            self.assertRaises(ConnectionError, load_session, self.filename())
818    
819        def test_cancel(self):
820            """Test loading a session with postgis and cancelling authentication
821            """
822            def cancel(*args):
823                self.db_connection_callback_called = True
824                return None
825    
826            # If the user cancels, i.e. if the callbakc returns None, a
827            # LoadCancelled exception is raised.
828            self.assertRaises(LoadCancelled,
829                              load_session, self.filename(), cancel)
830            self.failUnless(self.db_connection_callback_called)
831    
832    
833  class TestLoadError(LoadSessionTest):  class TestLoadError(LoadSessionTest):
834    
835      file_contents = '''\      file_contents = '''\
836  <?xml version="1.0" encoding="UTF-8"?>  <?xml version="1.0" encoding="UTF-8"?>
837  <!DOCTYPE session SYSTEM "thuban-0.9.dtd">  <!DOCTYPE session SYSTEM "thuban-1.0.dtd">
838  <session xmlns="http://thuban.intevation.org/dtds/thuban-0.9-dev.dtd"  <session xmlns="http://thuban.intevation.org/dtds/thuban-1.0-dev.dtd"
839          title="single map&amp;layer">          title="single map&amp;layer">
840      <fileshapesource id="D1" filename="../../Data/iceland/political.shp"/>      <fileshapesource id="D1" filename="../../Data/iceland/political.shp"/>
841      <map title="Test Map">      <map title="Test Map">
# Line 586  class TestLoadError(LoadSessionTest): Line 862  class TestLoadError(LoadSessionTest):
862              # LoadError really was about the missing attribute              # LoadError really was about the missing attribute
863              self.assertEquals(str(value),              self.assertEquals(str(value),
864                "Element "                "Element "
865                "(u'http://thuban.intevation.org/dtds/thuban-0.9-dev.dtd',"                "(u'http://thuban.intevation.org/dtds/thuban-1.0-dev.dtd',"
866                " u'fileshapesource') requires an attribute 'filetype'")                " u'fileshapesource') requires an attribute 'filetype'")
867          else:          else:
868              self.fail("Missing filetype attribute doesn't raise LoadError")              self.fail("Missing filetype attribute doesn't raise LoadError")
869    
870  if __name__ == "__main__":  if __name__ == "__main__":
871      unittest.main()      support.run_tests()

Legend:
Removed from v.1642  
changed lines
  Added in v.1976

[email protected]
ViewVC Help
Powered by ViewVC 1.1.26