Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add ErrorCollector to iso3_codes validation #390

Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 10 additions & 3 deletions nomenclature/code.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,8 @@
ValidationInfo,
)

from nomenclature.error import ErrorCollector

from pyam.utils import to_list

from .countries import countries
Expand Down Expand Up @@ -259,15 +261,20 @@ def check_countries(cls, v: List[str], info: ValidationInfo) -> List[str]:
@field_validator("iso3_codes")
def check_iso3_codes(cls, v: List[str], info: ValidationInfo) -> List[str]:
"""Verifies that each ISO3 code is valid according to pycountry library."""
errors = ErrorCollector()
if invalid_iso3_codes := [
iso3_code
for iso3_code in to_list(v)
if countries.get(alpha_3=iso3_code) is None
]:
raise ValueError(
f"Region '{info.data['name']}' has invalid ISO3 country code(s): "
+ ", ".join(invalid_iso3_codes)
errors.append(
ValueError(
f"Region '{info.data['name']}' has invalid ISO3 country code(s): "
+ ", ".join(invalid_iso3_codes)
)
)
if errors:
raise ValueError(errors)
return v


Expand Down
6 changes: 4 additions & 2 deletions tests/test_code.py
Original file line number Diff line number Diff line change
Expand Up @@ -157,7 +157,8 @@ def test_RegionCode_iso3_code_list_fail():
error_pattern = (
"1 validation error for RegionCode\n"
"iso3_codes\n"
" Value error, Region 'Western Europe' has "
" Value error, Collected 1 error:\n"
" 1. Region 'Western Europe' has "
"invalid ISO3 country code\(s\): DMK, IPL, ATZ, FNL, FRE, DEX, GRE, " # noqa
"IBL, ITL, LIC, MLA, BEG, FRT, ANB, GDR, LXB, MNO, NTD, NRW, PRE, EPA, " # noqa
"SWD, CEW, GTR, SOR" # noqa
Expand All @@ -170,7 +171,8 @@ def test_RegionCode_iso3_code_str_fail():
error_pattern = (
"1 validation error for RegionCode\n"
"iso3_codes\n"
" Value error, Region 'Austria' has invalid ISO3 country code\(s\): AUTT"
" Value error, Collected 1 error:\n"
" 1. Region 'Austria' has invalid ISO3 country code\(s\): AUTT"
)
with raises(ValueError, match=error_pattern):
RegionCode(name="Austria", hierarchy="country", iso3_codes="AUTT")
Expand Down