From a7eb5388923102ff0690cd1d187915b38ffe7cfd Mon Sep 17 00:00:00 2001 From: Karchnu Date: Fri, 27 Nov 2020 22:37:57 +0100 Subject: [PATCH] CBOR specs: a first bunch of tests, WIP. --- spec/cbor_spec.cr | 95 ++++++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 93 insertions(+), 2 deletions(-) diff --git a/spec/cbor_spec.cr b/spec/cbor_spec.cr index 4d6dc79..66bfa87 100644 --- a/spec/cbor_spec.cr +++ b/spec/cbor_spec.cr @@ -1,5 +1,96 @@ require "./spec_helper" -describe CBOR do - # TODO: Write tests +class Location + include CBOR::Serializable + + @[CBOR::Field(key: "lat")] + property latitude : Float64 + + @[CBOR::Field(key: "lng")] + property longitude : Float64 + + def initialize(@latitude, @longitude) + end +end + +class House + include CBOR::Serializable + + property address : String + property location : Location? + + def initialize(@address) + end +end + +class Person + include CBOR::Serializable + include CBOR::Serializable::Unmapped + + property name : String? + def initialize(@name = nil) + end +end + +describe CBOR do + + describe "basics: to_cbor" do + it "array - strings" do + ["a", "b", "c"].to_cbor.hexstring.should eq "83616161626163" + end + it "array - " do + ["a", "b", "c"].to_cbor.hexstring.should eq "83616161626163" + end + it "hash" do + {"a" => 10, "b" => true, "c" => nil}.to_cbor.hexstring.should eq "a361610a6162f56163f6" + end + end + + describe "CBOR library annotations and features" do + it "Person#from_cbor with unmapped values" do + h = Hash(String | Int32, String | Int32).new + h["name"] = "Alice" + h["age"] = 30 + h["size"] = 160 + alice = Person.from_cbor h.to_cbor + alice.to_cbor.hexstring.should eq "a3646e616d6565416c69636563616765181e6473697a6518a0" + end + + it "Person#to_cbor with unmapped values" do + alice = Person.new "Alice" + alice.cbor_unmapped["age"] = 30 + alice.cbor_unmapped["size"] = 160 + alice.to_cbor.hexstring.should eq "a3646e616d6565416c69636563616765181e6473697a6518a0" + end + end + + describe "CBOR::Any" do + it "from JSON::Any - 1" do + h_any = {"a" => "b", "c" => "d", "e" => true, "f" => 10} + json_any = JSON.parse h_any.to_json + cbor_any = CBOR::Any.new json_any + cbor_any.to_cbor.hexstring.should eq "a461616162616361646165f561660a" + end + + it "from JSON::Any - 2" do + h_any = {"a" => "b", "c" => "d", "e" => true, "f" => 10} + json_any = JSON.parse h_any.to_json + cbor_any = CBOR::Any.new json_any + cbor_any["f"].should eq 10 + end + + it "from array" do + array = CBOR::Any.from_cbor [ "a", "b", "c", "d" ].to_cbor + array.to_cbor.hexstring.should eq "846161616261636164" + end + + it "from hash" do + h_cany = Hash(String | Int32, String | Int32).new + h_cany["name"] = "Alice" + h_cany["age"] = 30 + h_cany["size"] = 160 + cbor_any_hash = CBOR::Any.from_cbor h_cany.to_cbor + cbor_any_hash.to_cbor.hexstring.should eq "a3646e616d6565416c69636563616765181e6473697a6518a0" + end + end end