1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436
|
# ------------------------------------------------------------------------------------------------------
# Copyright (c) 2013-2025, Nucleic Development Team.
#
# Distributed under the terms of the Modified BSD License.
#
# The full license is in the file LICENSE, distributed with this software.
# ------------------------------------------------------------------------------------------------------
"""Tests for member validation handlers:
no_op_handler
bool_handler
int_handler
int_promote_handler
long_handler
long_promote_handler
float_handler
float_promote_handler
str_handler
str_promote_handler
unicode_handler
unicode_promote_handler
tuple_handler
fixed_tuple_handler
list_handler
container_list_handler
set_handler
dict_handler
instance_handler
typed_handler
subclass_handler
enum_handler
callable_handler
float_range_handler
range_handler
coerced_handler
delegate_handler: not tested here
object_method_old_new_handler: used when defining validate on Atom subclass
object_method_name_old_new_handler: unused as far as I can tell
member_method_object_old_new_handler: used in ForwardType/Instance/Subclass
"""
import sys
from typing import List as TList, Optional, Sequence, Set as TSet, Union
import pytest
from atom.api import (
Atom,
Bool,
Bytes,
Callable,
CAtom,
Coerced,
Constant,
ContainerList,
Delegator,
Dict,
Enum,
Event,
FixedTuple,
Float,
FloatRange,
ForwardInstance,
ForwardSubclass,
ForwardTyped,
Instance,
Int,
List,
Range,
ReadOnly,
Set,
Str,
Subclass,
Tuple,
Typed,
Validate,
Value,
)
def test_no_op_validation():
"""Test the no-op handler."""
a = Atom()
m = Value()
m.set_validate_mode(Validate.NoOp, None)
for value in (1, 1.0, "", [], {}):
assert m.do_validate(a, None, value) == value
def c(x: object) -> int:
return int(str(x), 2)
@pytest.mark.parametrize(
"member, set_values, values, raising_values",
[
(Value(), ["a", 1, None], ["a", 1, None], []),
(ReadOnly(int), [1], [1], [1.0]),
(Bool(), [True, False], [True, False], "r"),
(Int(strict=True), [1], [1], [1.0]),
(Int(strict=False), [1, 1.0, (1)], 3 * [1], ["a"]),
(Range(0, 2), [0, 2], [0, 2], [-1, 3, ""]),
(Range(2, 0), [0, 2], [0, 2], [-1, 3]),
(Range(0), [0, 3], [0, 3], [-1]),
(Range(high=2), [-1, 2], [-1, 2], [3]),
(
Range(sys.maxsize, sys.maxsize + 2),
[sys.maxsize, sys.maxsize + 2],
[sys.maxsize, sys.maxsize + 2],
[sys.maxsize - 1, sys.maxsize + 3],
),
(Float(), [1, (1), 1.1], [1.0, 1.0, 1.1], [""]),
(Float(strict=True), [1.1], [1.1], [1]),
(FloatRange(0.0, 0.5), [0.0, 0.5], [0.0, 0.5], [-0.1, 0.6]),
(FloatRange(0.5, 0.0), [0.0, 0.5], [0.0, 0.5], [-0.1, 0.6]),
(FloatRange(0.0), [0.0, 0.6], [0.0, 0.6], [-0.1, ""]),
(FloatRange(high=0.5), [-0.3, 0.5], [-0.3, 0.5], [0.6]),
(FloatRange(1.0, 10.0, strict=True), [1.0, 3.7], [1.0, 3.7], [2, 4, 0, -11]),
(FloatRange(low=0, strict=False), [1, 25], [1.0, 25.0], [-1, -10.0]),
(Bytes(strict=False), [b"a", "a"], [b"a"] * 2, [1]),
(Bytes(), [b"a"], [b"a"], ["a"]),
(Str(strict=False), [b"a", "a"], ["a"] * 2, [1]),
(Str(), ["a"], ["a"], [b"a"]),
(Enum(1, 2, "a"), [1, 2, "a"], [1, 2, "a"], [3]),
(Callable(), [int, None], [int, None], [1]),
# 3.9 subs and 3.10 union tests in test_typing_utils are sufficient
(Coerced(set), [{1}, [1], (1,)], [{1}] * 3, [1]),
(Coerced(int, coercer=c), ["101"], [5], []),
(Coerced((int, float), coercer=c), ["101"], [5], []),
(Coerced(int, coercer=lambda x: []), [], [], [""]), # type: ignore
(Coerced(TSet[int]), [{1}, [1], (1,)], [{1}] * 3, [1]),
(Tuple(), [(1,)], [(1,)], [[1]]),
(Tuple(Int()), [(1,)], [(1,)], [(1.0,)]),
(Tuple(int), [(1,)], [(1,)], [(1.0,), (None,)]),
(Tuple(TSet[int]), [({1},)], [({1},)], [(1.0,), (None,)]),
(Tuple(Optional[int]), [(1, None)], [(1, None)], [("",)]),
(FixedTuple(Int()), [(1,)], [(1,)], [(None,), (1, 2)]),
(FixedTuple(Int(), Str()), [(1, "")], [(1, "")], [(None,), (1, 2)]),
(FixedTuple(int), [(1,)], [(1,)], [(None,), (1, 2)]),
(FixedTuple(TSet[int]), [({1},)], [({1},)], [(None,), (1, 2)]),
(List(), [[1]], [[1]], [(1,)]),
(List(Int()), [[1]], [[1]], [[1.0]]),
(List(float), [[1.0]], [[1.0]], [[1], [None]]),
(List((int, float)), [[1, 1.0]], [[1, 1.0]], [[""]]),
(List(TSet[int]), [[{1}]], [[{1}]], [[1], [None]]),
(List(Optional[int]), [[1, None]], [[1, None]], [[""]]),
(ContainerList(), [[1]], [[1]], [(1,)]),
(ContainerList(Int()), [[1]], [[1]], [[1.0]]),
(ContainerList(float), [[1.0]], [[1.0]], [[1], [None]]),
(ContainerList((int, float)), [[1, 1.0]], [[1, 1.0]], [[""]]),
(ContainerList(TSet[int]), [[{1}]], [[{1}]], [[1], [None]]),
(ContainerList(Optional[int]), [[1, None]], [[1, None]], [[""]]),
(Set(), [{1}], [{1}], [()]),
(Set(Int()), [{1}], [{1}], [{""}]),
(Set(item=Int()), [{1}], [{1}], [{""}]),
(Set(int), [{1}], [{1}], [{""}, {None}]),
(Set(Optional[int]), [{1, None}], [{1, None}], [[1]]),
(Dict(), [{1: 2}], [{1: 2}], [()]),
(Dict(Int()), [{1: 2}], [{1: 2}], [{"": 2}]),
(Dict(value=Int()), [{1: 2}], [{1: 2}], [{2: ""}]),
(Dict(int, int), [{1: 2}], [{1: 2}], [{"": 2}, {2: ""}, {None: 2}, {2: None}]),
(Dict(Optional[int]), [{None: 1, 1: 2}], [{None: 1, 1: 2}], [[1]]),
(Instance((int, float)), [1, 2.0, None], [1, 2.0, None], [""]),
(Instance((int, float), ()), [1, 2.0], [1, 2.0], ["", None]),
(
Instance((int, float), (), optional=True),
[1, 2.0, None],
[1, 2.0, None],
[""],
),
(
Instance(Optional[Union[int, float]], ()),
[1, 2.0, None],
[1, 2.0, None],
[""],
),
(Instance((int, float), optional=False), [1, 2.0], [1, 2.0], [None, ""]),
(Instance(TList[int], optional=False), [[1]], [[1]], [None, ""]),
(Instance(Sequence[int], optional=False), [[1]], [[1]], [None, 1]),
(ForwardInstance(lambda: (int, float)), [1, 2.0, None], [1, 2.0, None], [""]),
(ForwardInstance(lambda: (int, float), ()), [1, 2.0], [1, 2.0], ["", None]),
(
ForwardInstance(lambda: (int, float), (), optional=True),
[1, 2.0, None],
[1, 2.0, None],
[""],
),
(
ForwardInstance(lambda: Optional[Union[int, float]], ()),
[1, 2.0, None],
[1, 2.0, None],
[""],
),
(
ForwardInstance(lambda: (int, float), optional=False),
[1, 2.0],
[1, 2.0],
[None, ""],
),
(Typed(float), [1.0, None], [1.0, None], [1]),
(Typed(float, ()), [1.0], [1.0], [1, None]),
(Typed(float, (), optional=True), [1.0, None], [1.0, None], [1]),
(Typed(Optional[float], ()), [1.0, None], [1.0, None], [1]),
(Typed(float, optional=False), [1.0], [1.0], [1, None]),
(ForwardTyped(lambda: float), [1.0, None], [1.0, None], [1]),
(ForwardTyped(lambda: float, ()), [1.0], [1.0], [1, None]),
(ForwardTyped(lambda: float, (), optional=True), [1.0, None], [1.0, None], [1]),
(ForwardTyped(lambda: float, optional=False), [1.0], [1.0], [1, None]),
(Subclass(CAtom), [Atom], [Atom], [int, 1]),
(Subclass((CAtom, float)), [Atom], [Atom], [int, 1]),
(ForwardSubclass(lambda: CAtom), [Atom], [Atom], [int]),
],
)
def test_validation_modes(member, set_values, values, raising_values):
"""Test the validation modes."""
class MemberTest(Atom):
m = member
tester = MemberTest()
for sv, v in zip(set_values, values):
tester.m = sv
assert tester.m == v
for rv in raising_values:
if isinstance(member, Int) and isinstance(rv, float) and rv > 2**32:
error_type = OverflowError
elif isinstance(member, Enum):
error_type = ValueError
elif isinstance(member, (Range, FloatRange)):
error_type = (ValueError, TypeError)
else:
error_type = TypeError
with pytest.raises(error_type):
tester.m = rv
@pytest.mark.parametrize(
"members, value",
[
((List(Int()), List()), [1]),
((ContainerList(Int()), ContainerList()), [1]),
((Dict(Int(), Int()), Dict()), {1: 1}),
],
)
def test_validating_container_subclasses(members, value):
"""Ensure that we can pass atom containers to members."""
class MemberTest(Atom):
m1 = members[0]
m2 = members[1]
tester = MemberTest()
tester.m1 = value
tester.m2 = tester.m1
@pytest.mark.parametrize(
"member, mode, arg, msg",
[
(List(), "List", 1, "Member or None"),
(Tuple(), "Tuple", 1, "Member or None"),
(FixedTuple(int), "FixedTuple", 1, "tuple of types or Members"),
(ContainerList(), "ContainerList", 1, "Member or None"),
(Set(), "Set", 1, "Member or None"),
(Dict(), "Dict", 1, "2-tuple of Member or None"),
(Dict(), "Dict", (), "2-tuple of Member or None"),
(Dict(), "Dict", (1, None), "2-tuple of Member or None"),
(Dict(), "Dict", (None, 1), "2-tuple of Member or None"),
(Typed(int), "Typed", 1, "type"),
(Enum(1, 2), "Enum", 1, "sequence"),
(FloatRange(), "FloatRange", 1, "2-tuple of float or None"),
(FloatRange(), "FloatRange", (), "2-tuple of float or None"),
(FloatRange(), "FloatRange", ("", None), "2-tuple of float or None"),
(FloatRange(), "FloatRange", (0, 0), "2-tuple of float or None"),
(FloatRange(), "FloatRangePromote", (0.0, ""), "2-tuple of float or None"),
(Range(), "Range", 1, "2-tuple of int or None"),
(Range(), "Range", (), "2-tuple of int or None"),
(Range(), "Range", ("", None), "2-tuple of int or None"),
(Range(), "Range", (None, ""), "2-tuple of int or None"),
(Coerced(int), "Coerced", 1, "2-tuple of (type, callable)"),
(Coerced(int), "Coerced", (), "2-tuple of (type, callable)"),
(Coerced(int), "Coerced", (int, 1), "2-tuple of (type, callable)"),
(Instance(int), "Instance", 1, "type or tuple of types"),
(Instance(int), "Instance", (int, 1), "type or tuple of types"),
(Subclass(int), "Instance", 1, "type or tuple of types"),
(Subclass(int), "Instance", (int, 1), "type or tuple of types"),
(Delegator(Int()), "Delegate", 1, "Member"),
],
)
def test_handling_wrong_context(member, mode, arg, msg):
"""Test handling wrong args to members leading to wrong validate behaviors."""
with pytest.raises(TypeError) as excinfo:
member.set_validate_mode(getattr(Validate, mode), arg)
assert msg in excinfo.exconly()
def test_event_validation():
"""Test validating the payload of an Event."""
class EventValidationTest(Atom):
ev_member = Event(Int())
ev_type = Event(int)
evt = EventValidationTest()
evt.ev_member = 1
evt.ev_type = 1
with pytest.raises(TypeError):
evt.ev_member = 1.0
with pytest.raises(TypeError):
evt.ev_type = 1.0
def test_constant_validation():
"""Test validating a constant."""
class A(Atom):
c = Constant(kind=int)
def _default_c(self):
return id(self)
A().c
class B(A):
def _default_c(self):
return str(super()._default_c())
with pytest.raises(TypeError):
B().c
def no_atom():
"""Set a member with a no-op validator."""
class NoOpValAtom(Atom):
v = Value()
v.set_validate_mode(Validate.NoOp, None)
return NoOpValAtom()
def om_on_atom():
"""Use an object method to customize validate."""
class ValidatorTest(Atom):
v = Value(0)
def _validate_v(self, old, new):
if not isinstance(new, int):
raise TypeError()
if old is not None and new != old + 1:
raise ValueError()
return new
return ValidatorTest()
def om_non_atom():
"""Use an object method taking the member name to customize validate."""
class ValidatorTest(Atom):
v = Value(0)
v.set_validate_mode(Validate.ObjectMethod_NameOldNew, "validate_v")
def validate_v(self, name, old, new):
if not isinstance(new, int):
raise TypeError()
if old is not None and new != old + 1:
raise ValueError()
return new
return ValidatorTest()
def mm_oon_atom():
"""Use a member method to customize validate."""
class CustomValue(Value):
def __init__(self):
super(CustomValue, self).__init__(0)
self.set_validate_mode(Validate.MemberMethod_ObjectOldNew, "validate")
def validate(self, object, old, new):
if not isinstance(new, int):
raise TypeError()
if old is not None and new != old + 1:
raise ValueError()
return new
class ValidatorTest(Atom):
v = CustomValue()
return ValidatorTest()
@pytest.mark.parametrize(
"mode, factory",
[
("NoOp", no_atom),
("ObjectMethod_OldNew", om_on_atom),
("ObjectMethod_NameOldNew", om_non_atom),
("MemberMethod_ObjectOldNew", mm_oon_atom),
],
)
def test_custom_validate(mode, factory):
"""Test specifying a specific validator in the Atom and using do_validate."""
v = factory()
assert type(v).v.validate_mode[0] == getattr(Validate, mode)
assert v.v == (0 if mode != "NoOp" else None)
if mode == "NoOp":
return
v.v = 1
assert v.v == 1
with pytest.raises(TypeError):
v.v = None
assert v.v == 1
with pytest.raises(ValueError):
v.v = 4
v_member = type(factory()).v
with pytest.raises(TypeError):
v_member.do_validate(v, 1, None)
assert v.v == 1
with pytest.raises(ValueError):
v_member.do_full_validate(v, 1, 4)
with pytest.raises(TypeError) as excinfo:
type(v).v.set_validate_mode(getattr(Validate, mode), 1)
assert "str" in excinfo.exconly()
|