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

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

40 statements  

1"""Cron.""" 

2 

3# local 

4from .utils import validator 

5 

6 

7def _validate_cron_item(item: str, min_val: int, max_val: int): 

8 # An item may carry a step, e.g. "*/5", "1-30/2" or "5/10". 

9 if "/" in item: 

10 base, _, step = item.partition("/") 

11 if not step.isdecimal() or int(step) < 1: 

12 return False 

13 else: 

14 base = item 

15 

16 if base == "*": 

17 return True 

18 

19 if "-" in base: 

20 parts = base.split("-") 

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

22 return False 

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

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

25 

26 if base.isdecimal(): 

27 return min_val <= int(base) <= max_val 

28 

29 return False 

30 

31 

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

33 # A field is a comma-separated list of items, each optionally stepped. 

34 return all(_validate_cron_item(item, min_val, max_val) for item in component.split(",")) 

35 

36 

37@validator 

38def cron(value: str, /): 

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

40 

41 Examples: 

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

43 True 

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

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

46 

47 Args: 

48 value: 

49 Cron string to validate. 

50 

51 Returns: 

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

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

54 """ 

55 if not value: 

56 return False 

57 

58 try: 

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

60 except ValueError as err: 

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

62 

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

64 return False 

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

66 return False 

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

68 return False 

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

70 return False 

71 if not _validate_cron_component(weekdays, 0, 7): 

72 return False 

73 

74 return True