From ae274d4ca7dcd6b0caa05908d24c004149b16fab Mon Sep 17 00:00:00 2001 From: Kazuya Takei Date: Sun, 25 Feb 2024 01:11:29 +0900 Subject: [PATCH] feat(toolkit): Simple package class from single text --- src/rst_package_refs/toolkit.py | 23 +++++++++++++++++++++++ tests/test_toolkit.py | 16 ++++++++++++++++ 2 files changed, 39 insertions(+) diff --git a/src/rst_package_refs/toolkit.py b/src/rst_package_refs/toolkit.py index 94b5110..726f2be 100644 --- a/src/rst_package_refs/toolkit.py +++ b/src/rst_package_refs/toolkit.py @@ -1,8 +1,31 @@ """Toolkit to create original custom role.""" +import abc import re +from dataclasses import dataclass from typing import Tuple +@dataclass +class Package(abc.ABC): + """Package data struct (abstract).""" + + name: str + + @property + @abc.abstractmethod + def url(self) -> str: + """Return URL of package.""" + pass + + @classmethod + def parse(cls, target) -> "Package": + """Parse target and generate package object. + + If your definition package requires extra method to parse, override it. + """ + return cls(name=target) + + def split_text(source: str) -> Tuple[str, str]: """Split from content to displaying text and target text. diff --git a/tests/test_toolkit.py b/tests/test_toolkit.py index 8abfea1..499cec3 100644 --- a/tests/test_toolkit.py +++ b/tests/test_toolkit.py @@ -18,3 +18,19 @@ def test_split_text(text, display_text, target_text): display, target = toolkit.split_text(text) assert display == display_text assert target == target_text + + +def test_Package_require_inherit(): + with pytest.raises(TypeError): + package = toolkit.Package.parse("test") + package.url + + +def test_InheritPackage(): + class MyPackage(toolkit.Package): + @property + def url(self): + return "ok" + + package = MyPackage.parse("name") + assert package.url == "ok"