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

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

[email protected]
ViewVC Help
Powered by ViewVC 1.1.26