/[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 692 by jonathan, Wed Apr 16 14:10:10 2003 UTC revision 1664 by bh, Wed Aug 27 15:20:54 2003 UTC
# Line 1  Line 1 
1  # Copyright (c) 2002 by Intevation GmbH  # Copyright (c) 2002, 2003 by Intevation GmbH
2  # Authors:  # Authors:
3  # Bernhard Herzog <[email protected]>  # Bernhard Herzog <[email protected]>
4  #  #
# 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.session import Session  from xmlsupport import sax_eventlist
 from Thuban.Model.map import Map  
 from Thuban.Model.layer import Layer  
 from Thuban.Model.proj import Projection  
 from Thuban.Model.color import Color  
39    
40  from Thuban.Model.table import FIELDTYPE_INT, FIELDTYPE_DOUBLE, FIELDTYPE_STRING  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 43  def filenames_equal(name1, name2): Line 59  def filenames_equal(name1, name2):
59      return os.path.normpath(name1) == os.path.normpath(name2)      return os.path.normpath(name1) == os.path.normpath(name2)
60    
61    
62  contents_single_map = '''\  
63    class LoadSessionTest(support.FileLoadTestCase):
64    
65        """Base class for .thuban file loading tests
66    
67        Basically the same as the FileLoadTestCase, except that all tests
68        use the '.thuban' extension by default and that setUp and tearDown
69        handle sessions.
70        """
71    
72        file_extension = ".thuban"
73    
74        def setUp(self):
75            """Create the test files"""
76            support.FileLoadTestCase.setUp(self)
77            self.session = None
78    
79        def tearDown(self):
80            if self.session is not None:
81                self.session.Destroy()
82            self.session = None
83    
84    
85        dtd = "http://thuban.intevation.org/dtds/thuban-0.9.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        del n, m, dtd
96    
97        def check_format(self):
98            """Check whether the file we loaded from matches the one that
99            would be written. Call this from each test case after loading
100            the session
101            """
102            filename = self.temp_file_name(self.id() + ".roundtrip.thuban")
103            save_session(self.session, filename)
104            el1 = sax_eventlist(filename = filename, ids = self.thubanids,
105                                idrefs = self.thubanidrefs)
106            el2 = sax_eventlist(filename = self.filename(), ids = self.thubanids,
107                                idrefs = self.thubanidrefs)
108            if 0:
109                for a, b in zip(el1, el2):
110                    print a != b and "***************" or ""
111                    print a
112                    print b
113            self.assertEquals(el1, el2,
114                              "loaded file not equivalent to the saved file")
115    
116    
117    class ClassificationTest(LoadSessionTest):
118    
119        """
120        Base class for tests that do some detailed checking of classifications
121        """
122    
123        def TestLayers(self, layers, expected):
124            TITLE = 0
125            NUM_GROUPS = 1
126            CLASSES = 2
127            GROUP_TYPE = 0
128            GROUP_DATA = 1
129            GROUP_LABEL = 2
130            GROUP_PROPS = 3
131    
132            eq = self.assertEquals
133    
134            eq(len(layers), len(expected))
135    
136            for layer, data in zip(layers, expected):
137                eq(layer.Title(), data[TITLE])
138    
139                clazz = layer.GetClassification()
140                eq(clazz.GetNumGroups(), data[NUM_GROUPS])
141                eq(clazz.GetNumGroups() + 1, len(data[CLASSES]))
142    
143                i = 0
144                for group in clazz:
145                    props = ClassGroupProperties()
146                    props.SetLineColor(
147                        parse_color(data[CLASSES][i][GROUP_PROPS][0]))
148                    props.SetLineWidth(data[CLASSES][i][GROUP_PROPS][1])
149                    props.SetFill(
150                        parse_color(data[CLASSES][i][GROUP_PROPS][2]))
151    
152                    if data[CLASSES][i][GROUP_TYPE] == "default":
153                        g = ClassGroupDefault(props, data[CLASSES][i][GROUP_LABEL])
154                    elif data[CLASSES][i][GROUP_TYPE] == "range":
155                        g = ClassGroupRange((data[CLASSES][i][GROUP_DATA][0],
156                                             data[CLASSES][i][GROUP_DATA][1]),
157                                            props, data[CLASSES][i][GROUP_LABEL])
158                    elif data[CLASSES][i][GROUP_TYPE] == "single":
159                        g = ClassGroupSingleton(data[CLASSES][i][GROUP_DATA],
160                                              props, data[CLASSES][i][GROUP_LABEL])
161    
162                    eq(group, g)
163    
164                    i += 1
165    
166    
167    
168    class TestSingleLayer(LoadSessionTest):
169    
170        file_contents = '''\
171  <?xml version="1.0" encoding="UTF-8"?>  <?xml version="1.0" encoding="UTF-8"?>
172  <!DOCTYPE session SYSTEM "thuban.dtd">  <!DOCTYPE session SYSTEM "thuban-0.9.dtd">
173  <session title="single map&amp;layer">  <session xmlns="http://thuban.intevation.org/dtds/thuban-0.9.dtd"
174          <map title="Test Map">          title="single map&amp;layer">
175                  <projection>      <fileshapesource filetype="shapefile" id="D1"
176                          <parameter value="zone=26"/>          filename="../../Data/iceland/political.shp"/>
177                          <parameter value="proj=utm"/>      <map title="Test Map">
178                          <parameter value="ellps=clrk66"/>          <projection name="Unknown">
179                  </projection>              <parameter value="zone=26"/>
180                  <layer title="My Layer" stroke_width="1" fill="None"              <parameter value="proj=utm"/>
181                      filename="../../Data/iceland/political.shp"              <parameter value="ellps=clrk66"/>
182                      stroke="#000000"/>          </projection>
183          </map>          <layer shapestore="D1" visible="true"
184                    stroke="#000000" title="My Layer" stroke_width="1"
185                    fill="None"/>
186        </map>
187    </session>
188    '''
189    
190        def test(self):
191            """Load a session with a single map with a single layer"""
192            eq = self.assertEquals
193            session = load_session(self.filename())
194            self.session = session
195    
196            # Check the title
197            eq(session.Title(), "single map&layer")
198    
199            # the session has one map.
200            maps = session.Maps()
201            eq(len(maps), 1)
202    
203            # Check the map's attributes
204            map = maps[0]
205            eq(map.Title(), "Test Map")
206    
207            # the map has a single layer
208            layers = map.Layers()
209            eq(len(layers), 1)
210    
211            # Check the layer attributes
212            layer = layers[0]
213            eq(layer.Title(), "My Layer")
214            self.failUnless(filenames_equal(layer.ShapeStore().FileName(),
215                                            os.path.join(self.temp_dir(),
216                                                         os.pardir, os.pardir,
217                                                         "Data", "iceland",
218                                                         "political.shp")))
219            eq(layer.GetClassification().GetDefaultFill(), Transparent)
220            eq(layer.GetClassification().GetDefaultLineColor().hex(), "#000000")
221            eq(layer.Visible(), True)
222    
223            self.check_format()
224    
225            self.session.Destroy()
226            self.session = None
227    
228    
229    class TestLayerVisibility(LoadSessionTest):
230    
231        file_contents = '''\
232    <?xml version="1.0" encoding="UTF-8"?>
233    <!DOCTYPE session SYSTEM "thuban-0.9.dtd">
234    <session xmlns="http://thuban.intevation.org/dtds/thuban-0.9.dtd"
235            title="single map&amp;layer">
236        <fileshapesource filetype="shapefile" id="D1"
237            filename="../../Data/iceland/political.shp"/>
238        <map title="Test Map">
239            <projection name="Unknown">
240                <parameter value="zone=26"/>
241                <parameter value="proj=utm"/>
242                <parameter value="ellps=clrk66"/>
243            </projection>
244            <layer shapestore="D1" visible="false" stroke="#000000"
245                    title="My Layer" stroke_width="1" fill="None"/>
246        </map>
247  </session>  </session>
248  '''  '''
249    
250  contents_classified_map_v0_2 = '''\      def test(self):
251            """Test that the visible flag is correctly loaded for a layer."""
252            eq = self.assertEquals
253            session = load_session(self.filename())
254            self.session = session
255            maps = session.Maps()
256            eq(len(maps), 1)
257            map = maps[0]
258            layers = map.Layers()
259            eq(len(layers), 1)
260            layer = layers[0]
261    
262            eq(layer.Visible(), False)
263    
264            self.check_format()
265    
266    
267    class TestClassification(ClassificationTest):
268    
269        file_contents = '''\
270  <?xml version="1.0" encoding="UTF-8"?>  <?xml version="1.0" encoding="UTF-8"?>
271  <!DOCTYPE session SYSTEM "thuban.dtd">  <!DOCTYPE session SYSTEM "thuban.dtd">
272  <session title="single map&amp;layer">  <session title="single map&amp;layer">
# Line 83  contents_classified_map_v0_2 = '''\ Line 289  contents_classified_map_v0_2 = '''\
289                  <clpoint value="1">                  <clpoint value="1">
290                      <cldata stroke="#000000" stroke_width="10" fill="None"/>                      <cldata stroke="#000000" stroke_width="10" fill="None"/>
291                  </clpoint>                  </clpoint>
292                    <clpoint value="\xc3\xa4\xc3\xb6\xc3\xbc"
293                             label="\xc3\x9cml\xc3\xa4uts">
294                        <cldata fill="None" stroke="#000000" stroke_width="1"/>
295                    </clpoint>
296              </classification>              </classification>
297          </layer>          </layer>
298                  <layer title="My Layer 2" stroke_width="1" fill="None"                  <layer title="My Layer 2" stroke_width="1" fill="None"
# Line 110  contents_classified_map_v0_2 = '''\ Line 320  contents_classified_map_v0_2 = '''\
320  </session>  </session>
321  '''  '''
322    
323  contents_test_labels = '''\      def test(self):
324            """Load a Thuban session with a map and classified layers."""
325            session = load_session(self.filename())
326            self.session = session
327    
328            map = self.session.Maps()[0] # only one map in the sample
329    
330            expected = [("My Layer", 3,
331                            [("default", (), "",
332                                ("#000000", 1, "None")),
333                             ("single", "1", "",
334                                ("#000000", 2, "None")),
335                             ("single", "1", "",
336                                ("#000000", 10, "None")),
337                             ("single", "\xe4\xf6\xfc", "\xdcml\xe4uts",
338                                ("#000000", 1, "None"))]),
339                         ("My Layer 2", 4,
340                             [("default", (), "",
341                                ("#000000", 2, "None")),
342                              ("range", (0, 1), "",
343                                ("#111111", 1, "None")),
344                              ("single", .5, "",
345                                ("#000000", 1, "#111111")),
346                              ("range", (-1, 0), "",
347                                ("#000000", 1, "None")),
348                              ("single", -.5, "",
349                                ("#000000", 1, "None"))])]
350    
351            self.TestLayers(map.Layers(), expected)
352    
353    
354    class TestLabels(ClassificationTest):
355    
356        file_contents = '''\
357  <?xml version="1.0" encoding="UTF-8"?>  <?xml version="1.0" encoding="UTF-8"?>
358  <!DOCTYPE session SYSTEM "thuban.dtd">  <!DOCTYPE session SYSTEM "thuban-0.9.dtd">
359  <session title="single map&amp;layer">  <session xmlns="http://thuban.intevation.org/dtds/thuban-0.9.dtd"
360          <map title="Test Map">          title="single map&amp;layer">
361                  <projection>      <fileshapesource filetype="shapefile" id="D1"
362                          <parameter value="zone=26"/>          filename="../../Data/iceland/political.shp"/>
363                          <parameter value="proj=utm"/>      <map title="Test Map">
364                          <parameter value="ellps=clrk66"/>          <projection name="Unknown">
365                  </projection>              <parameter value="zone=26"/>
366                  <layer title="My Layer" stroke_width="1" fill="None"              <parameter value="proj=utm"/>
367                      filename="../../Data/iceland/political.shp"              <parameter value="ellps=clrk66"/>
368                      stroke="#000000">          </projection>
369            <layer shapestore="D1" visible="true" stroke="#000000"
370                    title="My Layer" stroke_width="1" fill="None">
371              <classification field="POPYREG" field_type="string">              <classification field="POPYREG" field_type="string">
372                  <clnull label="hallo">                  <clnull label="hallo">
373                      <cldata stroke="#000000" stroke_width="1" fill="None"/>                      <cldata stroke="#000000" stroke_width="1" fill="None"/>
# Line 136  contents_test_labels = '''\ Line 381  contents_test_labels = '''\
381  </session>  </session>
382  '''  '''
383    
384  class LoadSessionTest(unittest.TestCase, support.FileTestMixin):      def test(self):
385            """Load a session and test for reading the group labels."""
386            eq = self.assertEquals
387            session = load_session(self.filename())
388            self.session = session
389    
390      def setUp(self):          map = self.session.Maps()[0] # only one map in the sample
         """Create the test files"""  
         file = open(self.temp_file_name("load_singlelayer.thuban"), "w")  
         file.write(contents_single_map)  
         file.close()  
   
         file = open(self.temp_file_name("load_classified_v0_2.thuban"), "w")  
         file.write(contents_classified_map_v0_2)  
         file.close()  
   
         file = open(self.temp_file_name("load_labels.thuban"), "w")  
         file.write(contents_test_labels)  
         file.close()  
         self.session = None  
391    
392      def tearDown(self):          expected = [("My Layer", 1,
393          if self.session is not None:                          [("default", (), "hallo",
394              self.session.Destroy()                              ("#000000", 1, "None")),
395                             ("single", "1", "welt",
396                                ("#000000", 2, "None"))])]
397    
398      def testSingleLayer(self):          self.TestLayers(map.Layers(), expected)
399          """Load a session with a single map with a single layer"""          self.check_format()
400    
401    
402    class TestLayerProjection(LoadSessionTest):
403    
404        file_contents = '''\
405    <?xml version="1.0" encoding="UTF-8"?>
406    <!DOCTYPE session SYSTEM "thuban-0.9.dtd">
407    <session xmlns="http://thuban.intevation.org/dtds/thuban-0.9.dtd"
408            title="single map&amp;layer">
409        <fileshapesource filetype="shapefile" id="D2"
410            filename="../../Data/iceland/roads-line.shp"/>
411        <fileshapesource filetype="shapefile" id="D4"
412            filename="../../Data/iceland/political.shp"/>
413        <map title="Test Map">
414            <projection name="Unknown">
415                <parameter value="zone=26"/>
416                <parameter value="proj=utm"/>
417                <parameter value="ellps=clrk66"/>
418            </projection>
419            <layer shapestore="D4" visible="true" stroke="#000000"
420                    title="My Layer" stroke_width="1" fill="None">
421                <projection name="hello">
422                    <parameter value="zone=13"/>
423                    <parameter value="proj=tmerc"/>
424                    <parameter value="ellps=clrk66"/>
425                </projection>
426                <classification field="POPYREG" field_type="string">
427                    <clnull label="hallo">
428                        <cldata stroke="#000000" stroke_width="1" fill="None"/>
429                    </clnull>
430                    <clpoint label="welt" value="1">
431                        <cldata stroke="#000000" stroke_width="2" fill="None"/>
432                    </clpoint>
433                </classification>
434            </layer>
435            <layer shapestore="D2" visible="true" stroke="#000000"
436                    title="My Layer" stroke_width="1" fill="None">
437                <projection name="Unknown">
438                    <parameter value="proj=lcc"/>
439                    <parameter value="ellps=clrk66"/>
440                </projection>
441            </layer>
442        </map>
443    </session>
444    '''
445    
446        def test(self):
447            """Test loading layers with projections"""
448          eq = self.assertEquals          eq = self.assertEquals
449          session = load_session(self.temp_file_name("load_singlelayer.thuban"))          neq = self.assertNotEqual
450    
451            session = load_session(self.filename())
452          self.session = session          self.session = session
453    
454          # Check the title          map = self.session.Maps()[0] # only one map in the sample
         eq(session.Title(), "single map&layer")  
455    
456          # the session has one map.          layers = map.Layers() # two layers in the sample
         maps = session.Maps()  
         eq(len(maps), 1)  
457    
458          # Check the map's attributes          # test layer with a named projection
459          map = maps[0]          proj = layers[0].GetProjection()
460          eq(map.Title(), "Test Map")          neq(proj, None)
461            eq(proj.GetName(), "hello")
462            eq(proj.GetParameter("proj"), "tmerc")
463            eq(proj.GetParameter("zone"), "13")
464            eq(proj.GetParameter("ellps"), "clrk66")
465    
466          # the map has a single layer          # test layer with an unnamed projection
467          layers = map.Layers()          proj = layers[1].GetProjection()
468          eq(len(layers), 1)          neq(proj, None)
469            eq(proj.GetName(), "Unknown")
470            eq(proj.GetParameter("proj"), "lcc")
471            eq(proj.GetParameter("ellps"), "clrk66")
472    
473          # Check the layer attributes          self.check_format()
         layer = layers[0]  
         eq(layer.Title(), "My Layer")  
         self.failUnless(filenames_equal(layer.filename,  
                                         os.path.join(self.temp_dir(),  
                                                      os.pardir, os.pardir,  
                                                      "Data", "iceland",  
                                                      "political.shp")))  
         eq(layer.GetClassification().GetDefaultFill(), Color.Transparent)  
         eq(layer.GetClassification().GetDefaultLineColor().hex(), "#000000")  
474    
         self.session.Destroy()  
         self.session = None  
475    
476      def testClassification(self):  class TestRasterLayer(LoadSessionTest):
477          """Load a session with a map and classified layers."""  
478        file_contents = '''\
479    <?xml version="1.0" encoding="UTF-8"?>
480    <!DOCTYPE session SYSTEM "thuban-0.9.dtd">
481    <session xmlns="http://thuban.intevation.org/dtds/thuban-0.9.dtd"
482            title="single map&amp;layer">
483        <map title="Test Map">
484            <rasterlayer visible="false" filename="../../Data/iceland/island.tif"
485                    title="My RasterLayer"/>
486        </map>
487    </session>
488    '''
489    
490        def test(self):
491            eq = self.assertEquals
492            neq = self.assertNotEqual
493    
494          session = load_session(self.temp_file_name("load_classified_v0_2.thuban"))          session = load_session(self.filename())
495          self.session = session          self.session = session
496    
497          map = self.session.Maps()[0] # only one map in the sample          map = self.session.Maps()[0] # only one map in the sample
498    
499          expected = [("My Layer", 2,          layer = map.Layers()[0] # one layer in the sample
                         [("default", (), "",  
                             ("#000000", 1, "None")),  
                          ("single", "1", "",  
                             ("#000000", 2, "None")),  
                          ("single", "1", "",  
                             ("#000000", 10, "None"))]),  
                      ("My Layer 2", 4,  
                          [("default", (), "",  
                             ("#000000", 2, "None")),  
                           ("range", (0, 1), "",  
                             ("#111111", 1, "None")),  
                           ("single", .5, "",  
                             ("#000000", 1, "#111111")),  
                           ("range", (-1, 0), "",  
                             ("#000000", 1, "None")),  
                           ("single", -.5, "",  
                             ("#000000", 1, "None"))])]  
500    
501          self.TestLayers(map.Layers(), expected)          eq(layer.Title(), "My RasterLayer")
502            self.failIf(layer.Visible())
503            self.failUnless(filenames_equal(layer.GetImageFilename(),
504                                            os.path.join(self.temp_dir(),
505                                                         os.pardir, os.pardir,
506                                                         "Data", "iceland",
507                                                         "island.tif")))
508            self.check_format()
509    
     def TestLayers(self, layers, expected):  
510    
511          TITLE = 0  class TestJoinedTable(LoadSessionTest):
         NUM_GROUPS = 1  
         CLASSES = 2  
         GROUP_TYPE = 0  
         GROUP_DATA = 1  
         GROUP_LABEL = 2  
         GROUP_PROPS = 3  
512    
513          eq = self.assertEquals      file_contents = '''<?xml version="1.0" encoding="UTF-8"?>
514    <!DOCTYPE session SYSTEM "thuban-0.9.dtd">
515    <session xmlns="http://thuban.intevation.org/dtds/thuban-0.9.dtd" title="A Joined Table session">
516        <fileshapesource filetype="shapefile" id="D137227612"
517            filename="../../Data/iceland/roads-line.shp"/>
518        <filetable filetype="DBF" filename="load_joinedtable.dbf" id="D136171140"
519            title="Some Title"/>
520        <jointable id="D136169900" title="Joined"
521            right="D136171140" left="D137227612"
522            leftcolumn="RDLNTYPE" rightcolumn="RDTYPE"
523            jointype="LEFT OUTER"/>
524        <derivedshapesource table="D136169900" shapesource="D137227612"
525            id="D136170932"/>
526        <map title="Test Map">
527            <layer shapestore="D136170932" visible="true" stroke="#000000"
528                    title="My Layer" stroke_width="1" fill="None"/>
529        </map>
530    </session>
531    '''
532    
533          eq(len(layers), len(expected))      def setUp(self):
534            """Extend inherited method to create the dbffile for the join"""
535            LoadSessionTest.setUp(self)
536            dbffile = self.temp_file_name("load_joinedtable.dbf")
537            dbf = dbflib.create(dbffile)
538            dbf.add_field("RDTYPE", dbflib.FTInteger, 10, 0)
539            dbf.add_field("TEXT", dbflib.FTString, 10, 0)
540            dbf.write_record(0, {'RDTYPE': 8, "TEXT": "foo"})
541            dbf.write_record(1, {'RDTYPE': 2, "TEXT": "bar"})
542            dbf.write_record(2, {'RDTYPE': 3, "TEXT": "baz"})
543            dbf.close()
544    
545        def test(self):
546            """Test loading a session containing a joined table"""
547            session = load_session(self.filename())
548            self.session = session
549    
550          for layer, data in zip(layers, expected):          tables = session.Tables()
551              eq(layer.Title(), data[TITLE])          self.assertEquals(len(tables), 3)
552            # FIXME: The tests shouldn't assume a certain order of the tables
553            self.assertEquals(tables[0].Title(), "Some Title")
554            self.assertEquals(tables[1].Title(), "Joined")
555            self.assertEquals(tables[1].JoinType(), "LEFT OUTER")
556            self.check_format()
557    
             clazz = layer.GetClassification()  
             eq(clazz.GetNumGroups(), data[NUM_GROUPS])  
             eq(clazz.GetNumGroups() + 1, len(data[CLASSES]))  
558    
             i = 0  
             for group in clazz:  
                   
                 props = ClassGroupProperties()  
                 props.SetLineColor(  
                     parse_color(data[CLASSES][i][GROUP_PROPS][0]))  
                 props.SetLineWidth(data[CLASSES][i][GROUP_PROPS][1])  
                 props.SetFill(  
                     parse_color(data[CLASSES][i][GROUP_PROPS][2]))  
559    
560                  if data[CLASSES][i][GROUP_TYPE] == "default":  class TestPostGISLayer(LoadSessionTest):
561                      g = ClassGroupDefault(props, data[CLASSES][i][GROUP_LABEL])  
562                  elif data[CLASSES][i][GROUP_TYPE] == "range":      file_contents = '''<?xml version="1.0" encoding="UTF-8"?>
563                      g = ClassGroupRange(data[CLASSES][i][GROUP_DATA][0],  <!DOCTYPE session SYSTEM "thuban-0.9.dtd">
564                                          data[CLASSES][i][GROUP_DATA][1],  <session xmlns="http://thuban.intevation.org/dtds/thuban-0.9.dtd"
565                                          props, data[CLASSES][i][GROUP_LABEL])          title="unnamed session">
566                  elif data[CLASSES][i][GROUP_TYPE] == "single":      <dbconnection port="%(port)s" host="%(host)s" user="%(user)s"
567                      g = ClassGroupSingleton(data[CLASSES][i][GROUP_DATA],          dbtype="postgis" id="D142684948" dbname="%(dbname)s"/>
568                                            props, data[CLASSES][i][GROUP_LABEL])      <dbshapesource tablename="landmarks" id="D143149420" dbconn="D142684948"/>
569        <map title="unnamed map">
570            <layer shapestore="D143149420" visible="true" stroke="#000000"
571                    title="landmarks" stroke_width="1" fill="None"/>
572        </map>
573    </session>
574    '''
575    
576                  eq(group, g)      def setUp(self):
577            """Extend the inherited method to start the postgis server
578    
579                  i += 1          Furthermore, patch the file contents with the real postgis db
580            information
581            """
582            postgissupport.skip_if_no_postgis()
583            self.server = postgissupport.get_test_server()
584            self.postgisdb = self.server.get_default_static_data_db()
585    
586            self.file_contents = self.__class__.file_contents % {
587                "dbname": self.postgisdb.dbname,
588                "user": self.server.user_name,
589                "port": self.server.port,
590                "host": self.server.host}
591            LoadSessionTest.setUp(self)
592    
593        def test(self):
594            """Test loading a session containing a postgis shapestore"""
595            session = load_session(self.filename())
596            self.session = session
597            connections = session.DBConnections()
598            self.assertEquals(len(connections), 1)
599            conn = connections[0]
600            for attr, value in [("host", self.server.host),
601                                ("port", str(self.server.port)),
602                                ("user", self.server.user_name),
603                                ("dbname", self.postgisdb.dbname)]:
604                self.assertEquals(getattr(conn, attr), value)
605            layer = session.Maps()[0].Layers()[0]
606            self.failUnless(layer.ShapeStore().DBConnection() is conn)
607    
608    
609    class TestPostGISLayerPassword(LoadSessionTest):
610    
611        file_contents = '''<?xml version="1.0" encoding="UTF-8"?>
612    <!DOCTYPE session SYSTEM "thuban-0.9.dtd">
613    <session xmlns="http://thuban.intevation.org/dtds/thuban-0.9.dtd"
614            title="unnamed session">
615        <dbconnection port="%(port)s" host="%(host)s" user="%(user)s"
616            dbtype="postgis" id="D142684948" dbname="%(dbname)s"/>
617        <dbshapesource tablename="landmarks" id="D143149420" dbconn="D142684948"/>
618        <map title="unnamed map">
619            <layer shapestore="D143149420" visible="true" stroke="#000000"
620                    title="landmarks" stroke_width="1" fill="None"/>
621        </map>
622    </session>
623    '''
624    
625      def testLabels(self):      def setUp(self):
626          """Load a session and test for reading the group labels."""          """Extend the inherited method to start the postgis server
627    
628          eq = self.assertEquals          Furthermore, patch the file contents with the real postgis db
629          session = load_session(self.temp_file_name("load_labels.thuban"))          information
630          self.session = session          """
631            postgissupport.skip_if_no_postgis()
632            self.server = postgissupport.get_test_server()
633            self.postgisdb = self.server.get_default_static_data_db()
634    
635            self.file_contents = self.__class__.file_contents % {
636                "dbname": self.postgisdb.dbname,
637                "user": self.server.user_name,
638                "port": self.server.port,
639                "host": self.server.host}
640            LoadSessionTest.setUp(self)
641    
642          map = self.session.Maps()[0] # only one map in the sample          self.db_connection_callback_called = False
643            self.server.require_authentication(True)
644    
645          expected = [("My Layer", 1,      def tearDown(self):
646                          [("default", (), "hallo",          """Extend the inherited method to switch off postgresql authentication
647                              ("#000000", 1, "None")),          """
648                           ("single", "1", "welt",          self.server.require_authentication(False)
649                              ("#000000", 2, "None"))])]          LoadSessionTest.tearDown(self)
650    
651        def db_connection_callback(self, params, message):
652            """Implementation of Thuban.Model.hooks.query_db_connection_parameters
653            """
654            self.assertEquals(params,
655                              {"dbname": self.postgisdb.dbname,
656                               "user": self.server.user_name,
657                               "port": str(self.server.port),
658                               "host": self.server.host})
659            self.db_connection_callback_called = True
660            params = params.copy()
661            params["password"] = self.server.user_password
662            return params
663    
664        def test_with_callback(self):
665            """Test loading a session with postgis, authentication and a callback
666            """
667            session = load_session(self.filename(),
668                          db_connection_callback = self.db_connection_callback)
669            self.session = session
670            connections = session.DBConnections()
671            self.assertEquals(len(connections), 1)
672            conn = connections[0]
673            for attr, value in [("host", self.server.host),
674                                ("port", str(self.server.port)),
675                                ("user", self.server.user_name),
676                                ("dbname", self.postgisdb.dbname)]:
677                self.assertEquals(getattr(conn, attr), value)
678            layer = session.Maps()[0].Layers()[0]
679            self.failUnless(layer.ShapeStore().DBConnection() is conn)
680            self.failUnless(self.db_connection_callback_called)
681    
682        def test_without_callback(self):
683            """Test loading a session with postgis, authentication and no callback
684            """
685            # A password is required and there's no callback, so we should
686            # get a ConnectionError
687            self.assertRaises(ConnectionError, load_session, self.filename())
688    
689        def test_cancel(self):
690            """Test loading a session with postgis and cancelling authentication
691            """
692            def cancel(*args):
693                self.db_connection_callback_called = True
694                return None
695    
696            # If the user cancels, i.e. if the callbakc returns None, a
697            # LoadCancelled exception is raised.
698            self.assertRaises(LoadCancelled,
699                              load_session, self.filename(), cancel)
700            self.failUnless(self.db_connection_callback_called)
701    
         self.TestLayers(map.Layers(), expected)  
702    
703  if __name__ == "__main__":  class TestLoadError(LoadSessionTest):
     unittest.main()  
704    
705        file_contents = '''\
706    <?xml version="1.0" encoding="UTF-8"?>
707    <!DOCTYPE session SYSTEM "thuban-0.9.dtd">
708    <session xmlns="http://thuban.intevation.org/dtds/thuban-0.9.dtd"
709            title="single map&amp;layer">
710        <fileshapesource id="D1" filename="../../Data/iceland/political.shp"/>
711        <map title="Test Map">
712            <projection name="Unknown">
713                <parameter value="zone=26"/>
714                <parameter value="proj=utm"/>
715                <parameter value="ellps=clrk66"/>
716            </projection>
717            <layer shapestore="D1" visible="true"
718                    stroke="#000000" title="My Layer" stroke_width="1"
719                    fill="None"/>
720        </map>
721    </session>
722    '''
723    
724        def test(self):
725            """Test loading a session missing a required attribute"""
726            # Don't use assertRaises to make sure that if a session is
727            # actually returned it gets destroyed properly.
728            try:
729                self.session = load_session(self.filename())
730            except LoadError, value:
731                # Check the actual messge in value to make sure the
732                # LoadError really was about the missing attribute
733                self.assertEquals(str(value),
734                  "Element "
735                  "(u'http://thuban.intevation.org/dtds/thuban-0.9.dtd',"
736                  " u'fileshapesource') requires an attribute 'filetype'")
737            else:
738                self.fail("Missing filetype attribute doesn't raise LoadError")
739    
740    if __name__ == "__main__":
741        unittest.main()

Legend:
Removed from v.692  
changed lines
  Added in v.1664

[email protected]
ViewVC Help
Powered by ViewVC 1.1.26