Skip to content

Commit

Permalink
feat: Added integration test with several cadastral registries to test
Browse files Browse the repository at this point in the history
  • Loading branch information
JCruiz15 committed Jun 26, 2024
1 parent 7d8bfa2 commit 1014dc8
Show file tree
Hide file tree
Showing 8 changed files with 141 additions and 54 deletions.
2 changes: 1 addition & 1 deletion sigpac_tools/__main__.py
Original file line number Diff line number Diff line change
Expand Up @@ -155,7 +155,7 @@ def get_parser():
type=str,
help="Cadastral registry to search for",
required=True,
metavar="STRING"
metavar="STRING",
)

return parser
Expand Down
63 changes: 44 additions & 19 deletions sigpac_tools/_globals.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,23 +5,48 @@
# Provinces divided into communities
# https://www.ine.es/daco/daco42/codmun/cod_ccaa_provincia.htm
PROVINCES_BY_COMMUNITY = {
1: [4, 11, 14, 18, 21, 23, 29, 41], # Andalucía : [Almería, Cádiz, Córdoba, Granada, Huelva, Jaén, Málaga, Sevilla]
2: [22, 44, 50], # Aragón : [Huesca, Teruel, Zaragoza]
3: [33], # Principado de Asturias : [Asturias]
4: [7], # Illes Balears : [Illes Balears]
5: [35, 38], # Canarias : [Las Palmas, Santa Cruz de Tenerife]
6: [39], # Cantabria : [Cantabria]
7: [5, 9, 24, 34, 37, 40, 42, 47, 49], # Castilla y León : [Ávila, Burgos, León, Palencia, Salamanca, Segovia, Soria, Valladolid, Zamora]
8: [2, 13, 16, 19, 45], # Castilla-La Mancha : [Albacete, Ciudad Real, Cuenca, Guadalajara, Toledo]
9: [8, 17, 25, 43], # Cataluña : [Barcelona, Girona, Lleida, Tarragona]
10: [3, 12, 46], # Comunitat Valenciana : [Alicante, Castellón, Valencia]
11: [6, 10], # Extremadura : [Badajoz, Cáceres]
12: [15, 27, 32, 36], # Galicia : [A Coruña, Lugo, Ourense, Pontevedra]
13: [28], # Comunidad de Madrid : [Madrid]
14: [30], # Región de Murcia : [Murcia]
15: [31], # Comunidad Foral de Navarra : [Navarra]
16: [1, 20, 48], # País Vasco : [Álava, Gipuzkoa, Bizkaia]
17: [26], # La Rioja : [La Rioja]
18: [51], # Ceuta : [Ceuta]
19: [52], # Melilla : [Melilla]
1: [
4,
11,
14,
18,
21,
23,
29,
41,
], # Andalucía : [Almería, Cádiz, Córdoba, Granada, Huelva, Jaén, Málaga, Sevilla]
2: [22, 44, 50], # Aragón : [Huesca, Teruel, Zaragoza]
3: [33], # Principado de Asturias : [Asturias]
4: [7], # Illes Balears : [Illes Balears]
5: [35, 38], # Canarias : [Las Palmas, Santa Cruz de Tenerife]
6: [39], # Cantabria : [Cantabria]
7: [
5,
9,
24,
34,
37,
40,
42,
47,
49,
], # Castilla y León : [Ávila, Burgos, León, Palencia, Salamanca, Segovia, Soria, Valladolid, Zamora]
8: [
2,
13,
16,
19,
45,
], # Castilla-La Mancha : [Albacete, Ciudad Real, Cuenca, Guadalajara, Toledo]
9: [8, 17, 25, 43], # Cataluña : [Barcelona, Girona, Lleida, Tarragona]
10: [3, 12, 46], # Comunitat Valenciana : [Alicante, Castellón, Valencia]
11: [6, 10], # Extremadura : [Badajoz, Cáceres]
12: [15, 27, 32, 36], # Galicia : [A Coruña, Lugo, Ourense, Pontevedra]
13: [28], # Comunidad de Madrid : [Madrid]
14: [30], # Región de Murcia : [Murcia]
15: [31], # Comunidad Foral de Navarra : [Navarra]
16: [1, 20, 48], # País Vasco : [Álava, Gipuzkoa, Bizkaia]
17: [26], # La Rioja : [La Rioja]
18: [51], # Ceuta : [Ceuta]
19: [52], # Melilla : [Melilla]
}
24 changes: 9 additions & 15 deletions sigpac_tools/find.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@
logger = structlog.get_logger()


