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 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179
|
require "../spec_helper"
require "json"
require "yaml"
require "big"
require "big/json"
require "uuid"
require "uuid/json"
class JSONAttrValue(T)
include JSON::Serializable
property value : T
end
record JSONAttrPoint, x : Int32, y : Int32 do
include JSON::Serializable
end
class JSONAttrEmptyClass
include JSON::Serializable
def initialize; end
end
class JSONAttrEmptyClassWithUnmapped
include JSON::Serializable
include JSON::Serializable::Unmapped
def initialize; end
end
class JSONAttrPerson
include JSON::Serializable
property name : String
property age : Int32?
def_equals name, age
def initialize(@name : String)
end
end
struct JSONAttrPersonWithTwoFieldInInitialize
include JSON::Serializable
property name : String
property age : Int32
def initialize(@name, @age)
end
end
class StrictJSONAttrPerson
include JSON::Serializable
include JSON::Serializable::Strict
property name : String
property age : Int32?
end
class JSONAttrPersonExtraFields
include JSON::Serializable
include JSON::Serializable::Unmapped
property name : String
property age : Int32?
end
class JSONAttrPersonEmittingNull
include JSON::Serializable
property name : String
@[JSON::Field(emit_null: true)]
property age : Int32?
end
@[JSON::Serializable::Options(emit_nulls: true)]
class JSONAttrPersonEmittingNullsByOptions
include JSON::Serializable
property name : String
property age : Int32?
property value1 : Int32?
@[JSON::Field(emit_null: false)]
property value2 : Int32?
end
class JSONAttrWithTime
include JSON::Serializable
@[JSON::Field(converter: Time::Format.new("%F %T"))]
property value : Time
end
class JSONAttrWithNilableTime
include JSON::Serializable
@[JSON::Field(converter: Time::Format.new("%F"))]
property value : Time?
def initialize
end
end
class JSONAttrWithNilableTimeEmittingNull
include JSON::Serializable
@[JSON::Field(converter: Time::Format.new("%F"), emit_null: true)]
property value : Time?
def initialize
end
end
class JSONAttrWithTimeArray1
include JSON::Serializable
@[JSON::Field(converter: JSON::ArrayConverter(Time::EpochConverter))]
property value : Array(Time)
end
class JSONAttrWithTimeArray2
include JSON::Serializable
@[JSON::Field(converter: JSON::ArrayConverter.new(Time::EpochConverter))]
property value : Array(Time)
end
class JSONAttrWithTimeArray3
include JSON::Serializable
@[JSON::Field(converter: JSON::ArrayConverter.new(Time::Format.new("%F %T")))]
property value : Array(Time)
end
class JSONAttrWithTimeHash1
include JSON::Serializable
@[JSON::Field(converter: JSON::HashValueConverter(Time::EpochConverter))]
property value : Hash(String, Time)
end
class JSONAttrWithTimeHash2
include JSON::Serializable
@[JSON::Field(converter: JSON::HashValueConverter.new(Time::EpochConverter))]
property value : Hash(String, Time)
end
class JSONAttrWithTimeHash3
include JSON::Serializable
@[JSON::Field(converter: JSON::HashValueConverter.new(Time::Format.new("%F %T")))]
property value : Hash(String, Time)
end
class JSONAttrWithSimpleMapping
include JSON::Serializable
property name : String
property age : Int32
end
class JSONAttrWithKeywordsMapping
include JSON::Serializable
property end : Int32
property abstract : Int32
end
class JSONAttrWithAny
include JSON::Serializable
property name : String
property any : JSON::Any
end
class JSONAttrWithProblematicKeys
include JSON::Serializable
property key : Int32
property pull : Int32
end
class JSONAttrWithDefaults
include JSON::Serializable
property a = 11
property b = "Haha"
property c = true
property d = false
property e : Bool? = false
property f : Int32? = 1
property g : Int32?
property h = [1, 2, 3]
end
class JSONAttrWithSmallIntegers
include JSON::Serializable
property foo : Int16
property bar : Int8
end
class JSONAttrWithTimeEpoch
include JSON::Serializable
@[JSON::Field(converter: Time::EpochConverter)]
property value : Time
end
class JSONAttrNilableWithTimeEpoch
include JSON::Serializable
@[JSON::Field(converter: Time::EpochConverter)]
property value : Time?
end
class JSONAttrDefaultWithTimeEpoch
include JSON::Serializable
@[JSON::Field(converter: Time::EpochConverter)]
property value : Time = Time.unix(0)
end
class JSONAttrWithTimeEpochMillis
include JSON::Serializable
@[JSON::Field(converter: Time::EpochMillisConverter)]
property value : Time
end
class JSONAttrWithRaw
include JSON::Serializable
@[JSON::Field(converter: String::RawConverter)]
property value : String
end
class JSONAttrWithRoot
include JSON::Serializable
@[JSON::Field(root: "heroes")]
property result : Array(JSONAttrPerson)
end
class JSONAttrWithNilableRoot
include JSON::Serializable
@[JSON::Field(root: "heroes")]
property result : Array(JSONAttrPerson)?
end
class JSONAttrWithNilableRootEmitNull
include JSON::Serializable
@[JSON::Field(root: "heroes", emit_null: true)]
property result : Array(JSONAttrPerson)?
end
class JSONAttrWithPresence
include JSON::Serializable
@[JSON::Field(presence: true)]
property first_name : String?
@[JSON::Field(presence: true)]
property last_name : String?
@[JSON::Field(ignore: true)]
getter? first_name_present : Bool
@[JSON::Field(ignore: true)]
getter? last_name_present : Bool
end
class JSONAttrWithPresenceAndIgnoreSerialize
include JSON::Serializable
@[JSON::Field(presence: true, ignore_serialize: ignore_first_name?)]
property first_name : String?
@[JSON::Field(presence: true, ignore_serialize: last_name.nil? && !last_name_present?, emit_null: true)]
property last_name : String?
@[JSON::Field(ignore: true)]
getter? first_name_present : Bool = false
@[JSON::Field(ignore: true)]
getter? last_name_present : Bool = false
def initialize(@first_name : String? = nil, @last_name : String? = nil)
end
def ignore_first_name?
first_name.nil? || first_name == ""
end
end
class JSONAttrWithQueryAttributes
include JSON::Serializable
property? foo : Bool
@[JSON::Field(key: "is_bar", presence: true)]
property? bar : Bool = false
@[JSON::Field(ignore: true)]
getter? bar_present : Bool
end
module JSONAttrModule
property moo : Int32 = 10
end
class JSONAttrModuleTest
include JSONAttrModule
include JSON::Serializable
@[JSON::Field(key: "phoo")]
property foo = 15
def initialize; end
def to_tuple
{@moo, @foo}
end
end
class JSONAttrModuleTest2 < JSONAttrModuleTest
property bar : Int32
def initialize(@bar : Int32); end
def to_tuple
{@moo, @foo, @bar}
end
end
struct JSONAttrPersonWithYAML
include JSON::Serializable
include YAML::Serializable
property name : String
property age : Int32?
def initialize(@name : String, @age : Int32? = nil)
end
end
struct JSONAttrPersonWithYAMLInitializeHook
include JSON::Serializable
include YAML::Serializable
property name : String
property age : Int32?
def initialize(@name : String, @age : Int32? = nil)
after_initialize
end
@[JSON::Field(ignore: true)]
@[YAML::Field(ignore: true)]
property msg : String?
def after_initialize
@msg = "Hello " + name
end
end
struct JSONAttrPersonWithSelectiveSerialization
include JSON::Serializable
property name : String
@[JSON::Field(ignore_serialize: true)]
property password : String
@[JSON::Field(ignore_deserialize: true)]
property generated : String = "generated-internally"
def initialize(@name : String, @password : String)
end
end
abstract class JSONShape
include JSON::Serializable
use_json_discriminator "type", {point: JSONPoint, circle: JSONCircle}
property type : String
end
class JSONPoint < JSONShape
property x : Int32
property y : Int32
end
class JSONCircle < JSONShape
property x : Int32
property y : Int32
property radius : Int32
end
enum JSONVariableDiscriminatorEnumFoo
Foo = 4
end
enum JSONVariableDiscriminatorEnumFoo8 : UInt8
Foo = 1_8
end
class JSONVariableDiscriminatorValueType
include JSON::Serializable
use_json_discriminator "type", {
0 => JSONVariableDiscriminatorNumber,
"1" => JSONVariableDiscriminatorString,
true => JSONVariableDiscriminatorBoolTrue,
false => JSONVariableDiscriminatorBoolFalse,
JSONVariableDiscriminatorEnumFoo::Foo => JSONVariableDiscriminatorEnum,
JSONVariableDiscriminatorEnumFoo8::Foo => JSONVariableDiscriminatorEnum8,
}
end
class JSONVariableDiscriminatorNumber < JSONVariableDiscriminatorValueType
end
class JSONVariableDiscriminatorString < JSONVariableDiscriminatorValueType
end
class JSONVariableDiscriminatorBoolTrue < JSONVariableDiscriminatorValueType
end
class JSONVariableDiscriminatorBoolFalse < JSONVariableDiscriminatorValueType
end
class JSONVariableDiscriminatorEnum < JSONVariableDiscriminatorValueType
end
class JSONVariableDiscriminatorEnum8 < JSONVariableDiscriminatorValueType
end
class JSONStrictDiscriminator
include JSON::Serializable
include JSON::Serializable::Strict
property type : String
use_json_discriminator "type", {foo: JSONStrictDiscriminatorFoo, bar: JSONStrictDiscriminatorBar}
end
class JSONStrictDiscriminatorFoo < JSONStrictDiscriminator
end
class JSONStrictDiscriminatorBar < JSONStrictDiscriminator
property x : JSONStrictDiscriminator
property y : JSONStrictDiscriminator
end
module JSONNamespace
struct FooRequest
include JSON::Serializable
getter foo : Foo
getter bar = Bar.new
end
struct Foo
include JSON::Serializable
getter id = "id:foo"
end
struct Bar
include JSON::Serializable
getter id = "id:bar"
def initialize # Allow for default value above
end
end
end
class JSONSomething
include JSON::Serializable
property value : JSONSomething?
end
module JsonDiscriminatorBug
abstract class Base
include JSON::Serializable
use_json_discriminator("type", {"a" => A, "b" => B, "c" => C})
end
class A < Base
end
class B < Base
property source : Base
property value : Int32 = 1
end
class C < B
end
end
describe "JSON mapping" do
it "works with record" do
JSONAttrPoint.new(1, 2).to_json.should eq "{\"x\":1,\"y\":2}"
JSONAttrPoint.from_json(%({"x": 1, "y": 2})).should eq JSONAttrPoint.new(1, 2)
end
it "empty class" do
e = JSONAttrEmptyClass.new
e.to_json.should eq "{}"
JSONAttrEmptyClass.from_json("{}")
end
it "empty class with unmapped" do
JSONAttrEmptyClassWithUnmapped.from_json(%({"name": "John", "age": 30})).json_unmapped.should eq({"name" => "John", "age" => 30})
end
it "parses person" do
person = JSONAttrPerson.from_json(%({"name": "John", "age": 30}))
person.should be_a(JSONAttrPerson)
person.name.should eq("John")
person.age.should eq(30)
end
it "parses person without age" do
person = JSONAttrPerson.from_json(%({"name": "John"}))
person.should be_a(JSONAttrPerson)
person.name.should eq("John")
person.name.size.should eq(4) # This verifies that name is not nilable
person.age.should be_nil
end
it "parses array of people" do
people = Array(JSONAttrPerson).from_json(%([{"name": "John"}, {"name": "Doe"}]))
people.size.should eq(2)
end
it "works with class with two fields" do
person1 = JSONAttrPersonWithTwoFieldInInitialize.from_json(%({"name": "John", "age": 30}))
person2 = JSONAttrPersonWithTwoFieldInInitialize.new("John", 30)
person1.should eq person2
end
it "does to_json" do
person = JSONAttrPerson.from_json(%({"name": "John", "age": 30}))
person2 = JSONAttrPerson.from_json(person.to_json)
person2.should eq(person)
end
it "parses person with unknown attributes" do
person = JSONAttrPerson.from_json(%({"name": "John", "age": 30, "foo": "bar"}))
person.should be_a(JSONAttrPerson)
person.name.should eq("John")
person.age.should eq(30)
end
it "parses strict person with unknown attributes" do
error_message = <<-'MSG'
Unknown JSON attribute: foo
parsing StrictJSONAttrPerson
MSG
ex = expect_raises ::JSON::SerializableError, error_message do
StrictJSONAttrPerson.from_json <<-JSON
{
"name": "John",
"age": 30,
"foo": "bar"
}
JSON
end
ex.location.should eq({4, 3})
end
it "should parse extra fields (JSONAttrPersonExtraFields with on_unknown_json_attribute)" do
person = JSONAttrPersonExtraFields.from_json(%({"name": "John", "age": 30, "x": "1", "y": 2, "z": [1,2,3]}))
person.name.should eq("John")
person.age.should eq(30)
person.json_unmapped.should eq({"x" => "1", "y" => 2_i64, "z" => [1, 2, 3]})
end
it "should to store extra fields (JSONAttrPersonExtraFields with on_to_json)" do
person = JSONAttrPersonExtraFields.from_json(%({"name": "John", "age": 30, "x": "1", "y": 2, "z": [1,2,3]}))
person.name = "John1"
person.json_unmapped.delete("y")
person.json_unmapped["q"] = JSON::Any.new("w")
person.to_json.should eq "{\"name\":\"John1\",\"age\":30,\"x\":\"1\",\"z\":[1,2,3],\"q\":\"w\"}"
end
it "raises if non-nilable attribute is nil" do
error_message = <<-'MSG'
Missing JSON attribute: name
parsing JSONAttrPerson at line 1, column 1
MSG
ex = expect_raises ::JSON::SerializableError, error_message do
JSONAttrPerson.from_json(%({"age": 30}))
end
ex.location.should eq({1, 1})
end
it "raises if not an object" do
error_message = <<-'MSG'
Expected BeginObject but was String at line 1, column 1
parsing StrictJSONAttrPerson at line 0, column 0
MSG
ex = expect_raises ::JSON::SerializableError, error_message do
StrictJSONAttrPerson.from_json <<-JSON
"foo"
JSON
end
ex.location.should eq({1, 1})
end
it "raises if data type does not match" do
error_message = <<-MSG
Couldn't parse (Int32 | Nil) from "foo" at line 3, column 10
MSG
ex = expect_raises ::JSON::SerializableError, error_message do
StrictJSONAttrPerson.from_json <<-JSON
{
"name": "John",
"age": "foo",
"foo": "bar"
}
JSON
end
ex.location.should eq({3, 10})
end
it "doesn't emit null by default when doing to_json" do
person = JSONAttrPerson.from_json(%({"name": "John"}))
person.to_json.should_not match /age/
end
it "emits null on request when doing to_json" do
person = JSONAttrPersonEmittingNull.from_json(%({"name": "John"}))
person.to_json.should match /age/
end
it "emit_nulls option" do
person = JSONAttrPersonEmittingNullsByOptions.from_json(%({"name": "John"}))
person.to_json.should eq "{\"name\":\"John\",\"age\":null,\"value1\":null}"
end
it "doesn't raises on false value when not-nil" do
json = JSONAttrValue(Bool).from_json(%({"value": false}))
json.value.should be_false
end
it "parses JSON integer into a float property (#8618)" do
json = JSONAttrValue(Float64).from_json(%({"value": 123}))
json.value.should eq(123.0)
end
it "parses UUID" do
uuid = JSONAttrValue(UUID).from_json(%({"value": "ba714f86-cac6-42c7-8956-bcf5105e1b81"}))
uuid.should be_a(JSONAttrValue(UUID))
uuid.value.should eq(UUID.new("ba714f86-cac6-42c7-8956-bcf5105e1b81"))
end
it "parses json with Time::Format converter" do
json = JSONAttrWithTime.from_json(%({"value": "2014-10-31 23:37:16"}))
json.value.should be_a(Time)
json.value.to_s.should eq("2014-10-31 23:37:16 UTC")
json.to_json.should eq(%({"value":"2014-10-31 23:37:16"}))
end
it "allows setting a nilable property to nil" do
person = JSONAttrPerson.new("John")
person.age = 1
person.age = nil
end
it "parses simple mapping" do
person = JSONAttrWithSimpleMapping.from_json(%({"name": "John", "age": 30}))
person.should be_a(JSONAttrWithSimpleMapping)
person.name.should eq("John")
person.age.should eq(30)
end
it "outputs with converter when nilable" do
json = JSONAttrWithNilableTime.new
json.to_json.should eq("{}")
end
it "outputs with converter when nilable when emit_null is true" do
json = JSONAttrWithNilableTimeEmittingNull.new
json.to_json.should eq(%({"value":null}))
end
it "outputs JSON with Hash" do
input = {
value: {"foo" => "bar"},
}.to_json
json = JSONAttrValue(Hash(String, String)).from_json(input)
json.to_json.should eq(input)
end
it "parses json with keywords" do
json = JSONAttrWithKeywordsMapping.from_json(%({"end": 1, "abstract": 2}))
json.end.should eq(1)
json.abstract.should eq(2)
end
it "parses json with any" do
json = JSONAttrWithAny.from_json(%({"name": "Hi", "any": [{"x": 1}, 2, "hey", true, false, 1.5, null]}))
json.name.should eq("Hi")
json.any.raw.should eq([{"x" => 1}, 2, "hey", true, false, 1.5, nil])
json.to_json.should eq(%({"name":"Hi","any":[{"x":1},2,"hey",true,false,1.5,null]}))
end
it "parses json with problematic keys" do
json = JSONAttrWithProblematicKeys.from_json(%({"key": 1, "pull": 2}))
json.key.should eq(1)
json.pull.should eq(2)
end
it "parses json array as set" do
json = JSONAttrValue(Set(String)).from_json(%({"value": ["a", "a", "b"]}))
json.value.should eq(Set(String){"a", "b"})
end
it "allows small types of integer" do
json = JSONAttrWithSmallIntegers.from_json(%({"foo": 23, "bar": 7}))
json.foo.should eq(23)
typeof(json.foo).should eq(Int16)
json.bar.should eq(7)
typeof(json.bar).should eq(Int8)
end
describe "parses json with defaults" do
it "mixed" do
json = JSONAttrWithDefaults.from_json(%({"a":1,"b":"bla"}))
json.a.should eq 1
json.b.should eq "bla"
json = JSONAttrWithDefaults.from_json(%({"a":1}))
json.a.should eq 1
json.b.should eq "Haha"
json = JSONAttrWithDefaults.from_json(%({"b":"bla"}))
json.a.should eq 11
json.b.should eq "bla"
json = JSONAttrWithDefaults.from_json(%({}))
json.a.should eq 11
json.b.should eq "Haha"
json = JSONAttrWithDefaults.from_json(%({"a":null,"b":null,"f":null}))
json.a.should eq 11
json.b.should eq "Haha"
json.f.should be_nil
end
it "bool" do
json = JSONAttrWithDefaults.from_json(%({}))
json.c.should eq true
typeof(json.c).should eq Bool
json.d.should eq false
typeof(json.d).should eq Bool
json = JSONAttrWithDefaults.from_json(%({"c":false}))
json.c.should eq false
json = JSONAttrWithDefaults.from_json(%({"c":true}))
json.c.should eq true
json = JSONAttrWithDefaults.from_json(%({"d":false}))
json.d.should eq false
json = JSONAttrWithDefaults.from_json(%({"d":true}))
json.d.should eq true
end
it "with nilable" do
json = JSONAttrWithDefaults.from_json(%({}))
json.e.should eq false
typeof(json.e).should eq(Bool | Nil)
json.f.should eq 1
typeof(json.f).should eq(Int32 | Nil)
json.g.should eq nil
typeof(json.g).should eq(Int32 | Nil)
json = JSONAttrWithDefaults.from_json(%({"e":false}))
json.e.should eq false
json = JSONAttrWithDefaults.from_json(%({"e":true}))
json.e.should eq true
end
it "create new array every time" do
json = JSONAttrWithDefaults.from_json(%({}))
json.h.should eq [1, 2, 3]
json.h << 4
json.h.should eq [1, 2, 3, 4]
json = JSONAttrWithDefaults.from_json(%({}))
json.h.should eq [1, 2, 3]
end
end
it "converter with null value (#13655)" do
JSONAttrNilableWithTimeEpoch.from_json(%({"value": null})).value.should be_nil
JSONAttrNilableWithTimeEpoch.from_json(%({"value":1459859781})).value.should eq Time.unix(1459859781)
end
it "converter with default value" do
JSONAttrDefaultWithTimeEpoch.from_json(%({"value": null})).value.should eq Time.unix(0)
JSONAttrDefaultWithTimeEpoch.from_json(%({"value":1459859781})).value.should eq Time.unix(1459859781)
end
it "uses Time::EpochConverter" do
string = %({"value":1459859781})
json = JSONAttrWithTimeEpoch.from_json(string)
json.value.should be_a(Time)
json.value.should eq(Time.unix(1459859781))
json.to_json.should eq(string)
end
it "uses Time::EpochMillisConverter" do
string = %({"value":1459860483856})
json = JSONAttrWithTimeEpochMillis.from_json(string)
json.value.should be_a(Time)
json.value.should eq(Time.unix_ms(1459860483856))
json.to_json.should eq(string)
end
describe JSON::ArrayConverter do
it "uses converter metaclass" do
string = %({"value":[1459859781]})
json = JSONAttrWithTimeArray1.from_json(string)
json.value.should be_a(Array(Time))
json.value.should eq([Time.unix(1459859781)])
json.to_json.should eq(string)
end
it "uses converter instance with nested converter metaclass" do
string = %({"value":[1459859781]})
json = JSONAttrWithTimeArray2.from_json(string)
json.value.should be_a(Array(Time))
json.value.should eq([Time.unix(1459859781)])
json.to_json.should eq(string)
end
it "uses converter instance with nested converter instance" do
string = %({"value":["2014-10-31 23:37:16"]})
json = JSONAttrWithTimeArray3.from_json(string)
json.value.should be_a(Array(Time))
json.value.map(&.to_s).should eq(["2014-10-31 23:37:16 UTC"])
json.to_json.should eq(string)
end
end
describe JSON::HashValueConverter do
it "uses converter metaclass" do
string = %({"value":{"foo":1459859781}})
json = JSONAttrWithTimeHash1.from_json(string)
json.value.should be_a(Hash(String, Time))
json.value.should eq({"foo" => Time.unix(1459859781)})
json.to_json.should eq(string)
end
it "uses converter instance with nested converter metaclass" do
string = %({"value":{"foo":1459859781}})
json = JSONAttrWithTimeHash2.from_json(string)
json.value.should be_a(Hash(String, Time))
json.value.should eq({"foo" => Time.unix(1459859781)})
json.to_json.should eq(string)
end
it "uses converter instance with nested converter instance" do
string = %({"value":{"foo":"2014-10-31 23:37:16"}})
json = JSONAttrWithTimeHash3.from_json(string)
json.value.should be_a(Hash(String, Time))
json.value.transform_values(&.to_s).should eq({"foo" => "2014-10-31 23:37:16 UTC"})
json.to_json.should eq(string)
end
end
it "parses raw value from int" do
string = %({"value":123456789123456789123456789123456789})
json = JSONAttrWithRaw.from_json(string)
json.value.should eq("123456789123456789123456789123456789")
json.to_json.should eq(string)
end
it "parses raw value from float" do
string = %({"value":123456789123456789.123456789123456789})
json = JSONAttrWithRaw.from_json(string)
json.value.should eq("123456789123456789.123456789123456789")
json.to_json.should eq(string)
end
it "parses raw value from object" do
string = %({"value":[null,true,false,{"x":[1,1.5]}]})
json = JSONAttrWithRaw.from_json(string)
json.value.should eq(%([null,true,false,{"x":[1,1.5]}]))
json.to_json.should eq(string)
end
it "parses with root" do
json = %({"result":{"heroes":[{"name":"Batman"}]}})
result = JSONAttrWithRoot.from_json(json)
result.result.should be_a(Array(JSONAttrPerson))
result.result.first.name.should eq "Batman"
result.to_json.should eq(json)
end
it "parses with nilable root" do
json = %({"result":null})
result = JSONAttrWithNilableRoot.from_json(json)
result.result.should be_nil
result.to_json.should eq("{}")
end
it "parses with nilable root and emit null" do
json = %({"result":null})
result = JSONAttrWithNilableRootEmitNull.from_json(json)
result.result.should be_nil
result.to_json.should eq(json)
end
it "parses nilable union" do
obj = JSONAttrValue(Int32?).from_json(%({"value": 1}))
obj.value.should eq(1)
obj.to_json.should eq(%({"value":1}))
obj = JSONAttrValue(Int32?).from_json(%({"value": null}))
obj.value.should be_nil
obj.to_json.should eq(%({}))
obj = JSONAttrValue(Int32?).from_json(%({}))
obj.value.should be_nil
obj.to_json.should eq(%({}))
end
describe "parses JSON with presence markers" do
it "parses person with absent attributes" do
json = JSONAttrWithPresence.from_json(%({"first_name": null}))
json.first_name.should be_nil
json.first_name_present?.should be_true
json.last_name.should be_nil
json.last_name_present?.should be_false
end
end
describe "serializes JSON with presence markers and ignore_serialize" do
context "ignore_serialize is set to a method which returns true when value is nil or empty string" do
it "ignores field when value is empty string" do
json = JSONAttrWithPresenceAndIgnoreSerialize.from_json(%({"first_name": ""}))
json.first_name_present?.should be_true
json.to_json.should eq(%({}))
end
it "ignores field when value is nil" do
json = JSONAttrWithPresenceAndIgnoreSerialize.from_json(%({"first_name": null}))
json.first_name_present?.should be_true
json.to_json.should eq(%({}))
end
end
context "ignore_serialize is set to conditional expressions 'last_name.nil? && !last_name_present?'" do
it "emits null when value is null and @last_name_present is true" do
json = JSONAttrWithPresenceAndIgnoreSerialize.from_json(%({"last_name": null}))
json.last_name_present?.should be_true
json.to_json.should eq(%({"last_name":null}))
end
it "does not emit null when value is null and @last_name_present is false" do
json = JSONAttrWithPresenceAndIgnoreSerialize.from_json(%({}))
json.last_name_present?.should be_false
json.to_json.should eq(%({}))
end
it "emits field when value is not nil and @last_name_present is false" do
json = JSONAttrWithPresenceAndIgnoreSerialize.new(last_name: "something")
json.last_name_present?.should be_false
json.to_json.should eq(%({"last_name":"something"}))
end
it "emits field when value is not nil and @last_name_present is true" do
json = JSONAttrWithPresenceAndIgnoreSerialize.from_json(%({"last_name":"something"}))
json.last_name_present?.should be_true
json.to_json.should eq(%({"last_name":"something"}))
end
end
end
describe "with query attributes" do
it "defines query getter" do
json = JSONAttrWithQueryAttributes.from_json(%({"foo": true}))
json.foo?.should be_true
json.bar?.should be_false
end
it "defines query getter with class restriction" do
{% begin %}
{% methods = JSONAttrWithQueryAttributes.methods %}
{{ methods.find(&.name.==("foo?")).return_type }}.should eq(Bool)
{{ methods.find(&.name.==("bar?")).return_type }}.should eq(Bool)
{% end %}
end
it "defines non-query setter and presence methods" do
json = JSONAttrWithQueryAttributes.from_json(%({"foo": false}))
json.bar_present?.should be_false
json.bar = true
json.bar?.should be_true
end
it "maps non-query attributes" do
json = JSONAttrWithQueryAttributes.from_json(%({"foo": false, "is_bar": false}))
json.bar_present?.should be_true
json.bar?.should be_false
json.bar = true
json.to_json.should eq(%({"foo":false,"is_bar":true}))
end
it "raises if non-nilable attribute is nil" do
error_message = <<-'MSG'
Missing JSON attribute: foo
parsing JSONAttrWithQueryAttributes at line 1, column 1
MSG
ex = expect_raises ::JSON::SerializableError, error_message do
JSONAttrWithQueryAttributes.from_json(%({"is_bar": true}))
end
ex.location.should eq({1, 1})
end
end
describe "BigDecimal" do
it "parses json string with BigDecimal" do
json = JSONAttrValue(BigDecimal).from_json(%({"value": "10.05"}))
json.value.should eq(BigDecimal.new("10.05"))
end
it "parses large json ints with BigDecimal" do
json = JSONAttrValue(BigDecimal).from_json(%({"value": 9223372036854775808}))
json.value.should eq(BigDecimal.new("9223372036854775808"))
end
it "parses json float with BigDecimal" do
json = JSONAttrValue(BigDecimal).from_json(%({"value": 10.05}))
json.value.should eq(BigDecimal.new("10.05"))
end
it "parses large precision json floats with BigDecimal" do
json = JSONAttrValue(BigDecimal).from_json(%({"value": 0.00045808999999999997}))
json.value.should eq(BigDecimal.new("0.00045808999999999997"))
end
end
it "parses 128-bit integer" do
json = JSONAttrValue(Int128).from_json(%({"value": #{Int128::MAX}}))
json.value.should eq Int128::MAX
end
describe "work with module and inheritance" do
it { JSONAttrModuleTest.from_json(%({"phoo": 20})).to_tuple.should eq({10, 20}) }
it { JSONAttrModuleTest.from_json(%({"phoo": 20})).to_tuple.should eq({10, 20}) }
it { JSONAttrModuleTest2.from_json(%({"phoo": 20, "bar": 30})).to_tuple.should eq({10, 20, 30}) }
it { JSONAttrModuleTest2.from_json(%({"bar": 30, "moo": 40})).to_tuple.should eq({40, 15, 30}) }
end
it "works together with yaml" do
person = JSONAttrPersonWithYAML.new("Vasya", 30)
person.to_json.should eq "{\"name\":\"Vasya\",\"age\":30}"
person.to_yaml.should eq "---\nname: Vasya\nage: 30\n"
JSONAttrPersonWithYAML.from_json(person.to_json).should eq person
JSONAttrPersonWithYAML.from_yaml(person.to_yaml).should eq person
end
it "yaml and json with after_initialize hook" do
person = JSONAttrPersonWithYAMLInitializeHook.new("Vasya", 30)
person.msg.should eq "Hello Vasya"
person.to_json.should eq "{\"name\":\"Vasya\",\"age\":30}"
person.to_yaml.should eq "---\nname: Vasya\nage: 30\n"
JSONAttrPersonWithYAMLInitializeHook.from_json(person.to_json).msg.should eq "Hello Vasya"
JSONAttrPersonWithYAMLInitializeHook.from_yaml(person.to_yaml).msg.should eq "Hello Vasya"
end
it "json with selective serialization" do
person = JSONAttrPersonWithSelectiveSerialization.new("Vasya", "P@ssw0rd")
person.to_json.should eq "{\"name\":\"Vasya\",\"generated\":\"generated-internally\"}"
person_json = "{\"name\":\"Vasya\",\"generated\":\"should not set\",\"password\":\"update\"}"
person = JSONAttrPersonWithSelectiveSerialization.from_json(person_json)
person.generated.should eq "generated-internally"
person.password.should eq "update"
end
describe "use_json_discriminator" do
it "deserializes with discriminator" do
point = JSONShape.from_json(%({"type": "point", "x": 1, "y": 2})).as(JSONPoint)
point.x.should eq(1)
point.y.should eq(2)
circle = JSONShape.from_json(%({"type": "circle", "x": 1, "y": 2, "radius": 3})).as(JSONCircle)
circle.x.should eq(1)
circle.y.should eq(2)
circle.radius.should eq(3)
end
it "raises if missing discriminator" do
expect_raises(::JSON::SerializableError, "Missing JSON discriminator field 'type'") do
JSONShape.from_json("{}")
end
end
it "raises if unknown discriminator value" do
expect_raises(::JSON::SerializableError, %(Unknown 'type' discriminator value: "unknown")) do
JSONShape.from_json(%({"type": "unknown"}))
end
end
it "deserializes with variable discriminator value type" do
object_number = JSONVariableDiscriminatorValueType.from_json(%({"type": 0}))
object_number.should be_a(JSONVariableDiscriminatorNumber)
object_string = JSONVariableDiscriminatorValueType.from_json(%({"type": "1"}))
object_string.should be_a(JSONVariableDiscriminatorString)
object_bool = JSONVariableDiscriminatorValueType.from_json(%({"type": true}))
object_bool.should be_a(JSONVariableDiscriminatorBoolTrue)
object_bool = JSONVariableDiscriminatorValueType.from_json(%({"type": false}))
object_bool.should be_a(JSONVariableDiscriminatorBoolFalse)
object_enum = JSONVariableDiscriminatorValueType.from_json(%({"type": 4}))
object_enum.should be_a(JSONVariableDiscriminatorEnum)
object_enum = JSONVariableDiscriminatorValueType.from_json(%({"type": 18}))
object_enum.should be_a(JSONVariableDiscriminatorEnum8)
end
it "deserializes with discriminator, strict recursive type" do
foo = JSONStrictDiscriminator.from_json(%({"type": "foo"}))
foo = foo.should be_a(JSONStrictDiscriminatorFoo)
bar = JSONStrictDiscriminator.from_json(%({"type": "bar", "x": {"type": "foo"}, "y": {"type": "foo"}}))
bar = bar.should be_a(JSONStrictDiscriminatorBar)
bar.x.should be_a(JSONStrictDiscriminatorFoo)
bar.y.should be_a(JSONStrictDiscriminatorFoo)
end
it "deserializes with discriminator, another recursive type, fixes: #13429" do
c = JsonDiscriminatorBug::Base.from_json %q({"type": "c", "source": {"type": "a"}, "value": 2})
c.as(JsonDiscriminatorBug::C).value.should eq 2
c = JsonDiscriminatorBug::Base.from_json %q({"type": "c", "source": {"type": "a"}})
c.as(JsonDiscriminatorBug::C).value.should eq 1
end
end
describe "namespaced classes" do
it "lets default values use the object's own namespace" do
request = JSONNamespace::FooRequest.from_json(%({"foo":{}}))
request.foo.id.should eq "id:foo"
request.bar.id.should eq "id:bar"
end
end
it "fixes #13337" do
JSONSomething.from_json(%({"value":{}})).value.should_not be_nil
end
end
|