/[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 1219 by bh, Mon Jun 16 17:42:54 2003 UTC revision 1846 by bh, Tue Oct 21 10:49:53 2003 UTC
# Line 7  Line 7 
7    
8  """  """
9  Test loading a thuban session from a file  Test loading a thuban session from a file
10    
11    The tests in this file (test_load.py) are always be the tests for the
12    current version of the thuban file format. Tests for older versions can
13    be found in the version specific test modules, e.g. test_load_0_2 for
14    files created by Thuban 0.2.
15    
16    Maintenance of the test cases:
17    
18    When during a development period the file format is changed with respect
19    to the last released version for the first, the tests here should be
20    copied to the version specific test file. The round-trip tests which
21    save the session again and compare the XML files should not be copied
22    over as they only make sense here to make sure th that the files checked
23    here are actually ones that may have been written by the current thuban
24    version.
25  """  """
26    
27  __version__ = "$Revision$"  __version__ = "$Revision$"
# Line 19  import unittest Line 34  import unittest
34  import support  import support
35  support.initthuban()  support.initthuban()
36    
37  from Thuban.Model.load import load_session, parse_color  import postgissupport
38  from Thuban.Model.color import Color  from xmlsupport import sax_eventlist
39    
40    import dbflib
41    
42    from Thuban.Model.save import save_session
43    from Thuban.Model.load import load_session, parse_color, LoadError, \
44         LoadCancelled
45    from Thuban.Model.color import Transparent
46  from Thuban.Model.classification import ClassGroupProperties, ClassGroupRange,\  from Thuban.Model.classification import ClassGroupProperties, ClassGroupRange,\
47      ClassGroupSingleton, ClassGroupDefault      ClassGroupSingleton, ClassGroupDefault
48    from Thuban.Model.postgisdb import ConnectionError
49    
50  def filenames_equal(name1, name2):  def filenames_equal(name1, name2):
51      """Return true if the filenames name1 and name2 are equal.      """Return true if the filenames name1 and name2 are equal.
# Line 60  class LoadSessionTest(support.FileLoadTe Line 82  class LoadSessionTest(support.FileLoadTe
82          self.session = None          self.session = None
83    
84    
85        dtd = "http://thuban.intevation.org/dtds/thuban-1.0-dev.dtd"
86        thubanids = [((dtd, n), (None, "id")) for n in
87                     ["fileshapesource", "filetable", "jointable",
88                      "derivedshapesource"]]
89        thubanidrefs = [((dtd, n), (None, m)) for n, m in
90                        [("layer", "shapestore"),
91                         ("jointable", "left"),
92                         ("jointable", "right"),
93                         ("derivedshapesource", "table"),
94                         ("derivedshapesource", "shapesource")]]
95        filenames = [((dtd, n), (None, m)) for n, m in
96                     [("fileshapesource", "filename"),
97                      ("rasterlayer", "filename"),
98                      ("filetable", "filename")]]
99        del n, m, dtd
100    
101        def check_format(self):
102            """Check whether the file we loaded from matches the one that
103            would be written. Call this from each test case after loading
104            the session
105            """
106            filename = self.temp_file_name(self.id() + ".roundtrip.thuban")
107            save_session(self.session, filename)
108            el1 = sax_eventlist(filename = filename, ids = self.thubanids,
109                                idrefs = self.thubanidrefs,
110                                filenames = self.filenames)
111            el2 = sax_eventlist(filename = self.filename(), ids = self.thubanids,
112                                idrefs = self.thubanidrefs,
113                                filenames = self.filenames)
114            if 0:
115                for a, b in zip(el1, el2):
116                    print a != b and "***************" or ""
117                    print a
118                    print b
119            self.assertEquals(el1, el2,
120                              "loaded file not equivalent to the saved file")
121    
122    
123  class ClassificationTest(LoadSessionTest):  class ClassificationTest(LoadSessionTest):
124    
125      """      """
# Line 98  class ClassificationTest(LoadSessionTest Line 158  class ClassificationTest(LoadSessionTest
158                  if data[CLASSES][i][GROUP_TYPE] == "default":                  if data[CLASSES][i][GROUP_TYPE] == "default":
159                      g = ClassGroupDefault(props, data[CLASSES][i][GROUP_LABEL])                      g = ClassGroupDefault(props, data[CLASSES][i][GROUP_LABEL])
160                  elif data[CLASSES][i][GROUP_TYPE] == "range":                  elif data[CLASSES][i][GROUP_TYPE] == "range":
161                      g = ClassGroupRange(data[CLASSES][i][GROUP_DATA][0],                      g = ClassGroupRange((data[CLASSES][i][GROUP_DATA][0],
162                                          data[CLASSES][i][GROUP_DATA][1],                                           data[CLASSES][i][GROUP_DATA][1]),
163                                          props, data[CLASSES][i][GROUP_LABEL])                                          props, data[CLASSES][i][GROUP_LABEL])
164                  elif data[CLASSES][i][GROUP_TYPE] == "single":                  elif data[CLASSES][i][GROUP_TYPE] == "single":
165                      g = ClassGroupSingleton(data[CLASSES][i][GROUP_DATA],                      g = ClassGroupSingleton(data[CLASSES][i][GROUP_DATA],
# Line 113  class ClassificationTest(LoadSessionTest Line 173  class ClassificationTest(LoadSessionTest
173    
174  class TestSingleLayer(LoadSessionTest):  class TestSingleLayer(LoadSessionTest):
175    
176        # Note: The use of & and non-ascii characters is deliberate. We
177        # want to test whether the loading code handles that correctly.
178      file_contents = '''\      file_contents = '''\
179  <?xml version="1.0" encoding="UTF-8"?>  <?xml version="1.0" encoding="UTF-8"?>
180  <!DOCTYPE session SYSTEM "thuban.dtd">  <!DOCTYPE session SYSTEM "thuban-1.0.dtd">
181  <session title="single map&amp;layer">  <session xmlns="http://thuban.intevation.org/dtds/thuban-1.0-dev.dtd"
182          <map title="Test Map">          title="single map&amp;layer">
183                  <projection>      <fileshapesource filetype="shapefile" id="D1"
184                          <parameter value="zone=26"/>          filename="../../Data/iceland/political.shp"/>
185                          <parameter value="proj=utm"/>      <map title="Test Map">
186                          <parameter value="ellps=clrk66"/>          <projection epsg="32627" name="WGS 84 / UTM zone 27N">
187                  </projection>              <parameter value="datum=WGS84"/>
188                  <layer title="My Layer" stroke_width="1" fill="None"              <parameter value="ellps=WGS84"/>
189                      filename="../../Data/iceland/political.shp"              <parameter value="proj=utm"/>
190                      stroke="#000000"/>              <parameter value="units=m"/>
191          </map>              <parameter value="zone=27"/>
192            </projection>
193            <layer shapestore="D1" visible="true"
194                    stroke="#000000" title="My Layer" stroke_width="1"
195                    fill="None"/>
196        </map>
197  </session>  </session>
198  '''  '''
199    
# Line 146  class TestSingleLayer(LoadSessionTest): Line 213  class TestSingleLayer(LoadSessionTest):
213          # Check the map's attributes          # Check the map's attributes
214          map = maps[0]          map = maps[0]
215          eq(map.Title(), "Test Map")          eq(map.Title(), "Test Map")
216            proj = map.GetProjection()
217            eq(proj.GetName(), "WGS 84 / UTM zone 27N")
218            eq(proj.EPSGCode(), "32627")
219            params = proj.GetAllParameters()
220            params.sort()
221            eq(params, ["datum=WGS84", "ellps=WGS84", "proj=utm", "units=m",
222                        "zone=27"])
223    
224          # the map has a single layer          # the map has a single layer
225          layers = map.Layers()          layers = map.Layers()
# Line 159  class TestSingleLayer(LoadSessionTest): Line 233  class TestSingleLayer(LoadSessionTest):
233                                                       os.pardir, os.pardir,                                                       os.pardir, os.pardir,
234                                                       "Data", "iceland",                                                       "Data", "iceland",
235                                                       "political.shp")))                                                       "political.shp")))
236          eq(layer.GetClassification().GetDefaultFill(), Color.Transparent)          eq(layer.GetClassification().GetDefaultFill(), Transparent)
237          eq(layer.GetClassification().GetDefaultLineColor().hex(), "#000000")          eq(layer.GetClassification().GetDefaultLineColor().hex(), "#000000")
238          eq(layer.Visible(), True)          eq(layer.Visible(), True)
239    
240            self.check_format()
241    
242          self.session.Destroy()          self.session.Destroy()
243          self.session = None          self.session = None
244    
# Line 171  class TestLayerVisibility(LoadSessionTes Line 247  class TestLayerVisibility(LoadSessionTes
247    
248      file_contents = '''\      file_contents = '''\
249  <?xml version="1.0" encoding="UTF-8"?>  <?xml version="1.0" encoding="UTF-8"?>
250  <!DOCTYPE session SYSTEM "thuban.dtd">  <!DOCTYPE session SYSTEM "thuban-1.0.dtd">
251  <session title="single map&amp;layer">  <session xmlns="http://thuban.intevation.org/dtds/thuban-1.0-dev.dtd"
252          <map title="Test Map">          title="single map&amp;layer">
253                  <projection>      <fileshapesource filetype="shapefile" id="D1"
254                          <parameter value="zone=26"/>          filename="../../Data/iceland/political.shp"/>
255                          <parameter value="proj=utm"/>      <map title="Test Map">
256                          <parameter value="ellps=clrk66"/>          <projection name="Unknown">
257                  </projection>              <parameter value="zone=26"/>
258                  <layer title="My Layer" stroke_width="1" fill="None"              <parameter value="proj=utm"/>
259                      filename="../../Data/iceland/political.shp"              <parameter value="ellps=clrk66"/>
260                      stroke="#000000" visible="false">          </projection>
261          </layer>          <layer shapestore="D1" visible="false" stroke="#000000"
262                    title="My Layer" stroke_width="1" fill="None"/>
263      </map>      </map>
264  </session>  </session>
265  '''  '''
# Line 201  class TestLayerVisibility(LoadSessionTes Line 278  class TestLayerVisibility(LoadSessionTes
278    
279          eq(layer.Visible(), False)          eq(layer.Visible(), False)
280    
281            self.check_format()
282    
283    
284  class TestClassification(ClassificationTest):  class TestClassification(ClassificationTest):
# Line 229  class TestClassification(ClassificationT Line 306  class TestClassification(ClassificationT
306                  <clpoint value="1">                  <clpoint value="1">
307                      <cldata stroke="#000000" stroke_width="10" fill="None"/>                      <cldata stroke="#000000" stroke_width="10" fill="None"/>
308                  </clpoint>                  </clpoint>
309                    <clpoint value="\xc3\xa4\xc3\xb6\xc3\xbc"
310                             label="\xc3\x9cml\xc3\xa4uts">
311                        <cldata fill="None" stroke="#000000" stroke_width="1"/>
312                    </clpoint>
313              </classification>              </classification>
314          </layer>          </layer>
315                  <layer title="My Layer 2" stroke_width="1" fill="None"                  <layer title="My Layer 2" stroke_width="1" fill="None"
# Line 257  class TestClassification(ClassificationT Line 338  class TestClassification(ClassificationT
338  '''  '''
339    
340      def test(self):      def test(self):
341          """Load a Thuban 0.2 session with a map and classified layers."""          """Load a Thuban session with a map and classified layers."""
342          session = load_session(self.filename())          session = load_session(self.filename())
343          self.session = session          self.session = session
344    
345          map = self.session.Maps()[0] # only one map in the sample          map = self.session.Maps()[0] # only one map in the sample
346    
347          expected = [("My Layer", 2,          expected = [("My Layer", 3,
348                          [("default", (), "",                          [("default", (), "",
349                              ("#000000", 1, "None")),                              ("#000000", 1, "None")),
350                           ("single", "1", "",                           ("single", "1", "",
351                              ("#000000", 2, "None")),                              ("#000000", 2, "None")),
352                           ("single", "1", "",                           ("single", "1", "",
353                              ("#000000", 10, "None"))]),                              ("#000000", 10, "None")),
354                             ("single", "\xe4\xf6\xfc", "\xdcml\xe4uts",
355                                ("#000000", 1, "None"))]),
356                       ("My Layer 2", 4,                       ("My Layer 2", 4,
357                           [("default", (), "",                           [("default", (), "",
358                              ("#000000", 2, "None")),                              ("#000000", 2, "None")),
# Line 289  class TestLabels(ClassificationTest): Line 372  class TestLabels(ClassificationTest):
372    
373      file_contents = '''\      file_contents = '''\
374  <?xml version="1.0" encoding="UTF-8"?>  <?xml version="1.0" encoding="UTF-8"?>
375  <!DOCTYPE session SYSTEM "thuban.dtd">  <!DOCTYPE session SYSTEM "thuban-1.0.dtd">
376  <session title="single map&amp;layer">  <session xmlns="http://thuban.intevation.org/dtds/thuban-1.0-dev.dtd"
377          <map title="Test Map">          title="single map&amp;layer">
378                  <projection>      <fileshapesource filetype="shapefile" id="D1"
379                          <parameter value="zone=26"/>          filename="../../Data/iceland/political.shp"/>
380                          <parameter value="proj=utm"/>      <map title="Test Map">
381                          <parameter value="ellps=clrk66"/>          <projection name="Unknown">
382                  </projection>              <parameter value="zone=26"/>
383                  <layer title="My Layer" stroke_width="1" fill="None"              <parameter value="proj=utm"/>
384                      filename="../../Data/iceland/political.shp"              <parameter value="ellps=clrk66"/>
385                      stroke="#000000">          </projection>
386            <layer shapestore="D1" visible="true" stroke="#000000"
387                    title="My Layer" stroke_width="1" fill="None">
388              <classification field="POPYREG" field_type="string">              <classification field="POPYREG" field_type="string">
389                  <clnull label="hallo">                  <clnull label="hallo">
390                      <cldata stroke="#000000" stroke_width="1" fill="None"/>                      <cldata stroke="#000000" stroke_width="1" fill="None"/>
# Line 328  class TestLabels(ClassificationTest): Line 413  class TestLabels(ClassificationTest):
413                              ("#000000", 2, "None"))])]                              ("#000000", 2, "None"))])]
414    
415          self.TestLayers(map.Layers(), expected)          self.TestLayers(map.Layers(), expected)
416            self.check_format()
417    
418    
419  class TestLayerProjection(LoadSessionTest):  class TestLayerProjection(LoadSessionTest):
420    
421      file_contents = '''\      file_contents = '''\
422  <?xml version="1.0" encoding="UTF-8"?>  <?xml version="1.0" encoding="UTF-8"?>
423  <!DOCTYPE session SYSTEM "thuban.dtd">  <!DOCTYPE session SYSTEM "thuban-1.0.dtd">
424  <session title="single map&amp;layer">  <session xmlns="http://thuban.intevation.org/dtds/thuban-1.0-dev.dtd"
425          <map title="Test Map">          title="single map&amp;layer">
426                  <projection>      <fileshapesource filetype="shapefile" id="D2"
427                          <parameter value="zone=26"/>          filename="../../Data/iceland/roads-line.shp"/>
428                          <parameter value="proj=utm"/>      <fileshapesource filetype="shapefile" id="D4"
429                          <parameter value="ellps=clrk66"/>          filename="../../Data/iceland/political.shp"/>
430                  </projection>      <map title="Test Map">
431                  <layer title="My Layer" stroke_width="1" fill="None"          <projection name="Unknown">
432                      filename="../../Data/iceland/political.shp"              <parameter value="zone=26"/>
433                      stroke="#000000">              <parameter value="proj=utm"/>
434                      <projection name="hello">              <parameter value="ellps=clrk66"/>
435                          <parameter value="zone=13"/>          </projection>
436                          <parameter value="proj=tmerc"/>          <layer shapestore="D4" visible="true" stroke="#000000"
437                          <parameter value="ellps=clrk66"/>                  title="My Layer" stroke_width="1" fill="None">
438                      </projection>              <projection name="hello">
439                    <parameter value="zone=13"/>
440                    <parameter value="proj=tmerc"/>
441                    <parameter value="ellps=clrk66"/>
442                </projection>
443              <classification field="POPYREG" field_type="string">              <classification field="POPYREG" field_type="string">
444                  <clnull label="hallo">                  <clnull label="hallo">
445                      <cldata stroke="#000000" stroke_width="1" fill="None"/>                      <cldata stroke="#000000" stroke_width="1" fill="None"/>
# Line 359  class TestLayerProjection(LoadSessionTes Line 449  class TestLayerProjection(LoadSessionTes
449                  </clpoint>                  </clpoint>
450              </classification>              </classification>
451          </layer>          </layer>
452                  <layer title="My Layer" stroke_width="1" fill="None"          <layer shapestore="D2" visible="true" stroke="#000000"
453                      filename="../../Data/iceland/political.shp"                  title="My Layer" stroke_width="1" fill="None">
454                      stroke="#000000">              <projection name="Unknown">
455                      <projection>                  <parameter value="proj=lcc"/>
456                          <parameter value="proj=lcc"/>                  <parameter value="lat_1=10"/>
457                          <parameter value="ellps=clrk66"/>                  <parameter value="lat_2=20"/>
458                      </projection>                  <parameter value="ellps=clrk66"/>
459                </projection>
460          </layer>          </layer>
461      </map>      </map>
462  </session>  </session>
# Line 396  class TestLayerProjection(LoadSessionTes Line 487  class TestLayerProjection(LoadSessionTes
487          neq(proj, None)          neq(proj, None)
488          eq(proj.GetName(), "Unknown")          eq(proj.GetName(), "Unknown")
489          eq(proj.GetParameter("proj"), "lcc")          eq(proj.GetParameter("proj"), "lcc")
490            eq(proj.GetParameter("lat_1"), "10")
491            eq(proj.GetParameter("lat_2"), "20")
492          eq(proj.GetParameter("ellps"), "clrk66")          eq(proj.GetParameter("ellps"), "clrk66")
493    
494            self.check_format()
495    
496    
497  class TestRasterLayer(LoadSessionTest):  class TestRasterLayer(LoadSessionTest):
498    
499      file_contents = '''\      file_contents = '''\
500  <?xml version="1.0" encoding="UTF-8"?>  <?xml version="1.0" encoding="UTF-8"?>
501  <!DOCTYPE session SYSTEM "thuban.dtd">  <!DOCTYPE session SYSTEM "thuban-1.0.dtd">
502  <session title="single map&amp;layer">  <session xmlns="http://thuban.intevation.org/dtds/thuban-1.0-dev.dtd"
503          <map title="Test Map">          title="single map&amp;layer">
504                  <rasterlayer title="My RasterLayer"      <map title="Test Map">
505                       filename="../../Data/iceland/island.tif"          <rasterlayer visible="false" filename="../../Data/iceland/island.tif"
506                       visible="false">                  title="My RasterLayer"/>
         </rasterlayer>  
