Repository: IAMconsortium/nomenclature

Issue:
Invalid regions do not raise an error as part of RegionProcessor
The method `RegionProcessor.apply()` does not raise an error when the IamDataFrame includes (or aggregates to) a region that is not listed in the region definitions.

This is because the `validate_items()` method only returns the invalid items but does not itself raise an error - so the following line does not have any effect.
https://github.com/IAMconsortium/nomenclature/blob/c2769559263617c6b0a066e958ca1f1627080b55/nomenclature/processor/region.py#L453

Discussion:
phackstock: > Nice, thank you! And for what it’s worth, I did run into exactlythis corner case… 😜

Ah ok, I see, I'll see to set it live soon.


Patch:
diff --git a/nomenclature/processor/region.py b/nomenclature/processor/region.py
index 3c6e1b6..2da9d07 100644
--- a/nomenclature/processor/region.py
+++ b/nomenclature/processor/region.py
@@ -26,6 +26,7 @@ from nomenclature.error.region import (
 )
 from nomenclature.processor import Processor
 from nomenclature.processor.utils import get_relative_path
+from nomenclature.validation import log_error
 
 logger = logging.getLogger(__name__)
 
@@ -450,7 +451,9 @@ class RegionProcessor(Processor):
                 processed_dfs.append(self._apply_region_processing(model_df)[0])
 
         res = pyam.concat(processed_dfs)
-        self.region_codelist.validate_items(res.region)
+        if not_defined_regions := self.region_codelist.validate_items(res.region):
+            log_error("region", not_defined_regions)
+            raise ValueError("The validation failed. Please check the log for details.")
         return res
 
     def check_region_aggregation(


Test patch:
diff --git a/tests/test_core.py b/tests/test_core.py
index 9f04df6..1a06cb5 100644
--- a/tests/test_core.py
+++ b/tests/test_core.py
@@ -455,3 +455,31 @@ def test_aggregation_differences_export(input_data, expected_difference):
     exp = pd.DataFrame(expected_difference, columns=index + columns).set_index(index)
 
     assert_frame_equal(exp, obs)
+
+
+def test_region_aggregation_unknown_region(simple_df, simple_definition, caplog):
+    # add an unknown region
+    df_with_unknown_region = simple_df.append(
+        pd.DataFrame(
+            [
+                [
+                    "model_a",
+                    "scen_a",
+                    "unknown region",
+                    "Primary Energy",
+                    "EJ/yr",
+                    1,
+                    6.0,
+                ],
+            ],
+            columns=IAMC_IDX + [2005, 2010],
+        )
+    )
+    with pytest.raises(ValueError):
+        RegionProcessor.from_directory(
+            TEST_DATA_DIR / "region_processing" / "no_mapping", simple_definition
+        ).apply(df_with_unknown_region)
+    assert all(
+        text in caplog.text
+        for text in ["not defined in the 'region' codelist", "unknown region"]
+    )