Coretex
base_list_parameter.py
1 # Copyright (C) 2023 Coretex LLC
2 
3 # This file is part of Coretex.ai
4 
5 # This program is free software: you can redistribute it and/or modify
6 # it under the terms of the GNU Affero General Public License as
7 # published by the Free Software Foundation, either version 3 of the
8 # License, or (at your option) any later version.
9 
10 # This program is distributed in the hope that it will be useful,
11 # but WITHOUT ANY WARRANTY; without even the implied warranty of
12 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 # GNU Affero General Public License for more details.
14 
15 # You should have received a copy of the GNU Affero General Public License
16 # along with this program. If not, see <https://www.gnu.org/licenses/>.
17 
18 from typing import Optional, Tuple, List, Generic
19 from abc import abstractmethod
20 
21 from .base_parameter import BaseParameter, T
22 
23 
24 class BaseListParameter(BaseParameter[T], Generic[T]):
25 
26  @property
27  def types(self) -> List[type]:
28  return [list]
29 
30  @property
31  @abstractmethod
32  def listTypes(self) -> List[type]:
33  pass
34 
35  def validate(self) -> Tuple[bool, Optional[str]]:
36  isValid, error = super().validate()
37  if not isValid:
38  return isValid, error
39 
40  if not self.required and self.value is None:
41  return True, None
42 
43  if self.required and len(self.value) == 0: # type: ignore[arg-type]
44  return False, f"Required parameter \"{self.name}\" must contain a non-empty array"
45 
46  # self.value is of type Optional[Any], but base class validate method already
47  # checks if it is a list, if that fails this is not reachable
48  for element in self.value: # type: ignore[union-attr]
49 
50  # bool is a subclass of int, do not allow validation to pass if
51  # we are looking for integer, but bool is received
52  if isinstance(element, bool) and int in self.listTypes and not bool in self.listTypes:
53  return False, None
54 
55  if not any(isinstance(element, type_) for type_ in self.listTypes):
56  return False, None
57 
58  return True, None