Skip to content

Commit

Permalink
urban helper tests
Browse files Browse the repository at this point in the history
  • Loading branch information
elbeejay committed Apr 13, 2024
1 parent 6c88d11 commit 328f884
Show file tree
Hide file tree
Showing 2 changed files with 82 additions and 4 deletions.
9 changes: 5 additions & 4 deletions src/GOSTurban/urban_helper.py
Original file line number Diff line number Diff line change
Expand Up @@ -27,8 +27,8 @@ def __init__(
----------
pop_layer : string
Path to population layer
admin_layer : string
Path to admin layer
admin_layer : gpd.GeoDataFrame
geopandas dataframe of admin layer
urban_layer : string, optional
Path to urban layer. The default is ''.
hd_urban_layer : string, optional
Expand Down Expand Up @@ -177,12 +177,12 @@ def __init__(
NAMING CONVENTION
To save this renaming step on my side, which can also induce mistakes, would be possible for you Ben to rename the files in your code directly? This would be also helpful for all other countries we have to do, and for the 1km*1km rasters.
My conventions are pretty simple. All rasters starts with the three lettres of the country and then _ as you do, and then 3 lettres for the variable, and possibly two figures for the year. So for instance for Tanzania, this is:
My conventions are pretty simple. All rasters starts with the three letters of the country and then _ as you do, and then 3 letters for the variable, and possibly two figures for the year. So for instance for Tanzania, this is:
tza_ele tza_slo tza_wat for elevation, slope and water
tza_gpo tza_gbu for GHS population and built-up
tza_upo15 and tza_upo18 for WorldPop population unconstrained
tza_cpo15 and tza_cpo18 for WorldPop population constrained.
Then for 1km*1km raster, names are the same except that the three lettres of the country's name are followed by 1k, ie tza1k_slo, tza1k_ele and so on.
Then for 1km*1km raster, names are the same except that the three letters of the country's name are followed by 1k, ie tza1k_slo, tza1k_ele and so on.
"""
self.iso3 = iso3
Expand Down Expand Up @@ -480,6 +480,7 @@ def pop_zonal_admin(self, admin_layer):
else:
print("Error summarizing population for %s" % pop_file)
admin_layer = admin_layer.reset_index()
# final can be called here without having been defined
final = final.filter(regex="_SUM")
final = final.join(admin_layer)
final = final.drop(["geometry"], axis=1)
Expand Down
77 changes: 77 additions & 0 deletions tests/test_urban_helper.py
Original file line number Diff line number Diff line change
@@ -1,11 +1,81 @@
"""Unit tests for the urban_helper.py module"""
import pytest # noqa: F401
from GOSTurban import urban_helper
import numpy as np
from unittest import mock
import geopandas as gpd
import pandas as pd
from shapely.geometry import Polygon
from unittest.mock import MagicMock


class TestSummarizePopulation:
"""Tests for the summarize_population class."""

def mocked_rasterio_open(self, t="w"):
"""Mocked function for rasterio.open()"""

class tmpOutput:
def __init__(self):
self.crs = "EPSG:4326"
self.meta = MagicMock()

def read(self):
raster = np.zeros((10, 10))
raster[:5, :5] = 4
raster[5:, 5:] = 3
return raster

return_val = tmpOutput()
return return_val

def mocked_zonal_stats(self, inr, minVal=0):
"""Mocking the gostrocks zonalstats function."""
return np.ones((1, 4))

@mock.patch("rasterio.open", mocked_rasterio_open)
@mock.patch("GOSTrocks.rasterMisc.zonalStats", mocked_zonal_stats)
def test_01(self, tmp_path):
# make the admin layer gpd
df = pd.DataFrame(
{
"idx": ["a", "b", "c"],
"geometry": [
Polygon([(0, 0), (1, 0), (1, 1)]),
Polygon([(0, 0), (1, 0), (1, 1)]),
Polygon([(0, 0), (1, 0), (1, 1)]),
],
}
)
admin_layer = gpd.GeoDataFrame(df, geometry=df.geometry, crs="EPSG:3857")
# try to initialize the class
sp = urban_helper.summarize_population(
"pop_path.tif", admin_layer, temp_folder=tmp_path
)
assert isinstance(sp, urban_helper.summarize_population)
assert isinstance(sp.admin_layer, gpd.GeoDataFrame)
assert isinstance(sp.urban_layer, str)

# check the inputs - they don't exist so check value will be False
cv = sp.check_inputs()
assert isinstance(cv, bool)
assert cv is False
assert isinstance(sp.check_vals, dict)

# run the calculate method
# zs = sp.calculate_zonal()


class TestUrbanCountry:
"""Tests for the urban_country class."""

def mocked_elevation_clip(
bounds=None, max_download_tiles=None, output=None, product=None
):
"""Mocked version of elevation.clip()"""
return MagicMock()

@mock.patch("elevation.clip", mocked_elevation_clip)
def test_init(self, tmp_path):
# put USA_adm.shp in the tmp_path
with open(tmp_path / "usa_adm.shp", "w") as f:
Expand All @@ -19,3 +89,10 @@ def test_init(self, tmp_path):
final_folder=tmp_path,
)
assert uc.iso3 == "USA"

# change the uc.inD object
uc.inD = MagicMock()

# process the dem
uc.process_dem()
# doesn't return anything or change any attributes so nothing to assert

0 comments on commit 328f884

Please sign in to comment.