Coverage for utils/input_validator.py: 94%
35 statements
« prev ^ index » next coverage.py v7.4.3, created at 2024-03-09 21:08 +0000
« prev ^ index » next coverage.py v7.4.3, created at 2024-03-09 21:08 +0000
1"""This Module contains functions to validate input data."""
3from datetime import datetime, date
5def validate_date(date_input):
6 """Validates that the input is a datetime object or a string
7 that can be converted to a datetime object."""
8 if isinstance(date_input, datetime):
9 return date_input.date()
10 elif isinstance(date_input, date):
11 return date_input
12 elif isinstance(date_input, str):
13 try:
14 return datetime.strptime(date_input, '%Y-%m-%d').date()
15 except ValueError as exc:
16 raise TypeError(
17 "Date must be a datetime object, a date object, or a string in 'YYYY-MM-DD' format"
18 ) from exc
19 else:
20 raise TypeError(
21 "Date must be a datetime object, a date object, or a string in 'YYYY-MM-DD' format"
22 )
24def validate_int(number, variable_name):
25 """Validates that the input is an integer or a string
26 that can be converted to an integer."""
27 if not isinstance(number, int):
28 try:
29 return int(number)
30 except ValueError as exc:
31 raise TypeError(
32 f"{variable_name} must be an integer or a string \
33 that can be converted to an integer"
34 ) from exc
35 return number
37def validate_bool(value, variable_name):
38 """Validates that the input is a boolean or a string
39 that can be converted to a boolean."""
40 if not isinstance(value, bool):
41 if isinstance(value, str):
42 if value.lower() in ['true', 'false']:
43 return value.lower() == 'true'
44 raise TypeError(
45 f"{variable_name} must be a boolean or a string that can \
46 be converted to a boolean ('true' or 'false')"
47 )
48 return value
50def validate_array(array, variable_name):
51 """Validates that the input is a list or a string that can be
52 converted to a list."""
53 if not isinstance(array, list):
54 if isinstance(array, str):
55 try:
56 return list(map(float, array.split(',')))
57 except ValueError as exc:
58 raise TypeError(
59 f"{variable_name} must be a list or a string that can \
60 be converted to a list"
61 ) from exc
62 raise TypeError(
63 f"{variable_name} must be a list or a string that can be \
64 converted to a list"
65 )
66 return array