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

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

Parent Directory Parent Directory | Revision Log Revision Log


Revision 1664 - (hide annotations)
Wed Aug 27 15:20:54 2003 UTC (21 years, 6 months ago) by bh
Original Path: trunk/thuban/test/test_load.py
File MIME type: text/x-python
File size: 27154 byte(s)
As preparation for the 0.9 release, switch thuban files to a
non-dev namespace

* Thuban/Model/save.py (SessionSaver.write_session): Write files
with the http://thuban.intevation.org/dtds/thuban-0.9.dtd
namespace

* Thuban/Model/load.py (SessionLoader.__init__): Accept the
http://thuban.intevation.org/dtds/thuban-0.9.dtd namespace too

* test/test_save.py (SaveSessionTest.dtd)
(SaveSessionTest.testEmptySession)
(SaveSessionTest.testSingleLayer)
(SaveSessionTest.testLayerProjection)
(SaveSessionTest.testRasterLayer)
(SaveSessionTest.testClassifiedLayer)
(SaveSessionTest.test_dbf_table)
(SaveSessionTest.test_joined_table)
(SaveSessionTest.test_save_postgis): Update for new namespace

* test/test_load.py (LoadSessionTest.dtd, TestSingleLayer)
(TestLayerVisibility.file_contents, TestLabels.file_contents)
(TestLayerProjection.file_contents)
(TestRasterLayer.file_contents, TestJoinedTable.file_contents)
(TestPostGISLayer.file_contents)
(TestPostGISLayerPassword.file_contents)
(TestLoadError.file_contents, TestLoadError.test): Update for new
namespace