507      </map>      </map>
508  </session>  </session>
509  '''  '''
# Line 432  class TestRasterLayer(LoadSessionTest): Line 526  class TestRasterLayer(LoadSessionTest):
526                                                       os.pardir, os.pardir,                                                       os.pardir, os.pardir,
527                                                       "Data", "iceland",                                                       "Data", "iceland",
528                                                       "island.tif")))                                                       "island.tif")))
529            self.check_format()
530    
531    
532    class TestJoinedTable(LoadSessionTest):
533    
534        file_contents = '''<?xml version="1.0" encoding="UTF-8"?>
535    <!DOCTYPE session SYSTEM "thuban-1.0.dtd">
536    <session xmlns="http://thuban.intevation.org/dtds/thuban-1.0-dev.dtd" title="A Joined Table session">
537        <fileshapesource filetype="shapefile" id="D137227612"
538            filename="../../Data/iceland/roads-line.shp"/>
539        <filetable filetype="DBF" filename="load_joinedtable.dbf" id="D136171140"
540            title="Some Title"/>
541        <jointable id="D136169900" title="Joined"
542            right="D136171140" left="D137227612"
543            leftcolumn="RDLNTYPE" rightcolumn="RDTYPE"
544            jointype="LEFT OUTER"/>
545        <derivedshapesource table="D136169900" shapesource="D137227612"
546            id="D136170932"/>
547        <map title="Test Map">
548            <layer shapestore="D136170932" visible="true" stroke="#000000"
549                    title="My Layer" stroke_width="1" fill="None"/>
550        </map>
551    </session>
552    '''
553    
554        def setUp(self):
555            """Extend inherited method to create the dbffile for the join"""
556            LoadSessionTest.setUp(self)
557            dbffile = self.temp_file_name("load_joinedtable.dbf")
558            dbf = dbflib.create(dbffile)
559            dbf.add_field("RDTYPE", dbflib.FTInteger, 10, 0)
560            dbf.add_field("TEXT", dbflib.FTString, 10, 0)
561            dbf.write_record(0, {'RDTYPE': 8, "TEXT": "foo"})
562            dbf.write_record(1, {'RDTYPE': 2, "TEXT": "bar"})
563            dbf.write_record(2, {'RDTYPE': 3, "TEXT": "baz"})
564            dbf.close()
565    
566        def test(self):
567            """Test loading a session containing a joined table"""
568            session = load_session(self.filename())
569            self.session = session
570    
571            tables = session.Tables()
572            self.assertEquals(len(tables), 3)
573            # FIXME: The tests shouldn't assume a certain order of the tables
574            self.assertEquals(tables[0].Title(), "Some Title")
575            self.assertEquals(tables[1].Title(), "Joined")
576            self.assertEquals(tables[1].JoinType(), "LEFT OUTER")
577            self.check_format()
578    
579    
580    
581    class TestPostGISLayer(LoadSessionTest):
582    
583        file_contents = '''<?xml version="1.0" encoding="UTF-8"?>
584    <!DOCTYPE session SYSTEM "thuban-1.0.dtd">
585    <session xmlns="http://thuban.intevation.org/dtds/thuban-1.0-dev.dtd"
586            title="unnamed session">
587        <dbconnection port="%(port)s" host="%(host)s" user="%(user)s"
588            dbtype="postgis" id="D142684948" dbname="%(dbname)s"/>
589        <dbshapesource tablename="landmarks" id="D143149420" dbconn="D142684948"/>
590        <map title="unnamed map">
591            <layer shapestore="D143149420" visible="true" stroke="#000000"
592                    title="landmarks" stroke_width="1" fill="None"/>
593        </map>
594    </session>
595    '''
596    
597        def setUp(self):
598            """Extend the inherited method to start the postgis server
599    
600            Furthermore, patch the file contents with the real postgis db
601            information
602            """
603            postgissupport.skip_if_no_postgis()
604            self.server = postgissupport.get_test_server()
605            self.postgisdb = self.server.get_default_static_data_db()
606    
607            self.file_contents = self.__class__.file_contents % {
608                "dbname": self.postgisdb.dbname,
609                "user": self.server.user_name,
610                "port": self.server.port,
611                "host": self.server.host}
612            LoadSessionTest.setUp(self)
613    
614        def test(self):
615            """Test loading a session containing a postgis shapestore"""
616            session = load_session(self.filename())
617            self.session = session
618            connections = session.DBConnections()
619            self.assertEquals(len(connections), 1)
620            conn = connections[0]
621            for attr, value in [("host", self.server.host),
622                                ("port", str(self.server.port)),
623                                ("user", self.server.user_name),
624                                ("dbname", self.postgisdb.dbname)]:
625                self.assertEquals(getattr(conn, attr), value)
626            layer = session.Maps()[0].Layers()[0]
627            self.failUnless(layer.ShapeStore().DBConnection() is conn)
628    
629    
630    class TestPostGISLayerPassword(LoadSessionTest):
631    
632        file_contents = '''<?xml version="1.0" encoding="UTF-8"?>
633    <!DOCTYPE session SYSTEM "thuban-1.0.dtd">
634    <session xmlns="http://thuban.intevation.org/dtds/thuban-1.0-dev.dtd"
635            title="unnamed session">
636        <dbconnection port="%(port)s" host="%(host)s" user="%(user)s"
637            dbtype="postgis" id="D142684948" dbname="%(dbname)s"/>
638        <dbshapesource tablename="landmarks" id="D143149420" dbconn="D142684948"/>
639        <map title="unnamed map">
640            <layer shapestore="D143149420" visible="true" stroke="#000000"
641                    title="landmarks" stroke_width="1" fill="None"/>
642        </map>
643    </session>
644    '''
645    
646        def setUp(self):
647            """Extend the inherited method to start the postgis server
648    
649            Furthermore, patch the file contents with the real postgis db
650            information
651            """
652            postgissupport.skip_if_no_postgis()
653            self.server = postgissupport.get_test_server()
654            self.postgisdb = self.server.get_default_static_data_db()
655    
656            self.file_contents = self.__class__.file_contents % {
657                "dbname": self.postgisdb.dbname,
658                "user": self.server.user_name,
659                "port": self.server.port,
660                "host": self.server.host}
661            LoadSessionTest.setUp(self)
662    
663            self.db_connection_callback_called = False
664            self.server.require_authentication(True)
665    
666        def tearDown(self):
667            """Extend the inherited method to switch off postgresql authentication
668            """
669            self.server.require_authentication(False)
670            LoadSessionTest.tearDown(self)
671    
672        def db_connection_callback(self, params, message):
673            """Implementation of Thuban.Model.hooks.query_db_connection_parameters
674            """
675            self.assertEquals(params,
676                              {"dbname": self.postgisdb.dbname,
677                               "user": self.server.user_name,
678                               "port": str(self.server.port),
679                               "host": self.server.host})
680            self.db_connection_callback_called = True
681            params = params.copy()
682            params["password"] = self.server.user_password
683            return params
684    
685        def test_with_callback(self):
686            """Test loading a session with postgis, authentication and a callback
687            """
688            session = load_session(self.filename(),
689                          db_connection_callback = self.db_connection_callback)
690            self.session = session
691            connections = session.DBConnections()
692            self.assertEquals(len(connections), 1)
693            conn = connections[0]
694            for attr, value in [("host", self.server.host),
695                                ("port", str(self.server.port)),
696                                ("user", self.server.user_name),
697                                ("dbname", self.postgisdb.dbname)]:
698                self.assertEquals(getattr(conn, attr), value)
699            layer = session.Maps()[0].Layers()[0]
700            self.failUnless(layer.ShapeStore().DBConnection() is conn)
701            self.failUnless(self.db_connection_callback_called)
702    
703        def test_without_callback(self):
704            """Test loading a session with postgis, authentication and no callback
705            """
706            # A password is required and there's no callback, so we should
707            # get a ConnectionError
708            self.assertRaises(ConnectionError, load_session, self.filename())
709    
710        def test_cancel(self):
711            """Test loading a session with postgis and cancelling authentication
712            """
713            def cancel(*args):
714                self.db_connection_callback_called = True
715                return None
716    
717            # If the user cancels, i.e. if the callbakc returns None, a
718            # LoadCancelled exception is raised.
719            self.assertRaises(LoadCancelled,
720                              load_session, self.filename(), cancel)
721            self.failUnless(self.db_connection_callback_called)
722    
723    
724    class TestLoadError(LoadSessionTest):
725    
726        file_contents = '''\
727    <?xml version="1.0" encoding="UTF-8"?>
728    <!DOCTYPE session SYSTEM "thuban-1.0.dtd">
729    <session xmlns="http://thuban.intevation.org/dtds/thuban-1.0-dev.dtd"
730            title="single map&amp;layer">
731        <fileshapesource id="D1" filename="../../Data/iceland/political.shp"/>
732        <map title="Test Map">
733            <projection name="Unknown">
734                <parameter value="zone=26"/>
735                <parameter value="proj=utm"/>
736                <parameter value="ellps=clrk66"/>
737            </projection>
738            <layer shapestore="D1" visible="true"
739                    stroke="#000000" title="My Layer" stroke_width="1"
740                    fill="None"/>
741        </map>
742    </session>
743    '''
744    
745        def test(self):
746            """Test loading a session missing a required attribute"""
747            # Don't use assertRaises to make sure that if a session is
748            # actually returned it gets destroyed properly.
749            try:
750                self.session = load_session(self.filename())
751            except LoadError, value:
752                # Check the actual messge in value to make sure the
753                # LoadError really was about the missing attribute
754                self.assertEquals(str(value),
755                  "Element "
756                  "(u'http://thuban.intevation.org/dtds/thuban-1.0-dev.dtd',"
757                  " u'fileshapesource') requires an attribute 'filetype'")
758            else:
759                self.fail("Missing filetype attribute doesn't raise LoadError")
760    
761  if __name__ == "__main__":  if __name__ == "__main__":
762      unittest.main()      support.run_tests()

Legend:
Removed from v.1219  
changed lines
  Added in v.1846

[email protected]
ViewVC Help
Powered by ViewVC 1.1.26