s4:kdc: adjust formatting of samba_kdc_update_pac() documentation
[Samba.git] / python / samba / netcmd / validators.py
blobc8c5697d23fb675c7b6bf65c05661ad61985d7b9
1 # Unix SMB/CIFS implementation.
3 # validators
5 # Copyright (C) Catalyst.Net Ltd. 2023
7 # Written by Rob van der Linde <rob@catalyst.net.nz>
9 # This program is free software; you can redistribute it and/or modify
10 # it under the terms of the GNU General Public License as published by
11 # the Free Software Foundation; either version 3 of the License, or
12 # (at your option) any later version.
14 # This program is distributed in the hope that it will be useful,
15 # but WITHOUT ANY WARRANTY; without even the implied warranty of
16 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17 # GNU General Public License for more details.
19 # You should have received a copy of the GNU General Public License
20 # along with this program. If not, see <http://www.gnu.org/licenses/>.
23 from abc import ABCMeta, abstractmethod
26 class ValidationError(Exception):
27 pass
30 class Validator(metaclass=ABCMeta):
32 @abstractmethod
33 def __call__(self, field, value):
34 pass
37 class Range(Validator):
38 """Checks if the value is within range min ... max."""
40 def __init__(self, min=None, max=None):
41 if min is None and max is None:
42 raise ValueError("Range without a min and max doesn't make sense.")
44 self.min = min
45 self.max = max
47 def __call__(self, field, value):
48 """Check if value is within the range min ... max.
50 It is possible to omit min, or omit max, in which case a more
51 tailored error message is returned.
52 """
53 if self.min is not None and self.max is None:
54 if value < self.min:
55 raise ValidationError(f"{field} must be at least {self.min}")
57 elif self.min is None and self.max is not None:
58 if value > self.max:
59 raise ValidationError(
60 f"{field} cannot be greater than {self.max}")
62 elif self.min is not None and self.max is not None:
63 if value < self.min or value > self.max:
64 raise ValidationError(
65 f"{field} must be between {self.min} and {self.max}")
68 class OneOf(Validator):
69 """Checks if the value is in a list of possible choices."""
71 def __init__(self, choices):
72 self.choices = sorted(choices)
74 def __call__(self, field, value):
75 if value not in self.choices:
76 allowed_choices = ", ".join(self.choices)
77 raise ValidationError(f"{field} must be one of: {allowed_choices}")