From 66dc4e5772054eb426524da018652cf8e83e6ae1 Mon Sep 17 00:00:00 2001 From: Jakob Ketterl Date: Sun, 24 Jan 2021 21:25:26 +0100 Subject: [PATCH] get validator by string --- owrx/property/validators.py | 12 ++++++++++++ test/property/validators/test_validator.py | 6 +++++- 2 files changed, 17 insertions(+), 1 deletion(-) diff --git a/owrx/property/validators.py b/owrx/property/validators.py index fce2955..1812fb2 100644 --- a/owrx/property/validators.py +++ b/owrx/property/validators.py @@ -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, +} diff --git a/test/property/validators/test_validator.py b/test/property/validators/test_validator.py index a083889..6fbbf78 100644 --- a/test/property/validators/test_validator.py +++ b/test/property/validators/test_validator.py @@ -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)