| 1 |
import math |
| 2 |
|
| 3 |
from strictyaml.exceptions import YAMLSerializationError |
| 4 |
from strictyaml.validators import Validator |
| 5 |
from strictyaml.representation import YAML |
| 6 |
from strictyaml import constants |
| 7 |
from strictyaml import utils |
| 8 |
from datetime import datetime |
| 9 |
import dateutil.parser |
| 10 |
import decimal |
| 11 |
import sys |
| 12 |
import re |
| 13 |
import urllib.parse |
| 14 |
from strictyaml.ruamel.scalarstring import PreservedScalarString |
| 15 |
|
| 16 |
|
| 17 |
if sys.version_info[0] == 3: |
| 18 |
unicode = str |
| 19 |
|
| 20 |
|
| 21 |
class ScalarValidator(Validator): |
| 22 |
@property |
| 23 |
def rule_description(self): |
| 24 |
return "a {0}".format(self.__class__.__name__.lower()) |
| 25 |
|
| 26 |
def __call__(self, chunk): |
| 27 |
chunk.expect_scalar(self.rule_description) |
| 28 |
return YAML(chunk, validator=self) |
| 29 |
|
| 30 |
def validate(self, chunk): |
| 31 |
return self.validate_scalar(chunk) |
| 32 |
|
| 33 |
def should_be_string(self, data, message): |
| 34 |
if not utils.is_string(data): |
| 35 |
raise YAMLSerializationError( |
| 36 |
"{0} got '{1}' of type {2}.".format(message, data, type(data).__name__) |
| 37 |
) |
| 38 |
|
| 39 |
def validate_scalar(self, chunk): |
| 40 |
raise NotImplementedError("validate_scalar(self, chunk) must be implemented") |
| 41 |
|
| 42 |
|
| 43 |
class Enum(ScalarValidator): |
| 44 |
def __init__(self, restricted_to, item_validator=None): |
| 45 |
self._item_validator = Str() if item_validator is None else item_validator |
| 46 |
assert isinstance( |
| 47 |
self._item_validator, ScalarValidator |
| 48 |
), "item validator must be scalar too" |
| 49 |
self._restricted_to = restricted_to |
| 50 |
|
| 51 |
def validate_scalar(self, chunk): |
| 52 |
val = self._item_validator(chunk) |
| 53 |
val._validator = self |
| 54 |
if val.scalar not in self._restricted_to: |
| 55 |
chunk.expecting_but_found( |
| 56 |
"when expecting one of: {0}".format( |
| 57 |
", ".join(map(str, self._restricted_to)) |
| 58 |
) |
| 59 |
) |
| 60 |
else: |
| 61 |
return val |
| 62 |
|
| 63 |
def to_yaml(self, data): |
| 64 |
if data not in self._restricted_to: |
| 65 |
raise YAMLSerializationError( |
| 66 |
"Got '{0}' when expecting one of: {1}".format( |
| 67 |
data, ", ".join(map(str, self._restricted_to)) |
| 68 |
) |
| 69 |
) |
| 70 |
return self._item_validator.to_yaml(data) |
| 71 |
|
| 72 |
def __repr__(self): |
| 73 |
# TODO : item_validator |
| 74 |
return "Enum({0})".format(repr(self._restricted_to)) |
| 75 |
|
| 76 |
|
| 77 |
class CommaSeparated(ScalarValidator): |
| 78 |
def __init__(self, item_validator): |
| 79 |
self._item_validator = item_validator |
| 80 |
assert isinstance( |
| 81 |
self._item_validator, ScalarValidator |
| 82 |
), "item validator must be scalar too" |
| 83 |
|
| 84 |
def validate_scalar(self, chunk): |
| 85 |
if chunk.contents == "": |
| 86 |
return [] |
| 87 |
return [ |
| 88 |
self._item_validator.validate_scalar( |
| 89 |
chunk.textslice(positions[0], positions[1]) |
| 90 |
) |
| 91 |
for positions in utils.comma_separated_positions(chunk.contents) |
| 92 |
] |
| 93 |
|
| 94 |
def to_yaml(self, data): |
| 95 |
if isinstance(data, list): |
| 96 |
return ", ".join([self._item_validator.to_yaml(item) for item in data]) |
| 97 |
elif utils.is_string(data): |
| 98 |
for item in data.split(","): |
| 99 |
self._item_validator.to_yaml(item) |
| 100 |
return data |
| 101 |
else: |
| 102 |
raise YAMLSerializationError( |
| 103 |
"expected string or list, got '{}' of type '{}'".format( |
| 104 |
data, type(data).__name__ |
| 105 |
) |
| 106 |
) |
| 107 |
|
| 108 |
def __repr__(self): |
| 109 |
return "CommaSeparated({0})".format(self._item_validator) |
| 110 |
|
| 111 |
|
| 112 |
class Regex(ScalarValidator): |
| 113 |
def __init__(self, regular_expression): |
| 114 |
""" |
| 115 |
Give regular expression, e.g. u'[0-9]' |
| 116 |
""" |
| 117 |
self._regex = regular_expression |
| 118 |
# re.fullmatch is only available in Python 3.4+ so append "$" if needed |
| 119 |
if not regular_expression.endswith(r"$"): |
| 120 |
regular_expression += r"$" |
| 121 |
self._fullmatch = re.compile(regular_expression).match |
| 122 |
self._matching_message = "when expecting string matching {0}".format( |
| 123 |
self._regex |
| 124 |
) |
| 125 |
|
| 126 |
def validate_scalar(self, chunk): |
| 127 |
if self._fullmatch(chunk.contents) is None: |
| 128 |
chunk.expecting_but_found( |
| 129 |
self._matching_message, "found non-matching string" |
| 130 |
) |
| 131 |
return chunk.contents |
| 132 |
|
| 133 |
def to_yaml(self, data): |
| 134 |
self.should_be_string(data, self._matching_message) |
| 135 |
if self._fullmatch(data) is None: |
| 136 |
raise YAMLSerializationError( |
| 137 |
"{} found '{}'".format(self._matching_message, data) |
| 138 |
) |
| 139 |
return data |
| 140 |
|
| 141 |
|
| 142 |
class Email(Regex): |
| 143 |
def __init__(self): |
| 144 |
super(Email, self).__init__(constants.REGEXES["email"]) |
| 145 |
self._matching_message = "when expecting an email address" |
| 146 |
|
| 147 |
|
| 148 |
class Url(ScalarValidator): |
| 149 |
def __is_absolute_url(self, raw): |
| 150 |
try: |
| 151 |
ret = urllib.parse.urlparse(raw) |
| 152 |
return ret.scheme != "" and ret.netloc != "" |
| 153 |
except ValueError: |
| 154 |
return False |
| 155 |
|
| 156 |
def validate_scalar(self, chunk): |
| 157 |
if not self.__is_absolute_url(chunk.contents): |
| 158 |
chunk.expecting_but_found("when expecting a URL") |
| 159 |
return chunk.contents |
| 160 |
|
| 161 |
def to_yaml(self, data): |
| 162 |
self.should_be_string(data, "expected a URL,") |
| 163 |
if not self.__is_absolute_url(data): |
| 164 |
raise YAMLSerializationError("'{}' is not a URL".format(data)) |
| 165 |
return data |
| 166 |
|
| 167 |
|
| 168 |
class Str(ScalarValidator): |
| 169 |
def validate_scalar(self, chunk): |
| 170 |
return chunk.contents |
| 171 |
|
| 172 |
def to_yaml(self, data): |
| 173 |
if not utils.is_string(data): |
| 174 |
raise YAMLSerializationError("'{}' is not a string".format(data)) |
| 175 |
if "\n" in data: |
| 176 |
return PreservedScalarString(data) |
| 177 |
return data |
| 178 |
|
| 179 |
|
| 180 |
class Int(ScalarValidator): |
| 181 |
def validate_scalar(self, chunk): |
| 182 |
val = chunk.contents |
| 183 |
if not utils.is_integer(val): |
| 184 |
chunk.expecting_but_found("when expecting an integer") |
| 185 |
else: |
| 186 |
# Only Python 3.6+ supports underscores in numeric literals |
| 187 |
return int(val.replace("_", "")) |
| 188 |
|
| 189 |
def to_yaml(self, data): |
| 190 |
if utils.is_string(data) or isinstance(data, int): |
| 191 |
if utils.is_integer(str(data)): |
| 192 |
return str(data) |
| 193 |
raise YAMLSerializationError("'{}' not an integer.".format(data)) |
| 194 |
|
| 195 |
|
| 196 |
class HexInt(ScalarValidator): |
| 197 |
def validate_scalar(self, chunk): |
| 198 |
val = chunk.contents |
| 199 |
if not utils.is_hexadecimal(val): |
| 200 |
chunk.expecting_but_found("when expecting a hexadecimal integer") |
| 201 |
return int(val, 16) |
| 202 |
|
| 203 |
def to_yaml(self, data): |
| 204 |
if utils.is_hexadecimal(data): |
| 205 |
if isinstance(data, int): |
| 206 |
return hex(data) |
| 207 |
else: |
| 208 |
return data |
| 209 |
raise YAMLSerializationError("'{}' not a hexademial integer.".format(data)) |
| 210 |
|
| 211 |
|
| 212 |
class Bool(ScalarValidator): |
| 213 |
def validate_scalar(self, chunk): |
| 214 |
val = chunk.contents |
| 215 |
if unicode(val).lower() not in constants.BOOL_VALUES: |
| 216 |
chunk.expecting_but_found( |
| 217 |
"""when expecting a boolean value (one of "{0}")""".format( |
| 218 |
'", "'.join(constants.BOOL_VALUES) |
| 219 |
) |
| 220 |
) |
| 221 |
else: |
| 222 |
if val.lower() in constants.TRUE_VALUES: |
| 223 |
return True |
| 224 |
else: |
| 225 |
return False |
| 226 |
|
| 227 |
def to_yaml(self, data): |
| 228 |
if not isinstance(data, bool): |
| 229 |
if str(data).lower() in constants.BOOL_VALUES: |
| 230 |
return data |
| 231 |
else: |
| 232 |
raise YAMLSerializationError("Not a boolean") |
| 233 |
else: |
| 234 |
return "yes" if data else "no" |
| 235 |
|
| 236 |
|
| 237 |
class Float(ScalarValidator): |
| 238 |
def validate_scalar(self, chunk): |
| 239 |
val = chunk.contents |
| 240 |
if utils.is_infinity(val) or utils.is_not_a_number(val): |
| 241 |
val = val.replace(".", "") |
| 242 |
elif not utils.is_decimal(val): |
| 243 |
chunk.expecting_but_found("when expecting a float") |
| 244 |
# Only Python 3.6+ supports underscores in numeric literals |
| 245 |
return float(val.replace("_", "")) |
| 246 |
|
| 247 |
def to_yaml(self, data): |
| 248 |
if utils.has_number_type(data): |
| 249 |
if math.isnan(data): |
| 250 |
return "nan" |
| 251 |
if data == float("inf"): |
| 252 |
return "inf" |
| 253 |
if data == float("-inf"): |
| 254 |
return "-inf" |
| 255 |
return str(data) |
| 256 |
if utils.is_string(data) and utils.is_decimal(data): |
| 257 |
return data |
| 258 |
raise YAMLSerializationError("when expecting a float, got '{}'".format(data)) |
| 259 |
|
| 260 |
|
| 261 |
class Decimal(ScalarValidator): |
| 262 |
def validate_scalar(self, chunk): |
| 263 |
val = chunk.contents |
| 264 |
if not utils.is_decimal(val): |
| 265 |
chunk.expecting_but_found("when expecting a decimal") |
| 266 |
else: |
| 267 |
return decimal.Decimal(val) |
| 268 |
|
| 269 |
|
| 270 |
class Datetime(ScalarValidator): |
| 271 |
def validate_scalar(self, chunk): |
| 272 |
try: |
| 273 |
return dateutil.parser.parse(chunk.contents) |
| 274 |
except ValueError: |
| 275 |
chunk.expecting_but_found("when expecting a datetime") |
| 276 |
|
| 277 |
def to_yaml(self, data): |
| 278 |
if isinstance(data, datetime): |
| 279 |
return data.isoformat() |
| 280 |
if utils.is_string(data): |
| 281 |
try: |
| 282 |
dateutil.parser.parse(data) |
| 283 |
return data |
| 284 |
except ValueError: |
| 285 |
raise YAMLSerializationError( |
| 286 |
"expected a datetime, got '{}'".format(data) |
| 287 |
) |
| 288 |
raise YAMLSerializationError( |
| 289 |
"expected a datetime, got '{}' of type '{}'".format( |
| 290 |
data, type(data).__name__ |
| 291 |
) |
| 292 |
) |
| 293 |
|
| 294 |
|
| 295 |
class NullNone(ScalarValidator): |
| 296 |
def validate_scalar(self, chunk): |
| 297 |
val = chunk.contents |
| 298 |
if val.lower() != "null": |
| 299 |
chunk.expecting_but_found( |
| 300 |
"when expecting a 'null', got '{}' instead.".format(val) |
| 301 |
) |
| 302 |
else: |
| 303 |
return self.empty(chunk) |
| 304 |
|
| 305 |
def empty(self, chunk): |
| 306 |
return None |
| 307 |
|
| 308 |
def to_yaml(self, data): |
| 309 |
if data is None: |
| 310 |
return "null" |
| 311 |
raise YAMLSerializationError("expected None, got '{}'") |
| 312 |
|
| 313 |
|
| 314 |
class EmptyNone(ScalarValidator): |
| 315 |
def validate_scalar(self, chunk): |
| 316 |
val = chunk.contents |
| 317 |
if val != "": |
| 318 |
chunk.expecting_but_found("when expecting an empty value") |
| 319 |
else: |
| 320 |
return self.empty(chunk) |
| 321 |
|
| 322 |
def empty(self, chunk): |
| 323 |
return None |
| 324 |
|
| 325 |
def to_yaml(self, data): |
| 326 |
if data is None: |
| 327 |
return "" |
| 328 |
raise YAMLSerializationError("expected None, got '{}'") |
| 329 |
|
| 330 |
|
| 331 |
class EmptyDict(EmptyNone): |
| 332 |
def empty(self, chunk): |
| 333 |
return {} |
| 334 |
|
| 335 |
def to_yaml(self, data): |
| 336 |
if data == {}: |
| 337 |
return "" |
| 338 |
raise YAMLSerializationError("Not an empty dict") |
| 339 |
|
| 340 |
|
| 341 |
class EmptyList(EmptyNone): |
| 342 |
def empty(self, chunk): |
| 343 |
return [] |
| 344 |
|
| 345 |
def to_yaml(self, data): |
| 346 |
if data == []: |
| 347 |
return "" |
| 348 |
raise YAMLSerializationError("expected empty list, got '{}'") |