Coverage for stricto/string.py: 100%

21 statements  

« prev     ^ index     » next       coverage.py v7.4.1, created at 2024-02-08 22:10 +0100

1"""Module providing the String() Class""" 

2import re 

3from .generic import GenericType 

4from .error import Error, ErrorType 

5 

6 

7class String(GenericType): 

8 """ 

9 A generic type (class for int, string, etc) 

10 """ 

11 

12 def __init__(self, **kwargs): 

13 """ 

14 A string 

15 

16 regexp=pattern=patterns : A (list of) regular expression to match 

17 

18 """ 

19 regexp = kwargs.pop("regexp", kwargs.pop("pattern", kwargs.pop("patterns", []))) 

20 self._regexps = regexp if isinstance(regexp, list) else [regexp] 

21 GenericType.__init__(self, **kwargs) 

22 

23 def __len__(self): 

24 return self._value.__len__() 

25 

26 def check_type(self, value): 

27 if isinstance(value, (str, String)): 

28 return True 

29 raise Error(ErrorType.WRONGTYPE, "Must be a string", self.path_name()) 

30 

31 def check_constraints(self, value): 

32 GenericType.check_constraints(self, value) 

33 

34 # Match regex 

35 for regexp in self._regexps: 

36 reg = self.get_args_or_execute_them(regexp, value) 

37 if not re.match(reg, value): 

38 raise Error(ErrorType.REGEXP, "Dont match regexp", self.path_name()) 

39 

40 return True