/[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 947 by jonathan, Tue May 20 15:27:19 2003 UTC revision 1646 by bh, Mon Aug 25 13:43:56 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.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    
 contents_single_map = '''\  
 <?xml version="1.0" encoding="UTF-8"?>  
 <!DOCTYPE session SYSTEM "thuban.dtd">  
 <session title="single map&amp;layer">  
         <map title="Test Map">  
                 <projection>  
                         <parameter value="zone=26"/>  
                         <parameter value="proj=utm"/>  
                         <parameter value="ellps=clrk66"/>  
                 </projection>  
                 <layer title="My Layer" stroke_width="1" fill="None"  
                     filename="../../Data/iceland/political.shp"  
                     stroke="#000000"/>  
         </map>  
 </session>  
 '''  
   
 contents_classified_map_v0_2 = '''\  
 <?xml version="1.0" encoding="UTF-8"?>  
 <!DOCTYPE session SYSTEM "thuban.dtd">  
 <session title="single map&amp;layer">  
         <map title="Test Map">  
                 <projection>  
                         <parameter value="zone=26"/>  
                         <parameter value="proj=utm"/>  
                         <parameter value="ellps=clrk66"/>  
                 </projection>  
                 <layer title="My Layer" stroke_width="1" fill="None"  
                     filename="../../Data/iceland/political.shp"  
                     stroke="#000000">  
             <classification field="POPYREG" field_type="string">  
                 <clnull>  
                     <cldata stroke="#000000" stroke_width="1" fill="None"/>  
                 </clnull>  
                 <clpoint value="1">  
                     <cldata stroke="#000000" stroke_width="2" fill="None"/>  
                 </clpoint>  
                 <clpoint value="1">  
                     <cldata stroke="#000000" stroke_width="10" fill="None"/>  
                 </clpoint>  
             </classification>  
         </layer>  
                 <layer title="My Layer 2" stroke_width="1" fill="None"  
                     filename="../../Data/iceland/political.shp"  
                     stroke="#000000">  
             <classification field="AREA" field_type="double">  
                 <clnull>  
                     <cldata stroke="#000000" stroke_width="2" fill="None"/>  
                 </clnull>  
                 <clrange min="0" max="1">  
                     <cldata stroke="#111111" stroke_width="1" fill="None"/>  
                 </clrange>  
                 <clpoint value=".5">  
                     <cldata stroke="#000000" stroke_width="1" fill="#111111"/>  
                 </clpoint>  
                 <clrange min="-1" max="0">  
                     <cldata stroke="#000000" stroke_width="1" fill="None"/>  
                 </clrange>  
                 <clpoint value="-.5">  
                     <cldata stroke="#000000" stroke_width="1" fill="None"/>  
                 </clpoint>  
             </classification>  
         </layer>  
         </map>  
 </session>  
 '''  
   
 contents_test_labels = '''\  
 <?xml version="1.0" encoding="UTF-8"?>  
 <!DOCTYPE session SYSTEM "thuban.dtd">  
 <session title="single map&amp;layer">  
         <map title="Test Map">  
                 <projection>  
                         <parameter value="zone=26"/>  
                         <parameter value="proj=utm"/>  
                         <parameter value="ellps=clrk66"/>  
                 </projection>  
                 <layer title="My Layer" stroke_width="1" fill="None"  
                     filename="../../Data/iceland/political.shp"  
                     stroke="#000000">  
             <classification field="POPYREG" field_type="string">  
                 <clnull label="hallo">  
                     <cldata stroke="#000000" stroke_width="1" fill="None"/>  
                 </clnull>  
                 <clpoint label="welt" value="1">  
                     <cldata stroke="#000000" stroke_width="2" fill="None"/>  
                 </clpoint>  
             </classification>  
         </layer>  
     </map>  
 </session>  
 '''  
62    
63  contents_test_layer_projection = '''\  class LoadSessionTest(support.FileLoadTestCase):
 <?xml version="1.0" encoding="UTF-8"?>  
 <!DOCTYPE session SYSTEM "thuban.dtd">  
 <session title="single map&amp;layer">  
         <map title="Test Map">  
                 <projection>  
                         <parameter value="zone=26"/>  
                         <parameter value="proj=utm"/>  
                         <parameter value="ellps=clrk66"/>  
                 </projection>  
                 <layer title="My Layer" stroke_width="1" fill="None"  
                     filename="../../Data/iceland/political.shp"  
                     stroke="#000000">  
                     <projection name="hello">  
                         <parameter value="zone=13"/>  
                         <parameter value="proj=tmerc"/>  
                         <parameter value="ellps=clrk66"/>  
                     </projection>  
             <classification field="POPYREG" field_type="string">  
                 <clnull label="hallo">  
                     <cldata stroke="#000000" stroke_width="1" fill="None"/>  
                 </clnull>  
                 <clpoint label="welt" value="1">  
                     <cldata stroke="#000000" stroke_width="2" fill="None"/>  
                 </clpoint>  
             </classification>  
         </layer>  
                 <layer title="My Layer" stroke_width="1" fill="None"  
                     filename="../../Data/iceland/political.shp"  
                     stroke="#000000">  
                     <projection>  
                         <parameter value="proj=lcc"/>  
                         <parameter value="ellps=clrk66"/>  
                     </projection>  
         </layer>  
     </map>  
 </session>  
 '''  
64    
65  contents_test_visible = '''\      """Base class for .thuban file loading tests
 <?xml version="1.0" encoding="UTF-8"?>  
 <!DOCTYPE session SYSTEM "thuban.dtd">  
 <session title="single map&amp;layer">  
         <map title="Test Map">  
                 <projection>  
                         <parameter value="zone=26"/>  
                         <parameter value="proj=utm"/>  
                         <parameter value="ellps=clrk66"/>  
                 </projection>  
                 <layer title="My Layer" stroke_width="1" fill="None"  
                     filename="../../Data/iceland/political.shp"  
                     stroke="#000000" visible="false">  
         </layer>  
     </map>  
 </session>  
 '''  
66    
67  contents_test_rasterlayer = '''\      Basically the same as the FileLoadTestCase, except that all tests
68  <?xml version="1.0" encoding="UTF-8"?>      use the '.thuban' extension by default and that setUp and tearDown
69  <!DOCTYPE session SYSTEM "thuban.dtd">      handle sessions.
70  <session title="single map&amp;layer">      """
         <map title="Test Map">  
                 <rasterlayer title="My RasterLayer"  
                      filename="../../Data/iceland/island.tif"  
                      visible="false">  
         </rasterlayer>  
     </map>  
 </session>  
 '''  
71    
72  class LoadSessionTest(unittest.TestCase, support.FileTestMixin):      file_extension = ".thuban"
73    
74      def setUp(self):      def setUp(self):
75          """Create the test files"""          """Create the test files"""
76          file = open(self.temp_file_name("load_singlelayer.thuban"), "w")          support.FileLoadTestCase.setUp(self)
         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()  
   
         file = open(self.temp_file_name("load_layerproj.thuban"), "w")  
         file.write(contents_test_layer_projection)  
         file.close()  
   
         file = open(self.temp_file_name("load_visible.thuban"), "w")  
         file.write(contents_test_visible)  
         file.close()  
   
         file = open(self.temp_file_name("load_rasterlayer.thuban"), "w")  
         file.write(contents_test_rasterlayer)  
         file.close()  
   
77          self.session = None          self.session = None
78    
79      def tearDown(self):      def tearDown(self):
# Line 241  class LoadSessionTest(unittest.TestCase, Line 81  class LoadSessionTest(unittest.TestCase,
81              self.session.Destroy()              self.session.Destroy()
82          self.session = None          self.session = None
83    
84      def testSingleLayer(self):  
85        dtd = "http://thuban.intevation.org/dtds/thuban-0.9-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        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"?>
172    <!DOCTYPE session SYSTEM "thuban-0.9.dtd">
173    <session xmlns="http://thuban.intevation.org/dtds/thuban-0.9-dev.dtd"
174            title="single map&amp;layer">
175        <fileshapesource filetype="shapefile" id="D1"
176            filename="../../Data/iceland/political.shp"/>
177        <map title="Test Map">
178            <projection name="Unknown">
179                <parameter value="zone=26"/>
180                <parameter value="proj=utm"/>
181                <parameter value="ellps=clrk66"/>
182            </projection>
183            <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"""          """Load a session with a single map with a single layer"""
192          eq = self.assertEquals          eq = self.assertEquals
193          session = load_session(self.temp_file_name("load_singlelayer.thuban"))          session = load_session(self.filename())
194          self.session = session          self.session = session
195    
196          # Check the title          # Check the title
# Line 265  class LoadSessionTest(unittest.TestCase, Line 211  class LoadSessionTest(unittest.TestCase,
211          # Check the layer attributes          # Check the layer attributes
212          layer = layers[0]          layer = layers[0]
213          eq(layer.Title(), "My Layer")          eq(layer.Title(), "My Layer")
214          self.failUnless(filenames_equal(layer.filename,          self.failUnless(filenames_equal(layer.ShapeStore().FileName(),
215                                          os.path.join(self.temp_dir(),                                          os.path.join(self.temp_dir(),
216                                                       os.pardir, os.pardir,                                                       os.pardir, os.pardir,
217                                                       "Data", "iceland",                                                       "Data", "iceland",
218                                                       "political.shp")))                                                       "political.shp")))
219          eq(layer.GetClassification().GetDefaultFill(), Color.Transparent)          eq(layer.GetClassification().GetDefaultFill(), Transparent)
220          eq(layer.GetClassification().GetDefaultLineColor().hex(), "#000000")          eq(layer.GetClassification().GetDefaultLineColor().hex(), "#000000")
221          eq(layer.Visible(), True)          eq(layer.Visible(), True)
222    
223            self.check_format()
224    
225          self.session.Destroy()          self.session.Destroy()
226          self.session = None          self.session = None
227    
     def testLayerVisibility(self):  
         """Test that the visible flag is correctly loaded for a layer."""  
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-dev.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>
248    '''
249    
250        def test(self):
251            """Test that the visible flag is correctly loaded for a layer."""
252          eq = self.assertEquals          eq = self.assertEquals
253          session = load_session(self.temp_file_name("load_visible.thuban"))          session = load_session(self.filename())
254          self.session = session          self.session = session
255          maps = session.Maps()          maps = session.Maps()
256          eq(len(maps), 1)          eq(len(maps), 1)
# Line 292  class LoadSessionTest(unittest.TestCase, Line 261  class LoadSessionTest(unittest.TestCase,
261    
262          eq(layer.Visible(), False)          eq(layer.Visible(), False)
263    
264      def testClassification(self):          self.check_format()
265          """Load a session with a map and classified layers."""  
266    
267    class TestClassification(ClassificationTest):
268    
269        file_contents = '''\
270    <?xml version="1.0" encoding="UTF-8"?>
271    <!DOCTYPE session SYSTEM "thuban.dtd">
272    <session title="single map&amp;layer">
273            <map title="Test Map">
274                    <projection>
275                            <parameter value="zone=26"/>
276                            <parameter value="proj=utm"/>
277                            <parameter value="ellps=clrk66"/>
278                    </projection>
279                    <layer title="My Layer" stroke_width="1" fill="None"
280                        filename="../../Data/iceland/political.shp"
281                        stroke="#000000">
282                <classification field="POPYREG" field_type="string">
283                    <clnull>
284                        <cldata stroke="#000000" stroke_width="1" fill="None"/>
285                    </clnull>
286                    <clpoint value="1">
287                        <cldata stroke="#000000" stroke_width="2" fill="None"/>
288                    </clpoint>
289                    <clpoint value="1">
290                        <cldata stroke="#000000" stroke_width="10" fill="None"/>
291                    </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>
297            </layer>
298                    <layer title="My Layer 2" stroke_width="1" fill="None"
299                        filename="../../Data/iceland/political.shp"
300                        stroke="#000000">
301                <classification field="AREA" field_type="double">
302                    <clnull>
303                        <cldata stroke="#000000" stroke_width="2" fill="None"/>
304                    </clnull>
305                    <clrange min="0" max="1">
306                        <cldata stroke="#111111" stroke_width="1" fill="None"/>
307                    </clrange>
308                    <clpoint value=".5">
309                        <cldata stroke="#000000" stroke_width="1" fill="#111111"/>
310                    </clpoint>
311                    <clrange min="-1" max="0">
312                        <cldata stroke="#000000" stroke_width="1" fill="None"/>
313                    </clrange>
314                    <clpoint value="-.5">
315                        <cldata stroke="#000000" stroke_width="1" fill="None"/>
316                    </clpoint>
317                </classification>
318            </layer>
319            </map>
320    </session>
321    '''
322    
323          session = load_session(self.temp_file_name("load_classified_v0_2.thuban"))      def test(self):
324            """Load a Thuban session with a map and classified layers."""
325            session = load_session(self.filename())
326          self.session = session          self.session = session
327    
328          map = self.session.Maps()[0] # only one map in the sample          map = self.session.Maps()[0] # only one map in the sample
329    
330          expected = [("My Layer", 2,          expected = [("My Layer", 3,
331                          [("default", (), "",                          [("default", (), "",
332                              ("#000000", 1, "None")),                              ("#000000", 1, "None")),
333                           ("single", "1", "",                           ("single", "1", "",
334                              ("#000000", 2, "None")),                              ("#000000", 2, "None")),
335                           ("single", "1", "",                           ("single", "1", "",
336                              ("#000000", 10, "None"))]),                              ("#000000", 10, "None")),
337                             ("single", "\xe4\xf6\xfc", "\xdcml\xe4uts",
338                                ("#000000", 1, "None"))]),
339                       ("My Layer 2", 4,                       ("My Layer 2", 4,
340                           [("default", (), "",                           [("default", (), "",
341                              ("#000000", 2, "None")),                              ("#000000", 2, "None")),
# Line 321  class LoadSessionTest(unittest.TestCase, Line 350  class LoadSessionTest(unittest.TestCase,
350    
351          self.TestLayers(map.Layers(), expected)          self.TestLayers(map.Layers(), expected)
352    
     def TestLayers(self, layers, expected):  
353    
354          TITLE = 0  class TestLabels(ClassificationTest):
         NUM_GROUPS = 1  
         CLASSES = 2  
         GROUP_TYPE = 0  
         GROUP_DATA = 1  
         GROUP_LABEL = 2  
         GROUP_PROPS = 3  
   
         eq = self.assertEquals  
355    
356          eq(len(layers), len(expected))      file_contents = '''\
357    <?xml version="1.0" encoding="UTF-8"?>
358          for layer, data in zip(layers, expected):  <!DOCTYPE session SYSTEM "thuban-0.9.dtd">
359              eq(layer.Title(), data[TITLE])  <session xmlns="http://thuban.intevation.org/dtds/thuban-0.9-dev.dtd"
360            title="single map&amp;layer">
361              clazz = layer.GetClassification()      <fileshapesource filetype="shapefile" id="D1"
362              eq(clazz.GetNumGroups(), data[NUM_GROUPS])          filename="../../Data/iceland/political.shp"/>
363              eq(clazz.GetNumGroups() + 1, len(data[CLASSES]))      <map title="Test Map">
364            <projection name="Unknown">
365              i = 0              <parameter value="zone=26"/>
366              for group in clazz:              <parameter value="proj=utm"/>
367                                <parameter value="ellps=clrk66"/>
368                  props = ClassGroupProperties()          </projection>
369                  props.SetLineColor(          <layer shapestore="D1" visible="true" stroke="#000000"
370                      parse_color(data[CLASSES][i][GROUP_PROPS][0]))                  title="My Layer" stroke_width="1" fill="None">
371                  props.SetLineWidth(data[CLASSES][i][GROUP_PROPS][1])              <classification field="POPYREG" field_type="string">
372                  props.SetFill(                  <clnull label="hallo">
373                      parse_color(data[CLASSES][i][GROUP_PROPS][2]))                      <cldata stroke="#000000" stroke_width="1" fill="None"/>
374                    </clnull>
375                  if data[CLASSES][i][GROUP_TYPE] == "default":                  <clpoint label="welt" value="1">
376                      g = ClassGroupDefault(props, data[CLASSES][i][GROUP_LABEL])                      <cldata stroke="#000000" stroke_width="2" fill="None"/>
377                  elif data[CLASSES][i][GROUP_TYPE] == "range":                  </clpoint>
378                      g = ClassGroupRange(data[CLASSES][i][GROUP_DATA][0],              </classification>
379                                          data[CLASSES][i][GROUP_DATA][1],          </layer>
380                                          props, data[CLASSES][i][GROUP_LABEL])      </map>
381                  elif data[CLASSES][i][GROUP_TYPE] == "single":  </session>
382                      g = ClassGroupSingleton(data[CLASSES][i][GROUP_DATA],  '''
                                           props, data[CLASSES][i][GROUP_LABEL])  
   
                 eq(group, g)  
   
                 i += 1  
383    
384      def testLabels(self):      def test(self):
385          """Load a session and test for reading the group labels."""          """Load a session and test for reading the group labels."""
   
386          eq = self.assertEquals          eq = self.assertEquals
387          session = load_session(self.temp_file_name("load_labels.thuban"))          session = load_session(self.filename())
388          self.session = session          self.session = session
389    
390          map = self.session.Maps()[0] # only one map in the sample          map = self.session.Maps()[0] # only one map in the sample
# Line 382  class LoadSessionTest(unittest.TestCase, Line 396  class LoadSessionTest(unittest.TestCase,
396                              ("#000000", 2, "None"))])]                              ("#000000", 2, "None"))])]
397    
398          self.TestLayers(map.Layers(), expected)          self.TestLayers(map.Layers(), expected)
399            self.check_format()
400    
401    
402      def testLayerProjection(self):  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-dev.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          neq = self.assertNotEqual          neq = self.assertNotEqual
450    
451          session = load_session(self.temp_file_name("load_layerproj.thuban"))          session = load_session(self.filename())
452          self.session = session          self.session = session
453    
454          map = self.session.Maps()[0] # only one map in the sample          map = self.session.Maps()[0] # only one map in the sample
# Line 409  class LoadSessionTest(unittest.TestCase, Line 470  class LoadSessionTest(unittest.TestCase,
470          eq(proj.GetParameter("proj"), "lcc")          eq(proj.GetParameter("proj"), "lcc")
471          eq(proj.GetParameter("ellps"), "clrk66")          eq(proj.GetParameter("ellps"), "clrk66")
472    
473      def testRasterLayer(self):          self.check_format()
474    
475    
476    class TestRasterLayer(LoadSessionTest):
477    
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-dev.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          eq = self.assertEquals
492          neq = self.assertNotEqual          neq = self.assertNotEqual
493    
494          session = load_session(self.temp_file_name("load_rasterlayer.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
# Line 427  class LoadSessionTest(unittest.TestCase, Line 505  class LoadSessionTest(unittest.TestCase,
505                                                       os.pardir, os.pardir,                                                       os.pardir, os.pardir,
506                                                       "Data", "iceland",                                                       "Data", "iceland",
507                                                       "island.tif")))                                                       "island.tif")))
508            self.check_format()
509    
 if __name__ == "__main__":  
     unittest.main()  
510    
511    class TestJoinedTable(LoadSessionTest):
512    
513        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-dev.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        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            tables = session.Tables()
551            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    
558    
559    
560    class TestPostGISLayer(LoadSessionTest):
561    
562        file_contents = '''<?xml version="1.0" encoding="UTF-8"?>
563    <!DOCTYPE session SYSTEM "thuban-0.9.dtd">
564    <session xmlns="http://thuban.intevation.org/dtds/thuban-0.9-dev.dtd"
565            title="unnamed session">
566        <dbconnection port="%(port)s" host="%(host)s" user="%(user)s"
567            dbtype="postgis" id="D142684948" dbname="%(dbname)s"/>
568        <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        def setUp(self):
577            """Extend the inherited method to start the postgis server
578    
579            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-dev.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 setUp(self):
626            """Extend the inherited method to start the postgis server
627    
628            Furthermore, patch the file contents with the real postgis db
629            information
630            """
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            self.db_connection_callback_called = False
643            self.server.require_authentication(True)
644    
645        def tearDown(self):
646            """Extend the inherited method to switch off postgresql authentication
647            """
648            self.server.require_authentication(False)
649            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    
702    
703    class TestLoadError(LoadSessionTest):
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-dev.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-dev.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.947  
changed lines
  Added in v.1646

[email protected]
ViewVC Help
Powered by ViewVC 1.1.26