|
| 1 | +// Copyright 2024 Blink Labs Software |
| 2 | +// |
| 3 | +// Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 | +// you may not use this file except in compliance with the License. |
| 5 | +// You may obtain a copy of the License at |
| 6 | +// |
| 7 | +// http://www.apache.org/licenses/LICENSE-2.0 |
| 8 | +// |
| 9 | +// Unless required by applicable law or agreed to in writing, software |
| 10 | +// distributed under the License is distributed on an "AS IS" BASIS, |
| 11 | +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 | +// See the License for the specific language governing permissions and |
| 13 | +// limitations under the License. |
| 14 | + |
| 15 | +package cbor_test |
| 16 | + |
| 17 | +import ( |
| 18 | + "encoding/hex" |
| 19 | + "math/big" |
| 20 | + "reflect" |
| 21 | + "testing" |
| 22 | + |
| 23 | + "github.com/blinklabs-io/gouroboros/cbor" |
| 24 | +) |
| 25 | + |
| 26 | +var tagsTestDefs = []struct { |
| 27 | + cborHex string |
| 28 | + object any |
| 29 | +}{ |
| 30 | + { |
| 31 | + cborHex: "d81843abcdef", |
| 32 | + object: cbor.WrappedCbor([]byte{0xab, 0xcd, 0xef}), |
| 33 | + }, |
| 34 | + { |
| 35 | + cborHex: "d81e82031903e8", |
| 36 | + object: cbor.Rat{ |
| 37 | + Rat: big.NewRat(3, 1000), |
| 38 | + }, |
| 39 | + }, |
| 40 | + { |
| 41 | + cborHex: "d9010283010203", |
| 42 | + object: cbor.Set( |
| 43 | + []any{ |
| 44 | + uint64(1), uint64(2), uint64(3), |
| 45 | + }, |
| 46 | + ), |
| 47 | + }, |
| 48 | + { |
| 49 | + cborHex: "d90103a201020304", |
| 50 | + object: cbor.Map( |
| 51 | + map[any]any{ |
| 52 | + uint64(1): uint64(2), |
| 53 | + uint64(3): uint64(4), |
| 54 | + }, |
| 55 | + ), |
| 56 | + }, |
| 57 | +} |
| 58 | + |
| 59 | +func TestTagsDecode(t *testing.T) { |
| 60 | + for _, testDef := range tagsTestDefs { |
| 61 | + cborData, err := hex.DecodeString(testDef.cborHex) |
| 62 | + if err != nil { |
| 63 | + t.Fatalf("failed to decode CBOR hex: %s", err) |
| 64 | + } |
| 65 | + var dest any |
| 66 | + if _, err := cbor.Decode(cborData, &dest); err != nil { |
| 67 | + t.Fatalf("failed to decode CBOR: %s", err) |
| 68 | + } |
| 69 | + if !reflect.DeepEqual(dest, testDef.object) { |
| 70 | + t.Fatalf( |
| 71 | + "CBOR did not decode to expected object\n got: %#v\n wanted: %#v", |
| 72 | + dest, |
| 73 | + testDef.object, |
| 74 | + ) |
| 75 | + } |
| 76 | + } |
| 77 | +} |
| 78 | + |
| 79 | +func TestTagsEncode(t *testing.T) { |
| 80 | + for _, testDef := range tagsTestDefs { |
| 81 | + cborData, err := cbor.Encode(testDef.object) |
| 82 | + if err != nil { |
| 83 | + t.Fatalf("failed to encode object to CBOR: %s", err) |
| 84 | + } |
| 85 | + cborHex := hex.EncodeToString(cborData) |
| 86 | + if cborHex != testDef.cborHex { |
| 87 | + t.Fatalf( |
| 88 | + "object did not encode to expected CBOR\n got: %s\n wanted: %s", |
| 89 | + cborHex, |
| 90 | + testDef.cborHex, |
| 91 | + ) |
| 92 | + } |
| 93 | + } |
| 94 | +} |
0 commit comments