-
-
Notifications
You must be signed in to change notification settings - Fork 260
/
test_shapefile.py
1842 lines (1607 loc) · 56.3 KB
/
test_shapefile.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
"""
This module tests the functionality of shapefile.py.
"""
import datetime
import json
import os.path
try:
from pathlib import Path
except ImportError:
# pathlib2 is a dependency of pytest >= 3.7
from pathlib2 import Path
# third party imports
import pytest
# our imports
import shapefile
# define various test shape tuples of (type, points, parts indexes, and expected geo interface output)
geo_interface_tests = [
(
shapefile.POINT, # point
[(1, 1)],
[],
{"type": "Point", "coordinates": (1, 1)},
),
(
shapefile.MULTIPOINT, # multipoint
[(1, 1), (2, 1), (2, 2)],
[],
{"type": "MultiPoint", "coordinates": [(1, 1), (2, 1), (2, 2)]},
),
(
shapefile.POLYLINE, # single linestring
[(1, 1), (2, 1)],
[0],
{"type": "LineString", "coordinates": [(1, 1), (2, 1)]},
),
(
shapefile.POLYLINE, # multi linestring
[
(1, 1),
(2, 1), # line 1
(10, 10),
(20, 10),
], # line 2
[0, 2],
{
"type": "MultiLineString",
"coordinates": [
[(1, 1), (2, 1)], # line 1
[(10, 10), (20, 10)], # line 2
],
},
),
(
shapefile.POLYGON, # single polygon, no holes
[
(1, 1),
(1, 9),
(9, 9),
(9, 1),
(1, 1), # exterior
],
[0],
{
"type": "Polygon",
"coordinates": [
[(1, 1), (1, 9), (9, 9), (9, 1), (1, 1)],
],
},
),
(
shapefile.POLYGON, # single polygon, holes (ordered)
[
(1, 1),
(1, 9),
(9, 9),
(9, 1),
(1, 1), # exterior
(2, 2),
(4, 2),
(4, 4),
(2, 4),
(2, 2), # hole 1
(5, 5),
(7, 5),
(7, 7),
(5, 7),
(5, 5), # hole 2
],
[0, 5, 5 + 5],
{
"type": "Polygon",
"coordinates": [
[(1, 1), (1, 9), (9, 9), (9, 1), (1, 1)], # exterior
[(2, 2), (4, 2), (4, 4), (2, 4), (2, 2)], # hole 1
[(5, 5), (7, 5), (7, 7), (5, 7), (5, 5)], # hole 2
],
},
),
(
shapefile.POLYGON, # single polygon, holes (unordered)
[
(2, 2),
(4, 2),
(4, 4),
(2, 4),
(2, 2), # hole 1
(1, 1),
(1, 9),
(9, 9),
(9, 1),
(1, 1), # exterior
(5, 5),
(7, 5),
(7, 7),
(5, 7),
(5, 5), # hole 2
],
[0, 5, 5 + 5],
{
"type": "Polygon",
"coordinates": [
[(1, 1), (1, 9), (9, 9), (9, 1), (1, 1)], # exterior
[(2, 2), (4, 2), (4, 4), (2, 4), (2, 2)], # hole 1
[(5, 5), (7, 5), (7, 7), (5, 7), (5, 5)], # hole 2
],
},
),
(
shapefile.POLYGON, # multi polygon, no holes
[
(1, 1),
(1, 9),
(9, 9),
(9, 1),
(1, 1), # exterior
(11, 11),
(11, 19),
(19, 19),
(19, 11),
(11, 11), # exterior
],
[0, 5],
{
"type": "MultiPolygon",
"coordinates": [
[ # poly 1
[(1, 1), (1, 9), (9, 9), (9, 1), (1, 1)],
],
[ # poly 2
[(11, 11), (11, 19), (19, 19), (19, 11), (11, 11)],
],
],
},
),
(
shapefile.POLYGON, # multi polygon, holes (unordered)
[
(1, 1),
(1, 9),
(9, 9),
(9, 1),
(1, 1), # exterior 1
(11, 11),
(11, 19),
(19, 19),
(19, 11),
(11, 11), # exterior 2
(12, 12),
(14, 12),
(14, 14),
(12, 14),
(12, 12), # hole 2.1
(15, 15),
(17, 15),
(17, 17),
(15, 17),
(15, 15), # hole 2.2
(2, 2),
(4, 2),
(4, 4),
(2, 4),
(2, 2), # hole 1.1
(5, 5),
(7, 5),
(7, 7),
(5, 7),
(5, 5), # hole 1.2
],
[0, 5, 10, 15, 20, 25],
{
"type": "MultiPolygon",
"coordinates": [
[ # poly 1
[(1, 1), (1, 9), (9, 9), (9, 1), (1, 1)], # exterior
[(2, 2), (4, 2), (4, 4), (2, 4), (2, 2)], # hole 1
[(5, 5), (7, 5), (7, 7), (5, 7), (5, 5)], # hole 2
],
[ # poly 2
[(11, 11), (11, 19), (19, 19), (19, 11), (11, 11)], # exterior
[(12, 12), (14, 12), (14, 14), (12, 14), (12, 12)], # hole 1
[(15, 15), (17, 15), (17, 17), (15, 17), (15, 15)], # hole 2
],
],
},
),
(
shapefile.POLYGON, # multi polygon, nested exteriors with holes (unordered)
[
(1, 1),
(1, 9),
(9, 9),
(9, 1),
(1, 1), # exterior 1
(3, 3),
(3, 7),
(7, 7),
(7, 3),
(3, 3), # exterior 2
(4.5, 4.5),
(4.5, 5.5),
(5.5, 5.5),
(5.5, 4.5),
(4.5, 4.5), # exterior 3
(4, 4),
(6, 4),
(6, 6),
(4, 6),
(4, 4), # hole 2.1
(2, 2),
(8, 2),
(8, 8),
(2, 8),
(2, 2), # hole 1.1
],
[0, 5, 10, 15, 20],
{
"type": "MultiPolygon",
"coordinates": [
[ # poly 1
[(1, 1), (1, 9), (9, 9), (9, 1), (1, 1)], # exterior 1
[(2, 2), (8, 2), (8, 8), (2, 8), (2, 2)], # hole 1.1
],
[ # poly 2
[(3, 3), (3, 7), (7, 7), (7, 3), (3, 3)], # exterior 2
[(4, 4), (6, 4), (6, 6), (4, 6), (4, 4)], # hole 2.1
],
[ # poly 3
[
(4.5, 4.5),
(4.5, 5.5),
(5.5, 5.5),
(5.5, 4.5),
(4.5, 4.5),
], # exterior 3
],
],
},
),
(
shapefile.POLYGON, # multi polygon, nested exteriors with holes (unordered and tricky holes designed to throw off ring_sample() test)
[
(1, 1),
(1, 9),
(9, 9),
(9, 1),
(1, 1), # exterior 1
(3, 3),
(3, 7),
(7, 7),
(7, 3),
(3, 3), # exterior 2
(4.5, 4.5),
(4.5, 5.5),
(5.5, 5.5),
(5.5, 4.5),
(4.5, 4.5), # exterior 3
(4, 4),
(4, 4),
(6, 4),
(6, 4),
(6, 4),
(6, 6),
(4, 6),
(4, 4), # hole 2.1 (hole has duplicate coords)
(2, 2),
(3, 3),
(4, 2),
(8, 2),
(8, 8),
(4, 8),
(2, 8),
(2, 4),
(
2,
2,
), # hole 1.1 (hole coords form straight line and starts in concave orientation)
],
[0, 5, 10, 15, 20 + 3],
{
"type": "MultiPolygon",
"coordinates": [
[ # poly 1
[(1, 1), (1, 9), (9, 9), (9, 1), (1, 1)], # exterior 1
[
(2, 2),
(3, 3),
(4, 2),
(8, 2),
(8, 8),
(4, 8),
(2, 8),
(2, 4),
(2, 2),
], # hole 1.1
],
[ # poly 2
[(3, 3), (3, 7), (7, 7), (7, 3), (3, 3)], # exterior 2
[
(4, 4),
(4, 4),
(6, 4),
(6, 4),
(6, 4),
(6, 6),
(4, 6),
(4, 4),
], # hole 2.1
],
[ # poly 3
[
(4.5, 4.5),
(4.5, 5.5),
(5.5, 5.5),
(5.5, 4.5),
(4.5, 4.5),
], # exterior 3
],
],
},
),
(
shapefile.POLYGON, # multi polygon, holes incl orphaned holes (unordered), should raise warning
[
(1, 1),
(1, 9),
(9, 9),
(9, 1),
(1, 1), # exterior 1
(11, 11),
(11, 19),
(19, 19),
(19, 11),
(11, 11), # exterior 2
(12, 12),
(14, 12),
(14, 14),
(12, 14),
(12, 12), # hole 2.1
(15, 15),
(17, 15),
(17, 17),
(15, 17),
(15, 15), # hole 2.2
(95, 95),
(97, 95),
(97, 97),
(95, 97),
(95, 95), # hole x.1 (orphaned hole, should be interpreted as exterior)
(2, 2),
(4, 2),
(4, 4),
(2, 4),
(2, 2), # hole 1.1
(5, 5),
(7, 5),
(7, 7),
(5, 7),
(5, 5), # hole 1.2
],
[0, 5, 10, 15, 20, 25, 30],
{
"type": "MultiPolygon",
"coordinates": [
[ # poly 1
[(1, 1), (1, 9), (9, 9), (9, 1), (1, 1)], # exterior
[(2, 2), (4, 2), (4, 4), (2, 4), (2, 2)], # hole 1
[(5, 5), (7, 5), (7, 7), (5, 7), (5, 5)], # hole 2
],
[ # poly 2
[(11, 11), (11, 19), (19, 19), (19, 11), (11, 11)], # exterior
[(12, 12), (14, 12), (14, 14), (12, 14), (12, 12)], # hole 1
[(15, 15), (17, 15), (17, 17), (15, 17), (15, 15)], # hole 2
],
[ # poly 3 (orphaned hole)
[(95, 95), (97, 95), (97, 97), (95, 97), (95, 95)], # exterior
],
],
},
),
(
shapefile.POLYGON, # multi polygon, exteriors with wrong orientation (be nice and interpret as such), should raise warning
[
(1, 1),
(9, 1),
(9, 9),
(1, 9),
(1, 1), # exterior with hole-orientation
(11, 11),
(19, 11),
(19, 19),
(11, 19),
(11, 11), # exterior with hole-orientation
],
[0, 5],
{
"type": "MultiPolygon",
"coordinates": [
[ # poly 1
[(1, 1), (9, 1), (9, 9), (1, 9), (1, 1)],
],
[ # poly 2
[(11, 11), (19, 11), (19, 19), (11, 19), (11, 11)],
],
],
},
),
]
def test_empty_shape_geo_interface():
"""
Assert that calling __geo_interface__
on a Shape with no points or parts
raises an Exception.
"""
shape = shapefile.Shape()
with pytest.raises(Exception):
getattr(shape, "__geo_interface__")
@pytest.mark.parametrize("typ,points,parts,expected", geo_interface_tests)
def test_expected_shape_geo_interface(typ, points, parts, expected):
"""
Assert that calling __geo_interface__
on arbitrary input Shape works as expected.
"""
shape = shapefile.Shape(typ, points, parts)
geoj = shape.__geo_interface__
assert geoj == expected
def test_reader_geo_interface():
with shapefile.Reader("shapefiles/blockgroups") as r:
geoj = r.__geo_interface__
assert geoj["type"] == "FeatureCollection"
assert "bbox" in geoj
assert json.dumps(geoj)
def test_shapes_geo_interface():
with shapefile.Reader("shapefiles/blockgroups") as r:
geoj = r.shapes().__geo_interface__
assert geoj["type"] == "GeometryCollection"
assert json.dumps(geoj)
def test_shaperecords_geo_interface():
with shapefile.Reader("shapefiles/blockgroups") as r:
geoj = r.shapeRecords().__geo_interface__
assert geoj["type"] == "FeatureCollection"
assert json.dumps(geoj)
def test_shaperecord_geo_interface():
with shapefile.Reader("shapefiles/blockgroups") as r:
for shaperec in r:
assert json.dumps(shaperec.__geo_interface__)
@pytest.mark.network
def test_reader_url():
"""
Assert that Reader can open shapefiles from a url.
"""
# test with extension
url = "https://github.com/nvkelso/natural-earth-vector/blob/master/110m_cultural/ne_110m_admin_0_tiny_countries.shp?raw=true"
with shapefile.Reader(url) as sf:
for __recShape in sf.iterShapeRecords():
pass
assert sf.shp.closed is sf.shx.closed is sf.dbf.closed is True
# test without extension
url = "https://github.com/nvkelso/natural-earth-vector/blob/master/110m_cultural/ne_110m_admin_0_tiny_countries?raw=true"
with shapefile.Reader(url) as sf:
for __recShape in sf.iterShapeRecords():
pass
assert len(sf) > 0
assert sf.shp.closed is sf.shx.closed is sf.dbf.closed is True
# test no files found
url = "https://raw.githubusercontent.com/nvkelso/natural-earth-vector/master/README.md"
with pytest.raises(shapefile.ShapefileException):
with shapefile.Reader(url) as sf:
pass
# test reading zipfile from url
url = "https://github.com/JamesParrott/PyShp_test_shapefile/raw/main/gis_osm_natural_a_free_1.zip"
with shapefile.Reader(url) as sf:
for __recShape in sf.iterShapeRecords():
pass
assert len(sf) > 0
assert sf.shp.closed is sf.shx.closed is sf.dbf.closed is True
def test_reader_zip():
"""
Assert that Reader can open shapefiles inside a zipfile.
"""
# test reading zipfile only
with shapefile.Reader("shapefiles/blockgroups.zip") as sf:
for __recShape in sf.iterShapeRecords():
pass
assert len(sf) > 0
assert sf.shp.closed is sf.shx.closed is sf.dbf.closed is True
# test require specific path when reading multi-shapefile zipfile
with pytest.raises(shapefile.ShapefileException):
with shapefile.Reader("shapefiles/blockgroups_multishapefile.zip") as sf:
pass
# test specifying the path when reading multi-shapefile zipfile (with extension)
with shapefile.Reader(
"shapefiles/blockgroups_multishapefile.zip/blockgroups2.shp"
) as sf:
for __recShape in sf.iterShapeRecords():
pass
assert len(sf) > 0
assert sf.shp.closed is sf.shx.closed is sf.dbf.closed is True
# test specifying the path when reading multi-shapefile zipfile (without extension)
with shapefile.Reader(
"shapefiles/blockgroups_multishapefile.zip/blockgroups2"
) as sf:
for __recShape in sf.iterShapeRecords():
pass
assert len(sf) > 0
assert sf.shp.closed is sf.shx.closed is sf.dbf.closed is True
# test raising error when can't find shapefile inside zipfile
with pytest.raises(shapefile.ShapefileException):
with shapefile.Reader("shapefiles/empty_zipfile.zip") as sf:
pass
def test_reader_close_path():
"""
Assert that manually calling Reader.close()
closes the shp, shx, and dbf files
on exit, if given paths.
"""
# note uses an actual shapefile from
# the projects "shapefiles" directory
sf = shapefile.Reader("shapefiles/blockgroups.shp")
sf.close()
assert sf.shp.closed is True
assert sf.dbf.closed is True
assert sf.shx.closed is True
# check that can read again
sf = shapefile.Reader("shapefiles/blockgroups.shp")
sf.close()
def test_reader_close_filelike():
"""
Assert that manually calling Reader.close()
leaves the shp, shx, and dbf files open
on exit, if given filelike objects.
"""
# note uses an actual shapefile from
# the projects "shapefiles" directory
shp = open("shapefiles/blockgroups.shp", mode="rb")
shx = open("shapefiles/blockgroups.shx", mode="rb")
dbf = open("shapefiles/blockgroups.dbf", mode="rb")
sf = shapefile.Reader(shp=shp, shx=shx, dbf=dbf)
sf.close()
assert sf.shp.closed is False
assert sf.dbf.closed is False
assert sf.shx.closed is False
# check that can read again
sf = shapefile.Reader(shp=shp, shx=shx, dbf=dbf)
sf.close()
def test_reader_context_path():
"""
Assert that using the context manager
closes the shp, shx, and dbf files
on exit, if given paths.
"""
# note uses an actual shapefile from
# the projects "shapefiles" directory
with shapefile.Reader("shapefiles/blockgroups") as sf:
pass
assert sf.shp.closed is True
assert sf.dbf.closed is True
assert sf.shx.closed is True
# check that can read again
with shapefile.Reader("shapefiles/blockgroups") as sf:
pass
def test_reader_context_filelike():
"""
Assert that using the context manager
leaves the shp, shx, and dbf files open
on exit, if given filelike objects.
"""
# note uses an actual shapefile from
# the projects "shapefiles" directory
shp = open("shapefiles/blockgroups.shp", mode="rb")
shx = open("shapefiles/blockgroups.shx", mode="rb")
dbf = open("shapefiles/blockgroups.dbf", mode="rb")
with shapefile.Reader(shp=shp, shx=shx, dbf=dbf) as sf:
pass
assert sf.shp.closed is False
assert sf.dbf.closed is False
assert sf.shx.closed is False
# check that can read again
with shapefile.Reader(shp=shp, shx=shx, dbf=dbf) as sf:
pass
def test_reader_shapefile_type():
"""
Assert that the type of the shapefile
is returned correctly.
"""
with shapefile.Reader("shapefiles/blockgroups") as sf:
assert sf.shapeType == 5 # 5 means Polygon
assert sf.shapeType == shapefile.POLYGON
assert sf.shapeTypeName == "POLYGON"
def test_reader_shapefile_length():
"""
Assert that the length the reader gives us
matches up with the number of records
in the file.
"""
with shapefile.Reader("shapefiles/blockgroups") as sf:
assert len(sf) == len(sf.shapes())
def test_shape_metadata():
with shapefile.Reader("shapefiles/blockgroups") as sf:
shape = sf.shape(0)
assert shape.shapeType == 5 # Polygon
assert shape.shapeType == shapefile.POLYGON
assert sf.shapeTypeName == "POLYGON"
def test_reader_fields():
"""
Assert that the reader's fields attribute
gives the shapefile's fields as a list.
Assert that each field has a name,
type, field length, and decimal length.
"""
with shapefile.Reader("shapefiles/blockgroups") as sf:
fields = sf.fields
assert isinstance(fields, list)
field = fields[0]
assert isinstance(field[0], str) # field name
assert field[1] in ["C", "N", "F", "L", "D", "M"] # field type
assert isinstance(field[2], int) # field length
assert isinstance(field[3], int) # decimal length
def test_reader_shapefile_extension_ignored():
"""
Assert that the filename's extension is
ignored when reading a shapefile.
"""
base = "shapefiles/blockgroups"
ext = ".abc"
filename = base + ext
with shapefile.Reader(filename) as sf:
assert len(sf) == 663
# assert test.abc does not exist
assert not os.path.exists(filename)
def test_reader_pathlike():
"""
Assert that path-like objects can be read.
"""
base = Path("shapefiles")
with shapefile.Reader(base / "blockgroups") as sf:
assert len(sf) == 663
def test_reader_dbf_only():
"""
Assert that specifying just the
dbf argument to the shapefile reader
reads just the dbf file.
"""
with shapefile.Reader(dbf="shapefiles/blockgroups.dbf") as sf:
assert len(sf) == 663
record = sf.record(3)
assert record[1:3] == ["060750601001", 4715]
def test_reader_shp_shx_only():
"""
Assert that specifying just the
shp and shx argument to the shapefile reader
reads just the shp and shx file.
"""
with shapefile.Reader(
shp="shapefiles/blockgroups.shp", shx="shapefiles/blockgroups.shx"
) as sf:
assert len(sf) == 663
shape = sf.shape(3)
assert len(shape.points) == 173
def test_reader_shp_dbf_only():
"""
Assert that specifying just the
shp and shx argument to the shapefile reader
reads just the shp and dbf file.
"""
with shapefile.Reader(
shp="shapefiles/blockgroups.shp", dbf="shapefiles/blockgroups.dbf"
) as sf:
assert len(sf) == 663
shape = sf.shape(3)
assert len(shape.points) == 173
record = sf.record(3)
assert record[1:3] == ["060750601001", 4715]
def test_reader_shp_only():
"""
Assert that specifying just the
shp argument to the shapefile reader
reads just the shp file (shx optional).
"""
with shapefile.Reader(shp="shapefiles/blockgroups.shp") as sf:
assert len(sf) == 663
shape = sf.shape(3)
assert len(shape.points) == 173
def test_reader_filelike_dbf_only():
"""
Assert that specifying just the
dbf argument to the shapefile reader
reads just the dbf file.
"""
with shapefile.Reader(dbf=open("shapefiles/blockgroups.dbf", "rb")) as sf:
assert len(sf) == 663
record = sf.record(3)
assert record[1:3] == ["060750601001", 4715]
def test_reader_filelike_shp_shx_only():
"""
Assert that specifying just the
shp and shx argument to the shapefile reader
reads just the shp and shx file.
"""
with shapefile.Reader(
shp=open("shapefiles/blockgroups.shp", "rb"),
shx=open("shapefiles/blockgroups.shx", "rb"),
) as sf:
assert len(sf) == 663
shape = sf.shape(3)
assert len(shape.points) == 173
def test_reader_filelike_shp_dbf_only():
"""
Assert that specifying just the
shp and shx argument to the shapefile reader
reads just the shp and dbf file.
"""
with shapefile.Reader(
shp=open("shapefiles/blockgroups.shp", "rb"),
dbf=open("shapefiles/blockgroups.dbf", "rb"),
) as sf:
assert len(sf) == 663
shape = sf.shape(3)
assert len(shape.points) == 173
record = sf.record(3)
assert record[1:3] == ["060750601001", 4715]
def test_reader_filelike_shp_only():
"""
Assert that specifying just the
shp argument to the shapefile reader
reads just the shp file (shx optional).
"""
with shapefile.Reader(shp=open("shapefiles/blockgroups.shp", "rb")) as sf:
assert len(sf) == 663
shape = sf.shape(3)
assert len(shape.points) == 173
def test_reader_shapefile_delayed_load():
"""
Assert that the filename's extension is
ignored when reading a shapefile.
"""
with shapefile.Reader() as sf:
# assert that data request raises exception, since no file has been provided yet
with pytest.raises(shapefile.ShapefileException):
sf.shape(0)
# assert that works after loading file manually
sf.load("shapefiles/blockgroups")
assert len(sf) == 663
def test_records_match_shapes():
"""
Assert that the number of records matches
the number of shapes in the shapefile.
"""
with shapefile.Reader("shapefiles/blockgroups") as sf:
records = sf.records()
shapes = sf.shapes()
assert len(records) == len(shapes)
def test_record_attributes(fields=None):
"""
Assert that record retrieves all relevant values and can
be accessed as attributes and dictionary items.
"""
# note
# second element in fields matches first element
# in record because records dont have DeletionFlag
with shapefile.Reader("shapefiles/blockgroups") as sf:
for i in range(len(sf)):
# full record
full_record = sf.record(i)
# user-fetched record
if fields is not None:
# only a subset of fields
record = sf.record(i, fields=fields)
else:
# default all fields
record = full_record
fields = [
field[0] for field in sf.fields[1:]
] # fieldnames, sans del flag
# check correct length
assert len(record) == len(set(fields))
# check record values (should be in same order as shapefile fields)
i = 0
for field in sf.fields:
field_name = field[0]
if field_name in fields:
assert (
record[i] == record[field_name] == getattr(record, field_name)
)
i += 1
def test_record_subfields():
"""
Assert that reader correctly retrieves only a subset
of fields when specified.
"""
fields = ["AREA", "POP1990", "MALES", "FEMALES", "MOBILEHOME"]
test_record_attributes(fields=fields)
def test_record_subfields_unordered():
"""
Assert that reader correctly retrieves only a subset
of fields when specified, given in random order but
retrieved in the order of the shapefile fields.
"""
fields = sorted(["AREA", "POP1990", "MALES", "FEMALES", "MOBILEHOME"])
test_record_attributes(fields=fields)
def test_record_subfields_delflag_notvalid():
"""
Assert that reader does not consider DeletionFlag as a valid field name.
"""
fields = ["DeletionFlag", "AREA", "POP1990", "MALES", "FEMALES", "MOBILEHOME"]
with pytest.raises(ValueError):
test_record_attributes(fields=fields)
def test_record_subfields_duplicates():
"""
Assert that reader correctly retrieves only a subset
of fields when specified, handling duplicate input fields.
"""
fields = ["AREA", "AREA", "AREA", "MALES", "MALES", "MOBILEHOME"]
test_record_attributes(fields=fields)
# check that only 3 values
with shapefile.Reader("shapefiles/blockgroups") as sf:
rec = sf.record(0, fields=fields)
assert len(rec) == len(set(fields))
def test_record_subfields_empty():
"""
Assert that reader does not retrieve any fields when given
an empty list.
"""
fields = []
test_record_attributes(fields=fields)
# check that only 0 values
with shapefile.Reader("shapefiles/blockgroups") as sf:
rec = sf.record(0, fields=fields)
assert len(rec) == 0
def test_record_as_dict():
"""
Assert that a record object can be converted
into a dictionary and data remains correct.
"""
with shapefile.Reader("shapefiles/blockgroups") as sf:
record = sf.record(0)
as_dict = record.as_dict()
assert len(record) == len(as_dict)
for key, value in as_dict.items():
assert record[key] == value
def test_record_oid():
"""
Assert that the record's oid attribute returns
its index in the shapefile.
"""
with shapefile.Reader("shapefiles/blockgroups") as sf:
for i in range(len(sf)):
record = sf.record(i)
assert record.oid == i
for i, record in enumerate(sf.records()):
assert record.oid == i
for i, record in enumerate(sf.iterRecords()):
assert record.oid == i
for i, shaperec in enumerate(sf.iterShapeRecords()):
assert shaperec.record.oid == i
def test_iterRecords_start_stop():
"""
Assert that Reader.iterRecords(start, stop)
returns the correct records, as if searched for
by index with Reader.record
"""
with shapefile.Reader("shapefiles/blockgroups") as sf:
N = len(sf)
# Arbitrary selection of record indices
# (there are 663 records in blockgroups.dbf).
for i in [
0,
1,
2,
3,
5,
11,
17,
33,
51,
103,
170,
234,
435,