Skip to content

Commit

Permalink
Allow countries attribute as string (#412)
Browse files Browse the repository at this point in the history
* Allow countries attribute as string

* Add str countries attribute test

* Change to 'before' validator to ensure list of str internally
  • Loading branch information
dc-almeida authored Oct 10, 2024
1 parent e64ed34 commit 8850c9d
Show file tree
Hide file tree
Showing 3 changed files with 16 additions and 1 deletion.
3 changes: 2 additions & 1 deletion nomenclature/code.py
Original file line number Diff line number Diff line change
Expand Up @@ -246,9 +246,10 @@ class RegionCode(Code):
countries: Optional[List[str]] = None
iso3_codes: Optional[Union[List[str], str]] = None

@field_validator("countries")
@field_validator("countries", mode="before")
def check_countries(cls, v: List[str], info: ValidationInfo) -> List[str]:
"""Verifies that each country name is defined in `nomenclature.countries`."""
v = to_list(v)
if invalid_country_names := set(v) - set(countries.names):
raise ValueError(
f"Region '{info.data['name']}' uses non-standard country name(s): "
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
- common:
- World
- countries:
- Some region:
countries: Austria
9 changes: 9 additions & 0 deletions tests/test_codelist.py
Original file line number Diff line number Diff line change
Expand Up @@ -172,6 +172,15 @@ def test_region_codelist_nonexisting_country_name():
)


def test_region_codelist_str_country_name():
"""Check that country name as string is validated against `nomenclature.countries`"""
code = RegionCodeList.from_directory(
"region",
MODULE_TEST_DATA_DIR / "region_codelist" / "countries_attribute_str",
)
assert code["Some region"].countries == ["Austria"]


def test_norway_as_str():
"""guard against casting of 'NO' to boolean `False` by PyYAML or pydantic"""
region = RegionCodeList.from_directory(
Expand Down

0 comments on commit 8850c9d

Please sign in to comment.