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 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018
|
from enum import Enum
from typing import Any, TypeVar
import pytest
import voluptuous as vol
from voluptuous_openapi import (
UNSUPPORTED,
convert,
convert_to_voluptuous,
OpenApiVersion,
)
def test_int_schema():
for value in int, vol.Coerce(int):
assert {"type": "integer"} == convert(vol.Schema(value))
def test_str_schema():
for value in str, vol.Coerce(str):
assert {"type": "string"} == convert(vol.Schema(value))
def test_float_schema():
for value in float, vol.Coerce(float):
assert {"type": "number"} == convert(vol.Schema(value))
def test_bool_schema():
for value in bool, vol.Coerce(bool):
assert {"type": "boolean"} == convert(vol.Schema(value))
def test_integer_clamp():
assert {
"type": "integer",
"minimum": 100,
"maximum": 1000,
} == convert(vol.Schema(vol.All(vol.Coerce(int), vol.Clamp(min=100, max=1000))))
def test_length():
assert {
"type": "string",
"minLength": 100,
"maxLength": 1000,
} == convert(vol.Schema(vol.All(vol.Coerce(str), vol.Length(min=100, max=1000))))
def test_datetime():
assert {
"type": "string",
"format": "date-time",
} == convert(vol.Schema(vol.Datetime()))
def test_in():
assert {"type": "string", "enum": ["beer", "wine"]} == convert(
vol.Schema(vol.In(["beer", "wine"]))
)
def test_in_integer():
assert {"type": "integer", "enum": [1, 2]} == convert(vol.Schema(vol.In([1, 2])))
def test_in_dict():
assert {
"type": "string",
"enum": ["en_US", "zh_CN"],
} == convert(
vol.Schema(
vol.In({"en_US": "American English", "zh_CN": "Chinese (Simplified)"})
)
)
def test_dict():
assert {
"type": "object",
"properties": {
"name": {
"type": "string",
"minLength": 5,
},
"age": {
"type": "integer",
"minimum": 18,
},
"hobby": {
"type": "string",
"default": "not specified",
},
},
"required": ["name", "age"],
} == convert(
vol.Schema(
{
vol.Required("name"): vol.All(str, vol.Length(min=5)),
vol.Required("age"): vol.All(vol.Coerce(int), vol.Range(min=18)),
vol.Optional("hobby", default="not specified"): str,
}
)
)
assert {"type": "object", "additionalProperties": True} == convert(vol.Schema(dict))
assert {"type": "object", "additionalProperties": True} == convert(
vol.Schema(dict[str, Any])
)
assert {"type": "object", "additionalProperties": {"type": "integer"}} == convert(
vol.Schema({str: int})
)
assert {
"type": "object",
"properties": {"x": {"type": "integer"}},
"required": [],
"additionalProperties": {"type": "string"},
} == convert(vol.Schema({"x": int, str: str}))
assert {"type": "object", "properties": {}, "required": []} == convert(
vol.Schema({})
)
def string(x: str) -> str:
return x
assert {"type": "object", "additionalProperties": {"type": "string"}} == convert(
vol.Schema({string: string})
)
assert {"type": "object", "additionalProperties": True} == convert(
vol.Schema(object)
)
assert {"type": "object", "additionalProperties": True} == convert(
vol.Schema({string: object})
)
def test_tuple():
assert {"type": "array", "items": {"type": "string"}} == convert(vol.Schema(tuple))
assert {"type": "array", "items": {"type": "string"}} == convert(
vol.Schema(tuple[Any])
)
assert {"type": "array", "items": {"type": "integer"}} == convert(
vol.Schema(tuple[int])
)
def test_marker_description():
assert {
"type": "object",
"properties": {
"name": {
"type": "string",
"description": "Description of name",
},
},
"required": ["name"],
} == convert(
vol.Schema(
{
vol.Required("name", description="Description of name"): str,
}
)
)
def test_lower():
assert {
"type": "string",
"format": "lower",
} == convert(vol.Schema(vol.All(vol.Lower, str)))
def test_upper():
assert {
"type": "string",
"format": "upper",
} == convert(vol.Schema(vol.All(vol.Upper, str)))
def test_capitalize():
assert {
"type": "string",
"format": "capitalize",
} == convert(vol.Schema(vol.All(vol.Capitalize, str)))
def test_title():
assert {
"type": "string",
"format": "title",
} == convert(vol.Schema(vol.All(vol.Title, str)))
def test_strip():
assert {
"type": "string",
"format": "strip",
} == convert(vol.Schema(vol.All(vol.Strip, str)))
def test_email():
assert {
"type": "string",
"format": "email",
} == convert(vol.Schema(vol.All(vol.Email, str)))
def test_url():
assert {
"type": "string",
"format": "url",
} == convert(vol.Schema(vol.All(vol.Url, str)))
def test_fqdnurl():
assert {
"type": "string",
"format": "fqdnurl",
} == convert(vol.Schema(vol.All(vol.FqdnUrl, str)))
def test_maybe():
assert {
"type": "string",
"nullable": True,
} == convert(vol.Schema(vol.Maybe(str)))
def test_maybe_v3_1():
assert {
"anyOf": [
{"type": "null"},
{"type": "string"},
],
} == convert(vol.Schema(vol.Maybe(str)), openapi_version=OpenApiVersion.V3_1)
def test_custom_serializer():
def custem_serializer(schema):
if schema is str:
return {"pattern": "[A-Z]{1,8}\\.[A-Z]{3,3}", "type": "string"}
return UNSUPPORTED
assert {
"type": "string",
"pattern": "[A-Z]{1,8}\\.[A-Z]{3,3}",
"format": "upper",
} == convert(
vol.Schema(vol.All(vol.Upper, str)), custom_serializer=custem_serializer
)
def test_constant():
assert {"type": "boolean", "enum": [True]} == convert(vol.Schema(True))
assert {"type": "boolean", "enum": [False]} == convert(vol.Schema(False))
assert {"type": "string", "enum": ["Hello"]} == convert(vol.Schema("Hello"))
assert {"type": "integer", "enum": [1]} == convert(vol.Schema(1))
assert {"type": "number", "enum": [1.5]} == convert(vol.Schema(1.5))
assert {
"type": "object",
"nullable": True,
"description": "Must be null",
} == convert(vol.Schema(None))
assert {
"type": "object",
"nullable": True,
"description": "Must be null",
} == convert(vol.Schema(type(None)))
assert {
"type": "null",
} == convert(vol.Schema(None), openapi_version=OpenApiVersion.V3_1)
assert {
"type": "null",
} == convert(vol.Schema(type(None)), openapi_version=OpenApiVersion.V3_1)
def test_enum():
class StringEnum(Enum):
ONE = "one"
TWO = "two"
assert {"type": "string", "enum": ["one", "two"]} == convert(
vol.Schema(vol.Coerce(StringEnum))
)
class IntEnum(Enum):
ONE = 1
TWO = 2
assert {"type": "integer", "enum": [1, 2]} == convert(
vol.Schema(vol.Coerce(IntEnum))
)
def test_list():
assert {
"type": "array",
"items": {"type": "string"},
} == convert(vol.Schema([str]))
assert {"type": "array", "items": {"type": "string"}} == convert(vol.Schema(list))
assert {"type": "array", "items": {"type": "string"}} == convert(
vol.Schema(list[Any])
)
assert {"type": "array", "items": {"type": "integer"}} == convert(
vol.Schema(list[int])
)
def test_any_of():
assert {"anyOf": [{"type": "number"}, {"type": "integer"}]} == convert(
vol.Any(float, int)
)
assert {"anyOf": [{"type": "number"}, {"type": "integer"}]} == convert(
vol.Any(float, int, float, int, int)
)
assert {"type": "object", "additionalProperties": True} == convert(
vol.Any(float, int, object)
)
assert {"type": "integer", "nullable": True, "enum": [1, 2]} == convert(
vol.Schema(vol.In([1, 2, None]))
)
assert {"type": "integer", "enum": [1, 2, 3]} == convert(
vol.Schema(vol.Any(1, 2, 3))
)
assert {
"anyOf": [{"type": "number"}, {"type": "integer"}, {"type": "string"}]
} == convert(
vol.Any(
vol.Any(float, int), vol.Any(int, float), vol.Any(float, vol.Any(int, str))
)
)
assert {
"anyOf": [{"type": "number"}, {"type": "integer"}],
"nullable": True,
} == convert(vol.Any(vol.Maybe(float), vol.Maybe(int)))
assert {
"anyOf": [{"type": "null"}, {"type": "number"}, {"type": "integer"}],
} == convert(
vol.Any(vol.Maybe(float), vol.Maybe(int)), openapi_version=OpenApiVersion.V3_1
)
def test_all_of():
assert {"allOf": [{"minimum": 5}, {"minimum": 10}]} == convert(
vol.All(vol.Range(min=5), vol.Range(min=10))
)
assert {"type": "string"} == convert(vol.All(object, str))
assert {"type": "object", "additionalProperties": {"type": "string"}} == convert(
vol.All(object, {str: str})
)
assert {"maximum": 10, "minimum": 5, "type": "number"} == convert(
vol.All(vol.Range(min=5), vol.Range(max=10))
)
assert {"maximum": 10, "minimum": 5, "type": "number"} == convert(
vol.All(
vol.All(vol.Range(min=5), float),
vol.All(vol.All(vol.Range(max=10), float), float),
)
)
def test_key_any():
assert {
"type": "object",
"properties": {
"name": {
"type": "string",
},
"area": {
"type": "string",
"description": "The ID or the area",
},
},
"required": [],
} == convert(
vol.Schema(
{
vol.Any(
"name", vol.Optional("area", description="The ID or the area")
): str
}
)
)
assert {
"properties": {
"conversation_command": {"type": "string"},
"hours": {"type": "integer"},
"minutes": {"type": "integer"},
"name": {"type": "string"},
"seconds": {"type": "integer"},
},
"required": [],
"type": "object",
"anyOf": [
{"required": ["hours"]},
{"required": ["minutes"]},
{"required": ["seconds"]},
],
} == convert(
{
vol.Required(vol.Any("hours", "minutes", "seconds")): int,
vol.Optional("name"): str,
vol.Optional("conversation_command"): str,
}
)
def test_function():
def validator(data):
return data
assert {
"type": "object",
"properties": {"test_data": {"type": "string"}},
"required": [],
} == convert(vol.Schema({"test_data": validator}))
def validator_str(data: str):
return data
assert {"type": "string"} == convert(vol.Schema(validator_str))
def validator_any(data: Any):
return data
assert {} == convert(validator_any)
assert {"type": "integer"} == convert(vol.All(vol.Coerce(int), lambda x: x / 100))
def validator_nullable(data: float | None):
return data
assert {"type": "number", "nullable": True} == convert(
vol.Schema(validator_nullable)
)
assert {"anyOf": [{"type": "number"}, {"type": "null"}]} == convert(
vol.Schema(validator_nullable), openapi_version=OpenApiVersion.V3_1
)
def validator_union(data: float | int):
return data
assert {"anyOf": [{"type": "number"}, {"type": "integer"}]} == convert(
vol.Schema(validator_union)
)
_T = TypeVar("_T")
def validator_nullable_2(value: _T | None):
return value
assert {
"type": "object",
"properties": {"var": {"type": "array", "items": {"type": "string"}}},
"required": [],
} == convert(vol.Schema({"var": vol.All(validator_nullable_2, [validator_any])}))
def validator_list_int(value: list[int]):
return value
assert {"type": "array", "items": {"type": "integer"}} == convert(
validator_list_int
)
def validator_list_any(value: list[Any]):
return value
assert {"type": "array", "items": {"type": "string"}} == convert(validator_list_any)
def validator_list(value: list):
return value
assert {"type": "array", "items": {"type": "string"}} == convert(validator_list)
def validator_set_int(value: set[int]):
return value
assert {"type": "array", "items": {"type": "integer"}} == convert(validator_set_int)
def validator_set_any(value: set[Any]):
return value
assert {"type": "array", "items": {"type": "string"}} == convert(validator_set_any)
def validator_set(value: set):
return value
assert {"type": "array", "items": {"type": "string"}} == convert(validator_set)
def validator_dict(value: dict):
return value
assert {"type": "object", "additionalProperties": True} == convert(validator_dict)
def validator_dict_int(value: dict[str, int]):
return value
assert {"type": "object", "additionalProperties": {"type": "integer"}} == convert(
validator_dict_int
)
def test_nested_in_list():
assert {
"properties": {
"drink": {
"type": "array",
"items": {"type": "string", "enum": ["beer", "wine"]},
},
},
"required": [],
"type": "object",
} == convert(vol.Schema({vol.Optional("drink"): [vol.In(["beer", "wine"])]}))
assert {"type": "integer", "enum": [1, 2, 3]} == convert(
vol.Schema(vol.In([1, 2, 3]))
)
def test_reverse_int_schema():
assert convert_to_voluptuous({"type": "integer"}) == int
def test_reverse_str_schema():
assert convert_to_voluptuous({"type": "string"}) == str
def test_reverse_float_schema():
assert convert_to_voluptuous({"type": "number"}) == float
def test_reverse_bool_schema():
assert convert_to_voluptuous({"type": "boolean"}) == bool
def test_reverse_datetime():
validator = convert_to_voluptuous(
{
"type": "string",
"format": "date-time",
}
)
validator("2025-01-01T12:32:55.11Z")
with pytest.raises(vol.Invalid):
validator("2021-01-01")
with pytest.raises(vol.Invalid):
validator("abc")
def test_reverse_unknown_type():
with pytest.raises(ValueError):
convert_to_voluptuous({})
with pytest.raises(ValueError):
convert_to_voluptuous({"type": "unknown"})
def test_convert_to_voluptuous_wrong_type() -> None:
"""Test calling with the wrong type"""
with pytest.raises(ValueError):
convert_to_voluptuous({"oneOf": ["integer"]})
with pytest.raises(ValueError):
convert_to_voluptuous({"oneOf": "integer"})
with pytest.raises(ValueError):
convert_to_voluptuous("a")
def test_unsupported_features() -> None:
"""Test converting a mixed aray type."""
with pytest.raises(ValueError):
convert_to_voluptuous({"type": "integer", "multipleOf": 2})
with pytest.raises(ValueError):
convert_to_voluptuous({"type": "array", "items": {"minItems": 1}})
def test_mixed_type_list() -> None:
"""Test converting a mixed aray type."""
validator = convert_to_voluptuous(
{"type": "array", "items": {"oneOf": [{"type": "string"}, {"type": "integer"}]}}
)
validator(["a", "b"])
validator([1, 2])
validator(["a", 1, "b", 2])
with pytest.raises(vol.Invalid):
validator("abc")
with pytest.raises(vol.Invalid):
validator(123)
@pytest.mark.parametrize(
"required",
[
(["query"]),
([]),
],
)
def test_convert_to_voluptuous_marker_description(required: list[str]):
schema = convert_to_voluptuous(
{
"type": "object",
"properties": {
"query": {"type": "string", "description": "The query to search for"},
"max_results": {
"type": "number",
"description": "The maximum number of results to return",
},
},
"required": required,
}
)
assert [(key, key.description) for key in schema.schema.keys()] == [
("query", "The query to search for"),
("max_results", "The maximum number of results to return"),
]
def test_convert_to_voluptuous_nullable_string_openapi_3_0():
"""Test OpenAPI 3.0 nullable string."""
validator = convert_to_voluptuous({"type": "string", "nullable": True})
validator("test")
validator(None)
with pytest.raises(vol.Invalid):
validator(123)
def test_convert_to_voluptuous_non_nullable_string_openapi_3_0():
"""Test OpenAPI 3.0 non-nullable string."""
validator_type = convert_to_voluptuous({"type": "string", "nullable": False})
# Wrap in a Schema for proper validation
validator = vol.Schema(validator_type)
validator("test")
validator("") # empty string should be valid
with pytest.raises(vol.Invalid):
validator(None)
with pytest.raises(vol.Invalid):
validator(123)
def test_convert_to_voluptuous_nullable_integer_openapi_3_0():
"""Test OpenAPI 3.0 nullable integer."""
validator = convert_to_voluptuous({"type": "integer", "nullable": True})
validator(42)
validator(None)
with pytest.raises(vol.Invalid):
validator("string")
def test_convert_to_voluptuous_nullable_number_openapi_3_0():
"""Test OpenAPI 3.0 nullable number."""
validator = convert_to_voluptuous({"type": "number", "nullable": True})
validator(3.14)
validator(None)
with pytest.raises(vol.Invalid):
validator("string")
def test_convert_to_voluptuous_nullable_boolean_openapi_3_0():
"""Test OpenAPI 3.0 nullable boolean."""
validator = convert_to_voluptuous({"type": "boolean", "nullable": True})
validator(True)
validator(False)
validator(None)
with pytest.raises(vol.Invalid):
validator("string")
def test_convert_to_voluptuous_nullable_object_openapi_3_0():
"""Test OpenAPI 3.0 nullable object."""
validator = convert_to_voluptuous(
{"type": "object", "properties": {"name": {"type": "string"}}, "nullable": True}
)
validator({"name": "test"})
validator(None)
with pytest.raises(vol.Invalid):
validator("string")
def test_convert_to_voluptuous_nullable_array_openapi_3_0():
"""Test OpenAPI 3.0 nullable array."""
validator = convert_to_voluptuous(
{"type": "array", "items": {"type": "string"}, "nullable": True}
)
validator(["a", "b"])
validator(None)
with pytest.raises(vol.Invalid):
validator("string")
def test_convert_to_voluptuous_nullable_string_openapi_3_1():
"""Test OpenAPI 3.1 nullable string using type array."""
validator = convert_to_voluptuous({"type": ["string", "null"]})
validator("test")
validator(None)
with pytest.raises(vol.Invalid):
validator(123)
def test_convert_to_voluptuous_nullable_integer_openapi_3_1():
"""Test OpenAPI 3.1 nullable integer using type array."""
validator = convert_to_voluptuous({"type": ["integer", "null"]})
validator(42)
validator(None)
with pytest.raises(vol.Invalid):
validator("string")
def test_convert_to_voluptuous_multiple_types_with_null_openapi_3_1():
"""Test OpenAPI 3.1 multiple types with null."""
validator = convert_to_voluptuous({"type": ["string", "integer", "null"]})
validator("test")
validator(42)
validator(None)
with pytest.raises(vol.Invalid):
validator(3.14)
def test_convert_to_voluptuous_multiple_types_without_null_openapi_3_1():
"""Test OpenAPI 3.1 multiple types without null."""
validator = convert_to_voluptuous({"type": ["string", "integer"]})
validator("test")
validator(42)
with pytest.raises(vol.Invalid):
validator(None)
def test_convert_to_voluptuous_only_null_openapi_3_1():
"""Test OpenAPI 3.1 type array with only null."""
validator = convert_to_voluptuous({"type": ["null"]})
validator(None)
with pytest.raises(vol.Invalid):
validator("test")
def test_convert_to_voluptuous_nullable_string_with_pattern():
"""Test nullable string with pattern constraint."""
validator = convert_to_voluptuous(
{"type": "string", "pattern": r"^test", "nullable": True}
)
validator("testing")
validator(None)
with pytest.raises(vol.Invalid):
validator("nottest")
def test_convert_to_voluptuous_nullable_integer_with_range_openapi_3_0():
"""Test nullable integer with range constraint (OpenAPI 3.0 style)."""
validator = convert_to_voluptuous(
{"type": "integer", "minimum": 1, "maximum": 10, "nullable": True}
)
validator(5)
validator(None)
with pytest.raises(vol.Invalid):
validator(15)
def test_convert_to_voluptuous_nullable_integer_with_range_openapi_3_1():
"""Test nullable integer with range constraint (OpenAPI 3.1 style)."""
validator = convert_to_voluptuous(
{"type": ["integer", "null"], "minimum": 1, "maximum": 10}
)
validator(5)
validator(None)
with pytest.raises(vol.Invalid):
validator(15)
def test_convert_to_voluptuous_nullable_string_with_length_constraints():
"""Test nullable string with length constraints."""
validator = convert_to_voluptuous(
{"type": "string", "minLength": 3, "maxLength": 10, "nullable": True}
)
validator("hello")
validator(None)
with pytest.raises(vol.Invalid):
validator("hi") # too short
with pytest.raises(vol.Invalid):
validator("verylongstring") # too long
def test_convert_to_voluptuous_nullable_number_with_range():
"""Test nullable number with range constraints."""
validator = convert_to_voluptuous(
{"type": "number", "minimum": 0.0, "maximum": 100.0, "nullable": True}
)
validator(50.5)
validator(None)
with pytest.raises(vol.Invalid):
validator(-1.0) # too low
with pytest.raises(vol.Invalid):
validator(101.0) # too high
TEST_TASK_ITEM = {"content": "a task ", "description": "a description"}
TASK_SCHEMA = {
"type": "object",
"properties": {
"tasks": {
"type": "array",
"items": {
"type": "object",
"properties": {
"content": {
"type": "string",
"description": "The content of the task to create.",
},
"description": {
"type": "string",
"description": "The description of the task.",
},
},
"required": ["content"],
"additionalProperties": False,
},
}
},
}
@pytest.mark.parametrize(
"extra_tasks_data, input_data",
[
({"minItems": 1, "maxItems": 2}, {"tasks": [TEST_TASK_ITEM]}),
({"minItems": 1, "maxItems": 2}, {"tasks": [TEST_TASK_ITEM, TEST_TASK_ITEM]}),
({"minItems": 1}, {"tasks": [TEST_TASK_ITEM]}),
({"maxItems": 2}, {"tasks": [TEST_TASK_ITEM, TEST_TASK_ITEM]}),
],
)
def test_with_min_max_items_success(extra_tasks_data, input_data):
task_schema = TASK_SCHEMA.copy()
task_schema["properties"]["tasks"].update(extra_tasks_data)
validator = convert_to_voluptuous(task_schema)
validator(input_data)
@pytest.mark.parametrize(
"extra_tasks_data, input_data",
[
({"minItems": 1, "maxItems": 2}, {"tasks": []}),
(
{"minItems": 1, "maxItems": 2},
{"tasks": [TEST_TASK_ITEM, TEST_TASK_ITEM, TEST_TASK_ITEM]},
),
({"minItems": 1}, {"tasks": []}),
({"maxItems": 2}, {"tasks": [TEST_TASK_ITEM, TEST_TASK_ITEM, TEST_TASK_ITEM]}),
],
)
def test_with_min_max_items_fails_validation(extra_tasks_data, input_data):
task_schema = TASK_SCHEMA.copy()
task_schema["properties"]["tasks"].update(extra_tasks_data)
validator = convert_to_voluptuous(task_schema)
with pytest.raises(vol.Invalid):
validator(input_data)
def test_required_any_of():
"""Test schemas with Required(Any(...)) constraints."""
assert {
"properties": {
"color": {"type": "string"},
"temperature": {"type": "integer"},
"brightness": {"type": "integer"},
},
"required": [],
"type": "object",
"anyOf": [
{"required": ["color"]},
{"required": ["temperature"]},
{"required": ["brightness"]},
],
} == convert(
{
vol.Required(vol.Any("color", "temperature", "brightness")): object,
vol.Optional("color"): str,
vol.Optional("temperature"): int,
vol.Optional("brightness"): int,
}
)
assert {
"properties": {
"color": {"type": "string"},
"temperature": {"type": "integer"},
"brightness": {"type": "integer"},
"mode": {"type": "string"},
"preset": {"type": "string"},
},
"required": [],
"type": "object",
"anyOf": [
{"required": ["color", "mode"]},
{"required": ["color", "preset"]},
{"required": ["temperature", "mode"]},
{"required": ["temperature", "preset"]},
{"required": ["brightness", "mode"]},
{"required": ["brightness", "preset"]},
],
} == convert(
{
vol.Required(vol.Any("color", "temperature", "brightness")): object,
vol.Required(vol.Any("mode", "preset")): str,
vol.Optional("color"): str,
vol.Optional("temperature"): int,
vol.Optional("brightness"): int,
vol.Optional("mode"): str,
vol.Optional("preset"): str,
}
)
assert {
"properties": {
"entity_id": {"type": "string"},
"color": {"type": "string"},
"temperature": {"type": "integer"},
},
"required": ["entity_id"],
"type": "object",
"anyOf": [{"required": ["color"]}, {"required": ["temperature"]}],
} == convert(
{
vol.Required("entity_id"): str,
vol.Required(vol.Any("color", "temperature")): str,
vol.Optional("color"): str,
vol.Optional("temperature"): int,
}
)
def test_required_any_of_description():
"""Test that the description is preserved in a Required(Any(...)) constraint."""
assert {
"properties": {
"color": {"type": "string", "description": "Light appearance"},
"temperature": {"type": "string", "description": "Light appearance"},
},
"required": [],
"type": "object",
"anyOf": [{"required": ["color"]}, {"required": ["temperature"]}],
} == convert(
{
vol.Required(
vol.Any("color", "temperature"), description="Light appearance"
): str,
}
)
def test_required_any_of_inner_description():
"""Test that inner descriptions are preferred in a Required(Any(...)) constraint."""
assert {
"properties": {
"color": {"type": "string", "description": "Inner color description"},
"temperature": {"type": "string", "description": "Outer description"},
},
"required": [],
"type": "object",
"anyOf": [{"required": ["color"]}, {"required": ["temperature"]}],
} == convert(
{
vol.Required(
vol.Any(
vol.Optional("color", description="Inner color description"),
"temperature",
),
description="Outer description",
): str,
}
)
|