codec_test.go (2629B)
1 // This file is part of taler-cashless2ecash. 2 // Copyright (C) 2024 Joel Häberli 3 // 4 // taler-cashless2ecash is free software: you can redistribute it and/or modify it 5 // under the terms of the GNU Affero General Public License as published 6 // by the Free Software Foundation, either version 3 of the License, 7 // or (at your option) any later version. 8 // 9 // taler-cashless2ecash is distributed in the hope that it will be useful, but 10 // WITHOUT ANY WARRANTY; without even the implied warranty of 11 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 12 // Affero General Public License for more details. 13 // 14 // You should have received a copy of the GNU Affero General Public License 15 // along with this program. If not, see <http://www.gnu.org/licenses/>. 16 // 17 // SPDX-License-Identifier: AGPL3.0-or-later 18 19 package internal_utils_test 20 21 import ( 22 "bytes" 23 internal_api "c2ec/internal/api" 24 internal_utils "c2ec/internal/utils" 25 "fmt" 26 "testing" 27 28 "gotest.tools/v3/assert" 29 ) 30 31 func TestJsonCodecRoundTrip(t *testing.T) { 32 33 type TestStruct struct { 34 A string 35 B int 36 C []string 37 D byte 38 E []byte 39 F *TestStruct 40 } 41 42 testObj := TestStruct{ 43 "TestA", 44 1, 45 []string{"first", "second"}, 46 'A', 47 []byte{0xdf, 0x01, 0x34}, 48 &TestStruct{ 49 "TestAA", 50 2, 51 []string{"third", "fourth", "fifth"}, 52 'B', 53 []byte{0xdf, 0x01, 0x34}, 54 nil, 55 }, 56 } 57 58 jsonCodec := new(internal_utils.JsonCodec[TestStruct]) 59 60 encodedTestObj, err := jsonCodec.Encode(&testObj) 61 if err != nil { 62 fmt.Println("error happened while encoding test obj", err.Error()) 63 t.FailNow() 64 } 65 66 encodedTestObjBytes := make([]byte, 200) 67 _, err = encodedTestObj.Read(encodedTestObjBytes) 68 if err != nil { 69 fmt.Println("error happened while encoding test obj to byte array", err.Error()) 70 t.FailNow() 71 } 72 73 encodedTestObjReader := bytes.NewReader(encodedTestObjBytes) 74 decodedTestObj, err := jsonCodec.Decode(encodedTestObjReader) 75 if err != nil { 76 fmt.Println("error happened while encoding test obj to byte array", err.Error()) 77 t.FailNow() 78 } 79 80 assert.DeepEqual(t, &testObj, decodedTestObj) 81 } 82 83 func TestTransferRequest(t *testing.T) { 84 85 reqStr := "{\"request_uid\":\"test-1\",\"amount\":\"CHF:4.95\",\"exchange_base_url\":\"https://exchange.chf.taler.net\",\"wtid\":\"\",\"credit_account\":\"payto://wallee-transaction/R361ZT45TZ026EQ0S909C88F0E2YJY11HXV0VQTCHKR2VHA7DQCG\"}" 86 87 fmt.Println("request string:", reqStr) 88 89 codec := new(internal_utils.JsonCodec[internal_api.TransferRequest]) 90 91 rdr := bytes.NewReader([]byte(reqStr)) 92 93 req, err := codec.Decode(rdr) 94 if err != nil { 95 fmt.Println("error:", err) 96 t.FailNow() 97 } 98 99 fmt.Println(req) 100 }