def find_from_cadastral_registry(cadastral_reg : str):
def find_from_cadastral_registry(cadastral_reg: str):
"""
Find the geometry and metadata of a cadastral reference in the SIGPAC database. The reference must be rural. Urban references are not supported.
Expand All @@ -33,7 +33,7 @@ def find_from_cadastral_registry(cadastral_reg : str):
Geojson geometry of the found reference
dict
Metadata of the found reference
Raises
-------
ValueError
Expand All @@ -51,12 +51,12 @@ def find_from_cadastral_registry(cadastral_reg : str):

# Search for coordinates

search_data = search(
reg
)
search_data = search(reg)
if search_data["features"] == []:
raise ValueError(f"The cadastral reference {cadastral_reg} does not exist in the SIGPAC database. Please check the if the reference is correct and try again. Urban references are not supported.")

raise ValueError(
f"The cadastral reference {cadastral_reg} does not exist in the SIGPAC database. Please check the if the reference is correct and try again. Urban references are not supported."
)

coords_x = []
coords_y = []
for feat in search_data["features"]:
Expand All @@ -67,17 +67,11 @@ def find_from_cadastral_registry(cadastral_reg : str):
# Get geometry

geometry = geometry_from_coords(
layer="parcela",
lat=coords[1],
lon=coords[0],
reference=reg["parcel"]
layer="parcela", lat=coords[1], lon=coords[0], reference=reg["parcel"]
)

# Get metadata

metadata = get_metadata(
layer="parcela",
data=reg
)
metadata = get_metadata(layer="parcela", data=reg)

return geometry, metadata
11 changes: 6 additions & 5 deletions sigpac_tools/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@

logger = structlog.get_logger()


def lng_lat_to_tile(lng: float, lat: float, zoom: float) -> tuple[int, int]:
"""Transforms the given coordinates from longitude and latitude to tile coordinates for the given zoom level
Expand Down Expand Up @@ -121,10 +122,10 @@ def read_cadastral_registry(registry: str) -> dict:
-------
ValueError: If the length of the cadastral reference is not 20 characters
"""
registry = registry.upper().replace(" ", "")
if len(registry) != 20:
raise ValueError("The cadastral reference must have a length of 20 characters")
registry = registry.upper().replace(" ", "")


reg_prov = registry[:2]
reg_mun = registry[2:5]
reg_sec = registry[5]
Expand All @@ -133,14 +134,14 @@ def read_cadastral_registry(registry: str) -> dict:
reg_id = registry[14:18]
reg_control = registry[18:]

# Will raise an error if the reference is not valid or if it is urban, in any other case, it will log the result and continue
validate_cadastral_registry(registry)

if not find_community(int(reg_prov)):
raise ValueError(
"The province of the cadastral reference is not valid. Please check if it is a correct rural reference and try again."
)

# Will raise an error if the reference is not valid or if it is urban, in any other case, it will log the result and continue
validate_cadastral_registry(registry)

return {
"province": int(reg_prov),
"municipality": int(reg_mun),
Expand Down
57 changes: 57 additions & 0 deletions tests/test_integration.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
import pytest
from sigpac_tools.find import find_from_cadastral_registry


class TestFindCadastralRegistrySuite:
@pytest.mark.parametrize(
"cadastral_reg",
[
"06001A028000380000LH",
"02086A005000020000LQ",
"30024A284003000000IG",
"29011A007000200000EQ",
"38011A019001900000QY",
"12079A012004430000HH",
"47148A003000100000IH",
"28043A062000010000AW",
"12050A003001060000HA",
"21035A023001690000QT",
"06001a028000380000lh",
"06 001 A 028 00038 0000 LH",
" 06 001 a 028 000 38 0000 lh",
],
)
def test_cadastral_registry(self, cadastral_reg):
result_geom, result_meta = find_from_cadastral_registry(cadastral_reg)
assert result_geom is not None and result_meta is not None

@pytest.mark.parametrize(
"non_cadastral_reg",
[
"000000000000000000",
"1" "AAAAAAAAAAAAAAAAAAAAAAAAAA" "5836065QB0353N0001IJ",
"38011A019001900000XX",
"????????????????????",
"01000z000000000000MM",
],
)
def test_value_error_cadastral_registry(self, non_cadastral_reg):
with pytest.raises(ValueError):
find_from_cadastral_registry(non_cadastral_reg)

@pytest.mark.parametrize(
"non_cadastral_reg",
[
"9876113PB7197N0001OQ",
"010001000000000000MM",
"2755914VK4725F0001UT",
"0709205UF7600N0001BL",
],
)
def test_not_implemented_error_cadastral_registry(self, non_cadastral_reg):
with pytest.raises(NotImplementedError):
find_from_cadastral_registry(non_cadastral_reg)


if __name__ == "__main__":
pytest.main()
2 changes: 0 additions & 2 deletions tests/test_locate.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,5 @@
import pytest
from sigpac_tools.locate import geometry_from_coords
from sigpac_tools._globals import BASE_URL



class TestGeometryFromCoords:
Expand Down
10 changes: 5 additions & 5 deletions tests/test_search.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ def test_search_provinces(self, mock_get):
mock_get.return_value = mock_response

data = {"community": 1}
result = search(data)
search(data)

mock_get.assert_called_once_with(
f"{BASE_URL}/fega/ServiciosVisorSigpac/query/provincias/1.geojson"
Expand All @@ -32,7 +32,7 @@ def test_search_municipalities(self, mock_get):
mock_get.return_value = mock_response

data = {"province": 1}
result = search(data)
search(data)

mock_get.assert_called_once_with(
f"{BASE_URL}/fega/ServiciosVisorSigpac/query/municipios/1.geojson"
Expand All @@ -45,7 +45,7 @@ def test_search_polygons(self, mock_get):
mock_get.return_value = mock_response

data = {"province": 1, "municipality": 1}
result = search(data)
search(data)

mock_get.assert_called_once_with(
f"{BASE_URL}/fega/ServiciosVisorSigpac/query/poligonos/1/1/0/0.geojson"
Expand All @@ -58,7 +58,7 @@ def test_search_parcels(self, mock_get):
mock_get.return_value = mock_response

data = {"province": 1, "municipality": 1, "polygon": 1}
result = search(data)
search(data)

mock_get.assert_called_once_with(
f"{BASE_URL}/fega/ServiciosVisorSigpac/query/parcelas/1/1/0/0/1.geojson"
Expand All @@ -71,7 +71,7 @@ def test_search_specific_parcel(self, mock_get):
mock_get.return_value = mock_response

data = {"province": 1, "municipality": 1, "polygon": 1, "parcel": 1}
result = search(data)
search(data)

mock_get.assert_called_once_with(
f"{BASE_URL}/fega/ServiciosVisorSigpac/query/recintos/1/1/0/0/1/1.geojson"
Expand Down
26 changes: 19 additions & 7 deletions tests/test_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,9 +5,10 @@
transform_coords,
find_community,
read_cadastral_registry,
validate_cadastral_registry
validate_cadastral_registry,
)


class TestLngLatToTile:
def test_central_coordinates(self):
lng, lat, zoom = 0, 0, 1
Expand Down Expand Up @@ -76,13 +77,19 @@ def test_read_cadastral_registry_valid(self):
assert result == expected_result

def test_read_cadastral_registry_invalid_length(self):
with pytest.raises(ValueError, match="The cadastral reference must have a length of 20 characters"):
with pytest.raises(
ValueError,
match="The cadastral reference must have a length of 20 characters",
):
read_cadastral_registry("29008A008005720000EQ000")
with pytest.raises(ValueError, match="The cadastral reference must have a length of 20 characters"):
with pytest.raises(
ValueError,
match="The cadastral reference must have a length of 20 characters",
):
read_cadastral_registry("29008A00800572")

def test_read_cadastral_registry_invalid_province(self):
with pytest.raises(ValueError, match="The province of the cadastral reference is not valid"):
with pytest.raises(NotImplementedError):
read_cadastral_registry("99003000100123456789")


Expand All @@ -92,9 +99,15 @@ def test_validate_cadastral_registry_valid(self):
validate_cadastral_registry(registry) # This should pass without exceptions

def test_validate_cadastral_registry_invalid_length(self):
with pytest.raises(ValueError, match="The cadastral reference must have a length of 20 characters"):
with pytest.raises(
ValueError,
match="The cadastral reference must have a length of 20 characters",
):
validate_cadastral_registry("29008A008005720000EQ000")
with pytest.raises(ValueError, match="The cadastral reference must have a length of 20 characters"):
with pytest.raises(
ValueError,
match="The cadastral reference must have a length of 20 characters",
):
validate_cadastral_registry("29008A00800572")

def test_validate_cadastral_registry_urban_not_supported(self):
Expand All @@ -106,7 +119,6 @@ def test_validate_cadastral_registry_invalid_control(self):
registry = "29008A008005720000OL" # Incorrect control characters
with pytest.raises(ValueError):
validate_cadastral_registry(registry)



if __name__ == "__main__":
Expand Down

0 comments on commit 1014dc8

Please sign in to comment.