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

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

[email protected]
ViewVC Help
Powered by ViewVC 1.1.26