66 lines
1.7 KiB
Python
66 lines
1.7 KiB
Python
from abc import ABC, abstractmethod
|
|
from typing import Any, override
|
|
|
|
|
|
class NotValidatedIngestException(Exception):
|
|
def __init__(self, dataType: str):
|
|
super().__init__(f"Improper {dataType} data")
|
|
|
|
|
|
class DataProcessor(ABC):
|
|
@abstractmethod
|
|
def validate(self, data: Any) -> bool:
|
|
pass
|
|
|
|
@abstractmethod
|
|
def ingest(self, data: Any) -> None:
|
|
pass
|
|
|
|
def output(self) -> tuple[int, str]:
|
|
return (0, "abc")
|
|
|
|
|
|
class NumericProcessor(DataProcessor):
|
|
def isElementValid(self, data: Any) -> bool:
|
|
return data is int or data is float
|
|
|
|
@override
|
|
def validate(self, data: Any) -> bool:
|
|
if type(data) is not list:
|
|
return self.isElementValid(data)
|
|
for elem in data:
|
|
if not self.isElementValid(elem):
|
|
return False
|
|
return True
|
|
|
|
@override
|
|
def ingest(self, data: Any) -> None:
|
|
if not self.validate(data):
|
|
raise NotValidatedIngestException("numeric")
|
|
|
|
|
|
def testValidateInput(processor: DataProcessor, data: Any) -> None:
|
|
ok = processor.validate(data)
|
|
print(f" Trying to validate input '{data}': {ok}")
|
|
|
|
|
|
def testInvalidIngestion(
|
|
processor: DataProcessor, data: Any, dataType: str
|
|
) -> None:
|
|
print(
|
|
f"Test invalid ingestion of {dataType} '{data}' without "
|
|
"prior validation:"
|
|
)
|
|
try:
|
|
processor.ingest(data)
|
|
except NotValidatedIngestException as e:
|
|
print(f"Got exception: {e}")
|
|
|
|
|
|
if __name__ == "__main__":
|
|
print("=== Code Nexus - Data Processor ===\n")
|
|
numeric = NumericProcessor()
|
|
testValidateInput(numeric, 42)
|
|
testValidateInput(numeric, "Hello")
|
|
testInvalidIngestion(numeric, "foo", "string")
|