-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathjj_tests.py
1825 lines (1696 loc) · 79.7 KB
/
jj_tests.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
from __future__ import division
# --------------------------------
# Name: jj_tests.py
# Purpose: To test commonly used methods.
# Author: Jared Johnston
# Created: 11/10/2017
# Copyright: (c) TCC
# ArcGIS Version: 10.5
# Python Version: 2.7
# Template Source: https://blogs.esri.com/esri/arcgis/2011/08/04/pythontemplate/
# --------------------------------
import os # noqa
import sys # noqa
import arcpy
import logging
import json
import csv
import imp
import re
import jj_methods as jj
from datetime import datetime
def _bar(itterable):
return itterable
jj.bar = _bar # to disable progress bar
# arcpy.env.workspace = r'O:\Data\Planning_IP\Admin\Staff\Jared\GIS\Tools\arcpyScripts\TestingDataset.gdb'
arcpy.env.workspace = arcpy.env.scratchGDB
# testing = True
testing = False
logging.basicConfig(filename='jj_tests.log',
level=logging.DEBUG,
format='%(asctime)s @ %(lineno)d: %(message)s',
datefmt='%Y-%m-%d,%H:%M:%S')
logging.debug("workspace = %s" % arcpy.env.scratchGDB)
def log(text):
print(text)
logging.debug(text)
def test_delete_if_exists():
print "Testing delete_if_exists..."
basic_polygon = jj.create_basic_polygon()
jj.delete_if_exists(basic_polygon)
if arcpy.Exists(basic_polygon):
print " delete_if_exists failed. Layer not deleted."
else:
print " pass"
print "------"
def test_is_polygon():
print "Testing is_polygon..."
basic_polygon = jj.create_basic_polygon()
if jj.is_polygon(basic_polygon):
print " Pass"
else:
print " Fail: is_polygon did not return true when passed a polygon"
basic_point = jj.create_point()
try:
if jj.is_polygon(basic_point):
print(" Fail: is polygon returned True for a point")
else:
print(" Pass")
except Error as e:
print(" Fail: An error was encountered")
print(e.args)
print "Testing is_polygon with logical operators..."
if not (jj.is_polygon(basic_polygon) and jj.is_polygon(basic_point)):
print(" Pass")
else:
print(" Fail: both is_polygon(basic_polygon) and is_polygon(basic_point) returned true")
def test_field_in_feature_class():
print "Testing field_in_feature_class finds an existing field..."
test_feature_class = "testing_field_in_feature_class"
jj.delete_if_exists(test_feature_class)
arcpy.CreateFeatureclass_management(
arcpy.env.workspace, # out_path
test_feature_class, # out_name
"POLYGON") # geometry_type
arcpy.AddField_management(test_feature_class, "this_field_exists", "TEXT")
if jj.field_in_feature_class("this_field_exists", test_feature_class):
print " Pass"
else:
print " Fail, %s field exists in %s, but tool returns False" % ("this_field_exists", test_feature_class)
print "Testing field_in_feature_class doesn't find a missing field..."
if jj.field_in_feature_class("some_nonexistent_field", test_feature_class):
print " Fail, %s field is not in %s, but tool returns True" % ("some_nonexistent_field", test_feature_class)
print " Fields that exist:"
for field in arcpy.ListFields(test_feature_class):
print " %s" % field.name
else:
print " Pass"
jj.delete_if_exists(test_feature_class)
print "------"
def test_add_external_area_field():
print("Testing add_external_area_field...")
left_x = 479560 # TODO: use this in the test dataset
mid_left_x = 479580
mid_right_x = 479600
right_x = 479620
lower_y = 7871500
upper_y = 7871600
source_data = jj.create_polygon(
"add_external_area_field_in_features", [
(mid_left_x, lower_y),
(mid_left_x, upper_y),
(right_x, upper_y),
(right_x, lower_y),
(mid_left_x, lower_y)])
layer_with_area_to_grab = jj.create_polygon(
"area_to_grab", [
(left_x, lower_y),
(left_x, upper_y),
(mid_right_x, upper_y),
(mid_right_x, lower_y),
(left_x, lower_y)])
basic_point = jj.create_point()
print(" Testing point inputs raises an error...")
try:
output = jj.add_external_area_field(
source_data,
"external_area",
# "add_external_area_field_invalid_input",
basic_point,
dissolve=False)
print(" Fail: no error was raised.")
except AttributeError as e:
print(" Pass")
print(" Testing basic inputs...")
output = jj.add_external_area_field(
source_data,
"external_area",
layer_with_area_to_grab,
dissolve=False)
print(" Testing new field is added...")
if jj.field_in_feature_class("external_area", output):
print(" Pass")
else:
print(" Fail: %s does not contain the new field" % output)
print(" Testing new field contains the expected values...")
with arcpy.da.SearchCursor(output, ["external_area"]) as cursor:
for row in cursor:
if row[0] == 2000:
print(" Pass")
else:
print(" Fail: external area should have been 2000, but was %s" % row[0])
print(" Testing tool returns new dataset")
if str(output) == str(source_data):
print(" Fail: output and source_data should not be the same file (output=%s, source_data=%s)" % (output, source_data))
else:
print(" Pass")
print(" Testing conflicting filename is not an issue")
# conflicting_file = jj.create_basic_polygon(
# output = "add_external_area_field_in_features_with_new_field")
# output = jj.add_external_area_field(
# source_data,
# "external_area",
# layer_with_area_to_grab,
# dissolve=False)
print(" TODO")
print(" Testing dissolve make tool calculate correctly")
print(" Testing area that needs dissolving, but didn't get it")
layer_with_area_to_grab_divided = jj.create_polygon(
"area_to_grab_divided",
[
(left_x, lower_y),
(left_x, upper_y-50),
(mid_right_x, upper_y-50),
(mid_right_x, lower_y),
(left_x, lower_y)
], [
(left_x, upper_y-50),
(left_x, upper_y),
(mid_right_x, upper_y),
(mid_right_x, upper_y-50),
(left_x, upper_y-50)
])
output = jj.add_external_area_field(
source_data,
"external_area",
layer_with_area_to_grab_divided,
dissolve=False)
with arcpy.da.SearchCursor(output, ["external_area"]) as cursor:
for row in cursor:
if row[0] == 2000:
print(" Fail: this should not have produced the correct output since dissolve was set to False")
else:
# Should fail because dissolve is required
print(" Pass")
print(" Testing area that needs dissolving, and gets it")
output = jj.add_external_area_field(
source_data,
"external_area",
layer_with_area_to_grab_divided,
dissolve=True)
with arcpy.da.SearchCursor(output, ["external_area"]) as cursor:
for row in cursor:
if row[0] == 2000:
print(" Pass")
else:
# Should pass here
print(" Fail: external area should have been 2000, but was %s" % row[0])
print(" Testing 1/1 external area outside in_features adds 0, not Null")
in_features_not_overlapping = jj.create_polygon(
"in_features_not_overlapping", [
(left_x, lower_y),
(left_x, upper_y),
(mid_left_x, upper_y),
(mid_left_x, lower_y),
(left_x, lower_y)])
non_intersecting_area = jj.create_polygon(
"non_intersecting_area", [
(mid_right_x, lower_y),
(mid_right_x, upper_y),
(right_x, upper_y),
(right_x, lower_y),
(mid_right_x, lower_y)])
output = jj.add_external_area_field(
in_features_not_overlapping,
"external_area",
non_intersecting_area,
dissolve=False)
with arcpy.da.SearchCursor(output, ["external_area"]) as cursor:
for row in cursor:
if row[0] == 0:
print(" Pass")
else:
print(" Fail: external area should have been 0, but was %s" % row[0])
print(" Testing 1/2 external area outside in_features adds 0, not Null")
in_features_some_overlapping = jj.create_polygon(
"in_features_some_overlapping",
[
(left_x, lower_y),
(left_x, upper_y),
(mid_left_x, upper_y),
(mid_left_x, lower_y),
(left_x, lower_y)
],
[
(mid_left_x, lower_y),
(mid_left_x, upper_y),
(mid_right_x+10, upper_y),
(mid_right_x+10, lower_y),
(mid_left_x, lower_y)
])
singular_intersecting_area = jj.create_polygon(
"singular_intersecting_area", [
(mid_right_x, lower_y),
(mid_right_x, upper_y),
(right_x, upper_y),
(right_x, lower_y),
(mid_right_x, lower_y)])
output = jj.add_external_area_field(
in_features_some_overlapping,
"external_area",
singular_intersecting_area,
dissolve=False)
with arcpy.da.SearchCursor(output, ["external_area"]) as cursor:
for row in cursor:
if row[0] in (0, 1000.0):
print(" Pass")
else:
print(" Fail: external area should have been 0 or 1000, but was %s" % row[0])
# This was created to test a known problem, but it's passing. Not sure what's going on.
print(" Testing with known problematic dataset")
wingate = r'O:\Data\Planning_IP\Admin\Staff\Jared\Land_Use_Monitoring\tools\distribute_growth\testing_datasets.gdb\add_external_area_in_features'
nda = r'O:\Data\Planning_IP\Admin\Staff\Jared\Land_Use_Monitoring\tools\distribute_growth\testing_results.gdb\net_developable_area'
output = jj.add_external_area_field(
in_features=wingate,
new_field_name="external_area",
layer_with_area_to_grab=nda,
dissolve=True)
with arcpy.da.SearchCursor(output, ["external_area"]) as cursor:
for row in cursor:
if int(row[0]) == 833883:
print(" Pass")
else:
print(" Fail: external area should have been 833883, but was %s" % row[0])
def test_arguments_exist():
print "Testing arguments_exist..."
if jj.arguments_exist():
print " This file was called with arguments"
else:
print " This file was not called with arguments"
print "------"
# def test_return_tuple_of_args():
# # I don't think this function is actually used.
# print "Testing return_tuple_of_args..."
# print " Here are the passed in args: " + str(jj.return_tuple_of_args())
# print "------"
def test_calculate_external_field():
print "Testing calculate_external_field..."
print " Testing external field is joined..."
one_field = jj.create_basic_polygon(output="calculate_external_one_field")
arcpy.AddField_management(one_field, "first", "TEXT")
arcpy.CalculateField_management(one_field, "first", "get_text()", "PYTHON_9.3", """def get_text():
return 'from one_field'""")
two_fields = jj.create_basic_polygon()
arcpy.AddField_management(two_fields, "first", "TEXT")
arcpy.AddField_management(two_fields, "second", "TEXT")
# arcpy.CalculateField_management(in_table, field, expression, {expression_type}, {code_block})
arcpy.CalculateField_management(two_fields, "first", "get_text()", "PYTHON_9.3", """def get_text():
return 'from two_fields'""")
arcpy.CalculateField_management(two_fields, "second", "get_text()", "PYTHON_9.3", """def get_text():
return 'from two_fields'""")
output = "testing_calculate_external_field"
jj.calculate_external_field(one_field, "first", two_fields, "first", output)
with arcpy.da.SearchCursor(output, "first") as cursor:
for row in cursor:
regexp = re.compile('from two_fields')
assert(regexp.match("%s" % row))
print " pass"
print " Testing tmp_field_name is deleted..."
output = "testing_join_field_is_deleted"
conflicting_layer = jj.create_basic_polygon(output="calculate_external_conflicting_layer")
arcpy.AddField_management(conflicting_layer, "first", "TEXT")
arcpy.AddField_management(conflicting_layer, "second", "TEXT")
arcpy.AddField_management(conflicting_layer, "delete_me", "TEXT")
arcpy.CalculateField_management(
conflicting_layer,
"first",
"get_text()",
"PYTHON_9.3",
"""def get_text():
return 'from conflicting_layer'""")
arcpy.CalculateField_management(
conflicting_layer,
"second",
"get_text()",
"PYTHON_9.3",
"""def get_text():
return 'from conflicting_layer'""")
arcpy.CalculateField_management(
conflicting_layer,
"delete_me",
"get_text()",
"PYTHON_9.3",
"""def get_text():
return 'this text should not be visible'""")
jj.delete_if_exists(output)
try:
output = jj.calculate_external_field(one_field, "first", conflicting_layer, "delete_me", output)
print(" fail: no error was raised")
except AttributeError as e:
print(" pass")
except Exception as e:
print(" fail: some other error %s" % e.args[0])
jj.log(" Testing output must be provided...")
try:
output = jj.calculate_external_field(one_field, "first", conflicting_layer, "delete_me")
print(" fail: no execption raised")
except TypeError as e:
print(" pass: exception raised")
jj.log(" Testing using distance_field_name options raises an error...")
try:
output = jj.calculate_external_field(one_field, "first", two_fields, "first", output="testing_kwargs", match_option="CLOSEST", distance_field_name="distance_to", search_radius=100)
print(" fail - no error was raised")
except AttributeError as e:
print(" pass")
print " Testing output=None changes target_layer in place..."
output = jj.calculate_external_field(one_field, "first", two_fields, "first", output=None)
with arcpy.da.SearchCursor(one_field, "first") as cursor:
for row in cursor:
regexp = re.compile('from two_fields')
assert(regexp.match("%s" % row))
print " pass"
jj.log(" Testing Spatial Join keyword arguments affect join behaviour...")
test_join_method = jj.create_basic_polygon(output="test_join_method")
# create a new field to calculate
arcpy.AddField_management(test_join_method, "no_data", "TEXT")
arcpy.CalculateField_management(test_join_method, "no_data", "get_none()", "PYTHON_9.3", """def get_none():
return None""")
shape_near_by = jj.create_basic_polygon(output="shape_near_by", left_x=479570, lower_y=7871450, right_x=479572, upper_y=7871452)
# create a new field to get data form
arcpy.AddField_management(shape_near_by, "some_data", "TEXT")
arcpy.CalculateField_management(shape_near_by, "some_data", "get_text()", "PYTHON_9.3", """def get_text():
return 'wazoo'""")
jj.delete_if_exists("no_data_joined")
jj.delete_if_exists("data_joined")
no_data_joined = jj.calculate_external_field(test_join_method, "no_data", shape_near_by, "some_data", output="no_data_joined")
data_joined = jj.calculate_external_field(test_join_method, "no_data", shape_near_by, "some_data", output="data_joined", search_radius=100)
with arcpy.da.SearchCursor(no_data_joined, "no_data") as cursor:
for row in cursor:
assert(row[0] == None)
with arcpy.da.SearchCursor(data_joined, "no_data") as cursor:
for row in cursor:
regexp = re.compile('wazoo')
assert(regexp.match("%s" % row))
print " pass"
print "------"
def test_get_file_from_path():
print " Testing get_file_from_path..."
some_path = r'C:\TempArcGIS\testing.gdb\foobar'
if (jj.get_file_from_path(some_path) == "foobar"):
print " pass"
else:
print " fail"
print " Testing get_file_from_path with where \\ not found in string..."
some_string = r'foobar'
if (jj.get_file_from_path(some_string) == "foobar"):
print " pass"
else:
print " fail. results = %s" % jj.get_directory_from_path(some_string)
print " Testing get_file_from_path for non string..."
some_non_string = 2016
try:
if (jj.get_file_from_path(some_non_string) == "2016"):
print " pass"
else:
print " fail. results = %s" % jj.get_directory_from_path(some_non_string)
except Exception as e:
print " fail. Exception caught."
print " %s" % e.arge[0]
print "------"
def test_get_directory_from_path():
print "Testing get_directory_from_path..."
print " Testing get_directory_from_path with standard path..."
some_path = r'C:\TempArcGIS\testing.gdb\foobar'
if (jj.get_directory_from_path(some_path) == "C:\\TempArcGIS\\testing.gdb"):
print " pass"
else:
print " fail. results = %s" % jj.get_directory_from_path(some_path)
print " Testing get_directory_from_path with where \\ not found in string..."
some_string = r'foobar'
try:
path = jj.get_directory_from_path(some_string)
if (path == ""):
print " fail, path was an empty string. No error raised even though there was no path in the string"
else:
print " fail. Should raise an error. path = %s" % path
print "------"
except AttributeError as e:
print(" pass. get_directory_from_path raises an error")
def test_renameFieldMap():
print "Testing renameFieldMap"
print "TODO"
print "------"
def test_add_layer_count():
print "Testing add_layer_count..."
far_left_x = 479580
left_x = 479587.5
mid_x = 479595
right_x = 479600
far_right_x =479610
bottom_y = 7871600
top_y = 7871590
boundary_layer_mod = jj.create_basic_polygon(
output="boundary_layer_mod",
left_x = far_left_x,
lower_y = bottom_y,
right_x = 479602,
upper_y = top_y)
boundary_layer = jj.create_basic_polygon(
output="boundary_layer",
left_x = far_left_x,
lower_y = bottom_y,
right_x = 479602,
upper_y = top_y)
far_left_shape = [
(far_left_x, bottom_y),
(far_left_x, top_y),
(left_x, top_y),
(left_x, bottom_y),
(far_left_x, bottom_y)]
left_shape = [
(left_x, bottom_y),
(left_x, top_y),
(mid_x, top_y),
(mid_x, bottom_y),
(left_x, bottom_y)]
mid_shape = [
(mid_x, bottom_y),
(mid_x, top_y),
(right_x, top_y),
(right_x, bottom_y),
(mid_x, bottom_y)]
right_shape = [
(right_x, bottom_y),
(right_x, top_y),
(far_right_x, top_y),
(far_right_x, bottom_y),
(right_x, bottom_y)]
count_layer = "count_layer"
jj.delete_if_exists(count_layer)
count_layer = jj.create_polygon(count_layer, far_left_shape, left_shape, mid_shape, right_shape)
count_field_name = "count_field"
def test_by_area():
result = jj.add_layer_count(boundary_layer, count_layer, count_field_name, by_area=True)
def test_adds_a_field():
print " Testing add_layer_count adds a field..."
fields = [field.name for field in arcpy.ListFields(result)]
if count_field_name in fields:
print " Pass"
else:
print " Fail: %s not found in results. The following fiels were found: %s" % (count_field_name, fields)
def test_counts_correctly_by_area():
print(" Testing: newly added field counts the number of occurences of")
print(" count_layer that are inside the input boundary_layer by total amount")
print(" of area that falls within each shape...")
with arcpy.da.SearchCursor(result, count_field_name) as cursor:
for row in cursor:
if int(row[0]*10)/10 == 3.2:
print(" Pass")
else:
print(" Fail: result was %s. Should have been 1.3" %
row[0])
def test_points_raises_an_error():
print(" Testing: if add_layer_count is called with the by_area")
print(" method set to true, and point feature classes are")
print(" passed in, an error should be raised...")
point_1 = jj.create_point(output="point_1")
point_2 = jj.create_point(output="point_2")
polygon_1 = jj.create_basic_polygon(output="polygon_1")
try:
jj.add_layer_count(point_1, point_2, "some_field", by_area=True)
print(" Fail: no error raised.")
except AttributeError as e:
print(" Pass")
except Exception as e:
print(" Fail: some other error raised. See logs for details")
logging.exception(e.args[0])
try:
jj.add_layer_count(polygon_1, point_2, "some_field", by_area=True)
print(" Fail: no error raised.")
except AttributeError as e:
print(" Pass")
except Exception as e:
print(" Fail: some other error raised. See logs for details")
logging.exception(e.args[0])
try:
jj.add_layer_count(point_1, polygon_1, "some_field", by_area=True)
print(" Fail: no error raised.")
except AttributeError as e:
print(" Pass")
except Exception as e:
print(" Fail: some other error raised. See logs for details")
logging.exception(e.args[0])
test_points_raises_an_error()
test_adds_a_field()
test_counts_correctly_by_area()
def test_by_centroid():
result = jj.add_layer_count(boundary_layer_mod, count_layer, count_field_name)
def test_counts_correctly_by_centroid():
print(" Testing: newly added field counts the number of occurences of")
print(" count_layer that are inside the input boundary_layer_mod by each centroid")
print(" that falls within each shape...")
with arcpy.da.SearchCursor(result, count_field_name) as cursor:
for row in cursor:
if int(row[0]*10)/10 == 3.0:
print(" Pass")
else:
print(" Fail: result was %s. Should have been 3.0" % row[0])
print(" Testing: real dataset")
real_result = jj.add_layer_count(
in_features=r'O:\Data\Planning_IP\Admin\Staff\Jared\Land_Use_Monitoring\Residential_Estates\residential_estates.gdb\residential_estate_extents',
count_features=r'O:\Data\Planning_IP\Spatial\Base Layers\Snapshots.gdb\Land_2016_July',
new_field_name="properties_2016",
output="estates_with_consumption")
with arcpy.da.SearchCursor(real_result, "properties_2016", "estate_name = 'Bushland Beach'") as cursor:
for row in cursor:
if row[0] == 1:
jj.log(" pass")
else:
jj.log(" fail: number of joined features should have been 1 but was %s" % row[0])
def test_points_can_be_used_as_count_layer():
print(" Testing: point can be used as the count_layer if by_area is")
print(" not set to True...")
point_1 = jj.create_point(output="point_1")
point_2 = jj.create_point(output="point_2")
polygon_1 = jj.create_basic_polygon(output="polygon_1")
try:
jj.add_layer_count(polygon_1, point_1, "some_field")
print(" TODO: write tests")
except AttributeError as e:
print(" Fail: an Attribute error was raised")
def test_original_layer_is_modified():
print(" Testing that the input layer is not modified when no output provided")
if jj.field_in_feature_class(count_field_name, boundary_layer_mod):
print(" pass")
else:
print(" fail")
result_w_output = jj.add_layer_count(boundary_layer, count_layer, count_field_name, output="add_layer_count_w_output")
def test_original_layer_is_not_modified():
print(" Testing that the input layer is not modified when output provided")
if jj.field_in_feature_class(count_field_name, boundary_layer):
print(" fail")
else:
print(" pass")
def test_new_field_already_exists():
print(" Testing that if the field being added already exists, an error is raised")
layer_with_field = jj.create_basic_polygon()
arcpy.AddField_management(
in_table=layer_with_field,
field_name="existing_field",
field_type="TEXT")
try:
jj.add_layer_count(
in_features=layer_with_field,
count_features=count_layer,
new_field_name="existing_field")
print(" fail: no AttributeError was raised")
except AttributeError as e:
print(" pass")
def test_invalid_existing_fields_are_caught():
print(" Testing that if any fields used by the tool already exist, they are address, or an error is raised.")
# boundary_layer
# count_layer
boundary_layer_w_TARGET_FID = jj.create_basic_polygon()
arcpy.AddField_management(
in_table=boundary_layer_w_TARGET_FID,
field_name="TARGET_FID",
field_type="TEXT")
try:
jj.add_layer_count(
in_features=boundary_layer_w_TARGET_FID,
count_features=count_layer,
new_field_name="some_count")
print(" fail: no AttributeError was raised")
except AttributeError as e:
if re.match('.*TARGET_FID.*', e.args[0]):
log(" Pass")
else:
log(" Fail: appropriate error not raised when TARGET_FID already existed")
log(e.args[0])
boundary_layer_w_JOIN_FID = jj.create_basic_polygon()
arcpy.AddField_management(
in_table=boundary_layer_w_JOIN_FID,
field_name="JOIN_FID",
field_type="TEXT")
try:
jj.add_layer_count(
in_features=boundary_layer_w_JOIN_FID,
count_features=count_layer,
new_field_name="some_count")
print(" fail: no AttributeError was raised")
except AttributeError as e:
if re.match('.*JOIN_FID.*', e.args[0]):
log(" Pass")
else:
log(" Fail: appropriate error not raised when JOIN_FID already existed")
log(e.args[0])
boundary_layer_w_Join_Count = jj.create_basic_polygon()
arcpy.AddField_management(
in_table=boundary_layer_w_Join_Count,
field_name= "Join_Count",
field_type="TEXT")
try:
jj.add_layer_count(
in_features=boundary_layer_w_Join_Count,
count_features=count_layer,
new_field_name="some_count")
print(" fail: no AttributeError was raised")
except AttributeError as e:
if re.match('.*Join_Count.*', e.args[0]):
log(" Pass")
else:
log(" Fail: appropriate error not raised when Join_Count already existed")
log(e.args[0])
boundary_layer_w_FREQUENCY = jj.create_basic_polygon()
arcpy.AddField_management(
in_table=boundary_layer_w_FREQUENCY,
field_name= "FREQUENCY",
field_type="TEXT")
try:
jj.add_layer_count(
in_features=boundary_layer_w_FREQUENCY,
count_features=count_layer,
new_field_name="some_count")
print(" fail: no AttributeError was raised")
except AttributeError as e:
if re.match('.*FREQUENCY.*', e.args[0]):
log(" Pass")
else:
log(" Fail: appropriate error not raised when FREQUENCY already existed")
log(e.args[0])
test_counts_correctly_by_centroid()
test_points_can_be_used_as_count_layer()
test_original_layer_is_modified()
test_original_layer_is_not_modified()
test_new_field_already_exists()
# test_invalid_existing_fields_are_caught()
# test_by_area()
test_by_centroid()
def test_redistributePolygon():
# TODO: improve the tests for this method. All input data should be created on the fly, more tests should be added, more polygons should be added, etc.
log("Testing redistributePolygon...")
left_x = 479582.11
mid_x = 479649.579
right_x = 479773.05
lower_y = 7871640
upper_y = 7871680
layer_to_redistribute_to = arcpy.env.workspace + "\\layer_to_redistribute_to"
jj.delete_if_exists(layer_to_redistribute_to)
# This array creates an area that is around 40% of the growth model polygon.
jj.create_polygon(layer_to_redistribute_to, [
(left_x,lower_y),
(left_x,upper_y),
(mid_x,upper_y),
(mid_x,lower_y),
(left_x,lower_y)], [
(mid_x,lower_y),
(mid_x, upper_y),
(right_x, upper_y),
(right_x, lower_y),
(mid_x, lower_y)
])
layer_to_be_redistributed = arcpy.env.workspace + "\\layer_to_be_redistributed"
jj.delete_if_exists(layer_to_be_redistributed)
jj.create_polygon(layer_to_be_redistributed, [
(left_x,lower_y),
(left_x,upper_y),
(right_x,upper_y),
(right_x,lower_y),
(left_x,lower_y)])
arcpy.AddField_management(layer_to_be_redistributed, "Dwelling_1", "SHORT")
arcpy.CalculateField_management(layer_to_be_redistributed, "Dwelling_1", "get_12()", "PYTHON_9.3", """def get_12():
return 12""")
redistributePolygonInputs = {}
redistributePolygonInputs["layer_to_redistribute_to"] = layer_to_redistribute_to
redistributePolygonInputs["layer_to_be_redistributed"] = layer_to_be_redistributed
redistributePolygonInputs["output_filename"] = "output"
redistributePolygonInputs["fields_to_be_distributed"] = ["Dwelling_1"]
def testing_number_of_fields():
log(" Testing number of fields")
redistributePolygonInputs["distribution_method"] = 2
redistribution_layer_fields = [f.name for f in
arcpy.ListFields(redistributePolygonInputs["layer_to_redistribute_to"])]
layer_to_be_redistributed_fields = [f.name for f in
arcpy.ListFields(redistributePolygonInputs["layer_to_be_redistributed"])]
logging.debug(" Fields in %s" % redistributePolygonInputs["layer_to_redistribute_to"])
for field in redistribution_layer_fields:
logging.debug(" %s" % field)
logging.debug(" Fields in %s" % redistributePolygonInputs["layer_to_be_redistributed"])
for field in layer_to_be_redistributed_fields:
logging.debug(" %s" % field)
jj.redistributePolygon(redistributePolygonInputs)
output_fields = [f.name for f in arcpy.ListFields(redistributePolygonInputs["output_filename"])]
logging.debug(" Fields in %s" % redistributePolygonInputs["output_filename"])
for field in output_fields:
logging.debug(" %s" % field)
if (len(redistribution_layer_fields)-4 + len(layer_to_be_redistributed_fields)-4 == len(output_fields)-6): # every feature class has OBJECTID, Shape, Shape_Length, and Shape_Area. The output also has Join_Count, and TARGET_FID
log(" Pass")
else:
log(" Fail: the output has an unexpected number of fields")
def testing_invalid_distribution_method_is_caught():
log(" Testing invalid distribution method is caught")
for method in [0, "blah", 6.5]:
redistributePolygonInputs["distribution_method"] = method
try:
jj.redistributePolygon(redistributePolygonInputs)
except AttributeError as e:
if re.match('distribution method must be either 1, 2, 3, or the path to a feature class', e.args[0]):
log(" Pass")
else:
log(" Fail: an invalid distribution method did not raise an AttributeError")
except Exception as e:
log(" Fail:")
log(" " + e.args[0])
def testing_invalid_field_is_caught():
log(" Testing invalid field is caught")
redistributePolygonInputs["fields_to_be_distributed"] = ["nonexistent_field"]
try:
jj.redistributePolygon(redistributePolygonInputs)
raise ValueError
except AttributeError as e:
if re.match('.*does not exist.*', e.args[0]):
log(" Pass")
else:
log(" Fail: wrong error message")
log(" " + e.args[0])
except ValueError as e:
log(" Fail: redistributePolygon tool raises no error if pased a field that doesn't exist.")
except Exception as e:
log(" Fail: Some other exception raised")
log(" " + e.args[0])
def testing_number_of_properties_method():
log(" Testing number of properties method:")
log(" Testing simple distribution with no properties_layer provided:")
redistributePolygonInputs["fields_to_be_distributed"] = ["Dwelling_1"]
redistributePolygonInputs["distribution_method"] = 2
jj.redistributePolygon(redistributePolygonInputs)
with arcpy.da.SearchCursor(redistributePolygonInputs["output_filename"], ['OBJECTID', 'Dwelling_1']) as cursor:
for row in cursor:
if row[0] == 1 and row[1] == 9:
log(" Pass")
elif row[0] == 2 and row[1] == 3:
log(" Pass")
else:
log(" Fail: For Dwelling_1 should be 9 or 3, but was %s (for OBJECTID = %s)" % (row[1], row[0]))
log(" Testing that the sum of dwelling in the input and output layers are equal:")
#
redistributed_count = 0
with arcpy.da.SearchCursor(redistributePolygonInputs["output_filename"], "Dwelling_1") as cursor:
for row in cursor:
redistributed_count += row[0]
#
layer_to_be_redistributed_count = 0
with arcpy.da.SearchCursor(redistributePolygonInputs["layer_to_be_redistributed"], "Dwelling_1") as cursor:
for row in cursor:
layer_to_be_redistributed_count += row[0]
if layer_to_be_redistributed_count == redistributed_count:
log(" Pass")
else:
log(" Fail: sum of dewllings is not equal for layer_to_be_redistributed (%s) and output (%s)" % (layer_to_be_redistributed_count, redistributed_count))
log(" layer_to_be_redistributed = %s" % redistributePolygonInputs["layer_to_be_redistributed"])
log(" output_filename = %s" % redistributePolygonInputs["output_filename"])
def testing_custom_properties_layer():
log(" Testing number of properties method with custom properties layer:")
redistributePolygonInputs["fields_to_be_distributed"] = ["Dwelling_1"]
redistributePolygonInputs["distribution_method"] = 2
custom_properties_layer = jj.create_polygon(
"testing_custom_properties",
[
(left_x+10, lower_y+10),
(left_x+10, upper_y-10),
(left_x+20, upper_y-10),
(left_x+20, lower_y+10),
(left_x+10, lower_y+10)
], [
(left_x+20, lower_y+10),
(left_x+20, upper_y-10),
(left_x+30, upper_y-10),
(left_x+30, lower_y+10),
(left_x+20, lower_y+10)
], [
(mid_x+20, lower_y+10),
(mid_x+20, upper_y-10),
(mid_x+30, upper_y-10),
(mid_x+30, lower_y+10),
(mid_x+20, lower_y+10)
])
redistributePolygonInputs["properties_layer"] = custom_properties_layer
jj.redistributePolygon(redistributePolygonInputs)
with arcpy.da.SearchCursor(redistributePolygonInputs["output_filename"], ['OBJECTID', 'Dwelling_1']) as cursor:
for row in cursor:
if row[0] == 1 and row[1] == 8:
log(" Pass")
elif row[0] == 2 and row[1] == 4:
log(" Pass")
else:
log(" Fail: For Dwelling_1 should be 8 or 4, but was %s (for OBJECTID = %s)" % (row[1], row[0]))
def testing_area_method():
log(" Testing area method:")
log(" Testing 40% of area yeilds 40% of population:")
redistributePolygonInputs["distribution_method"] = 1
jj.redistributePolygon(redistributePolygonInputs)
with arcpy.da.SearchCursor(redistributePolygonInputs["output_filename"], ['OBJECTID', 'Dwelling_1']) as cursor:
for row in cursor:
if row[0] == 1 and row[1] == 4:
log(" Pass")
elif row[0] == 2 and row[1] == 8:
log(" Pass")
else:
log(" Fail: Dwelling_1 should be 4, but was %s" % row[0])
def testing_generic_distribution_method():
def generic_distribution():
log(" Testing even distribution for generic distribution method (distribution method provided by another feature class):")
net_developable_area = jj.create_polygon(
"net_developable_area",
[(mid_x-10, lower_y),
(mid_x-10, upper_y),
(mid_x+10, upper_y),
(mid_x+10, lower_y),
(mid_x-10, lower_y)])
redistributePolygonInputs["distribution_method"] = net_developable_area
jj.redistributePolygon(redistributePolygonInputs)
with arcpy.da.SearchCursor(
redistributePolygonInputs["output_filename"],
['Dwelling_1']
) as cursor:
for row in cursor:
if row[0] == 6:
log(" Pass")
else:
log(" Fail: Dwelling_1 should be 6 in each area, but was %s" % row[0])
def unever_distribution():
log(" Testing uneven distribution method:")
net_developable_area = jj.create_polygon(
"net_developable_area",
[(mid_x-5, lower_y),
(mid_x-5, upper_y),
(mid_x+15, upper_y),
(mid_x+15, lower_y),
(mid_x-5, lower_y)])
redistributePolygonInputs["distribution_method"] = net_developable_area
jj.redistributePolygon(redistributePolygonInputs)
with arcpy.da.SearchCursor(
redistributePolygonInputs["output_filename"],
['Dwelling_1']
) as cursor:
for row in cursor:
if row[0] in (3, 9):
log(" Pass")
else:
log(" Fail: Dwelling_1 should be 3 and 9, in each area, but was %s" % row[0])
def all_to_one():
log(" Testing all distribution to one polygon:")
net_developable_area = jj.create_polygon(
"net_developable_area",
[(mid_x+5, lower_y),
(mid_x+5, upper_y),
(mid_x+15, upper_y),
(mid_x+15, lower_y),
(mid_x+5, lower_y)])
redistributePolygonInputs["distribution_method"] = net_developable_area
jj.redistributePolygon(redistributePolygonInputs)
with arcpy.da.SearchCursor(
redistributePolygonInputs["output_filename"],
['Dwelling_1']
) as cursor:
for row in cursor:
if row[0] in (12, 0):
log(" Pass")
else:
log(" Fail: Dwelling_1 should be 12 and 0, in each area, but was %s" % row[0])
def no_exteral_but_with_properties():
log(" Testing areas with no external areas, but with properties:")
# This tests the case where data is to be distributed based on the area
# of some feature class, but that feature class doesn't cover every
# polygon. The case that this test was designed for was when growth was
# to be distributed by Net Developable Area. In the case where growth
# exists, but there is no net developable area, it should be assumed
# that the growth will occur due to increased density. In this case
# distribution should be performed by number of properties.
# In the future, the distribution method should be provided as a list
# of priorities. For example, you might want to first distribute by Net
# Developable Area (by area), then by properties (by centroid), then by
# area.
sample_properties = jj.create_polygon(
"one_property_in_each",
[
(mid_x-20, lower_y+10),
(mid_x-20, upper_y-10),
(mid_x-10, upper_y-10),
(mid_x-10, lower_y+10),
(mid_x-20, lower_y+10)
], [
(mid_x+10, lower_y+10),