From 8850c9d0afd8f080d9d08fbed7b91299046327d6 Mon Sep 17 00:00:00 2001 From: David Almeida <58078834+dc-almeida@users.noreply.github.com> Date: Thu, 10 Oct 2024 12:15:25 +0200 Subject: [PATCH] Allow countries attribute as string (#412) * Allow countries attribute as string * Add str countries attribute test * Change to 'before' validator to ensure list of str internally --- nomenclature/code.py | 3 ++- .../region_codelist/countries_attribute_str/region.yaml | 5 +++++ tests/test_codelist.py | 9 +++++++++ 3 files changed, 16 insertions(+), 1 deletion(-) create mode 100644 tests/data/codelist/region_codelist/countries_attribute_str/region.yaml diff --git a/nomenclature/code.py b/nomenclature/code.py index 0d7e536d..47762ce3 100644 --- a/nomenclature/code.py +++ b/nomenclature/code.py @@ -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): " diff --git a/tests/data/codelist/region_codelist/countries_attribute_str/region.yaml b/tests/data/codelist/region_codelist/countries_attribute_str/region.yaml new file mode 100644 index 00000000..a59a7f6b --- /dev/null +++ b/tests/data/codelist/region_codelist/countries_attribute_str/region.yaml @@ -0,0 +1,5 @@ +- common: + - World +- countries: + - Some region: + countries: Austria diff --git a/tests/test_codelist.py b/tests/test_codelist.py index 0ddca72d..a5c36428 100644 --- a/tests/test_codelist.py +++ b/tests/test_codelist.py @@ -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(