From e7563461b380bd3406a64d26e10c8ef44bf65f14 Mon Sep 17 00:00:00 2001 From: roll Date: Wed, 25 Sep 2024 10:09:56 +0100 Subject: [PATCH] Fixed DP-012 --- dplib/actions/__spec__/test_metadata_convert.py | 15 +++++++++++++++ dplib/actions/metadata/convert.py | 16 +++++++++++++--- 2 files changed, 28 insertions(+), 3 deletions(-) create mode 100644 dplib/actions/__spec__/test_metadata_convert.py diff --git a/dplib/actions/__spec__/test_metadata_convert.py b/dplib/actions/__spec__/test_metadata_convert.py new file mode 100644 index 0000000..6cb7581 --- /dev/null +++ b/dplib/actions/__spec__/test_metadata_convert.py @@ -0,0 +1,15 @@ +import pytest + +from dplib.actions.metadata.convert import convert_metadata + + +@pytest.mark.parametrize( + "source,target", + ( + ("bad", "ckan"), + ("ckan", "bad"), + ), +) +def test_convert_metadata_bad_source_or_target_dp_012(source: str, target: str): + with pytest.raises(ValueError): + convert_metadata("resource.json", type="resource", source=source, target=target) # type: ignore diff --git a/dplib/actions/metadata/convert.py b/dplib/actions/metadata/convert.py index f0b8aa2..2341bd9 100644 --- a/dplib/actions/metadata/convert.py +++ b/dplib/actions/metadata/convert.py @@ -1,7 +1,7 @@ from __future__ import annotations from importlib import import_module -from typing import Literal, Optional, Type, Union, cast +from typing import List, Literal, Optional, Type, cast, get_args from ...models import Package, Resource from ...system import Model @@ -17,9 +17,17 @@ def convert_metadata( ) -> Model: """Convert metadata from one notation to another.""" + # Validate source/target + if source and source not in NOTATIONS: + raise ValueError(f"Unknown source notation: {source}") + if target and target not in NOTATIONS: + raise ValueError(f"Unknown target notation: {target}") + # Source model Source = Resource if type == "resource" else Package if source: + if source not in NOTATIONS: + raise ValueError(f"Unknown source notation: {source}") module = import_module(f"dplib.plugins.{source}.models") Source: Type[Model] = getattr(module, f"{source.capitalize()}{type.capitalize()}") model = Source.from_path(path, format=format) @@ -35,5 +43,7 @@ def convert_metadata( return model -IType = Union[Literal["package"], Literal["resource"]] -INotation = Union[Literal["ckan"], Literal["dcat"], Literal["github"], Literal["zenodo"]] +IType = Literal["package", "resource"] +INotation = Literal["ckan", "dcat", "github", "zenodo"] + +NOTATIONS: List[INotation] = list(get_args(INotation))