1 bh 765 # Copyright (c) 2002, 2003 by Intevation GmbH
2 bh 292 # 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     Test loading a thuban session from a file
10 bh 1247
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 bh 1257 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 bh 292 """
26    
27     __version__ = "$Revision$"
28     # $Source$
29     # $Id$
30    
31     import os
32     import unittest
33    
34     import support
35     support.initthuban()
36    
37 bh 1646 import postgissupport
38 bh 1257 from xmlsupport import sax_eventlist
39 bh 1268
40     import dbflib
41    
42 bh 1257 from Thuban.Model.save import save_session
43 bh 1646 from Thuban.Model.load import load_session, parse_color, LoadError, \
44     LoadCancelled
45 jonathan 1350 from Thuban.Model.color import Transparent
46 jonathan 684 from Thuban.Model.classification import ClassGroupProperties, ClassGroupRange,\
47     ClassGroupSingleton, ClassGroupDefault
48 bh 1646 from Thuban.Model.postgisdb import ConnectionError
49 jonathan 684
50 bh 292 def filenames_equal(name1, name2):
51     """Return true if the filenames name1 and name2 are equal.
52    
53     On systems where it is available, simply use os.path.samefile,
54     otherwise return whether the normalized versions of the filenames
55     according to os.path.normpath are equal.
56     """
57     if hasattr(os.path, "samefile"):
58     return os.path.samefile(name1, name2)
59     return os.path.normpath(name1) == os.path.normpath(name2)
60    
61    
62 bh 957
63     class LoadSessionTest(support.FileLoadTestCase):
64    
65     """Base class for .thuban file loading tests
66    
67     Basically the same as the FileLoadTestCase, except that all tests
68     use the '.thuban' extension by default and that setUp and tearDown
69     handle sessions.
70     """
71    
72     file_extension = ".thuban"
73    
74     def setUp(self):
75     """Create the test files"""
76     support.FileLoadTestCase.setUp(self)
77     self.session = None
78    
79     def tearDown(self):
80     if self.session is not None:
81     self.session.Destroy()
82     self.session = None
83    
84 bh 1268
85 bh 1664 dtd = "http://thuban.intevation.org/dtds/thuban-0.9.dtd"
86 bh 1268 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 bh 1257 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 bh 1268 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 bh 957
116 bh 1257
117 bh 957 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 jonathan 1357 g = ClassGroupRange((data[CLASSES][i][GROUP_DATA][0],
156     data[CLASSES][i][GROUP_DATA][1]),
157 bh 957 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 bh 292 <?xml version="1.0" encoding="UTF-8"?>
172 bh 1375 <!DOCTYPE session SYSTEM "thuban-0.9.dtd">
173 bh 1664 <session xmlns="http://thuban.intevation.org/dtds/thuban-0.9.dtd"
174 bh 1268 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 bh 292 </session>
188     '''
189    
190 bh 957 def test(self):
191     """Load a session with a single map with a single layer"""
192     eq = self.assertEquals
193     session = load_session(self.filename())
194     self.session = session
195    
196     # Check the title
197     eq(session.Title(), "single map&layer")
198    
199     # the session has one map.
200     maps = session.Maps()
201     eq(len(maps), 1)
202    
203     # Check the map's attributes
204     map = maps[0]
205     eq(map.Title(), "Test Map")
206    
207     # the map has a single layer
208     layers = map.Layers()
209     eq(len(layers), 1)
210    
211     # Check the layer attributes
212     layer = layers[0]
213     eq(layer.Title(), "My Layer")
214 bh 1219 self.failUnless(filenames_equal(layer.ShapeStore().FileName(),
215 bh 957 os.path.join(self.temp_dir(),
216     os.pardir, os.pardir,
217     "Data", "iceland",
218     "political.shp")))
219 jonathan 1347 eq(layer.GetClassification().GetDefaultFill(), Transparent)
220 bh 957 eq(layer.GetClassification().GetDefaultLineColor().hex(), "#000000")
221     eq(layer.Visible(), True)
222    
223 bh 1257 self.check_format()
224    
225 bh 957 self.session.Destroy()
226     self.session = None
227    
228    
229     class TestLayerVisibility(LoadSessionTest):
230    
231     file_contents = '''\
232 jonathan 690 <?xml version="1.0" encoding="UTF-8"?>
233 bh 1375 <!DOCTYPE session SYSTEM "thuban-0.9.dtd">
234 bh 1664 <session xmlns="http://thuban.intevation.org/dtds/thuban-0.9.dtd"
235 bh 1268 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 bh 957 </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
253     session = load_session(self.filename())
254     self.session = session
255     maps = session.Maps()
256     eq(len(maps), 1)
257     map = maps[0]
258     layers = map.Layers()
259     eq(len(layers), 1)
260     layer = layers[0]
261    
262     eq(layer.Visible(), False)
263    
264 bh 1257 self.check_format()
265 bh 957
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 jonathan 690 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 bh 1417 <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 jonathan 690 </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 jonathan 692 <cldata stroke="#111111" stroke_width="1" fill="None"/>
307 jonathan 690 </clrange>
308     <clpoint value=".5">
309 jonathan 692 <cldata stroke="#000000" stroke_width="1" fill="#111111"/>
310 jonathan 690 </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 bh 292
323 bh 957 def test(self):
324 bh 1247 """Load a Thuban session with a map and classified layers."""
325 bh 957 session = load_session(self.filename())
326     self.session = session
327    
328     map = self.session.Maps()[0] # only one map in the sample
329    
330 bh 1417 expected = [("My Layer", 3,
331 bh 957 [("default", (), "",
332     ("#000000", 1, "None")),
333     ("single", "1", "",
334     ("#000000", 2, "None")),
335     ("single", "1", "",
336 bh 1417 ("#000000", 10, "None")),
337     ("single", "\xe4\xf6\xfc", "\xdcml\xe4uts",
338     ("#000000", 1, "None"))]),
339 bh 957 ("My Layer 2", 4,
340     [("default", (), "",
341     ("#000000", 2, "None")),
342     ("range", (0, 1), "",
343     ("#111111", 1, "None")),
344     ("single", .5, "",
345     ("#000000", 1, "#111111")),
346     ("range", (-1, 0), "",
347     ("#000000", 1, "None")),
348     ("single", -.5, "",
349     ("#000000", 1, "None"))])]
350    
351     self.TestLayers(map.Layers(), expected)
352    
353    
354     class TestLabels(ClassificationTest):
355    
356     file_contents = '''\
357 jonathan 690 <?xml version="1.0" encoding="UTF-8"?>
358 bh 1375 <!DOCTYPE session SYSTEM "thuban-0.9.dtd">
359 bh 1664 <session xmlns="http://thuban.intevation.org/dtds/thuban-0.9.dtd"
360 bh 1268 title="single map&amp;layer">
361     <fileshapesource filetype="shapefile" id="D1"
362     filename="../../Data/iceland/political.shp"/>
363     <map title="Test Map">
364     <projection name="Unknown">
365     <parameter value="zone=26"/>
366     <parameter value="proj=utm"/>
367     <parameter value="ellps=clrk66"/>
368     </projection>
369     <layer shapestore="D1" visible="true" stroke="#000000"
370     title="My Layer" stroke_width="1" fill="None">
371 jonathan 690 <classification field="POPYREG" field_type="string">
372     <clnull label="hallo">
373     <cldata stroke="#000000" stroke_width="1" fill="None"/>
374     </clnull>
375     <clpoint label="welt" value="1">
376     <cldata stroke="#000000" stroke_width="2" fill="None"/>
377     </clpoint>
378     </classification>
379     </layer>
380     </map>
381     </session>
382     '''
383    
384 bh 957 def test(self):
385     """Load a session and test for reading the group labels."""
386     eq = self.assertEquals
387     session = load_session(self.filename())
388     self.session = session
389    
390     map = self.session.Maps()[0] # only one map in the sample
391    
392     expected = [("My Layer", 1,
393     [("default", (), "hallo",
394     ("#000000", 1, "None")),
395     ("single", "1", "welt",
396     ("#000000", 2, "None"))])]
397    
398     self.TestLayers(map.Layers(), expected)
399 bh 1257 self.check_format()
400 bh 957
401    
402     class TestLayerProjection(LoadSessionTest):
403    
404     file_contents = '''\
405 jonathan 746 <?xml version="1.0" encoding="UTF-8"?>
406 bh 1375 <!DOCTYPE session SYSTEM "thuban-0.9.dtd">
407 bh 1664 <session xmlns="http://thuban.intevation.org/dtds/thuban-0.9.dtd"
408 bh 1268 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 jonathan 746 <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 bh 1268 <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 jonathan 746 </layer>
442     </map>
443     </session>
444     '''
445    
446 bh 957 def test(self):
447     """Test loading layers with projections"""
448 bh 292 eq = self.assertEquals
449 jonathan 746 neq = self.assertNotEqual
450    
451 bh 957 session = load_session(self.filename())
452 jonathan 746 self.session = session
453    
454     map = self.session.Maps()[0] # only one map in the sample
455    
456     layers = map.Layers() # two layers in the sample
457    
458     # test layer with a named projection
459     proj = layers[0].GetProjection()
460     neq(proj, None)
461     eq(proj.GetName(), "hello")
462     eq(proj.GetParameter("proj"), "tmerc")
463     eq(proj.GetParameter("zone"), "13")
464     eq(proj.GetParameter("ellps"), "clrk66")
465    
466     # test layer with an unnamed projection
467     proj = layers[1].GetProjection()
468     neq(proj, None)
469     eq(proj.GetName(), "Unknown")
470     eq(proj.GetParameter("proj"), "lcc")
471     eq(proj.GetParameter("ellps"), "clrk66")
472    
473 bh 1257 self.check_format()
474 bh 957
475 bh 1257
476 bh 957 class TestRasterLayer(LoadSessionTest):
477    
478     file_contents = '''\
479     <?xml version="1.0" encoding="UTF-8"?>
480 bh 1375 <!DOCTYPE session SYSTEM "thuban-0.9.dtd">
481 bh 1664 <session xmlns="http://thuban.intevation.org/dtds/thuban-0.9.dtd"
482 bh 1268 title="single map&amp;layer">
483     <map title="Test Map">
484     <rasterlayer visible="false" filename="../../Data/iceland/island.tif"
485     title="My RasterLayer"/>
486 bh 957 </map>
487     </session>
488     '''
489    
490     def test(self):
491 jonathan 947 eq = self.assertEquals
492     neq = self.assertNotEqual
493    
494 bh 957 session = load_session(self.filename())
495 jonathan 947 self.session = session
496    
497     map = self.session.Maps()[0] # only one map in the sample
498    
499     layer = map.Layers()[0] # one layer in the sample
500    
501     eq(layer.Title(), "My RasterLayer")
502     self.failIf(layer.Visible())
503     self.failUnless(filenames_equal(layer.GetImageFilename(),
504     os.path.join(self.temp_dir(),
505     os.pardir, os.pardir,
506     "Data", "iceland",
507     "island.tif")))
508 bh 1257 self.check_format()
509 jonathan 947
510 bh 1268
511     class TestJoinedTable(LoadSessionTest):
512    
513     file_contents = '''<?xml version="1.0" encoding="UTF-8"?>
514 bh 1375 <!DOCTYPE session SYSTEM "thuban-0.9.dtd">
515 bh 1664 <session xmlns="http://thuban.intevation.org/dtds/thuban-0.9.dtd" title="A Joined Table session">
516 bh 1282 <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 bh 1375 <jointable id="D136169900" title="Joined"
521     right="D136171140" left="D137227612"
522     leftcolumn="RDLNTYPE" rightcolumn="RDTYPE"
523     jointype="LEFT OUTER"/>
524 bh 1282 <derivedshapesource table="D136169900" shapesource="D137227612"
525     id="D136170932"/>
526 bh 1268 <map title="Test Map">
527 bh 1282 <layer shapestore="D136170932" visible="true" stroke="#000000"
528     title="My Layer" stroke_width="1" fill="None"/>
529 bh 1268 </map>
530 bh 1282 </session>
531     '''
532 bh 1268
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 bh 1375 self.assertEquals(tables[1].JoinType(), "LEFT OUTER")
556 bh 1282 self.check_format()
557 bh 1268
558    
559 bh 1646
560     class TestPostGISLayer(LoadSessionTest):
561    
562     file_contents = '''<?xml version="1.0" encoding="UTF-8"?>
563     <!DOCTYPE session SYSTEM "thuban-0.9.dtd">
564 bh 1664 <session xmlns="http://thuban.intevation.org/dtds/thuban-0.9.dtd"
565 bh 1646 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 bh 1664 <session xmlns="http://thuban.intevation.org/dtds/thuban-0.9.dtd"
614 bh 1646 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 bh 1268 class TestLoadError(LoadSessionTest):
704    
705     file_contents = '''\
706     <?xml version="1.0" encoding="UTF-8"?>
707 bh 1375 <!DOCTYPE session SYSTEM "thuban-0.9.dtd">
708 bh 1664 <session xmlns="http://thuban.intevation.org/dtds/thuban-0.9.dtd"
709 bh 1268 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 bh 1642 # 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 bh 1664 "(u'http://thuban.intevation.org/dtds/thuban-0.9.dtd',"
736 bh 1642 " u'fileshapesource') requires an attribute 'filetype'")
737 bh 1268 else:
738     self.fail("Missing filetype attribute doesn't raise LoadError")
739    
740 bh 292 if __name__ == "__main__":
741     unittest.main()

Properties

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

[email protected]
ViewVC Help
Powered by ViewVC 1.1.26