/[thuban]/branches/WIP-pyshapelib-bramz/test/test_load_0_9.py
ViewVC logotype

Annotation of /branches/WIP-pyshapelib-bramz/test/test_load_0_9.py

Parent Directory Parent Directory | Revision Log Revision Log


Revision 2104 - (hide annotations)
Fri Mar 12 12:19:15 2004 UTC (20 years, 11 months ago) by bh
Original Path: trunk/thuban/test/test_load_0_9.py
File MIME type: text/x-python
File size: 26092 byte(s)
Final step for explicit id/geometry columns: Loading and saving

* Resources/XML/thuban-1.1.dtd: New.  Derived from thuban-1.0.dtd
with the following changes:
(dbshapesource): Two new attributes id_column and geometry_column

* Thuban/Model/save.py (SessionSaver.write): Use the new dtd
(SessionSaver.write_session): Use the new namespace
(SessionSaver.write_data_containers): Write the new dbshapesource
parameters

* Thuban/Model/load.py (SessionLoader.__init__): New namespace for
the new file format version
(SessionLoader.start_dbshapesource): Handle the new db parameters

* test/test_save.py: Update to the new dtd and namespace
(SaveSessionTest.test_save_postgis): Update the NonConnectionStore
mock object to provide a working IDColumn method.

* test/test_load_1_0.py: New.  Copy of the test_load.py before
today's changes but with the round-trip tests removed.

* test/test_load_0_9.py: Update doc-string.

* test/test_load.py: Update all .thuban files to the new dtd and
namespace.
(TestPostGISLayer.file_contents): Add the new dbshapesource
paramters

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

Properties

Name Value
svn:eol-style native
svn:keywords Author Date Id Revision

[email protected]
ViewVC Help
Powered by ViewVC 1.1.26