/
test_dock.py
1653 lines (1400 loc) · 67 KB
/
test_dock.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""
InaSAFE Disaster risk assessment tool developed by AusAid and World Bank
- **GUI Test Cases.**
Contact : ole.moller.nielsen@gmail.com
.. note:: This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
"""
__author__ = 'tim@linfiniti.com'
__date__ = '10/01/2011'
__copyright__ = ('Copyright 2012, Australia Indonesia Facility for '
'Disaster Reduction')
import unittest
import sys
import os
import logging
from unittest import expectedFailure
from os.path import join
# Add PARENT directory to path to make test aware of other modules
pardir = os.path.abspath(join(os.path.dirname(__file__), '..'))
sys.path.append(pardir)
from PyQt4 import QtCore
from PyQt4.QtTest import QTest
from qgis.core import (QgsRasterLayer,
QgsVectorLayer,
QgsMapLayerRegistry,
QgsRectangle)
# TODO: get this via api
from safe.impact_functions.core import format_int
from safe.common.testing import HAZDATA, EXPDATA, TESTDATA, UNITDATA
from safe_qgis.utilities_test import (getQgisTestApp,
setCanvasCrs,
setPadangGeoExtent,
setBatemansBayGeoExtent,
setJakartaGeoExtent,
setYogyaGeoExtent,
setJakartaGoogleExtent,
setGeoExtent,
GEOCRS,
GOOGLECRS,
loadLayer)
from safe_qgis.dock import Dock
from safe_qgis.utilities import (setRasterStyle,
qgisVersion,
getDefaults)
# Retired impact function for characterisation (Ole)
# So ignore unused import errors for these? (Tim)
# pylint: disable=W0611
from safe.engine.impact_functions_for_testing import allen_fatality_model
from safe.engine.impact_functions_for_testing import HKV_flood_study
from safe.engine.impact_functions_for_testing import BNPB_earthquake_guidelines
#from safe.engine.impact_functions_for_testing import error_raising_functions
# pylint: enable=W0611
LOGGER = logging.getLogger('InaSAFE')
QGISAPP, CANVAS, IFACE, PARENT = getQgisTestApp()
DOCK = Dock(IFACE)
YOGYA2006_title = 'An earthquake in Yogyakarta like in 2006'
PADANG2009_title = 'An earthquake in Padang like in 2009'
TEST_FILES_DIR = os.path.join(os.path.dirname(__file__),
'test_data/test_files')
def getUiState(ui):
"""Get state of the 3 combos on the DOCK ui. This method is purely for
testing and not to be confused with the saveState and restoreState methods
of inasafedock.
"""
myHazard = str(ui.cboHazard.currentText())
myExposure = str(ui.cboExposure.currentText())
myImpactFunctionTitle = str(ui.cboFunction.currentText())
myImpactFunctionId = DOCK.getFunctionID()
myRunButton = ui.pbnRunStop.isEnabled()
return {'Hazard': myHazard,
'Exposure': myExposure,
'Impact Function Title': myImpactFunctionTitle,
'Impact Function Id': myImpactFunctionId,
'Run Button Enabled': myRunButton}
def formattedList(theList):
"""Return a string representing a list of layers (in correct order)
but formatted with line breaks between each entry."""
myListString = ''
for myItem in theList:
myListString += myItem + '\n'
return myListString
def canvasList():
"""Return a string representing the list of canvas layers (in correct
order) but formatted with line breaks between each entry."""
myListString = ''
for myLayer in CANVAS.layers():
myListString += str(myLayer.name()) + '\n'
return myListString
def combosToString(theUi):
"""Helper to return a string showing the state of all combos (all their
entries"""
myString = 'Hazard Layers\n'
myString += '-------------------------\n'
myCurrentId = theUi.cboHazard.currentIndex()
for myCount in range(0, theUi.cboHazard.count()):
myItemText = theUi.cboHazard.itemText(myCount)
if myCount == myCurrentId:
myString += '>> '
else:
myString += ' '
myString += str(myItemText) + '\n'
myString += '\n'
myString += 'Exposure Layers\n'
myString += '-------------------------\n'
myCurrentId = theUi.cboExposure.currentIndex()
for myCount in range(0, theUi.cboExposure.count()):
myItemText = theUi.cboExposure.itemText(myCount)
if myCount == myCurrentId:
myString += '>> '
else:
myString += ' '
myString += str(myItemText) + '\n'
myString += '\n'
myString += 'Functions\n'
myString += '-------------------------\n'
myCurrentId = theUi.cboFunction.currentIndex()
for myCount in range(0, theUi.cboFunction.count()):
myItemText = theUi.cboFunction.itemText(myCount)
if myCount == myCurrentId:
myString += '>> '
else:
myString += ' '
myString += '%s (Function ID: %s)\n' % (
str(myItemText), DOCK.getFunctionID(myCurrentId))
myString += '\n'
myString += 'Aggregation Layers\n'
myString += '-------------------------\n'
myCurrentId = theUi.cboAggregation.currentIndex()
for myCount in range(0, theUi.cboAggregation.count()):
myItemText = theUi.cboAggregation.itemText(myCount)
if myCount == myCurrentId:
myString += '>> '
else:
myString += ' '
myString += str(myItemText) + '\n'
myString += '\n\n >> means combo item is selected'
return myString
def setupScenario(theHazard, theExposure, theFunction, theFunctionId,
theOkButtonFlag=True, theAggregation=None,
theAggregationEnabledFlag=None):
"""Helper function to set the gui state to a given scenario.
Args:
theHazard str - (Required) name of the hazard combo entry to set.
theExposure str - (Required) name of exposure combo entry to set.
theFunction - (Required) name of the function combo entry to set.
theFunctionId - (Required) the impact function id that should be used.
theOkButtonFlag - (Optional) Whether the ok button should be enabled
after this scenario is set up.
theAggregationLayer - (Optional) which layer should be used for
aggregation
We require both theFunction and theFunctionId because safe allows for
multiple functions with the same name but different id's so we need to be
sure we have the right one.
Returns: bool - Indicating if the setup was successful
str - A message indicating why it may have failed.
Raises: None
"""
if theHazard is not None:
myIndex = DOCK.cboHazard.findText(theHazard)
myMessage = ('\nHazard Layer Not Found: %s\n Combo State:\n%s' %
(theHazard, combosToString(DOCK)))
if myIndex == -1:
return False, myMessage
DOCK.cboHazard.setCurrentIndex(myIndex)
if theExposure is not None:
myIndex = DOCK.cboExposure.findText(theExposure)
myMessage = ('\nExposure Layer Not Found: %s\n Combo State:\n%s' %
(theExposure, combosToString(DOCK)))
if myIndex == -1:
return False, myMessage
DOCK.cboExposure.setCurrentIndex(myIndex)
if theFunction is not None:
myIndex = DOCK.cboFunction.findText(theFunction)
myMessage = ('\nImpact Function Not Found: %s\n Combo State:\n%s' %
(theFunction, combosToString(DOCK)))
if myIndex == -1:
return False, myMessage
DOCK.cboFunction.setCurrentIndex(myIndex)
if theAggregation is not None:
myIndex = DOCK.cboAggregation.findText(theAggregation)
myMessage = ('Aggregation layer Not Found: %s\n Combo State:\n%s' %
(theAggregation, combosToString(DOCK)))
if myIndex == -1:
return False, myMessage
DOCK.cboAggregation.setCurrentIndex(myIndex)
if theAggregationEnabledFlag is not None:
if DOCK.cboAggregation.isEnabled() != theAggregationEnabledFlag:
myMessage = ('The aggregation combobox should be %s' %
('enabled' if theAggregationEnabledFlag else 'disabled'))
return False, myMessage
# Check that layers and impact function are correct
myDict = getUiState(DOCK)
myExpectedDict = {'Run Button Enabled': theOkButtonFlag,
'Impact Function Title': theFunction,
'Impact Function Id': theFunctionId,
'Hazard': theHazard,
'Exposure': theExposure}
myMessage = 'Expected versus Actual State\n'
myMessage += '--------------------------------------------------------\n'
for myKey in myExpectedDict.keys():
myMessage += 'Expected %s: %s\n' % (myKey, myExpectedDict[myKey])
myMessage += 'Actual %s: %s\n' % (myKey, myDict[myKey])
myMessage += '----\n'
myMessage += '--------------------------------------------------------\n'
myMessage += combosToString(DOCK)
if myDict != myExpectedDict:
return False, myMessage
return True, 'Matched ok.'
def populatemyDock():
"""A helper function to populate the DOCK and set it to a valid state.
"""
loadStandardLayers()
DOCK.cboHazard.setCurrentIndex(0)
DOCK.cboExposure.setCurrentIndex(0)
#QTest.mouseClick(myHazardItem, Qt.LeftButton)
#QTest.mouseClick(myExposureItem, Qt.LeftButton)
def loadStandardLayers():
"""Helper function to load standard layers into the dialog."""
# NOTE: Adding new layers here may break existing tests since
# combos are populated alphabetically. Each test will
# provide a detailed diagnostic if you break it so make sure
# to consult that and clean up accordingly.
#
# Update on above. We are refactoring tests so they use find on combos
# to set them appropriately, instead of relative in combo position
# so you should be able to put datasets in any order below.
# If chancing the order does cause tests to fail, please update the tests
# to also use find instead of relative position. (Tim)
myFileList = [join(TESTDATA, 'Padang_WGS84.shp'),
join(EXPDATA, 'glp10ag.asc'),
join(HAZDATA, 'Shakemap_Padang_2009.asc'),
join(TESTDATA, 'tsunami_max_inundation_depth_utm56s.tif'),
join(TESTDATA, 'tsunami_building_exposure.shp'),
join(HAZDATA, 'Flood_Current_Depth_Jakarta_geographic.asc'),
join(TESTDATA, 'Population_Jakarta_geographic.asc'),
join(HAZDATA, 'eq_yogya_2006.asc'),
join(HAZDATA, 'Jakarta_RW_2007flood.shp'),
join(TESTDATA, 'OSM_building_polygons_20110905.shp'),
join(EXPDATA, 'DKI_buildings.shp'),
join(HAZDATA, 'jakarta_flood_category_123.asc'),
join(TESTDATA, 'roads_Maumere.shp'),
join(TESTDATA, 'donut.shp'),
join(TESTDATA, 'Merapi_alert.shp'),
join(TESTDATA, 'kabupaten_jakarta_singlepart.shp')]
myHazardLayerCount, myExposureLayerCount = loadLayers(myFileList,
theDataDirectory=None)
#FIXME (MB) -1 is untill we add the aggregation category because of
# kabupaten_jakarta_singlepart not being either hayard nor exposure layer
assert myHazardLayerCount + myExposureLayerCount == len(myFileList) - 1
return myHazardLayerCount, myExposureLayerCount
def loadLayers(theLayerList, theClearFlag=True, theDataDirectory=TESTDATA):
"""Helper function to load layers as defined in a python list."""
# First unload any layers that may already be loaded
if theClearFlag:
QgsMapLayerRegistry.instance().removeAllMapLayers()
# Now go ahead and load our layers
myExposureLayerCount = 0
myHazardLayerCount = 0
# Now create our new layers
for myFile in theLayerList:
myLayer, myType = loadLayer(myFile, theDataDirectory)
if myType == 'hazard':
myHazardLayerCount += 1
elif myType == 'exposure':
myExposureLayerCount += 1
# Add layer to the registry (that QGis knows about) a slot
# in qgis_interface will also ensure it gets added to the canvas
QgsMapLayerRegistry.instance().addMapLayer(myLayer)
DOCK.getLayers()
# Add MCL's to the CANVAS
return myHazardLayerCount, myExposureLayerCount
class DockTest(unittest.TestCase):
"""Test the InaSAFE GUI"""
def setUp(self):
"""Fixture run before all tests"""
os.environ['LANG'] = 'en'
DOCK.showOnlyVisibleLayersFlag = True
loadStandardLayers()
DOCK.cboHazard.setCurrentIndex(0)
DOCK.cboExposure.setCurrentIndex(0)
DOCK.cboFunction.setCurrentIndex(0)
DOCK.runInThreadFlag = False
DOCK.showOnlyVisibleLayersFlag = False
DOCK.setLayerNameFromTitleFlag = False
DOCK.zoomToImpactFlag = False
DOCK.hideExposureFlag = False
DOCK.showPostProcLayers = False
def tearDown(self):
"""Fixture run after each test"""
QgsMapLayerRegistry.instance().removeAllMapLayers()
DOCK.cboHazard.clear()
DOCK.cboExposure.clear()
#DOCK.cboAggregation.clear() #dont do this because the cboAggregation
# need to be able to react to the status changes of the other combos
def test_defaults(self):
"""Test the GUI in its default state"""
self.assertEqual(DOCK.cboHazard.currentIndex(), 0)
self.assertEqual(DOCK.cboExposure.currentIndex(), 0)
self.assertEqual(DOCK.cboFunction.currentIndex(), 0)
self.assertEqual(DOCK.cboAggregation.currentIndex(), 0)
def test_validate(self):
"""Validate function work as expected"""
self.tearDown()
# First check that we DONT validate a clear DOCK
myFlag, myMessage = DOCK.validate()
assert myMessage is not None, 'No reason for failure given'
myMessage = 'Validation expected to fail on a cleared DOCK.'
self.assertEquals(myFlag, False, myMessage)
# Now check we DO validate a populated DOCK
populatemyDock()
myFlag = DOCK.validate()
myMessage = ('Validation expected to pass on '
'a populated for with selections.')
assert myFlag, myMessage
def test_setOkButtonStatus(self):
"""OK button changes properly according to DOCK validity"""
# First check that we ok ISNT enabled on a clear DOCK
self.tearDown()
myFlag, myMessage = DOCK.validate()
assert myMessage is not None, 'No reason for failure given'
myMessage = 'Validation expected to fail on a cleared DOCK.'
self.assertEquals(myFlag, False, myMessage)
# Now check OK IS enabled on a populated DOCK
populatemyDock()
myFlag = DOCK.validate()
myMessage = ('Validation expected to pass on a ' +
'populated DOCK with selections.')
assert myFlag, myMessage
def test_cboAggregationEmptyProject(self):
"""Aggregation combo changes properly according on no loaded layers"""
self.tearDown()
myMessage = ('The aggregation combobox should have only the "Entire '
'area" item when the project has no layer. Found:'
' %s' % (DOCK.cboAggregation.currentText()))
self.assertEqual(DOCK.cboAggregation.currentText(), DOCK.tr(
'Entire area'), myMessage)
assert not DOCK.cboAggregation.isEnabled(), 'The aggregation ' \
'combobox should be disabled when the project has no layer.'
def test_cboAggregationLoadedProject(self):
"""Aggregation combo changes properly according loaded layers"""
myLayerList = [DOCK.tr('Entire area'),
DOCK.tr('A flood in Jakarta'),
DOCK.tr('donut'),
DOCK.tr('Essential buildings'),
DOCK.tr('kabupaten jakarta singlepart'),
DOCK.tr('OSM Building Polygons')]
currentLayers = [DOCK.cboAggregation.itemText(i) for i in range(DOCK
.cboAggregation.count())]
myMessage = ('The aggregation combobox should have:\n %s \nFound: %s'
% (myLayerList, currentLayers))
self.assertEquals(currentLayers, myLayerList, myMessage)
#FIXME (MB) this is actually wrong, when calling the test directly it works
# in nosetest it fails at the second assert
@expectedFailure
def test_cboAggregationToggle(self):
"""Aggregation Combobox toggles on and off as expected."""
#raster hazard
#raster exposure
myResult, myMessage = setupScenario(
theHazard='A flood in Jakarta like in 2007',
theExposure='People',
theFunction='Need evacuation',
theFunctionId='Flood Evacuation Function',
theAggregationEnabledFlag=True)
myMessage += ' when the when hazard and exposure layer are raster'
assert myResult, myMessage
#vector hazard
#raster exposure
myResult, myMessage = setupScenario(
theHazard=('A flood in Jakarta'),
theExposure='People',
theFunction='Need evacuation',
theFunctionId='Flood Evacuation Function Vector Hazard',
theAggregationEnabledFlag=False)
myMessage += ' when the when hazard is vector and exposure is raster'
assert myResult, myMessage
#raster hazard
#vector exposure
myResult, myMessage = setupScenario(
theHazard='Tsunami Max Inundation',
theExposure='Tsunami Building Exposure',
theFunction='Be flooded',
theFunctionId='Flood Building Impact Function',
theAggregationEnabledFlag=False)
myMessage += ' when the when hazard is raster and exposure is vector'
assert myResult, myMessage
#vector hazard
#vector exposure
myResult, myMessage = setupScenario(
theHazard='A flood in Jakarta',
theExposure='Essential buildings',
theFunction='Be flooded',
theFunctionId='Flood Building Impact Function',
theAggregationEnabledFlag=False)
myMessage += ' when the when hazard and exposure layer are vector'
assert myResult, myMessage
def test_checkAggregationAttributeInKW(self):
"""Aggregation attribute is chosen correctly when present
in kezwords."""
myRunButton = DOCK.pbnRunStop
myAttrKey = getDefaults('AGGR_ATTR_KEY')
# with KAB_NAME aggregation attribute defined in .keyword using
# kabupaten_jakarta_singlepart.shp
myResult, myMessage = setupScenario(
theHazard='A flood in Jakarta like in 2007',
theExposure='People',
theFunction='Need evacuation',
theFunctionId='Flood Evacuation Function',
theAggregation='kabupaten jakarta singlepart',
theAggregationEnabledFlag=True)
assert myResult, myMessage
# Press RUN
QTest.mouseClick(myRunButton, QtCore.Qt.LeftButton)
DOCK.runtimeKeywordsDialog.accept()
myAttribute = DOCK.postProcessingAttributes[myAttrKey]
myMessage = ('The aggregation should be KAB_NAME. Found: %s' %
(myAttribute))
self.assertEqual(myAttribute, 'KAB_NAME', myMessage)
def test_checkAggregationAttribute1Attr(self):
"""Aggregation attribute is chosen correctly when there is only
one attr available."""
myRunButton = DOCK.pbnRunStop
myFileList = ['kabupaten_jakarta_singlepart_1_good_attr.shp']
#add additional layers
loadLayers(myFileList, theClearFlag=False, theDataDirectory=TESTDATA)
myAttrKey = getDefaults('AGGR_ATTR_KEY')
# with 1 good aggregation attribute using
# kabupaten_jakarta_singlepart_1_good_attr.shp
myResult, myMessage = setupScenario(
theHazard='A flood in Jakarta like in 2007',
theExposure='People',
theFunction='Need evacuation',
theFunctionId='Flood Evacuation Function',
theAggregation='kabupaten jakarta singlepart 1 good attr')
assert myResult, myMessage
# Press RUN
QTest.mouseClick(myRunButton, QtCore.Qt.LeftButton)
DOCK.runtimeKeywordsDialog.accept()
myAttribute = DOCK.postProcessingAttributes[myAttrKey]
myMessage = ('The aggregation should be KAB_NAME. Found: %s' %
(myAttribute))
self.assertEqual(myAttribute, 'KAB_NAME', myMessage)
def test_checkAggregationAttributeNoAttr(self):
"""Aggregation attribute is chosen correctly when there is no
attr available."""
myRunButton = DOCK.pbnRunStop
myFileList = ['kabupaten_jakarta_singlepart_0_good_attr.shp']
#add additional layers
loadLayers(myFileList, theClearFlag=False, theDataDirectory=TESTDATA)
myAttrKey = getDefaults('AGGR_ATTR_KEY')
# with no good aggregation attribute using
# kabupaten_jakarta_singlepart_0_good_attr.shp
myResult, myMessage = setupScenario(
theHazard='A flood in Jakarta like in 2007',
theExposure='People',
theFunction='Need evacuation',
theFunctionId='Flood Evacuation Function',
theAggregation='kabupaten jakarta singlepart 0 good attr')
assert myResult, myMessage
# Press RUN
QTest.mouseClick(myRunButton, QtCore.Qt.LeftButton)
DOCK.runtimeKeywordsDialog.accept()
myAttribute = DOCK.postProcessingAttributes[myAttrKey]
myMessage = ('The aggregation should be None. Found: %s' %
(myAttribute))
assert myAttribute is None, myMessage
def test_checkAggregationAttributeNoneAttr(self):
"""Aggregation attribute is chosen correctly when there None in the
kezwords"""
myRunButton = DOCK.pbnRunStop
myFileList = ['kabupaten_jakarta_singlepart_with_None_keyword.shp']
#add additional layers
loadLayers(myFileList, theClearFlag=False, theDataDirectory=TESTDATA)
myAttrKey = getDefaults('AGGR_ATTR_KEY')
# with None aggregation attribute defined in .keyword using
# kabupaten_jakarta_singlepart_with_None_keyword.shp
myResult, myMessage = setupScenario(
theHazard='A flood in Jakarta like in 2007',
theExposure='People',
theFunction='Need evacuation',
theFunctionId='Flood Evacuation Function',
theAggregation='kabupaten jakarta singlepart with None keyword')
assert myResult, myMessage
# Press RUN
QTest.mouseClick(myRunButton, QtCore.Qt.LeftButton)
DOCK.runtimeKeywordsDialog.accept()
myAttribute = DOCK.postProcessingAttributes[myAttrKey]
myMessage = ('The aggregation should be None. Found: %s' %
(myAttribute))
assert myAttribute is None, myMessage
#the generated layers are not added to the map registry
def test_checkPostProcessingLayersVisibility(self):
myRunButton = DOCK.pbnRunStop
# with KAB_NAME aggregation attribute defined in .keyword using
# kabupaten_jakarta_singlepart.shp
myResult, myMessage = setupScenario(
theHazard='A flood in Jakarta like in 2007',
theExposure='People',
theFunction='Need evacuation',
theFunctionId='Flood Evacuation Function',
theAggregation='kabupaten jakarta singlepart',
theOkButtonFlag=True)
assert myResult, myMessage
myBeforeCount = len(CANVAS.layers())
#LOGGER.info("Canvas list before:\n%s" % canvasList())
print [str(l.name()) for l in
QgsMapLayerRegistry.instance().mapLayers().values()]
LOGGER.info("Registry list before:\n%s" %
len(QgsMapLayerRegistry.instance().mapLayers()))
# Press RUN
QTest.mouseClick(myRunButton, QtCore.Qt.LeftButton)
myAfterCount = len(CANVAS.layers())
LOGGER.info("Registry list after:\n%s" %
len(QgsMapLayerRegistry.instance().mapLayers()))
# print [str(l.name()) for l in QgsMapLayerRegistry.instance(
# ).mapLayers().values()]
#LOGGER.info("Canvas list after:\n%s" % canvasList())
myMessage = ('Expected %s items in canvas, got %s' %
(myBeforeCount + 1, myAfterCount))
assert myBeforeCount + 1 == myAfterCount, myMessage
# Now run again showing intermediate layers
DOCK.showPostProcLayers = True
myBeforeCount = len(CANVAS.layers())
# Press RUN
QTest.mouseClick(myRunButton, QtCore.Qt.LeftButton)
myAfterCount = len(CANVAS.layers())
LOGGER.info("Canvas list after:\n %s" % canvasList())
myMessage = ('Expected %s items in canvas, got %s' %
(myBeforeCount + 2, myAfterCount))
# We expect two more since we enabled showing intermedate layers
assert myBeforeCount + 2 == myAfterCount, myMessage
def test_runEarthQuakeGuidelinesFunction(self):
"""GUI runs with Shakemap 2009 and Padang Buildings"""
# Push OK with the left mouse button
myButton = DOCK.pbnRunStop
setCanvasCrs(GEOCRS, True)
setPadangGeoExtent()
myMessage = 'Run button was not enabled'
assert myButton.isEnabled(), myMessage
#QTest.keyClick(DOCK.cboHazard, QtCore.Qt.Key_Down)
#QTest.keyClick(DOCK.cboHazard, QtCore.Qt.Key_Enter)
#
#QTest.keyClick(DOCK.cboExposure, QtCore.Qt.Key_Down)
#QTest.keyClick(DOCK.cboExposure, QtCore.Qt.Key_Enter)
# Hazard layer
myIndex = DOCK.cboHazard.findText(PADANG2009_title)
assert myIndex != -1, 'Padang 2009 scenario hazard layer not found'
DOCK.cboHazard.setCurrentIndex(myIndex)
# Exposure layer
myIndex = DOCK.cboExposure.findText('Padang_WGS84')
myMessage = ('Could not find layer Padang_WGS84:\n'
'%s' % (combosToString(DOCK)))
assert myIndex != -1, myMessage
DOCK.cboExposure.setCurrentIndex(myIndex)
# Impact function
myIndex = DOCK.cboFunction.findText('Earthquake Guidelines Function')
myMessage = ('Earthquake Guidelines function not '
'found: ' + combosToString(DOCK))
assert myIndex != -1, myMessage
DOCK.cboFunction.setCurrentIndex(myIndex)
myDict = getUiState(DOCK)
myExpectedDict = {'Hazard': PADANG2009_title,
'Exposure': 'Padang_WGS84',
'Impact Function Id':
'Earthquake Guidelines Function',
'Impact Function Title':
'Earthquake Guidelines Function',
'Run Button Enabled': True}
myMessage = 'Got:\n %s\nExpected:\n%s\n%s' % (
myDict, myExpectedDict, combosToString(DOCK))
assert myDict == myExpectedDict, myMessage
QTest.mouseClick(myButton, QtCore.Qt.LeftButton)
myResult = DOCK.wvResults.page().currentFrame().toPlainText()
# Expected output:
#Buildings Total
#All: 3160
#Low damage (10-25%): 0
#Medium damage (25-50%): 0
#Pre merge of clip on steroids branch:
#High damage (50-100%): 3160
# Post merge of clip on steoids branch:
#High damage (50-100%): 2993
myMessage = ('Unexpected result returned for Earthquake guidelines'
'function. Expected:\n "All" count of 2993, '
'received: \n %s' % myResult)
assert format_int(2993) in myResult, myMessage
def test_runEarthquakeFatalityFunction_small(self):
"""Padang 2009 fatalities estimated correctly (small extent)"""
# Push OK with the left mouse button
myButton = DOCK.pbnRunStop
setCanvasCrs(GEOCRS, True)
setPadangGeoExtent()
myMessage = 'Run button was not enabled'
assert myButton.isEnabled(), myMessage
# Simulate choosing another combo item and running
# the model again
myIndex = DOCK.cboHazard.findText(PADANG2009_title)
assert myIndex != -1, 'Padang 2009 scenario hazard layer not found'
DOCK.cboHazard.setCurrentIndex(myIndex)
# Exposure layers
myIndex = DOCK.cboExposure.findText('People')
assert myIndex != -1, 'People'
DOCK.cboExposure.setCurrentIndex(myIndex)
# Choose impact function
myIndex = DOCK.cboFunction.findText('Earthquake Fatality Function')
myMessage = ('Earthquake Fatality Function not '
'found: ' + combosToString(DOCK))
assert myIndex != -1, myMessage
DOCK.cboFunction.setCurrentIndex(myIndex)
myDict = getUiState(DOCK)
myExpectedDict = {'Hazard': PADANG2009_title,
'Exposure': 'People',
'Impact Function Id': 'Earthquake Fatality Function',
'Impact Function Title':
'Earthquake Fatality Function',
'Run Button Enabled': True}
myMessage = 'Got unexpected state: %s\nExpected: %s\n%s' % (
myDict, myExpectedDict, combosToString(DOCK))
assert myDict == myExpectedDict, myMessage
QTest.mouseClick(myButton, QtCore.Qt.LeftButton)
myResult = DOCK.wvResults.page().currentFrame().toPlainText()
# Check against expected output
myMessage = ('Unexpected result returned for Earthquake Fatality '
'Function Expected: fatality count of '
'116 , received: \n %s' % myResult)
assert format_int(116) in myResult, myMessage
myMessage = ('Unexpected result returned for Earthquake Fatality '
'Function Expected: total population count of '
'847529 , received: \n %s' % myResult)
assert format_int(847529) in myResult, myMessage
def test_runEarthquakeFatalityFunction_Padang_full(self):
"""Padang 2009 fatalities estimated correctly (large extent)"""
# Push OK with the left mouse button
myButton = DOCK.pbnRunStop
setCanvasCrs(GEOCRS, True)
setGeoExtent([96, -5, 105, 2]) # This covers all of the 2009 shaking
myMessage = 'Run button was not enabled'
assert myButton.isEnabled(), myMessage
# Hazard layers
myIndex = DOCK.cboHazard.findText(PADANG2009_title)
assert myIndex != -1, 'Padang 2009 scenario hazard layer not found'
DOCK.cboHazard.setCurrentIndex(myIndex)
# Exposure layers
myIndex = DOCK.cboExposure.findText('People')
assert myIndex != -1, 'People'
DOCK.cboExposure.setCurrentIndex(myIndex)
# Choose impact function
myIndex = DOCK.cboFunction.findText('Earthquake Fatality Function')
myMessage = ('Earthquake Fatality Function not '
'found: ' + combosToString(DOCK))
assert myIndex != -1, myMessage
DOCK.cboFunction.setCurrentIndex(myIndex)
myDict = getUiState(DOCK)
myExpectedDict = {'Hazard': PADANG2009_title,
'Exposure': 'People',
'Impact Function Id':
'Earthquake Fatality Function',
'Impact Function Title':
'Earthquake Fatality Function',
'Run Button Enabled': True}
myMessage = 'Got unexpected state: %s\nExpected: %s\n%s' % (
myDict, myExpectedDict, combosToString(DOCK))
assert myDict == myExpectedDict, myMessage
QTest.mouseClick(myButton, QtCore.Qt.LeftButton)
myResult = DOCK.wvResults.page().currentFrame().toPlainText()
# Check against expected output
myMessage = ('Unexpected result returned for Earthquake Fatality '
'Function Expected: fatality count of '
'500 , received: \n %s' % myResult)
assert format_int(500) in myResult, myMessage
myMessage = ('Unexpected result returned for Earthquake Fatality '
'Function Expected: total population count of '
'31372262 , received: \n %s' % myResult)
assert format_int(31372262) in myResult, myMessage
def test_runTsunamiBuildingImpactFunction(self):
"""Tsunami function runs in GUI as expected."""
# Push OK with the left mouse button
myButton = DOCK.pbnRunStop
myMessage = 'Run button was not enabled'
assert myButton.isEnabled(), myMessage
myResult, myMessage = setupScenario(
theHazard='Tsunami Max Inundation',
theExposure='Tsunami Building Exposure',
theFunction='Be flooded',
theFunctionId='Flood Building Impact Function')
assert myResult, myMessage
setCanvasCrs(GEOCRS, True)
setBatemansBayGeoExtent()
# Press RUN
QTest.mouseClick(myButton, QtCore.Qt.LeftButton)
myResult = DOCK.wvResults.page().currentFrame().toPlainText()
#print myResult
# Post clip on steroids refactor
# < 1 m: 1923
# 1 - 3 m: 89
# > 3 m: 0
# Post replacement of Batemans Bay dataset
#< 1 m: 10
#1 - 3 m: 7
#> 3 m: 0
# Post rewrite of impact function
#Building type closed Total
#All 7 17
myMessage = 'Result not as expected: %s' % myResult
assert format_int(17) in myResult, myMessage
assert format_int(7) in myResult, myMessage
def test_runFloodPopulationImpactFunction(self):
"""Flood function runs in GUI with Jakarta data
Raster on raster based function runs as expected."""
# Push OK with the left mouse button
myButton = DOCK.pbnRunStop
myMessage = 'Run button was not enabled'
assert myButton.isEnabled(), myMessage
myResult, myMessage = setupScenario(
theHazard='A flood in Jakarta like in 2007',
theExposure='Penduduk Jakarta',
theFunction='HKVtest',
theFunctionId='HKVtest')
assert myResult, myMessage
# Enable on-the-fly reprojection
setCanvasCrs(GEOCRS, True)
setJakartaGeoExtent()
# Press RUN
QTest.mouseClick(myButton, QtCore.Qt.LeftButton)
myResult = DOCK.wvResults.page().currentFrame().toPlainText()
# Check that the number is as what was calculated by
# Marco Hartman form HKV
myMessage = 'Result not as expected: %s' % myResult
# This is the expected impact number
assert format_int(2480) in myResult, myMessage
def test_runFloodPopulationImpactFunction_scaling(self):
"""Flood function runs in GUI with 5x5km population data
Raster on raster based function runs as expected with scaling."""
myResult, myMessage = setupScenario(
theHazard='A flood in Jakarta like in 2007',
theExposure='People',
theFunction='Need evacuation',
theFunctionId='Flood Evacuation Function')
assert myResult, myMessage
# Enable on-the-fly reprojection
setCanvasCrs(GEOCRS, True)
setJakartaGeoExtent()
# Press RUN
myButton = DOCK.pbnRunStop
QTest.mouseClick(myButton, QtCore.Qt.LeftButton)
myResult = DOCK.wvResults.page().currentFrame().toPlainText()
myMessage = 'Result not as expected: %s' % myResult
# Check numbers are OK (within expected errors from resampling)
# These are expected impact number
assert format_int(10484) in myResult, myMessage
assert format_int(977) in myResult, myMessage
def test_runFloodPopulationPolygonHazardImpactFunction(self):
"""Flood function runs in GUI with Jakarta polygon flood hazard data.
Uses population raster exposure layer"""
myResult, myMessage = setupScenario(
theHazard=('A flood in Jakarta'),
theExposure='Penduduk Jakarta',
theFunction='Need evacuation',
theFunctionId='Flood Evacuation Function Vector Hazard')
assert myResult, myMessage
# Enable on-the-fly reprojection
setCanvasCrs(GEOCRS, True)
setJakartaGeoExtent()
# Press RUN
myButton = DOCK.pbnRunStop
QTest.mouseClick(myButton, QtCore.Qt.LeftButton)
myResult = DOCK.wvResults.page().currentFrame().toPlainText()
myMessage = 'Result not as expected: %s' % myResult
# This is the expected number of people needing evacuation
assert format_int(134953000) in myResult, myMessage
def test_runCategorizedHazardBuildingImpact(self):
"""Flood function runs in GUI with Flood in Jakarta hazard data
Uses DKI buildings exposure data."""
myResult, myMessage = setupScenario(
theHazard='Flood in Jakarta',
theExposure='Essential buildings',
theFunction='Be affected',
theFunctionId='Categorised Hazard Building Impact Function')
assert myResult, myMessage
# Enable on-the-fly reprojection
setCanvasCrs(GEOCRS, True)
setJakartaGeoExtent()
# Press RUN
myButton = DOCK.pbnRunStop
QTest.mouseClick(myButton, QtCore.Qt.LeftButton)
myResult = DOCK.wvResults.page().currentFrame().toPlainText()
myMessage = 'Result not as expected: %s' % myResult
# This is the expected number of building might be affected
assert format_int(535) in myResult, myMessage
assert format_int(453) in myResult, myMessage
assert format_int(436) in myResult, myMessage
def test_runCategorisedHazardPopulationImpactFunction(self):
"""Flood function runs in GUI with Flood in Jakarta hazard data
Uses Penduduk Jakarta as exposure data."""
myResult, myMessage = setupScenario(
theHazard='Flood in Jakarta',
theExposure='Penduduk Jakarta',
theFunction='Be impacted',
theFunctionId='Categorised Hazard Population Impact Function')
assert myResult, myMessage
# Enable on-the-fly reprojection
setCanvasCrs(GEOCRS, True)
setJakartaGeoExtent()
# Press RUN
myButton = DOCK.pbnRunStop
QTest.mouseClick(myButton, QtCore.Qt.LeftButton)
myResult = DOCK.wvResults.page().currentFrame().toPlainText()
myMessage = 'Result not as expected: %s' % myResult
# This is the expected number of population might be affected
assert format_int(30938000) in myResult, myMessage
assert format_int(68280000) in myResult, myMessage
assert format_int(157551000) in myResult, myMessage
def test_runEarthquakeBuildingImpactFunction(self):
"""Earthquake function runs in GUI with An earthquake in Yogyakarta
like in 2006 hazard data uses OSM Building Polygons exposure data."""
myResult, myMessage = setupScenario(
theHazard='An earthquake in Yogyakarta like in 2006',
theExposure='OSM Building Polygons',
theFunction='Be affected',
theFunctionId='Earthquake Building Impact Function')
assert myResult, myMessage
# Enable on-the-fly reprojection
setCanvasCrs(GEOCRS, True)
setGeoExtent([101, -12 , 119, -4])
# Press RUN
myButton = DOCK.pbnRunStop
QTest.mouseClick(myButton, QtCore.Qt.LeftButton)
myResult = DOCK.wvResults.page().currentFrame().toPlainText()
LOGGER.debug(myResult)
myMessage = 'Result not as expected: %s' % myResult
# This is the expected number of building might be affected
assert format_int(786) in myResult, myMessage
assert format_int(15528) in myResult, myMessage