Coverage for /pythoncovmergedfiles/medio/medio/usr/local/lib/python3.11/site-packages/validators/cron.py: 11%

Shortcuts on this page

r m x   toggle line displays

j k   next/prev highlighted chunk

0   (zero) top of page

1   (one) first highlighted chunk

45 statements  

1"""Cron.""" 

2 

3# local 

4from .utils import validator 

5 

6 

7def _validate_cron_component(component: str, min_val: int, max_val: int): 

8 if component == "*": 

9 return True 

10 

11 if component.isdecimal(): 

12 return min_val <= int(component) <= max_val 

13 

14 if "/" in component: 

15 parts = component.split("/") 

16 if len(parts) != 2 or not parts[1].isdecimal() or int(parts[1]) < 1: 

17 return False 

18 if parts[0] == "*": 

19 return True 

20 return parts[0].isdecimal() and min_val <= int(parts[0]) <= max_val 

21 

22 if "-" in component: 

23 parts = component.split("-") 

24 if len(parts) != 2 or not parts[0].isdecimal() or not parts[1].isdecimal(): 

25 return False 

26 start, end = int(parts[0]), int(parts[1]) 

27 return min_val <= start <= max_val and min_val <= end <= max_val and start <= end 

28 

29 if "," in component: 

30 for item in component.split(","): 

31 if not _validate_cron_component(item, min_val, max_val): 

32 return False 

33 return True 

34 # return all( 

35 # _validate_cron_component(item, min_val, max_val) for item in component.split(",") 

36 # ) # throws type error. why? 

37 

38 return False 

39 

40 

41@validator 

42def cron(value: str, /): 

43 """Return whether or not given value is a valid cron string. 

44 

45 Examples: 

46 >>> cron('*/5 * * * *') 

47 True 

48 >>> cron('30-20 * * * *') 

49 ValidationError(func=cron, args={'value': '30-20 * * * *'}) 

50 

51 Args: 

52 value: 

53 Cron string to validate. 

54 

55 Returns: 

56 (Literal[True]): If `value` is a valid cron string. 

57 (ValidationError): If `value` is an invalid cron string. 

58 """ 

59 if not value: 

60 return False 

61 

62 try: 

63 minutes, hours, days, months, weekdays = value.strip().split() 

64 except ValueError as err: 

65 raise ValueError("Badly formatted cron string") from err 

66 

67 if not _validate_cron_component(minutes, 0, 59): 

68 return False 

69 if not _validate_cron_component(hours, 0, 23): 

70 return False 

71 if not _validate_cron_component(days, 1, 31): 

72 return False 

73 if not _validate_cron_component(months, 1, 12): 

74 return False 

75 if not _validate_cron_component(weekdays, 0, 6): 

76 return False 

77 

78 return True