Adding JSON serialization/deserialization for the ChargedIncrement

This commit is contained in:
DanB
2020-06-07 20:38:52 +02:00
parent 2fdc0ad262
commit 64cd0f365e
3 changed files with 91 additions and 3 deletions

View File

@@ -24,6 +24,6 @@ import "time"
type ChargedIncrement struct {
Usage time.Duration
Cost *Decimal
AccountSID string // AccountS charged information
AccountingID string // Accounting charged information
CompressFactor int
}

View File

@@ -0,0 +1,60 @@
/*
Real-time Online/Offline Charging System (OerS) for Telecom & ISP environments
Copyright (C) ITsysCOM GmbH
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>
*/
package utils
import (
"encoding/json"
"reflect"
"testing"
"time"
)
func TestJSONMarshalUnmarshal(t *testing.T) {
incrmt := &ChargedIncrement{
Usage: time.Duration(1 * time.Hour),
Cost: NewDecimalFromFloat64(2.13),
AccountingID: "abbsjweejrmdhfr",
CompressFactor: 1,
}
jsn, err := json.Marshal(incrmt)
if err != nil {
t.Error(err)
}
var uIncrmnt ChargedIncrement
if err := json.Unmarshal(jsn, &uIncrmnt); err != nil {
t.Error(err)
}
if !reflect.DeepEqual(incrmt, &uIncrmnt) {
t.Errorf("expecting: %+v, received: %+v", incrmt, uIncrmnt)
}
incrmt = &ChargedIncrement{
Usage: time.Duration(1 * time.Hour),
AccountingID: "abbsjweejrmdhfr",
CompressFactor: 1,
}
if jsn, err = json.Marshal(incrmt); err != nil {
t.Error(err)
}
if err := json.Unmarshal(jsn, &uIncrmnt); err != nil {
t.Error(err)
}
if !reflect.DeepEqual(incrmt, &uIncrmnt) {
t.Errorf("expecting: %+v, received: %+v", incrmt, uIncrmnt)
}
}

View File

@@ -22,6 +22,34 @@ import (
"github.com/ericlagergren/decimal"
)
type Decimal struct {
val *decimal.Big
func NewDecimalFromFloat64(x float64) *Decimal {
return &Decimal{new(decimal.Big).SetFloat64(x)}
}
func NewDecimal() *Decimal {
return &Decimal{new(decimal.Big)}
}
// Decimal extends the decimal.Big with additional methods
type Decimal struct {
*decimal.Big
}
func (d *Decimal) Float64() (f float64) {
f, _ = d.Big.Float64()
return
}
func (d *Decimal) MarshalJSON() ([]byte, error) {
if d.Big == nil {
d.Big = new(decimal.Big)
}
return d.Big.MarshalText()
}
func (d *Decimal) UnmarshalJSON(data []byte) error {
if d.Big == nil {
d.Big = new(decimal.Big)
}
return d.Big.UnmarshalJSON(data)
}