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 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809
|
import datetime
import math
import re
from typing import Dict, List, Union, Annotated
import pytest
import msgspec
from msgspec import Meta
@pytest.fixture(params=["json", "msgpack"])
def proto(request):
if request.param == "json":
return msgspec.json
elif request.param == "msgpack":
return msgspec.msgpack
FIELDS = {
"gt": 0,
"ge": 0,
"lt": 10,
"le": 10,
"multiple_of": 1,
"pattern": "^foo$",
"min_length": 0,
"max_length": 10,
"tz": True,
"title": "example title",
"description": "example description",
"examples": ["example 1", "example 2"],
"extra_json_schema": {"foo": "bar"},
"extra": {"fizz": "buzz"},
}
def assert_eq(a, b):
assert a == b
assert not a != b
def assert_ne(a, b):
assert a != b
assert not a == b
class TestMetaObject:
def test_init_nokwargs(self):
c = Meta()
for f in FIELDS:
assert getattr(c, f) is None
@pytest.mark.parametrize("field", FIELDS)
def test_init_explicit_none(self, field):
c = Meta(**{field: None})
for f in FIELDS:
assert getattr(c, f) is None
@pytest.mark.parametrize("field", FIELDS)
def test_init(self, field):
c = Meta(**{field: FIELDS[field]})
for f in FIELDS:
sol = FIELDS[field] if f == field else None
assert getattr(c, f) == sol
def test_repr_empty(self):
assert repr(Meta()) == "msgspec.Meta()"
for field in FIELDS:
c = Meta(**{field: None})
assert repr(c) == "msgspec.Meta()"
def test_repr_error(self):
class Oops:
def __repr__(self):
raise ValueError("Oh no!")
m = Meta(extra_json_schema={"oops": Oops()})
with pytest.raises(ValueError, match="Oh no!"):
repr(m)
@pytest.mark.parametrize("field", FIELDS)
def test_repr_one_field(self, field):
c = Meta(**{field: FIELDS[field]})
assert repr(c) == f"msgspec.Meta({field}={FIELDS[field]!r})"
def test_repr_multiple_fields(self):
c = Meta(gt=0, lt=1)
assert repr(c) == "msgspec.Meta(gt=0, lt=1)"
def test_rich_repr_empty(self):
assert Meta().__rich_repr__() == []
@pytest.mark.parametrize("field", FIELDS)
def test_rich_repr_one_field(self, field):
m = Meta(**{field: FIELDS[field]})
assert m.__rich_repr__() == [(field, FIELDS[field])]
def test_rich_repr_multiple_fields(self):
m = Meta(gt=0, lt=1)
assert m.__rich_repr__() == [("gt", 0), ("lt", 1)]
def test_equality(self):
assert_eq(Meta(), Meta())
assert_ne(Meta(), None)
with pytest.raises(TypeError):
Meta() > Meta()
with pytest.raises(TypeError):
Meta() > None
def test_hash(self):
def samples():
return [
Meta(),
Meta(ge=0),
Meta(ge=1, le=2),
Meta(ge=1, le=2, examples=["stuff"]),
]
lk = {k: k for k in samples()}
for key in samples():
assert lk[key] == key
@pytest.mark.parametrize("field", FIELDS)
def test_field_equality(self, field):
val = FIELDS[field]
if isinstance(val, dict):
val2 = {}
elif isinstance(val, list):
val2 = []
elif isinstance(val, bool):
val2 = not val
elif isinstance(val, int):
val2 = val + 25
else:
val2 = "foobar"
c = Meta(**{field: val})
c2 = Meta(**{field: val})
c3 = Meta(**{field: val2})
c4 = Meta()
assert_eq(c, c)
assert_eq(c, c2)
assert_ne(c, c3)
assert_ne(c, c4)
assert_ne(c4, c)
@pytest.mark.parametrize("field", ["gt", "ge", "lt", "le", "multiple_of"])
def test_numeric_fields(self, field):
Meta(**{field: 1})
Meta(**{field: 2.5})
with pytest.raises(
TypeError, match=f"`{field}` must be an int or float, got str"
):
Meta(**{field: "bad"})
with pytest.raises(ValueError, match=f"`{field}` must be finite"):
Meta(**{field: float("inf")})
@pytest.mark.parametrize("val", [0, 0.0])
def test_multiple_of_bounds(self, val):
with pytest.raises(ValueError, match=r"`multiple_of` must be > 0"):
Meta(multiple_of=val)
@pytest.mark.parametrize("field", ["min_length", "max_length"])
def test_nonnegative_integer_fields(self, field):
Meta(**{field: 0})
Meta(**{field: 10})
with pytest.raises(TypeError, match=f"`{field}` must be an int, got float"):
Meta(**{field: 1.5})
with pytest.raises(ValueError, match=f"{field}` must be >= 0, got -10"):
Meta(**{field: -10})
@pytest.mark.parametrize("field", ["pattern", "title", "description"])
def test_string_fields(self, field):
Meta(**{field: "good"})
with pytest.raises(TypeError, match=f"`{field}` must be a str, got bytes"):
Meta(**{field: b"bad"})
@pytest.mark.parametrize("field", ["tz"])
def test_bool_fields(self, field):
Meta(**{field: True})
Meta(**{field: False})
with pytest.raises(TypeError, match=f"`{field}` must be a bool, got float"):
Meta(**{field: 1.5})
@pytest.mark.parametrize("field", ["examples"])
def test_list_fields(self, field):
Meta(**{field: ["good", "stuff"]})
with pytest.raises(TypeError, match=f"`{field}` must be a list, got str"):
Meta(**{field: "bad"})
@pytest.mark.parametrize("field", ["extra_json_schema", "extra"])
def test_dict_fields(self, field):
Meta(**{field: {"good": "stuff"}})
with pytest.raises(TypeError, match=f"`{field}` must be a dict, got str"):
Meta(**{field: "bad"})
def test_invalid_pattern_errors(self):
with pytest.raises(re.error):
Meta(pattern="[abc")
def test_conflicting_bounds_errors(self):
with pytest.raises(ValueError, match="both `gt` and `ge`"):
Meta(gt=0, ge=1)
with pytest.raises(ValueError, match="both `lt` and `le`"):
Meta(lt=0, le=1)
def test_mixing_numeric_and_nonnumeric_constraints_errors(self):
with pytest.raises(ValueError, match="Cannot mix numeric constraints"):
Meta(gt=0, pattern="foo")
class TestInvalidConstraintAnnotations:
"""Constraint validity is applied in two places:
- Type checks on constraint values in the `Meta` constructor
- Type checks on type & constraint annotations in Decoder constructors
The tests here check the latter.
"""
@pytest.mark.parametrize("name", ["ge", "gt", "le", "lt", "multiple_of"])
def test_invalid_numeric_constraints(self, name):
with pytest.raises(TypeError, match=f"Can only set `{name}` on a numeric type"):
msgspec.json.Decoder(Annotated[str, Meta(**{name: 1})])
def test_invalid_pattern_constraint(self):
with pytest.raises(TypeError, match="Can only set `pattern` on a str type"):
msgspec.json.Decoder(Annotated[int, Meta(pattern="ok")])
@pytest.mark.parametrize("name", ["min_length", "max_length"])
def test_invalid_length_constraint(self, name):
with pytest.raises(
TypeError,
match=f"Can only set `{name}` on a str, bytes, or collection type",
):
msgspec.json.Decoder(Annotated[int, Meta(**{name: 1})])
def test_invalid_tz_constraint(self):
with pytest.raises(
TypeError,
match="Can only set `tz` on a datetime or time type",
):
msgspec.json.Decoder(Annotated[int, Meta(tz=True)])
@pytest.mark.parametrize(
"name, val",
[("ge", 2**63), ("gt", 2**63 - 1), ("le", 2**63), ("lt", -(2**63))],
)
def test_invalid_integer_bounds(self, name, val):
with pytest.raises(ValueError) as rec:
msgspec.json.Decoder(Annotated[int, Meta(**{name: val})])
assert name in str(rec.value)
assert "not supported" in str(rec.value)
def test_invalid_multiple_meta_annotations_conflict(self):
with pytest.raises(TypeError, match="Multiple `Meta` annotations"):
msgspec.json.Decoder(Annotated[int, Meta(ge=1), Meta(ge=2)])
def test_invalid_gt_and_ge_conflict(self):
with pytest.raises(TypeError, match="Cannot set both `gt` and `ge`"):
msgspec.json.Decoder(Annotated[int, Meta(gt=1), Meta(ge=2)])
def test_invalid_lt_and_le_conflict(self):
with pytest.raises(TypeError, match="Cannot set both `lt` and `le`"):
msgspec.json.Decoder(Annotated[int, Meta(lt=2), Meta(le=1)])
class TestIntConstraints:
@pytest.mark.parametrize(
"name, bound, good, bad",
[
("ge", -1, [-1, 2**63, 2**65], [-(2**64), -2]),
("gt", -1, [0, 2**63, 2**65], [-(2**64), -1]),
("le", -1, [-(2**64), -1], [0, 2**63, 2**65]),
("lt", -1, [-(2**64), -2], [-1, 2**63, 2**65]),
],
)
def test_bounds(self, proto, name, bound, good, bad):
if proto is msgspec.msgpack:
# msgpack only supports int64/uint64 values
good = [i for i in good if -(2**63) - 1 <= i <= 2**64]
bad = [i for i in bad if -(2**63) - 1 <= i <= 2**64]
class Ex(msgspec.Struct):
x: Annotated[int, Meta(**{name: bound})]
dec = proto.Decoder(Ex)
for x in good:
assert dec.decode(proto.encode(Ex(x))).x == x
op = ">=" if name.startswith("g") else "<="
offset = {"lt": -1, "gt": 1}.get(name, 0)
err_msg = rf"Expected `int` {op} {bound + offset} - at `\$.x`"
for x in bad:
with pytest.raises(msgspec.ValidationError, match=err_msg):
dec.decode(proto.encode(Ex(x)))
def test_multiple_of(self, proto):
good = [-(2**64), -2, 0, 2, 40, 2**63 + 2, 2**65]
bad = [1, -1, 2**63 + 1, 2**65 + 1]
if proto is msgspec.msgpack:
# msgpack only supports int64/uint64 values
good = [i for i in good if -(2**63) - 1 <= i <= 2**64]
bad = [i for i in bad if -(2**63) - 1 <= i <= 2**64]
class Ex(msgspec.Struct):
x: Annotated[int, Meta(multiple_of=2)]
dec = proto.Decoder(Ex)
for x in good:
assert dec.decode(proto.encode(Ex(x))).x == x
err_msg = r"Expected `int` that's a multiple of 2 - at `\$.x`"
for x in bad:
with pytest.raises(msgspec.ValidationError, match=err_msg):
dec.decode(proto.encode(Ex(x)))
@pytest.mark.parametrize(
"meta, good, bad",
[
(Meta(ge=0, le=10, multiple_of=2), [0, 2, 10], [-1, 1, 11]),
(Meta(ge=0, multiple_of=2), [0, 2**63 + 2], [-2, 2**63 + 1]),
(Meta(le=0, multiple_of=2), [0, -(2**63)], [-1, 2, 2**63]),
(Meta(ge=0, le=10), [0, 10], [-1, 11]),
(Meta(gt=0, lt=10), [1, 2, 9], [-1, 0, 10]),
],
)
def test_combinations(self, proto, meta, good, bad):
class Ex(msgspec.Struct):
x: Annotated[int, meta]
dec = proto.Decoder(Ex)
for x in good:
assert dec.decode(proto.encode(Ex(x))).x == x
for x in bad:
with pytest.raises(msgspec.ValidationError):
dec.decode(proto.encode(Ex(x)))
class TestFloatConstraints:
@pytest.mark.parametrize("name", ["ge", "gt", "le", "lt"])
def test_bound_constraint_uint64_valid_for_floats(self, name):
typ = Annotated[float, Meta(**{name: 2**63})]
msgspec.json.Decoder(typ)
def get_bounds_cases(self, name, bound):
def ceilp1(x):
return int(math.ceil(x + 1))
def floorm1(x):
return int(math.floor(x - 1))
if name.startswith("g"):
good_dir = math.inf
good_round = ceilp1
bad_round = floorm1
else:
good_dir = -math.inf
good_round = floorm1
bad_round = ceilp1
if name.endswith("e"):
good = bound
bad = math.nextafter(bound, -good_dir)
else:
good = math.nextafter(bound, good_dir)
bad = bound
good_cases = [good, good_round(good), float(good_round(good))]
bad_cases = [bad, bad_round(bad), float(bad_round(bad))]
op = ">" if name.startswith("g") else "<"
if name.endswith("e"):
op += "="
return good_cases, bad_cases, op
@pytest.mark.parametrize("name", ["ge", "gt", "le", "lt"])
@pytest.mark.parametrize("bound", [1.5, -1.5, 10.0])
def test_bounds(self, proto, name, bound):
class Ex(msgspec.Struct):
x: Annotated[float, Meta(**{name: bound})]
dec = proto.Decoder(Ex)
good, bad, op = self.get_bounds_cases(name, bound)
for x in good:
assert dec.decode(proto.encode(Ex(x))).x == x
err_msg = rf"Expected `float` {op} {bound} - at `\$.x`"
for x in bad:
with pytest.raises(msgspec.ValidationError, match=err_msg):
dec.decode(proto.encode(Ex(x)))
def test_multiple_of(self, proto):
"""multipleOf for floats will always have precisions issues. This check
just ensures that _some_ cases work. See
https://github.com/json-schema-org/json-schema-spec/issues/312 for more
info."""
class Ex(msgspec.Struct):
x: Annotated[float, Meta(multiple_of=0.1)]
dec = proto.Decoder(Ex)
for x in [0, 0.0, 0.1, -0.1, 0.2, -0.2]:
assert dec.decode(proto.encode(Ex(x))).x == x
err_msg = r"Expected `float` that's a multiple of 0.1 - at `\$.x`"
for x in [0.01, -0.15]:
with pytest.raises(msgspec.ValidationError, match=err_msg):
dec.decode(proto.encode(Ex(x)))
@pytest.mark.parametrize(
"meta, good, bad",
[
(Meta(ge=0.0, le=10.0, multiple_of=2.0), [0, 2.0, 10], [-2, 11, 3]),
(Meta(ge=0.0, multiple_of=2.0), [0, 2, 10.0], [-2, 3]),
(Meta(le=10.0, multiple_of=2.0), [-2.0, 10.0], [11.0, 3.0]),
(Meta(ge=0.0, le=10.0), [0.0, 2.0, 10.0], [-1.0, 11.5, 11]),
],
)
def test_combinations(self, proto, meta, good, bad):
class Ex(msgspec.Struct):
x: Annotated[float, meta]
dec = proto.Decoder(Ex)
for x in good:
assert dec.decode(proto.encode(Ex(x))).x == x
for x in bad:
with pytest.raises(msgspec.ValidationError):
assert dec.decode(proto.encode(Ex(x)))
class TestStrConstraints:
def test_min_length(self, proto):
class Ex(msgspec.Struct):
x: Annotated[str, Meta(min_length=2)]
dec = proto.Decoder(Ex)
for x in ["xx", "xxx", "𝄞x"]:
assert dec.decode(proto.encode(Ex(x))).x == x
err_msg = r"Expected `str` of length >= 2 - at `\$.x`"
for x in ["x", "𝄞", ""]:
with pytest.raises(msgspec.ValidationError, match=err_msg):
dec.decode(proto.encode(Ex(x)))
def test_max_length(self, proto):
class Ex(msgspec.Struct):
x: Annotated[str, Meta(max_length=2)]
dec = proto.Decoder(Ex)
for x in ["", "xx", "𝄞x"]:
assert dec.decode(proto.encode(Ex(x))).x == x
err_msg = r"Expected `str` of length <= 2 - at `\$.x`"
for x in ["xxx", "𝄞xx"]:
with pytest.raises(msgspec.ValidationError, match=err_msg):
dec.decode(proto.encode(Ex(x)))
@pytest.mark.parametrize(
"pattern, good, bad",
[
("", ["", "test"], []),
("as", ["as", "ease", "ast", "pass"], ["", "nope"]),
("^pre[123]*$", ["pre1", "pre123"], ["apre1", "pre1two"]),
],
)
def test_pattern(self, proto, pattern, good, bad):
class Ex(msgspec.Struct):
x: Annotated[str, Meta(pattern=pattern)]
dec = proto.Decoder(Ex)
for x in good:
assert dec.decode(proto.encode(Ex(x))).x == x
err_msg = f"Expected `str` matching regex {pattern!r} - at `$.x`"
for x in bad:
with pytest.raises(msgspec.ValidationError) as rec:
dec.decode(proto.encode(Ex(x)))
assert str(rec.value) == err_msg
@pytest.mark.parametrize(
"meta, good, bad",
[
(
Meta(min_length=2, max_length=3, pattern="x"),
["xy", "xyz"],
["x", "yy", "wxyz"],
),
(Meta(min_length=2, max_length=4), ["xx", "xxxx"], ["x", "xxxxx"]),
(Meta(min_length=2, pattern="x"), ["xy", "wxyz"], ["x", "bad"]),
(Meta(max_length=3, pattern="x"), ["xy", "xyz"], ["y", "wxyz"]),
],
)
def test_combinations(self, proto, meta, good, bad):
class Ex(msgspec.Struct):
x: Annotated[str, meta]
dec = proto.Decoder(Ex)
for x in good:
assert dec.decode(proto.encode(Ex(x))).x == x
for x in bad:
with pytest.raises(msgspec.ValidationError):
dec.decode(proto.encode(Ex(x)))
@pytest.mark.parametrize(
"meta, good, bad",
[
(Meta(min_length=2), ["xy", "𝄞xy"], ["", "𝄞"]),
(Meta(pattern="as"), ["as", "pass", "𝄞as"], ["", "nope", "𝄞"]),
],
)
def test_str_constraints_on_dict_keys(self, proto, meta, good, bad):
dec = proto.Decoder(Dict[Annotated[str, meta], int])
for x in good:
assert dec.decode(proto.encode({x: 1})) == {x: 1}
for x in bad:
with pytest.raises(msgspec.ValidationError):
dec.decode(proto.encode({x: 1}))
class TestDateTimeConstraints:
@staticmethod
def roundtrip(proto, cls, aware, as_str):
dt = datetime.datetime.now(datetime.timezone.utc if aware else None)
if as_str:
s = proto.encode(cls(dt.isoformat()))
else:
s = proto.encode(cls(dt))
res = proto.decode(s, type=cls)
assert res.x == dt
@pytest.mark.parametrize("as_str", [True, False])
def test_tz_none(self, proto, as_str):
class Ex(msgspec.Struct):
x: Annotated[datetime.datetime, Meta(tz=None)]
self.roundtrip(proto, Ex, True, as_str)
self.roundtrip(proto, Ex, False, as_str)
@pytest.mark.parametrize("as_str", [True, False])
def test_tz_false(self, proto, as_str):
class Ex(msgspec.Struct):
x: Annotated[datetime.datetime, Meta(tz=False)]
self.roundtrip(proto, Ex, False, as_str)
err_msg = r"Expected `datetime` with no timezone component - at `\$.x`"
with pytest.raises(msgspec.ValidationError, match=err_msg):
self.roundtrip(proto, Ex, True, as_str)
@pytest.mark.parametrize("as_str", [True, False])
def test_tz_true(self, proto, as_str):
class Ex(msgspec.Struct):
x: Annotated[datetime.datetime, Meta(tz=True)]
self.roundtrip(proto, Ex, True, as_str)
err_msg = r"Expected `datetime` with a timezone component - at `\$.x`"
with pytest.raises(msgspec.ValidationError, match=err_msg):
self.roundtrip(proto, Ex, False, as_str)
class TestTimeConstraints:
@staticmethod
def roundtrip(proto, cls, aware, as_str):
dt = datetime.datetime.now(datetime.timezone.utc if aware else None).timetz()
if as_str:
s = proto.encode(cls(dt.isoformat()))
else:
s = proto.encode(cls(dt))
res = proto.decode(s, type=cls)
assert res.x == dt
@pytest.mark.parametrize("as_str", [True, False])
def test_tz_none(self, proto, as_str):
class Ex(msgspec.Struct):
x: Annotated[datetime.time, Meta(tz=None)]
self.roundtrip(proto, Ex, True, as_str)
self.roundtrip(proto, Ex, False, as_str)
@pytest.mark.parametrize("as_str", [True, False])
def test_tz_false(self, proto, as_str):
class Ex(msgspec.Struct):
x: Annotated[datetime.time, Meta(tz=False)]
self.roundtrip(proto, Ex, False, as_str)
err_msg = r"Expected `time` with no timezone component - at `\$.x`"
with pytest.raises(msgspec.ValidationError, match=err_msg):
self.roundtrip(proto, Ex, True, as_str)
@pytest.mark.parametrize("as_str", [True, False])
def test_tz_true(self, proto, as_str):
class Ex(msgspec.Struct):
x: Annotated[datetime.time, Meta(tz=True)]
self.roundtrip(proto, Ex, True, as_str)
err_msg = r"Expected `time` with a timezone component - at `\$.x`"
with pytest.raises(msgspec.ValidationError, match=err_msg):
self.roundtrip(proto, Ex, False, as_str)
class TestBytesConstraints:
@pytest.mark.parametrize("typ", [bytes, bytearray, memoryview])
def test_min_length(self, proto, typ):
class Ex(msgspec.Struct):
x: Annotated[typ, Meta(min_length=2)]
dec = proto.Decoder(Ex)
for x in [b"xx", b"xxx"]:
assert bytes(dec.decode(proto.encode(Ex(x))).x) == x
err_msg = r"Expected `bytes` of length >= 2 - at `\$.x`"
for x in [b"", b"x"]:
with pytest.raises(msgspec.ValidationError, match=err_msg):
dec.decode(proto.encode(Ex(x)))
@pytest.mark.parametrize("typ", [bytes, bytearray, memoryview])
def test_max_length(self, proto, typ):
class Ex(msgspec.Struct):
x: Annotated[typ, Meta(max_length=2)]
dec = proto.Decoder(Ex)
for x in [b"", b"xx"]:
assert bytes(dec.decode(proto.encode(Ex(x))).x) == x
err_msg = r"Expected `bytes` of length <= 2 - at `\$.x`"
with pytest.raises(msgspec.ValidationError, match=err_msg):
dec.decode(proto.encode(Ex(b"xxx")))
@pytest.mark.parametrize("typ", [bytes, bytearray, memoryview])
def test_combinations(self, proto, typ):
class Ex(msgspec.Struct):
x: Annotated[typ, Meta(min_length=2, max_length=4)]
dec = proto.Decoder(Ex)
for x in [b"xx", b"xxx", b"xxxx"]:
assert bytes(dec.decode(proto.encode(Ex(x))).x) == x
for x in [b"x", b"xxxxx"]:
with pytest.raises(msgspec.ValidationError):
dec.decode(proto.encode(Ex(x)))
class TestArrayConstraints:
@pytest.mark.parametrize("typ", [list, tuple, set, frozenset])
def test_min_length(self, proto, typ):
class Ex(msgspec.Struct):
x: Annotated[typ, Meta(min_length=2)]
dec = proto.Decoder(Ex)
for n in [2, 3]:
x = typ(range(n))
assert dec.decode(proto.encode(Ex(x))).x == x
err_msg = r"Expected `array` of length >= 2 - at `\$.x`"
for n in [0, 1]:
x = typ(range(n))
with pytest.raises(msgspec.ValidationError, match=err_msg):
dec.decode(proto.encode(Ex(x)))
@pytest.mark.parametrize("typ", [list, tuple, set, frozenset])
def test_max_length(self, proto, typ):
class Ex(msgspec.Struct):
x: Annotated[typ, Meta(max_length=2)]
dec = proto.Decoder(Ex)
for n in [0, 2]:
x = typ(range(n))
assert dec.decode(proto.encode(Ex(x))).x == x
err_msg = r"Expected `array` of length <= 2 - at `\$.x`"
with pytest.raises(msgspec.ValidationError, match=err_msg):
dec.decode(proto.encode(Ex(typ(range(3)))))
@pytest.mark.parametrize("typ", [list, tuple, set, frozenset])
def test_combinations(self, proto, typ):
class Ex(msgspec.Struct):
x: Annotated[typ, Meta(min_length=2, max_length=4)]
dec = proto.Decoder(Ex)
for n in [2, 3, 4]:
x = typ(range(n))
assert dec.decode(proto.encode(Ex(x))).x == x
for n in [1, 5]:
x = typ(range(n))
with pytest.raises(msgspec.ValidationError):
dec.decode(proto.encode(Ex(x)))
class TestMapConstraints:
def test_min_length(self, proto):
class Ex(msgspec.Struct):
x: Annotated[Dict[str, int], Meta(min_length=2)]
dec = proto.Decoder(Ex)
for n in [2, 3]:
x = {str(i): i for i in range(n)}
assert dec.decode(proto.encode(Ex(x))).x == x
err_msg = r"Expected `object` of length >= 2 - at `\$.x`"
for n in [0, 1]:
x = {str(i): i for i in range(n)}
with pytest.raises(msgspec.ValidationError, match=err_msg):
dec.decode(proto.encode(Ex(x)))
def test_max_length(self, proto):
class Ex(msgspec.Struct):
x: Annotated[Dict[str, int], Meta(max_length=2)]
dec = proto.Decoder(Ex)
for n in [0, 2]:
x = {str(i): i for i in range(n)}
assert dec.decode(proto.encode(Ex(x))).x == x
err_msg = r"Expected `object` of length <= 2 - at `\$.x`"
x = {"1": 1, "2": 2, "3": 3}
with pytest.raises(msgspec.ValidationError, match=err_msg):
dec.decode(proto.encode(Ex(x)))
def test_combinations(self, proto):
class Ex(msgspec.Struct):
x: Annotated[Dict[str, int], Meta(min_length=2, max_length=4)]
dec = proto.Decoder(Ex)
for n in [2, 3, 4]:
x = {str(i): i for i in range(n)}
assert dec.decode(proto.encode(Ex(x))).x == x
for n in [1, 5]:
x = {str(i): i for i in range(n)}
with pytest.raises(msgspec.ValidationError):
dec.decode(proto.encode(Ex(x)))
class TestUnionConstraints:
def test_mix_float_and_int(self, proto):
class Ex(msgspec.Struct):
x: Union[
Annotated[int, Meta(ge=0, le=10)],
Annotated[float, Meta(ge=1000, le=2000)],
]
dec = proto.Decoder(Ex)
for x in [0, 5, 10, 1000.0, 1234.5, 2000.0]:
assert dec.decode(proto.encode(Ex(x))).x == x
for x in [0.0, 10.0, 1000, 2000]:
with pytest.raises(msgspec.ValidationError):
dec.decode(proto.encode(Ex(x)))
def test_mix_length_constraints(self, proto):
class Ex(msgspec.Struct):
x: Union[
Annotated[Dict[str, int], Meta(min_length=1, max_length=2)],
Annotated[List[int], Meta(min_length=3, max_length=4)],
Annotated[str, Meta(min_length=5, max_length=6)],
]
dec = proto.Decoder(Ex)
for x in [{"x": 1}, [1, 2, 3], "xxxxx"]:
assert dec.decode(proto.encode(Ex(x))).x == x
for x in [{}, [1], "x"]:
with pytest.raises(msgspec.ValidationError):
dec.decode(proto.encode(Ex(x)))
|