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

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

Parent Directory Parent Directory | Revision Log Revision Log


Revision 1846 - (show annotations)
Tue Oct 21 10:49:53 2003 UTC (21 years, 4 months ago) by bh
Original Path: trunk/thuban/test/test_load.py
File MIME type: text/x-python
File size: 28235 byte(s)
(LoadSessionTest.dtd): Update to 1.0-dev
namespace
(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 to use
1.0-dev namespace
(TestSingleLayer.file_contents, TestSingleLayer.test): Update to
use 1.0-dev namespace and use an EPSG projection to test whether
loading it works

1 # Copyright (c) 2002, 2003 by Intevation GmbH
2 # 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
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$"
28 # $Source$
29 # $Id$
30
31 import os
32 import unittest
33
34 import support
35 support.initthuban()
36
37 import postgissupport
38 from xmlsupport import sax_eventlist
39
40 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,\
47 ClassGroupSingleton, ClassGroupDefault
48 from Thuban.Model.postgisdb import ConnectionError
49
50 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
63 class LoadSessionTest(support.FileLoadTestCase):
64
65 """Base class for .thuban file loading tests
66
67 Basically the same as the FileLoadTestCase, except that all tests
68 use the '.thuban' extension by default and that setUp and tearDown
69 handle sessions.
70 """
71
72 file_extension = ".thuban"
73
74 def setUp(self):
75 """Create the test files"""
76 support.FileLoadTestCase.setUp(self)
77 self.session = None
78
79 def tearDown(self):
80 if self.session is not None:
81 self.session.Destroy()
82 self.session = None
83
84
85 dtd = "http://thuban.intevation.org/dtds/thuban-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"""
202 eq = self.assertEquals
203 session = load_session(self.filename())
204 self.session = session
205
206 # Check the title
207 eq(session.Title(), "single map&layer")
208
209 # the session has one map.
210 maps = session.Maps()
211 eq(len(maps), 1)
212
213 # Check the map's attributes
214 map = maps[0]
215 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
225 layers = map.Layers()
226 eq(len(layers), 1)
227
228 # Check the layer attributes
229 layer = layers[0]
230 eq(layer.Title(), "My Layer")
231 self.failUnless(filenames_equal(layer.ShapeStore().FileName(),
232 os.path.join(self.temp_dir(),
233 os.pardir, os.pardir,
234 "Data", "iceland",
235 "political.shp")))
236 eq(layer.GetClassification().GetDefaultFill(), Transparent)
237 eq(layer.GetClassification().GetDefaultLineColor().hex(), "#000000")
238 eq(layer.Visible(), True)
239
240 self.check_format()
241
242 self.session.Destroy()
243 self.session = None
244
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
270 session = load_session(self.filename())
271 self.session = session
272 maps = session.Maps()
273 eq(len(maps), 1)
274 map = maps[0]
275 layers = map.Layers()
276 eq(len(layers), 1)
277 layer = layers[0]
278
279 eq(layer.Visible(), False)
280
281 self.check_format()
282
283
284 class TestClassification(ClassificationTest):
285
286 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
344
345 map = self.session.Maps()[0] # only one map in the sample
346
347 expected = [("My Layer", 3,
348 [("default", (), "",
349 ("#000000", 1, "None")),
350 ("single", "1", "",
351 ("#000000", 2, "None")),
352 ("single", "1", "",
353 ("#000000", 10, "None")),
354 ("single", "\xe4\xf6\xfc", "\xdcml\xe4uts",
355 ("#000000", 1, "None"))]),
356 ("My Layer 2", 4,
357 [("default", (), "",
358 ("#000000", 2, "None")),
359 ("range", (0, 1), "",
360 ("#111111", 1, "None")),
361 ("single", .5, "",
362 ("#000000", 1, "#111111")),
363 ("range", (-1, 0), "",
364 ("#000000", 1, "None")),
365 ("single", -.5, "",
366 ("#000000", 1, "None"))])]
367
368 self.TestLayers(map.Layers(), expected)
369
370
371 class TestLabels(ClassificationTest):
372
373 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 test(self):
402 """Load a session and test for reading the group labels."""
403 eq = self.assertEquals
404 session = load_session(self.filename())
405 self.session = session
406
407 map = self.session.Maps()[0] # only one map in the sample
408
409 expected = [("My Layer", 1,
410 [("default", (), "hallo",
411 ("#000000", 1, "None")),
412 ("single", "1", "welt",
413 ("#000000", 2, "None"))])]
414
415 self.TestLayers(map.Layers(), expected)
416 self.check_format()
417
418
419 class TestLayerProjection(LoadSessionTest):
420
421 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
468 neq = self.assertNotEqual
469
470 session = load_session(self.filename())
471 self.session = session
472
473 map = self.session.Maps()[0] # only one map in the sample
474
475 layers = map.Layers() # two layers in the sample
476
477 # test layer with a named projection
478 proj = layers[0].GetProjection()
479 neq(proj, None)
480 eq(proj.GetName(), "hello")
481 eq(proj.GetParameter("proj"), "tmerc")
482 eq(proj.GetParameter("zone"), "13")
483 eq(proj.GetParameter("ellps"), "clrk66")
484
485 # test layer with an unnamed projection
486 proj = layers[1].GetProjection()
487 neq(proj, None)
488 eq(proj.GetName(), "Unknown")
489 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")
493
494 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
513 neq = self.assertNotEqual
514
515 session = load_session(self.filename())
516 self.session = session
517
518 map = self.session.Maps()[0] # only one map in the sample
519
520 layer = map.Layers()[0] # one layer in the sample
521
522 eq(layer.Title(), "My RasterLayer")
523 self.failIf(layer.Visible())
524 self.failUnless(filenames_equal(layer.GetImageFilename(),
525 os.path.join(self.temp_dir(),
526 os.pardir, os.pardir,
527 "Data", "iceland",
528 "island.tif")))
529 self.check_format()
530
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()

Properties

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

[email protected]
ViewVC Help
Powered by ViewVC 1.1.26