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 return x
if callable(x): if callable(x):
return LambdaValidator(x) return LambdaValidator(x)
if x in validator_types:
return validator_types[x]()
raise ValidatorException("Cannot create validator") raise ValidatorException("Cannot create validator")
@abstractmethod @abstractmethod
@ -40,3 +42,13 @@ class IntegerValidator(Validator):
class StringValidator(Validator): class StringValidator(Validator):
def isValid(self, value): def isValid(self, value):
return isinstance(value, str) 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 unittest import TestCase
from owrx.property.validators import Validator, NumberValidator, LambdaValidator from owrx.property.validators import Validator, NumberValidator, LambdaValidator, StringValidator
class ValidatorTest(TestCase): class ValidatorTest(TestCase):
@ -14,3 +14,7 @@ class ValidatorTest(TestCase):
validator = Validator.of(my_callable) validator = Validator.of(my_callable)
self.assertIsInstance(validator, LambdaValidator) self.assertIsInstance(validator, LambdaValidator)
self.assertTrue(validator.isValid("test")) self.assertTrue(validator.isValid("test"))
def testGetsValidatorByKey(self):
validator = Validator.of("str")
self.assertIsInstance(validator, StringValidator)