|
| 1 | +import os |
| 2 | +import tempfile |
| 3 | +import unittest |
| 4 | + |
| 5 | +import fiona |
| 6 | +from shapely.geometry import Polygon, mapping |
| 7 | + |
| 8 | +from opendm.cutline import largest_polygon |
| 9 | + |
| 10 | + |
| 11 | +class TestCutline(unittest.TestCase): |
| 12 | + def test_largest_polygon_from_single_polygon(self): |
| 13 | + """ Tests that the largest polygon from a single polygon is the polygon itself """ |
| 14 | + |
| 15 | + p = Polygon([(0, 0), (1, 0), (1, 1), (0, 1)]) # 1x1 square |
| 16 | + largest = largest_polygon([p]) |
| 17 | + |
| 18 | + self.assertEqual(largest.geom_type, "Polygon") |
| 19 | + self.assertAlmostEqual(largest.area, 1.0) |
| 20 | + |
| 21 | + def test_largest_polygon_from_multipolygon_union(self): |
| 22 | + """ Tests that the largest polygon from a multipolygon union is the largest polygon """ |
| 23 | + |
| 24 | + small = Polygon([(0, 0), (1, 0), (1, 1), (0, 1)]) # 1x1 square (area = 1) |
| 25 | + large = Polygon([(0, 0), (3, 0), (3, 2), (0, 2)]) # 3x2 rectangle (area = 6) |
| 26 | + largest = largest_polygon([small, large]) |
| 27 | + self.assertEqual(largest.geom_type, "Polygon") |
| 28 | + self.assertAlmostEqual(largest.area, 6.0) # matches large polygon |
| 29 | + |
| 30 | + def test_polygon_writes_to_gpkg_with_polygon_schema(self): |
| 31 | + """ Tests that fiona can write our polygon to a GPKG file""" |
| 32 | + |
| 33 | + geom = largest_polygon([ |
| 34 | + Polygon([(0, 0), (1, 0), (1, 1), (0, 1)]), |
| 35 | + Polygon([(2, 0), (5, 0), (5, 2), (2, 2)]), |
| 36 | + ]) |
| 37 | + self.assertEqual(mapping(geom)["type"], "Polygon") |
| 38 | + |
| 39 | + # Write out the polygon to quickly verify that Fiona can still process |
| 40 | + # our largest polygon. |
| 41 | + with tempfile.TemporaryDirectory() as tmp: |
| 42 | + path = os.path.join(tmp, "cutline.gpkg") |
| 43 | + with fiona.open( |
| 44 | + path, |
| 45 | + "w", |
| 46 | + driver="GPKG", |
| 47 | + crs="EPSG:4326", |
| 48 | + schema={"geometry": "Polygon", "properties": {}}, |
| 49 | + ) as sink: |
| 50 | + sink.write({"geometry": mapping(geom), "properties": {}}) |
| 51 | + |
| 52 | + with fiona.open(path) as src: |
| 53 | + feature = next(iter(src)) |
| 54 | + self.assertEqual(feature["geometry"]["type"], "Polygon") |
| 55 | + |
| 56 | + |
| 57 | +if __name__ == "__main__": |
| 58 | + unittest.main() |
0 commit comments