get validator by string

This commit is contained in:
Jakob Ketterl 2021-01-24 21:25:26 +01:00
parent ad0a5c27db
commit 66dc4e5772
2 changed files with 17 additions and 1 deletions

View File

@ -12,6 +12,8 @@ class Validator(ABC):
return x
if callable(x):
return LambdaValidator(x)
if x in validator_types:
return validator_types[x]()
raise ValidatorException("Cannot create validator")
@abstractmethod
@ -40,3 +42,13 @@ class IntegerValidator(Validator):
class StringValidator(Validator):
def isValid(self, value):
return isinstance(value, str)
validator_types = {
"string": StringValidator,
"str": StringValidator,
"integer": IntegerValidator,
"int": IntegerValidator,
"number": NumberValidator,
"num": NumberValidator,
}

View File

@ -1,5 +1,5 @@
from unittest import TestCase
from owrx.property.validators import Validator, NumberValidator, LambdaValidator
from owrx.property.validators import Validator, NumberValidator, LambdaValidator, StringValidator
class ValidatorTest(TestCase):
@ -14,3 +14,7 @@ class ValidatorTest(TestCase):
validator = Validator.of(my_callable)
self.assertIsInstance(validator, LambdaValidator)
self.assertTrue(validator.isValid("test"))
def testGetsValidatorByKey(self):
validator = Validator.of("str")
self.assertIsInstance(validator, StringValidator)