From cf94fb529296f81ff34dd4e66c2fc7414383afdd Mon Sep 17 00:00:00 2001 From: Trial97 Date: Tue, 30 Mar 2021 14:01:22 +0300 Subject: [PATCH] Updated unit tests --- apier/v1/api_interfaces.go | 1 - apier/v1/api_interfaces_test.go | 7 - config/cachecfg_test.go | 26 - config/config_json_test.go | 10 - config/configsanity_test.go | 4 +- config/stordbcfg_test.go | 15 - console/ping_test.go | 102 ---- engine/balance_filter.go | 398 -------------- engine/balance_filter_test.go | 176 ------- engine/balances.go | 291 ----------- engine/balances_test.go | 293 ----------- engine/caches.go | 1 - engine/cdr_test.go | 547 ------------------- engine/chargers_test.go | 2 + engine/filters_test.go | 533 ------------------- engine/loader_csv_test.go | 750 +-------------------------- engine/mapevent_test.go | 357 ------------- engine/model_helpers_test.go | 423 +-------------- engine/models_test.go | 126 ----- engine/storage_test.go | 259 --------- engine/units_counter.go | 104 ---- engine/units_counter_test.go | 591 --------------------- general_tests/acntacts_test.go | 114 ---- general_tests/auth_test.go | 173 ------ general_tests/costs1_test.go | 153 ------ general_tests/datachrg1_test.go | 146 ------ general_tests/ddazmbl1_test.go | 172 ------ general_tests/ddazmbl2_test.go | 175 ------- general_tests/ddazmbl3_test.go | 168 ------ general_tests/filters_test.go | 18 +- general_tests/objectdp_test.go | 86 --- general_tests/sessions_race_test.go | 181 ------- general_tests/smschrg1_test.go | 100 ---- general_tests/tutorial_calls_test.go | 20 +- sessions/session_test.go | 39 +- sessions/sessions.go | 3 - sessions/sessions_bench_test.go | 249 --------- sessions/sessions_test.go | 49 -- sessions/sessionscover_test.go | 120 ++--- 39 files changed, 65 insertions(+), 6917 deletions(-) delete mode 100644 engine/balance_filter.go delete mode 100644 engine/balance_filter_test.go delete mode 100644 engine/balances.go delete mode 100644 engine/balances_test.go delete mode 100644 engine/units_counter.go delete mode 100644 engine/units_counter_test.go delete mode 100644 general_tests/acntacts_test.go delete mode 100644 general_tests/auth_test.go delete mode 100644 general_tests/costs1_test.go delete mode 100644 general_tests/datachrg1_test.go delete mode 100644 general_tests/ddazmbl1_test.go delete mode 100644 general_tests/ddazmbl2_test.go delete mode 100644 general_tests/ddazmbl3_test.go delete mode 100644 general_tests/objectdp_test.go delete mode 100644 general_tests/sessions_race_test.go delete mode 100644 general_tests/smschrg1_test.go delete mode 100644 sessions/sessions_bench_test.go diff --git a/apier/v1/api_interfaces.go b/apier/v1/api_interfaces.go index 1527a7e9f..760c9f950 100644 --- a/apier/v1/api_interfaces.go +++ b/apier/v1/api_interfaces.go @@ -215,7 +215,6 @@ type ReplicatorSv1Interface interface { RemoveTiming(id *utils.StringWithAPIOpts, reply *string) error RemoveResource(args *utils.TenantIDWithAPIOpts, reply *string) error RemoveResourceProfile(args *utils.TenantIDWithAPIOpts, reply *string) error - RemoveActions(id *utils.StringWithAPIOpts, reply *string) error RemoveRouteProfile(args *utils.TenantIDWithAPIOpts, reply *string) error RemoveAttributeProfile(args *utils.TenantIDWithAPIOpts, reply *string) error RemoveChargerProfile(args *utils.TenantIDWithAPIOpts, reply *string) error diff --git a/apier/v1/api_interfaces_test.go b/apier/v1/api_interfaces_test.go index 847b4e777..3e1cbadab 100644 --- a/apier/v1/api_interfaces_test.go +++ b/apier/v1/api_interfaces_test.go @@ -20,8 +20,6 @@ package v1 import ( "testing" - - "github.com/cgrates/cgrates/engine" ) func TestThresholdSv1Interface(t *testing.T) { @@ -59,11 +57,6 @@ func TestSessionSv1Interface(t *testing.T) { _ = SessionSv1Interface(NewSessionSv1(nil, nil)) } -func TestResponderInterface(t *testing.T) { - _ = ResponderInterface(NewDispatcherResponder(nil)) - _ = ResponderInterface(&engine.Responder{}) -} - func TestRateProfileInterface(t *testing.T) { _ = RateProfileSv1Interface(NewDispatcherRateSv1(nil)) _ = RateProfileSv1Interface(NewRateSv1(nil)) diff --git a/config/cachecfg_test.go b/config/cachecfg_test.go index 12dc2a2ad..af5283b3e 100644 --- a/config/cachecfg_test.go +++ b/config/cachecfg_test.go @@ -133,32 +133,6 @@ func TestCacheParamCfgloadFromJsonCfg2(t *testing.T) { } } -/* -func TestAddTmpCaches(t *testing.T) { - cfgJSON := &CacheJsonCfg{ - Partitions: &map[string]*CacheParamJsonCfg{ - utils.CacheRatingProfilesTmp: { - Limit: utils.IntPointer(-1), - Ttl: utils.StringPointer(time.Minute.String()), - }, - }, - } - expected := &CacheCfg{ - Partitions: map[string]*CacheParamCfg{}, - } - expected.AddTmpCaches() - json := NewDefaultCGRConfig() - if err = json.cacheCfg.loadFromJSONCfg(cfgJSON); err != nil { - t.Error(err) - } else if !reflect.DeepEqual(expected.Partitions[utils.CacheRatingProfilesTmp], - json.cacheCfg.Partitions[utils.CacheRatingProfilesTmp]) { - t.Errorf("Expected %+v, received %+v", utils.ToJSON(expected.Partitions[utils.CacheRatingProfilesTmp]), - utils.ToJSON(json.cacheCfg.Partitions[utils.CacheRatingProfilesTmp])) - } -} - -*/ - func TestCachesCfgAsMapInterface1(t *testing.T) { cfgJSONStr := `{ "caches":{ diff --git a/config/config_json_test.go b/config/config_json_test.go index 75b9d7f54..7a2c3aa4f 100644 --- a/config/config_json_test.go +++ b/config/config_json_test.go @@ -229,12 +229,6 @@ func TestCacheJsonCfg(t *testing.T) { utils.CacheTBLTPDestinations: {Limit: utils.IntPointer(-1), Ttl: utils.StringPointer(""), Static_ttl: utils.BoolPointer(false), Replicate: utils.BoolPointer(false)}, - utils.CacheTBLTPResources: {Limit: utils.IntPointer(-1), - Ttl: utils.StringPointer(""), Static_ttl: utils.BoolPointer(false), - Replicate: utils.BoolPointer(false)}, - utils.CacheTBLTPStats: {Limit: utils.IntPointer(-1), - Ttl: utils.StringPointer(""), Static_ttl: utils.BoolPointer(false), - Replicate: utils.BoolPointer(false)}, utils.CacheTBLTPThresholds: {Limit: utils.IntPointer(-1), Ttl: utils.StringPointer(""), Static_ttl: utils.BoolPointer(false), Replicate: utils.BoolPointer(false)}, @@ -361,10 +355,6 @@ func TestDfDataDbJsonCfg(t *testing.T) { Replicate: utils.BoolPointer(false), Remote: utils.BoolPointer(false), }, - utils.MetaAccountActionPlans: { - Replicate: utils.BoolPointer(false), - Remote: utils.BoolPointer(false), - }, utils.MetaTimings: { Replicate: utils.BoolPointer(false), Remote: utils.BoolPointer(false), diff --git a/config/configsanity_test.go b/config/configsanity_test.go index d75a7e844..3ede0b5ef 100644 --- a/config/configsanity_test.go +++ b/config/configsanity_test.go @@ -1207,13 +1207,13 @@ func TestConfigSanityDataDB(t *testing.T) { } cfg.cacheCfg = &CacheCfg{ Partitions: map[string]*CacheParamCfg{ - utils.CacheRateProfiles: { + utils.CacheAccountProfiles: { Limit: 1, }, }, } expected := " *accounts needs to be 0 when DataBD is *internal, received : 1" - cfg.cacheCfg.Partitions[utils.CacheRateProfiles].Limit = 0 + cfg.cacheCfg.Partitions[utils.CacheAccountProfiles].Limit = 0 cfg.resourceSCfg.Enabled = true expected = " the StoreInterval field needs to be -1 when DataBD is *internal, received : 0" if err := cfg.checkConfigSanity(); err == nil || err.Error() != expected { diff --git a/config/stordbcfg_test.go b/config/stordbcfg_test.go index 3e228c626..4a85f08a2 100644 --- a/config/stordbcfg_test.go +++ b/config/stordbcfg_test.go @@ -37,10 +37,6 @@ func TestStoreDbCfgloadFromJsonCfgCase1(t *testing.T) { Remote_conns: &[]string{"*conn1"}, Replication_conns: &[]string{"*conn1"}, Items: &map[string]*ItemOptJson{ - utils.MetaSessionsCosts: { - Remote: utils.BoolPointer(true), - Replicate: utils.BoolPointer(true), - }, utils.MetaCDRs: { Remote: utils.BoolPointer(true), Replicate: utils.BoolPointer(false), @@ -65,10 +61,6 @@ func TestStoreDbCfgloadFromJsonCfgCase1(t *testing.T) { RmtConns: []string{"*conn1"}, RplConns: []string{"*conn1"}, Items: map[string]*ItemOpt{ - utils.MetaSessionsCosts: { - Remote: true, - Replicate: true, - }, utils.MetaCDRs: { Remote: true, Replicate: false, @@ -86,9 +78,6 @@ func TestStoreDbCfgloadFromJsonCfgCase1(t *testing.T) { jsonCfg := NewDefaultCGRConfig() if err = jsonCfg.storDbCfg.loadFromJSONCfg(cfgJSON); err != nil { t.Error(err) - } else if !reflect.DeepEqual(expected.Items[utils.MetaSessionsCosts], jsonCfg.storDbCfg.Items[utils.MetaSessionsCosts]) { - t.Errorf("Expected %+v \n, recevied %+v", utils.ToJSON(expected.Items[utils.MetaSessionsCosts]), - utils.ToJSON(jsonCfg.storDbCfg.Items[utils.MetaSessionsCosts])) } else if !reflect.DeepEqual(expected.Opts, jsonCfg.storDbCfg.Opts) { t.Errorf("Expected %+v \n, recevied %+v", utils.ToJSON(expected.Opts), utils.ToJSON(jsonCfg.storDbCfg.Opts)) } else if !reflect.DeepEqual(expected.RplConns, jsonCfg.storDbCfg.RplConns) { @@ -276,10 +265,6 @@ func TestStorDbCfgClone(t *testing.T) { RmtConns: []string{"*conn1"}, RplConns: []string{"*conn1"}, Items: map[string]*ItemOpt{ - utils.MetaSessionsCosts: { - Remote: true, - Replicate: true, - }, utils.MetaCDRs: { Remote: true, Replicate: false, diff --git a/console/ping_test.go b/console/ping_test.go index cb9ffb645..5bec97da6 100644 --- a/console/ping_test.go +++ b/console/ping_test.go @@ -370,108 +370,6 @@ func TestCmdPingAnalyzerSLow(t *testing.T) { } } -func TestCmdPingSchedulerSLow(t *testing.T) { - // commands map is initiated in init function - command := commands["ping"] - castCommand, canCast := command.(*CmdApierPing) - if !canCast { - t.Fatalf("cannot cast") - } - castCommand.item = utils.SchedulerSLow - result2 := command.RpcMethod() - if !reflect.DeepEqual(result2, utils.SchedulerSv1Ping) { - t.Errorf("Expected <%+v>, Received <%+v>", utils.SchedulerSv1Ping, result2) - } - m, ok := reflect.TypeOf(new(v1.SchedulerSv1)).MethodByName(strings.Split(command.RpcMethod(), utils.NestingSep)[1]) - if !ok { - t.Fatal("method not found") - } - if m.Type.NumIn() != 3 { // ApierSv1 is consider and we expect 3 inputs - t.Fatalf("invalid number of input parameters ") - } - // for coverage purpose - result := command.RpcParams(true) - if !reflect.DeepEqual(result, new(StringWrapper)) { - t.Errorf("Expected <%T>, Received <%T>", new(StringWrapper), result) - } - // verify the type of output parameter - if ok := m.Type.In(2).AssignableTo(reflect.TypeOf(command.RpcResult())); !ok { - t.Fatalf("cannot assign output parameter") - } - // for coverage purpose - if err := command.PostprocessRpcParams(); err != nil { - t.Fatal(err) - } -} - -func TestCmdPingRALsLow(t *testing.T) { - // commands map is initiated in init function - command := commands["ping"] - castCommand, canCast := command.(*CmdApierPing) - if !canCast { - t.Fatalf("cannot cast") - } - castCommand.item = utils.RALsLow - result2 := command.RpcMethod() - if !reflect.DeepEqual(result2, utils.RALsV1Ping) { - t.Errorf("Expected <%+v>, Received <%+v>", utils.RALsV1Ping, result2) - } - m, ok := reflect.TypeOf(new(v1.RALsV1)).MethodByName(strings.Split(command.RpcMethod(), utils.NestingSep)[1]) - if !ok { - t.Fatal("method not found") - } - if m.Type.NumIn() != 3 { // ApierSv1 is consider and we expect 3 inputs - t.Fatalf("invalid number of input parameters ") - } - // for coverage purpose - result := command.RpcParams(true) - if !reflect.DeepEqual(result, new(StringWrapper)) { - t.Errorf("Expected <%T>, Received <%T>", new(StringWrapper), result) - } - // verify the type of output parameter - if ok := m.Type.In(2).AssignableTo(reflect.TypeOf(command.RpcResult())); !ok { - t.Fatalf("cannot assign output parameter") - } - // for coverage purpose - if err := command.PostprocessRpcParams(); err != nil { - t.Fatal(err) - } -} - -func TestCmdPingReplicatorLow(t *testing.T) { - // commands map is initiated in init function - command := commands["ping"] - castCommand, canCast := command.(*CmdApierPing) - if !canCast { - t.Fatalf("cannot cast") - } - castCommand.item = utils.ReplicatorLow - result2 := command.RpcMethod() - if !reflect.DeepEqual(result2, utils.ReplicatorSv1Ping) { - t.Errorf("Expected <%+v>, Received <%+v>", utils.RALsV1Ping, result2) - } - m, ok := reflect.TypeOf(new(v1.ReplicatorSv1)).MethodByName(strings.Split(command.RpcMethod(), utils.NestingSep)[1]) - if !ok { - t.Fatal("method not found") - } - if m.Type.NumIn() != 3 { // ApierSv1 is consider and we expect 3 inputs - t.Fatalf("invalid number of input parameters ") - } - // for coverage purpose - result := command.RpcParams(true) - if !reflect.DeepEqual(result, new(StringWrapper)) { - t.Errorf("Expected <%T>, Received <%T>", new(StringWrapper), result) - } - // verify the type of output parameter - if ok := m.Type.In(2).AssignableTo(reflect.TypeOf(command.RpcResult())); !ok { - t.Fatalf("cannot assign output parameter") - } - // for coverage purpose - if err := command.PostprocessRpcParams(); err != nil { - t.Fatal(err) - } -} - func TestCmdPingApierSLow(t *testing.T) { // commands map is initiated in init function command := commands["ping"] diff --git a/engine/balance_filter.go b/engine/balance_filter.go deleted file mode 100644 index 409d4a642..000000000 --- a/engine/balance_filter.go +++ /dev/null @@ -1,398 +0,0 @@ -/* -Real-time Online/Offline Charging System (OCS) 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 -*/ - -package engine - -import ( - "math" - "reflect" - "time" - - "github.com/cgrates/cgrates/utils" -) - -type BalanceFilter struct { - Uuid *string - ID *string - Type *string - Value *utils.ValueFormula - ExpirationDate *time.Time - Weight *float64 - DestinationIDs *utils.StringMap - RatingSubject *string - Categories *utils.StringMap - SharedGroups *utils.StringMap - TimingIDs *utils.StringMap - Disabled *bool - Factor *ValueFactor - Blocker *bool -} - -// NewBalanceFilter creates a new BalanceFilter based on given filter -func NewBalanceFilter(filter map[string]interface{}, defaultTimezone string) (bf *BalanceFilter, err error) { - bf = new(BalanceFilter) - if id, has := filter[utils.ID]; has { - bf.ID = utils.StringPointer(utils.IfaceAsString(id)) - } - if uuid, has := filter[utils.UUID]; has { - bf.Uuid = utils.StringPointer(utils.IfaceAsString(uuid)) - } - // if ty, has := filter[utils.Type]; has { - // bf.Type = utils.StringPointer(utils.IfaceAsString(ty)) - // } - if val, has := filter[utils.Value]; has { - var value float64 - if value, err = utils.IfaceAsFloat64(val); err != nil { - return - } - bf.Value = &utils.ValueFormula{Static: math.Abs(value)} - } - if exp, has := filter[utils.ExpiryTime]; has { - var expTime time.Time - if expTime, err = utils.IfaceAsTime(exp, defaultTimezone); err != nil { - return - } - bf.ExpirationDate = utils.TimePointer(expTime) - } - if weight, has := filter[utils.Weight]; has { - var value float64 - if value, err = utils.IfaceAsFloat64(weight); err != nil { - return - } - bf.Weight = utils.Float64Pointer(value) - } - if dst, has := filter[utils.DestinationIDs]; has { - bf.DestinationIDs = utils.StringMapPointer(utils.ParseStringMap(utils.IfaceAsString(dst))) - } - if rs, has := filter[utils.RatingSubject]; has { - bf.RatingSubject = utils.StringPointer(utils.IfaceAsString(rs)) - } - if cat, has := filter[utils.Categories]; has { - bf.Categories = utils.StringMapPointer(utils.ParseStringMap(utils.IfaceAsString(cat))) - } - if grps, has := filter[utils.SharedGroups]; has { - bf.SharedGroups = utils.StringMapPointer(utils.ParseStringMap(utils.IfaceAsString(grps))) - } - if tim, has := filter[utils.TimingIDs]; has { - bf.TimingIDs = utils.StringMapPointer(utils.ParseStringMap(utils.IfaceAsString(tim))) - } - if dis, has := filter[utils.Disabled]; has { - var value bool - if value, err = utils.IfaceAsBool(dis); err != nil { - return - } - bf.Disabled = utils.BoolPointer(value) - } - if blk, has := filter[utils.Blocker]; has { - var value bool - if value, err = utils.IfaceAsBool(blk); err != nil { - return - } - bf.Blocker = utils.BoolPointer(value) - } - return -} - -func (bp *BalanceFilter) CreateBalance() *Balance { - b := &Balance{ - Uuid: bp.GetUuid(), - ID: bp.GetID(), - Value: bp.GetValue(), - ExpirationDate: bp.GetExpirationDate(), - Weight: bp.GetWeight(), - DestinationIDs: bp.GetDestinationIDs(), - RatingSubject: bp.GetRatingSubject(), - Categories: bp.GetCategories(), - SharedGroups: bp.GetSharedGroups(), - TimingIDs: bp.GetTimingIDs(), - Disabled: bp.GetDisabled(), - Factor: bp.GetFactor(), - Blocker: bp.GetBlocker(), - } - return b.Clone() -} - -func (bf *BalanceFilter) Clone() *BalanceFilter { - if bf == nil { - return nil - } - result := &BalanceFilter{} - if bf.Uuid != nil { - result.Uuid = new(string) - *result.Uuid = *bf.Uuid - } - if bf.ID != nil { - result.ID = new(string) - *result.ID = *bf.ID - } - if bf.Type != nil { - result.Type = new(string) - *result.Type = *bf.Type - } - if bf.Value != nil { - result.Value = new(utils.ValueFormula) - *result.Value = *bf.Value - } - if bf.ExpirationDate != nil { - result.ExpirationDate = new(time.Time) - *result.ExpirationDate = *bf.ExpirationDate - } - if bf.Weight != nil { - result.Weight = new(float64) - *result.Weight = *bf.Weight - } - if bf.DestinationIDs != nil { - result.DestinationIDs = utils.StringMapPointer(bf.DestinationIDs.Clone()) - } - if bf.RatingSubject != nil { - result.RatingSubject = new(string) - *result.RatingSubject = *bf.RatingSubject - } - if bf.Categories != nil { - result.Categories = utils.StringMapPointer(bf.Categories.Clone()) - } - if bf.SharedGroups != nil { - result.SharedGroups = utils.StringMapPointer(bf.SharedGroups.Clone()) - } - if bf.TimingIDs != nil { - result.TimingIDs = utils.StringMapPointer(bf.TimingIDs.Clone()) - } - if bf.Disabled != nil { - result.Disabled = new(bool) - *result.Disabled = *bf.Disabled - } - if bf.Factor != nil { - result.Factor = new(ValueFactor) - *result.Factor = *bf.Factor - } - if bf.Blocker != nil { - result.Blocker = new(bool) - *result.Blocker = *bf.Blocker - } - return result -} - -func (bf *BalanceFilter) LoadFromBalance(b *Balance) *BalanceFilter { - if b.Uuid != "" { - bf.Uuid = &b.Uuid - } - if b.ID != "" { - bf.ID = &b.ID - } - if b.Value != 0 { - bf.Value.Static = b.Value - } - if !b.ExpirationDate.IsZero() { - bf.ExpirationDate = &b.ExpirationDate - } - if b.Weight != 0 { - bf.Weight = &b.Weight - } - if !b.DestinationIDs.IsEmpty() { - bf.DestinationIDs = &b.DestinationIDs - } - if b.RatingSubject != "" { - bf.RatingSubject = &b.RatingSubject - } - if !b.Categories.IsEmpty() { - bf.Categories = &b.Categories - } - if !b.SharedGroups.IsEmpty() { - bf.SharedGroups = &b.SharedGroups - } - if !b.TimingIDs.IsEmpty() { - bf.TimingIDs = &b.TimingIDs - } - if len(b.Factor) != 0 { - bf.Factor = &b.Factor - } - if b.Disabled { - bf.Disabled = &b.Disabled - } - if b.Blocker { - bf.Blocker = &b.Blocker - } - return bf -} - -func (bp *BalanceFilter) Equal(o *BalanceFilter) bool { - if bp.ID != nil && o.ID != nil { - return *bp.ID == *o.ID - } - return reflect.DeepEqual(bp, o) -} - -func (bp *BalanceFilter) GetType() string { - if bp == nil || bp.Type == nil { - return "" - } - return *bp.Type -} - -func (bp *BalanceFilter) GetValue() float64 { - if bp == nil || bp.Value == nil { - return 0.0 - } - if bp.Value.Method == "" { - return bp.Value.Static - } - // calculate using formula - formula, exists := utils.ValueFormulas[bp.Value.Method] - if !exists { - return 0.0 - } - return formula(bp.Value.Params) -} - -func (bp *BalanceFilter) SetValue(v float64) { - if bp.Value == nil { - bp.Value = new(utils.ValueFormula) - } - bp.Value.Static = v -} - -func (bp *BalanceFilter) GetUuid() string { - if bp == nil || bp.Uuid == nil { - return "" - } - return *bp.Uuid -} - -func (bp *BalanceFilter) GetID() string { - if bp == nil || bp.ID == nil { - return "" - } - return *bp.ID -} - -func (bp *BalanceFilter) GetDestinationIDs() utils.StringMap { - if bp == nil || bp.DestinationIDs == nil { - return utils.StringMap{} - } - return *bp.DestinationIDs -} - -func (bp *BalanceFilter) GetCategories() utils.StringMap { - if bp == nil || bp.Categories == nil { - return utils.StringMap{} - } - return *bp.Categories -} - -func (bp *BalanceFilter) GetTimingIDs() utils.StringMap { - if bp == nil || bp.TimingIDs == nil { - return utils.StringMap{} - } - return *bp.TimingIDs -} - -func (bp *BalanceFilter) GetSharedGroups() utils.StringMap { - if bp == nil || bp.SharedGroups == nil { - return utils.StringMap{} - } - return *bp.SharedGroups -} - -func (bp *BalanceFilter) GetWeight() float64 { - if bp == nil || bp.Weight == nil { - return 0.0 - } - return *bp.Weight -} - -func (bp *BalanceFilter) GetRatingSubject() string { - if bp == nil || bp.RatingSubject == nil { - return "" - } - return *bp.RatingSubject -} - -func (bp *BalanceFilter) GetDisabled() bool { - if bp == nil || bp.Disabled == nil { - return false - } - return *bp.Disabled -} - -func (bp *BalanceFilter) GetBlocker() bool { - if bp == nil || bp.Blocker == nil { - return false - } - return *bp.Blocker -} - -func (bp *BalanceFilter) GetExpirationDate() time.Time { - if bp == nil || bp.ExpirationDate == nil { - return time.Time{} - } - return *bp.ExpirationDate -} - -func (bp *BalanceFilter) GetFactor() ValueFactor { - if bp == nil || bp.Factor == nil { - return ValueFactor{} - } - return *bp.Factor -} - -func (bp *BalanceFilter) EmptyExpirationDate() bool { - if bp.ExpirationDate == nil { - return true - } - return (*bp.ExpirationDate).IsZero() -} - -func (bf *BalanceFilter) ModifyBalance(b *Balance) { - if b == nil { - return - } - if bf.ID != nil { - b.ID = *bf.ID - } - if bf.Value != nil { - b.Value = bf.GetValue() - } - if bf.ExpirationDate != nil { - b.ExpirationDate = *bf.ExpirationDate - } - if bf.RatingSubject != nil { - b.RatingSubject = *bf.RatingSubject - } - if bf.Categories != nil { - b.Categories = *bf.Categories - } - if bf.DestinationIDs != nil { - b.DestinationIDs = *bf.DestinationIDs - } - if bf.SharedGroups != nil { - b.SharedGroups = *bf.SharedGroups - } - if bf.TimingIDs != nil { - b.TimingIDs = *bf.TimingIDs - } - if bf.Weight != nil { - b.Weight = *bf.Weight - } - if bf.Blocker != nil { - b.Blocker = *bf.Blocker - } - if bf.Disabled != nil { - b.Disabled = *bf.Disabled - } - b.SetDirty() // Mark the balance as dirty since we have modified and it should be checked by action triggers -} diff --git a/engine/balance_filter_test.go b/engine/balance_filter_test.go deleted file mode 100644 index 1f308bb0d..000000000 --- a/engine/balance_filter_test.go +++ /dev/null @@ -1,176 +0,0 @@ -/* -Real-time Online/Offline Charging System (OCS) 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 -*/ -package engine - -import ( - "testing" - "time" - - "reflect" - - "github.com/cgrates/cgrates/utils" -) - -func TestNewBalanceFilter(t *testing.T) { - attrs := map[string]interface{}{} - expected := &BalanceFilter{} - if rply, err := NewBalanceFilter(attrs, ""); err != nil { - t.Error(err) - } else if !reflect.DeepEqual(expected, rply) { - t.Errorf("Expected: %s ,received: %s", utils.ToJSON(expected), utils.ToJSON(rply)) - } - - tNow := time.Now() - attrs = map[string]interface{}{ - utils.ID: "ID", - utils.UUID: "UUID", - utils.Value: 10.5, - utils.ExpiryTime: tNow, - utils.Weight: 10, - utils.DestinationIDs: "dst1;dst2", - utils.RatingSubject: "*zero", - utils.Categories: "call;voice", - utils.SharedGroups: "shrdGroup", - utils.TimingIDs: "*asap", - utils.Disabled: false, - utils.Blocker: true, - } - expected = &BalanceFilter{ - ID: utils.StringPointer("ID"), - Uuid: utils.StringPointer("UUID"), - Value: &utils.ValueFormula{Static: 10.5}, - ExpirationDate: utils.TimePointer(tNow), - Weight: utils.Float64Pointer(10), - DestinationIDs: utils.StringMapPointer(utils.NewStringMap("dst1", "dst2")), - RatingSubject: utils.StringPointer("*zero"), - Categories: utils.StringMapPointer(utils.NewStringMap("call", "voice")), - SharedGroups: utils.StringMapPointer(utils.NewStringMap("shrdGroup")), - TimingIDs: utils.StringMapPointer(utils.NewStringMap("*asap")), - Disabled: utils.BoolPointer(false), - Blocker: utils.BoolPointer(true), - } - if rply, err := NewBalanceFilter(attrs, ""); err != nil { - t.Error(err) - } else if !reflect.DeepEqual(expected, rply) { - t.Errorf("Expected: %s ,received: %s", utils.ToJSON(expected), utils.ToJSON(rply)) - } - attrs[utils.Blocker] = "10" - if _, err := NewBalanceFilter(attrs, ""); err == nil { - t.Error("Expecxted error received nil") - } - attrs[utils.Disabled] = "10" - if _, err := NewBalanceFilter(attrs, ""); err == nil { - t.Error("Expecxted error received nil") - } - attrs[utils.Weight] = "NotFloat" - if _, err := NewBalanceFilter(attrs, ""); err == nil { - t.Error("Expecxted error received nil") - } - attrs[utils.ExpirationDate] = "NotTime" - if _, err := NewBalanceFilter(attrs, ""); err == nil { - t.Error("Expecxted error received nil") - } - attrs[utils.Value] = "NotFloat" - if _, err := NewBalanceFilter(attrs, ""); err == nil { - t.Error("Expecxted error received nil") - } -} - -func TestBalanceFilterClone(t *testing.T) { - bf := &BalanceFilter{} - eOut := &BalanceFilter{} - if rcv := bf.Clone(); !reflect.DeepEqual(rcv, eOut) { - t.Errorf("Expecting: %+v,\n received: %+v", eOut, rcv) - } - bf = &BalanceFilter{ - Uuid: utils.StringPointer("Uuid_test"), - ID: utils.StringPointer("ID_test"), - Type: utils.StringPointer("Type_test"), - Value: &utils.ValueFormula{ - Method: "ValueMethod_test", - }, - ExpirationDate: utils.TimePointer(time.Date(2020, time.April, 18, 23, 0, 4, 0, time.UTC)), - Weight: utils.Float64Pointer(0.7), - DestinationIDs: &utils.StringMap{ - "DestinationIDs_true": true, - "DestinationIDs_false": false, - }, - RatingSubject: utils.StringPointer("RatingSubject_test"), - Categories: &utils.StringMap{ - "Categories_true": true, - "Categories_false": false, - }, - SharedGroups: &utils.StringMap{ - "SharedGroups_true": true, - "SharedGroups_false": false, - }, - TimingIDs: &utils.StringMap{ - "TimingIDs_true": true, - "TimingIDs_false": false, - }, - Timings: []*RITiming{ - {Years: utils.Years{2019}}, - {Months: utils.Months{4}}, - }, - Disabled: utils.BoolPointer(true), - Factor: &ValueFactor{AccountActionsCSVContent: 0.7}, - Blocker: utils.BoolPointer(true), - } - eOut = &BalanceFilter{ - Uuid: utils.StringPointer("Uuid_test"), - ID: utils.StringPointer("ID_test"), - Type: utils.StringPointer("Type_test"), - Value: &utils.ValueFormula{ - Method: "ValueMethod_test", - }, - ExpirationDate: utils.TimePointer(time.Date(2020, time.April, 18, 23, 0, 4, 0, time.UTC)), - Weight: utils.Float64Pointer(0.7), - DestinationIDs: &utils.StringMap{ - "DestinationIDs_true": true, - "DestinationIDs_false": false, - }, - RatingSubject: utils.StringPointer("RatingSubject_test"), - Categories: &utils.StringMap{ - "Categories_true": true, - "Categories_false": false, - }, - SharedGroups: &utils.StringMap{ - "SharedGroups_true": true, - "SharedGroups_false": false, - }, - TimingIDs: &utils.StringMap{ - "TimingIDs_true": true, - "TimingIDs_false": false, - }, - Timings: []*RITiming{ - {Years: utils.Years{2019}}, - {Months: utils.Months{4}}, - }, - Disabled: utils.BoolPointer(true), - Factor: &ValueFactor{AccountActionsCSVContent: 0.7}, - Blocker: utils.BoolPointer(true), - } - rcv := bf.Clone() - if !reflect.DeepEqual(rcv, eOut) { - t.Errorf("Expecting: %+v,\n received: %+v", eOut, rcv) - } - rcv.Weight = utils.Float64Pointer(0.8) - if *bf.Weight != 0.7 { - t.Errorf("Expecting: 0.7, received: %+v", *bf.Weight) - } -} diff --git a/engine/balances.go b/engine/balances.go deleted file mode 100644 index 386cd21c7..000000000 --- a/engine/balances.go +++ /dev/null @@ -1,291 +0,0 @@ -/* -Real-time Online/Offline Charging System (OCS) 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 -*/ - -package engine - -import ( - "fmt" - "sort" - "time" - - "github.com/cgrates/cgrates/utils" -) - -// Can hold different units as seconds or monetary -type Balance struct { - Uuid string //system wide unique - ID string // account wide unique - Value float64 - ExpirationDate time.Time - Weight float64 - DestinationIDs utils.StringMap - RatingSubject string - Categories utils.StringMap - SharedGroups utils.StringMap - TimingIDs utils.StringMap - Disabled bool - Factor ValueFactor - Blocker bool - precision int - dirty bool -} - -func (b *Balance) Equal(o *Balance) bool { - if len(b.DestinationIDs) == 0 { - b.DestinationIDs = utils.StringMap{utils.MetaAny: true} - } - if len(o.DestinationIDs) == 0 { - o.DestinationIDs = utils.StringMap{utils.MetaAny: true} - } - return b.Uuid == o.Uuid && - b.ID == o.ID && - b.ExpirationDate.Equal(o.ExpirationDate) && - b.Weight == o.Weight && - b.DestinationIDs.Equal(o.DestinationIDs) && - b.RatingSubject == o.RatingSubject && - b.Categories.Equal(o.Categories) && - b.SharedGroups.Equal(o.SharedGroups) && - b.Disabled == o.Disabled && - b.Blocker == o.Blocker -} - -func (b *Balance) MatchFilter(o *BalanceFilter, skipIds, skipExpiry bool) bool { - if o == nil { - return true - } - if !skipIds && o.Uuid != nil && *o.Uuid != "" { - return b.Uuid == *o.Uuid - } - if !skipIds && o.ID != nil && *o.ID != "" { - return b.ID == *o.ID - } - if !skipExpiry { - if o.ExpirationDate != nil && !b.ExpirationDate.Equal(*o.ExpirationDate) { - return false - } - } - return (o.Weight == nil || b.Weight == *o.Weight) && - (o.Blocker == nil || b.Blocker == *o.Blocker) && - (o.Disabled == nil || b.Disabled == *o.Disabled) && - (o.DestinationIDs == nil || b.DestinationIDs.Includes(*o.DestinationIDs)) && - (o.Categories == nil || b.Categories.Includes(*o.Categories)) && - (o.TimingIDs == nil || b.TimingIDs.Includes(*o.TimingIDs)) && - (o.SharedGroups == nil || b.SharedGroups.Includes(*o.SharedGroups)) && - (o.RatingSubject == nil || b.RatingSubject == *o.RatingSubject) -} - -func (b *Balance) HardMatchFilter(o *BalanceFilter, skipIds bool) bool { - if o == nil { - return true - } - if !skipIds && o.Uuid != nil && *o.Uuid != "" { - return b.Uuid == *o.Uuid - } - if !skipIds && o.ID != nil && *o.ID != "" { - return b.ID == *o.ID - } - return (o.ExpirationDate == nil || b.ExpirationDate.Equal(*o.ExpirationDate)) && - (o.Weight == nil || b.Weight == *o.Weight) && - (o.Blocker == nil || b.Blocker == *o.Blocker) && - (o.Disabled == nil || b.Disabled == *o.Disabled) && - (o.DestinationIDs == nil || b.DestinationIDs.Equal(*o.DestinationIDs)) && - (o.Categories == nil || b.Categories.Equal(*o.Categories)) && - (o.TimingIDs == nil || b.TimingIDs.Equal(*o.TimingIDs)) && - (o.SharedGroups == nil || b.SharedGroups.Equal(*o.SharedGroups)) && - (o.RatingSubject == nil || b.RatingSubject == *o.RatingSubject) -} - -// the default balance has standard Id -func (b *Balance) IsDefault() bool { - return b.ID == utils.MetaDefault -} - -// IsExpiredAt check if ExpirationDate is before time t -func (b *Balance) IsExpiredAt(t time.Time) bool { - return !b.ExpirationDate.IsZero() && b.ExpirationDate.Before(t) -} - -func (b *Balance) MatchCategory(category string) bool { - return len(b.Categories) == 0 || b.Categories[category] -} - -func (b *Balance) HasDestination() bool { - return len(b.DestinationIDs) > 0 && !b.DestinationIDs[utils.MetaAny] -} - -func (b *Balance) MatchDestination(destinationID string) bool { - return !b.HasDestination() || b.DestinationIDs[destinationID] -} - -func (b *Balance) Clone() *Balance { - if b == nil { - return nil - } - n := &Balance{ - Uuid: b.Uuid, - ID: b.ID, - Value: b.Value, // this value is in seconds - ExpirationDate: b.ExpirationDate, - Weight: b.Weight, - RatingSubject: b.RatingSubject, - Categories: b.Categories, - SharedGroups: b.SharedGroups, - TimingIDs: b.TimingIDs, - Blocker: b.Blocker, - Disabled: b.Disabled, - dirty: b.dirty, - } - if b.DestinationIDs != nil { - n.DestinationIDs = b.DestinationIDs.Clone() - } - return n -} - -func (b *Balance) GetValue() float64 { - return b.Value -} - -func (b *Balance) SetDirty() { - b.dirty = true -} - -// AsBalanceSummary converts the balance towards compressed information to be displayed -func (b *Balance) AsBalanceSummary(typ string) *BalanceSummary { - bd := &BalanceSummary{UUID: b.Uuid, ID: b.ID, Type: typ, Value: b.Value, Disabled: b.Disabled} - if bd.ID == "" { - bd.ID = b.Uuid - } - return bd -} - -/* -Structure to store minute buckets according to weight, precision or price. -*/ -type Balances []*Balance - -func (bc Balances) Len() int { - return len(bc) -} - -func (bc Balances) Swap(i, j int) { - bc[i], bc[j] = bc[j], bc[i] -} - -// we need the better ones at the beginning -func (bc Balances) Less(j, i int) bool { - return bc[i].precision < bc[j].precision || - (bc[i].precision == bc[j].precision && bc[i].Weight < bc[j].Weight) -} - -func (bc Balances) Sort() { - sort.Sort(bc) -} - -func (bc Balances) Equal(o Balances) bool { - if len(bc) != len(o) { - return false - } - bc.Sort() - o.Sort() - for i := 0; i < len(bc); i++ { - if !bc[i].Equal(o[i]) { - return false - } - } - return true -} - -func (bc Balances) Clone() Balances { - var newChain Balances - for _, b := range bc { - newChain = append(newChain, b.Clone()) - } - return newChain -} - -func (bc Balances) GetBalance(uuid string) *Balance { - for _, balance := range bc { - if balance.Uuid == uuid { - return balance - } - } - return nil -} - -func (bc Balances) HasBalance(balance *Balance) bool { - for _, b := range bc { - if b.Equal(balance) { - return true - } - } - return false -} - -type ValueFactor map[string]float64 - -func (f ValueFactor) GetValue(tor string) float64 { - if value, ok := f[tor]; ok { - return value - } - return 1.0 -} - -// BalanceSummary represents compressed information about a balance -type BalanceSummary struct { - UUID string // Balance UUID - ID string // Balance ID if not defined - Type string // *voice, *data, etc - Initial float64 // initial value before the debit operation - Value float64 - Disabled bool -} - -// BalanceSummaries is a list of BalanceSummaries -type BalanceSummaries []*BalanceSummary - -// BalanceSummaryWithUUD returns a BalanceSummary based on an UUID -func (bs BalanceSummaries) BalanceSummaryWithUUD(bsUUID string) (b *BalanceSummary) { - for _, blc := range bs { - if blc.UUID == bsUUID { - b = blc - break - } - } - return -} - -// FieldAsInterface func to help EventCost FieldAsInterface -func (bl *BalanceSummary) FieldAsInterface(fldPath []string) (val interface{}, err error) { - if bl == nil || len(fldPath) != 1 { - return nil, utils.ErrNotFound - } - switch fldPath[0] { - default: - return nil, fmt.Errorf("unsupported field prefix: <%s>", fldPath[0]) - case utils.UUID: - return bl.UUID, nil - case utils.ID: - return bl.ID, nil - case utils.Type: - return bl.Type, nil - case utils.Value: - return bl.Value, nil - case utils.Disabled: - return bl.Disabled, nil - } -} diff --git a/engine/balances_test.go b/engine/balances_test.go deleted file mode 100644 index b512abddb..000000000 --- a/engine/balances_test.go +++ /dev/null @@ -1,293 +0,0 @@ -/* -Real-time Online/Offline Charging System (OCS) 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 -*/ -package engine - -import ( - "testing" - "time" - - "github.com/cgrates/cgrates/utils" -) - -func TestBalanceSortPrecision(t *testing.T) { - mb1 := &Balance{Weight: 1, precision: 2} - mb2 := &Balance{Weight: 2, precision: 1} - var bs Balances - bs = append(bs, mb2, mb1) - bs.Sort() - if bs[0] != mb1 || bs[1] != mb2 { - t.Error("Buckets not sorted by weight!") - } -} - -func TestBalanceSortPrecisionWeightEqual(t *testing.T) { - mb1 := &Balance{Weight: 1, precision: 2} - mb2 := &Balance{Weight: 1, precision: 1} - var bs Balances - bs = append(bs, mb2, mb1) - bs.Sort() - if bs[0] != mb1 || bs[1] != mb2 { - t.Error("Buckets not sorted by precision!") - } -} - -func TestBalanceSortPrecisionWeightGreater(t *testing.T) { - mb1 := &Balance{Weight: 2, precision: 2} - mb2 := &Balance{Weight: 1, precision: 1} - var bs Balances - bs = append(bs, mb2, mb1) - bs.Sort() - if bs[0] != mb1 || bs[1] != mb2 { - t.Error("Buckets not sorted by precision!") - } -} - -func TestBalanceSortWeight(t *testing.T) { - mb1 := &Balance{Weight: 2, precision: 1} - mb2 := &Balance{Weight: 1, precision: 1} - var bs Balances - bs = append(bs, mb2, mb1) - bs.Sort() - if bs[0] != mb1 || bs[1] != mb2 { - t.Error("Buckets not sorted by precision!") - } -} - -func TestBalanceSortWeight2(t *testing.T) { - bs := Balances{ - &Balance{ID: "B1", Weight: 2, precision: 1}, - &Balance{ID: "B2", Weight: 1, precision: 1}, - } - bs.Sort() - if bs[0].ID != "B1" && bs[1].ID != "B2" { - t.Error("Buckets not sorted by precision!") - } -} - -func TestBalanceSortWeight3(t *testing.T) { - bs := Balances{ - &Balance{ID: "B1", Weight: 2, Value: 10.0}, - &Balance{ID: "B2", Weight: 4, Value: 10.0}, - } - bs.Sort() - if bs[0].ID != "B2" && bs[1].ID != "B1" { - t.Error(utils.ToJSON(bs)) - } -} - -func TestBalanceSortWeightLess(t *testing.T) { - mb1 := &Balance{Weight: 1, precision: 1} - mb2 := &Balance{Weight: 2, precision: 1} - var bs Balances - bs = append(bs, mb2, mb1) - bs.Sort() - if bs[0] != mb2 || bs[1] != mb1 { - t.Error("Buckets not sorted by precision!") - } -} - -func TestBalanceEqual(t *testing.T) { - mb1 := &Balance{Weight: 1, precision: 1, RatingSubject: "1", DestinationIDs: utils.StringMap{}} - mb2 := &Balance{Weight: 1, precision: 1, RatingSubject: "1", DestinationIDs: utils.StringMap{}} - mb3 := &Balance{Weight: 1, precision: 1, RatingSubject: "2", DestinationIDs: utils.StringMap{}} - if !mb1.Equal(mb2) || mb2.Equal(mb3) { - t.Error("Equal failure!", mb1 == mb2, mb3) - } -} - -func TestBalanceMatchFilter(t *testing.T) { - mb1 := &Balance{Weight: 1, precision: 1, RatingSubject: "1", DestinationIDs: utils.StringMap{}} - mb2 := &BalanceFilter{Weight: utils.Float64Pointer(1), RatingSubject: nil, DestinationIDs: nil} - if !mb1.MatchFilter(mb2, false, false) { - t.Errorf("Match filter failure: %+v == %+v", mb1, mb2) - } -} - -func TestBalanceMatchFilterEmpty(t *testing.T) { - mb1 := &Balance{Weight: 1, precision: 1, RatingSubject: "1", DestinationIDs: utils.StringMap{}} - mb2 := &BalanceFilter{} - if !mb1.MatchFilter(mb2, false, false) { - t.Errorf("Match filter failure: %+v == %+v", mb1, mb2) - } -} - -func TestBalanceMatchFilterId(t *testing.T) { - mb1 := &Balance{ID: "T1", Weight: 2, precision: 2, RatingSubject: "2", DestinationIDs: utils.NewStringMap("NAT")} - mb2 := &BalanceFilter{ID: utils.StringPointer("T1"), Weight: utils.Float64Pointer(1), RatingSubject: utils.StringPointer("1"), DestinationIDs: nil} - if !mb1.MatchFilter(mb2, false, false) { - t.Errorf("Match filter failure: %+v == %+v", mb1, mb2) - } -} - -func TestBalanceMatchFilterDiffId(t *testing.T) { - mb1 := &Balance{ID: "T1", Weight: 1, precision: 1, RatingSubject: "1", DestinationIDs: utils.StringMap{}} - mb2 := &BalanceFilter{ID: utils.StringPointer("T2"), Weight: utils.Float64Pointer(1), RatingSubject: utils.StringPointer("1"), DestinationIDs: nil} - if mb1.MatchFilter(mb2, false, false) { - t.Errorf("Match filter failure: %+v != %+v", mb1, mb2) - } -} - -func TestBalanceClone(t *testing.T) { - mb1 := &Balance{Value: 1, Weight: 2, RatingSubject: "test", DestinationIDs: utils.NewStringMap("5")} - mb2 := mb1.Clone() - if mb1 == mb2 || !mb1.Equal(mb2) { - t.Errorf("Cloning failure: \n%+v\n%+v", mb1, mb2) - } -} - -func TestBalanceMatchActionTriggerId(t *testing.T) { - at := &ActionTrigger{Balance: &BalanceFilter{ID: utils.StringPointer("test")}} - b := &Balance{ID: "test"} - if !b.MatchActionTrigger(at) { - t.Errorf("Error matching action trigger: %+v %+v", b, at) - } - b.ID = "test1" - if b.MatchActionTrigger(at) { - t.Errorf("Error matching action trigger: %+v %+v", b, at) - } - b.ID = "" - if b.MatchActionTrigger(at) { - t.Errorf("Error matching action trigger: %+v %+v", b, at) - } - b.ID = "test" - at.Balance.ID = nil - if !b.MatchActionTrigger(at) { - t.Errorf("Error matching action trigger: %+v %+v", b, at) - } -} - -func TestBalanceMatchActionTriggerDestination(t *testing.T) { - at := &ActionTrigger{Balance: &BalanceFilter{DestinationIDs: utils.StringMapPointer(utils.NewStringMap("test"))}} - b := &Balance{DestinationIDs: utils.NewStringMap("test")} - if !b.MatchActionTrigger(at) { - t.Errorf("Error matching action trigger: %+v %+v", b, at) - } - b.DestinationIDs = utils.NewStringMap("test1") - if b.MatchActionTrigger(at) { - t.Errorf("Error matching action trigger: %+v %+v", b, at) - } - b.DestinationIDs = utils.NewStringMap("") - if b.MatchActionTrigger(at) { - t.Errorf("Error matching action trigger: %+v %+v", b, at) - } - b.DestinationIDs = utils.NewStringMap("test") - at.Balance.DestinationIDs = nil - if !b.MatchActionTrigger(at) { - t.Errorf("Error matching action trigger: %+v %+v", b, at) - } -} - -func TestBalanceMatchActionTriggerWeight(t *testing.T) { - at := &ActionTrigger{Balance: &BalanceFilter{Weight: utils.Float64Pointer(1)}} - b := &Balance{Weight: 1} - if !b.MatchActionTrigger(at) { - t.Errorf("Error matching action trigger: %+v %+v", b, at) - } - b.Weight = 2 - if b.MatchActionTrigger(at) { - t.Errorf("Error matching action trigger: %+v %+v", b, at) - } - b.Weight = 0 - if b.MatchActionTrigger(at) { - t.Errorf("Error matching action trigger: %+v %+v", b, at) - } - b.Weight = 1 - at.Balance.Weight = nil - if !b.MatchActionTrigger(at) { - t.Errorf("Error matching action trigger: %+v %+v", b, at) - } -} - -func TestBalanceMatchActionTriggerRatingSubject(t *testing.T) { - at := &ActionTrigger{Balance: &BalanceFilter{RatingSubject: utils.StringPointer("test")}} - b := &Balance{RatingSubject: "test"} - if !b.MatchActionTrigger(at) { - t.Errorf("Error matching action trigger: %+v %+v", b, at) - } - b.RatingSubject = "test1" - if b.MatchActionTrigger(at) { - t.Errorf("Error matching action trigger: %+v %+v", b, at) - } - b.RatingSubject = "" - if b.MatchActionTrigger(at) { - t.Errorf("Error matching action trigger: %+v %+v", b, at) - } - b.RatingSubject = "test" - at.Balance.RatingSubject = nil - if !b.MatchActionTrigger(at) { - t.Errorf("Error matching action trigger: %+v %+v", b, at) - } -} - -func TestBalanceMatchActionTriggerSharedGroup(t *testing.T) { - at := &ActionTrigger{Balance: &BalanceFilter{SharedGroups: utils.StringMapPointer(utils.NewStringMap("test"))}} - b := &Balance{SharedGroups: utils.NewStringMap("test")} - if !b.MatchActionTrigger(at) { - t.Errorf("Error matching action trigger: %+v %+v", b, at) - } - b.SharedGroups = utils.NewStringMap("test1") - if b.MatchActionTrigger(at) { - t.Errorf("Error matching action trigger: %+v %+v", b, at) - } - b.SharedGroups = utils.NewStringMap("") - if b.MatchActionTrigger(at) { - t.Errorf("Error matching action trigger: %+v %+v", b, at) - } - b.SharedGroups = utils.NewStringMap("test") - at.Balance.SharedGroups = nil - if !b.MatchActionTrigger(at) { - t.Errorf("Error matching action trigger: %+v %+v", b, at) - } -} - -func TestBalanceIsDefault(t *testing.T) { - b := &Balance{Weight: 0} - if b.IsDefault() { - t.Errorf("Balance should not be default: %+v", b) - } - b = &Balance{ID: utils.MetaDefault} - if !b.IsDefault() { - t.Errorf("Balance should be default: %+v", b) - } -} - -func TestBalanceIsExpiredAt(t *testing.T) { - //expiration date is 0 - balance := &Balance{} - var date2 time.Time - if rcv := balance.IsExpiredAt(date2); rcv { - t.Errorf("Expecting: false , received: %+v", rcv) - } - //expiration date before time t - balance.ExpirationDate = time.Date(2020, time.April, 18, 23, 0, 3, 0, time.UTC) - date2 = time.Date(2020, time.April, 18, 23, 0, 4, 0, time.UTC) - if rcv := balance.IsExpiredAt(date2); !rcv { - t.Errorf("Expecting: true , received: %+v", rcv) - } - //expiration date after time t - date2 = time.Date(2020, time.April, 18, 23, 0, 2, 0, time.UTC) - if rcv := balance.IsExpiredAt(date2); rcv { - t.Errorf("Expecting: false , received: %+v", rcv) - } - //time t = 0 - var date3 time.Time - if rcv := balance.IsExpiredAt(date3); rcv { - t.Errorf("Expecting: false , received: %+v", rcv) - } - -} diff --git a/engine/caches.go b/engine/caches.go index 32bd09fe5..250833215 100644 --- a/engine/caches.go +++ b/engine/caches.go @@ -94,7 +94,6 @@ func init() { gob.Register(time.Time{}) gob.Register(url.Values{}) gob.Register(json.RawMessage{}) - gob.Register(BalanceSummaries{}) gob.Register(new(utils.ArgCacheReplicateSet)) gob.Register(new(utils.ArgCacheReplicateRemove)) diff --git a/engine/cdr_test.go b/engine/cdr_test.go index 70b20d04c..fac2a9ca0 100644 --- a/engine/cdr_test.go +++ b/engine/cdr_test.go @@ -231,82 +231,6 @@ func TestFieldsAsString(t *testing.T) { } } -func TestFieldAsStringForCostDetails(t *testing.T) { - cc := &CallCost{ - Category: "generic", - Tenant: "cgrates.org", - Subject: "1001", - Account: "1001", - Destination: "data", - ToR: "*data", - Cost: 0, - AccountSummary: &AccountSummary{ - Tenant: "cgrates.org", - ID: "AccountFromAccountSummary", - BalanceSummaries: []*BalanceSummary{ - { - UUID: "f9be602747f4", - ID: "monetary", - Type: utils.MetaMonetary, - Value: 0.5, - }, - { - UUID: "2e02510ab90a", - ID: "voice", - Type: utils.MetaVoice, - Value: 10, - }, - }, - }, - } - - cdr := &CDR{ - CGRID: utils.Sha1("dsafdsaf", time.Date(2013, 11, 7, 8, 42, 26, 0, time.UTC).String()), - OrderID: 123, - ToR: utils.MetaVoice, - OriginID: "dsafdsaf", - OriginHost: "192.168.1.1", - Source: utils.UnitTest, - RequestType: utils.MetaRated, - Tenant: "cgrates.org", - Category: "call", - Account: "1002", - Subject: "1001", - Destination: "+4986517174963", - SetupTime: time.Date(2013, 11, 7, 8, 42, 20, 0, time.UTC), - AnswerTime: time.Date(2013, 11, 7, 8, 42, 26, 0, time.UTC), - RunID: utils.MetaDefault, - Usage: 10 * time.Second, - ExtraFields: map[string]string{"field_extr1": "val_extr1", "fieldextr2": "valextr2"}, - Cost: 1.01, - CostDetails: NewEventCostFromCallCost(cc, "TestCDRTestCDRAsMapStringIface2", utils.MetaDefault), - } - - prsr := config.NewRSRParserMustCompile("~*req.CostDetails.CGRID") - eFldVal := "TestCDRTestCDRAsMapStringIface2" - if fldVal, err := cdr.FieldAsString(prsr); err != nil { - t.Error(err) - } else if fldVal != eFldVal { - t.Errorf("field: <%v>, expected: <%v>, received: <%v>", prsr, eFldVal, fldVal) - } - - prsr = config.NewRSRParserMustCompile("~*req.CostDetails.AccountSummary.ID") - eFldVal = "AccountFromAccountSummary" - if fldVal, err := cdr.FieldAsString(prsr); err != nil { - t.Error(err) - } else if fldVal != eFldVal { - t.Errorf("field: <%v>, expected: <%v>, received: <%v>", prsr, eFldVal, fldVal) - } - - prsr = config.NewRSRParserMustCompile("~*req.CostDetails.AccountSummary.BalanceSummaries[1].ID") - eFldVal = "voice" - if fldVal, err := cdr.FieldAsString(prsr); err != nil { - t.Error(err) - } else if fldVal != eFldVal { - t.Errorf("field: <%v>, expected: <%v>, received: <%v>", prsr, eFldVal, fldVal) - } -} - func TestFormatCost(t *testing.T) { cdr := CDR{Cost: 1.01} if cdr.FormatCost(0, 4) != "1.0100" { @@ -327,67 +251,6 @@ func TestFormatCost(t *testing.T) { } } -/* -func TestCDRAsHttpForm(t *testing.T) { - storCdr := CDR{CGRID: utils.Sha1("dsafdsaf", time.Date(2013, 11, 7, 8, 42, 26, 0, time.UTC).String()), OrderID: 123, ToR: utils.MetaVoice, OriginID: "dsafdsaf", - OriginHost: "192.168.1.1", Source: utils.UNIT_TEST, RequestType: utils.MetaRated, - Tenant: "cgrates.org", Category: "call", Account: "1001", Subject: "1001", Destination: "1002", - SetupTime: time.Date(2013, 11, 7, 8, 42, 20, 0, time.UTC), AnswerTime: time.Date(2013, 11, 7, 8, 42, 26, 0, time.UTC), RunID: utils.MetaDefault, - Usage: 10 * time.Second, Supplier: "SUPPL1", - ExtraFields: map[string]string{"field_extr1": "val_extr1", "fieldextr2": "valextr2"}, Cost: 1.01, - } - cdrForm := storCdr.AsHttpForm() - if cdrForm.Get(utils.ToR) != utils.MetaVoice { - t.Errorf("Expected: %s, received: %s", utils.MetaVoice, cdrForm.Get(utils.ToR)) - } - if cdrForm.Get(utils.OriginID) != "dsafdsaf" { - t.Errorf("Expected: %s, received: %s", "dsafdsaf", cdrForm.Get(utils.OriginID)) - } - if cdrForm.Get(utils.OriginHost) != "192.168.1.1" { - t.Errorf("Expected: %s, received: %s", "192.168.1.1", cdrForm.Get(utils.OriginHost)) - } - if cdrForm.Get(utils.Source) != utils.UNIT_TEST { - t.Errorf("Expected: %s, received: %s", utils.UNIT_TEST, cdrForm.Get(utils.Source)) - } - if cdrForm.Get(utils.RequestType) != utils.MetaRated { - t.Errorf("Expected: %s, received: %s", utils.MetaRated, cdrForm.Get(utils.RequestType)) - } - if cdrForm.Get(utils.Tenant) != "cgrates.org" { - t.Errorf("Expected: %s, received: %s", "cgrates.org", cdrForm.Get(utils.Tenant)) - } - if cdrForm.Get(utils.Category) != "call" { - t.Errorf("Expected: %s, received: %s", "call", cdrForm.Get(utils.Category)) - } - if cdrForm.Get(utils.AccountField) != "1001" { - t.Errorf("Expected: %s, received: %s", "1001", cdrForm.Get(utils.AccountField)) - } - if cdrForm.Get(utils.Subject) != "1001" { - t.Errorf("Expected: %s, received: %s", "1001", cdrForm.Get(utils.Subject)) - } - if cdrForm.Get(utils.Destination) != "1002" { - t.Errorf("Expected: %s, received: %s", "1002", cdrForm.Get(utils.Destination)) - } - if cdrForm.Get(utils.SetupTime) != "2013-11-07T08:42:20Z" { - t.Errorf("Expected: %s, received: %s", "2013-11-07T08:42:20Z", cdrForm.Get(utils.SetupTime)) - } - if cdrForm.Get(utils.AnswerTime) != "2013-11-07T08:42:26Z" { - t.Errorf("Expected: %s, received: %s", "2013-11-07T08:42:26Z", cdrForm.Get(utils.AnswerTime)) - } - if cdrForm.Get(utils.Usage) != "10" { - t.Errorf("Expected: %s, received: %s", "10", cdrForm.Get(utils.Usage)) - } - if cdrForm.Get(utils.Route) != "SUPPL1" { - t.Errorf("Expected: %s, received: %s", "1001", cdrForm.Get(utils.Route)) - } - if cdrForm.Get("field_extr1") != "val_extr1" { - t.Errorf("Expected: %s, received: %s", "val_extr1", cdrForm.Get("field_extr1")) - } - if cdrForm.Get("fieldextr2") != "valextr2" { - t.Errorf("Expected: %s, received: %s", "valextr2", cdrForm.Get("fieldextr2")) - } -} -*/ - func TestCDRAsExternalCDR(t *testing.T) { storCdr := CDR{CGRID: utils.Sha1("dsafdsaf", time.Date(2013, 11, 7, 8, 42, 20, 0, time.UTC).String()), OrderID: 123, ToR: utils.MetaVoice, OriginID: "dsafdsaf", OriginHost: "192.168.1.1", @@ -410,71 +273,6 @@ func TestCDRAsExternalCDR(t *testing.T) { } } -func TestUsageReqAsCD(t *testing.T) { - req := &UsageRecord{ToR: utils.MetaVoice, RequestType: utils.MetaRated, - Tenant: "cgrates.org", Category: "call", - Account: "1001", Subject: "1001", Destination: "1002", - SetupTime: "2013-11-07T08:42:20Z", AnswerTime: "2013-11-07T08:42:26Z", - Usage: "10", - } - eCD := &CallDescriptor{CgrID: "c4630df20b2a0c5b11311e4b5a8c3178cf314344", ToR: req.ToR, - Tenant: req.Tenant, - Category: req.Category, Account: req.Account, - Subject: req.Subject, Destination: req.Destination, - TimeStart: time.Date(2013, 11, 7, 8, 42, 26, 0, time.UTC), - TimeEnd: time.Date(2013, 11, 7, 8, 42, 26, 0, time.UTC).Add(10), - DenyNegativeAccount: true} - if cd, err := req.AsCallDescriptor("", true); err != nil { - t.Error(err) - } else if !reflect.DeepEqual(eCD, cd) { - t.Errorf("Expected: %+v, received: %+v", eCD, cd) - } -} - -func TestCdrClone(t *testing.T) { - cdr := &CDR{} - eOut := &CDR{} - if rcv := cdr.Clone(); !reflect.DeepEqual(rcv, eOut) { - t.Errorf("Expecting: %+v, received: %+v", eOut, rcv) - } - cdr = &CDR{ - CGRID: "CGRID_test", - OrderID: 18, - SetupTime: time.Date(2020, time.April, 18, 23, 0, 4, 0, time.UTC), - Usage: 10, - ExtraFields: map[string]string{ - "test1": "_test1_", - "test2": "_test2_", - }, - Partial: true, - Cost: 0.74, - CostDetails: &EventCost{ - CGRID: "EventCost_CGRID", - Cost: utils.Float64Pointer(0.74), - }, - } - eOut = &CDR{ - CGRID: "CGRID_test", - OrderID: 18, - SetupTime: time.Date(2020, time.April, 18, 23, 0, 4, 0, time.UTC), - Usage: 10, - ExtraFields: map[string]string{ - "test1": "_test1_", - "test2": "_test2_", - }, - Partial: true, - Cost: 0.74, - CostDetails: &EventCost{ - CGRID: "EventCost_CGRID", - Cost: utils.Float64Pointer(0.74), - }, - } - eOut.CostDetails.initCache() - if rcv := cdr.Clone(); !reflect.DeepEqual(rcv, eOut) { - t.Errorf("Expecting: %+v,\n received: %+v", eOut, rcv) - } - -} func TestCDRAsMapStringIface(t *testing.T) { cdr := &CDR{ CGRID: utils.Sha1("dsafdsaf", time.Date(2013, 11, 7, 8, 42, 26, 0, time.UTC).String()), @@ -527,351 +325,6 @@ func TestCDRAsMapStringIface(t *testing.T) { } } -func TestCDRTestCDRAsMapStringIface2(t *testing.T) { - cc := &CallCost{ - Category: "generic", - Tenant: "cgrates.org", - Subject: "1001", - Account: "1001", - Destination: "data", - ToR: "*data", - Cost: 0, - } - - cdr := &CDR{ - CGRID: utils.Sha1("dsafdsaf", time.Date(2013, 11, 7, 8, 42, 26, 0, time.UTC).String()), - OrderID: 123, - ToR: utils.MetaVoice, - OriginID: "dsafdsaf", - OriginHost: "192.168.1.1", - Source: utils.UnitTest, - RequestType: utils.MetaRated, - Tenant: "cgrates.org", - Category: "call", - Account: "1002", - Subject: "1001", - Destination: "+4986517174963", - SetupTime: time.Date(2013, 11, 7, 8, 42, 20, 0, time.UTC), - AnswerTime: time.Date(2013, 11, 7, 8, 42, 26, 0, time.UTC), - RunID: utils.MetaDefault, - Usage: 10 * time.Second, - ExtraFields: map[string]string{"field_extr1": "val_extr1", "fieldextr2": "valextr2"}, - Cost: 1.01, - CostDetails: NewEventCostFromCallCost(cc, "TestCDRTestCDRAsMapStringIface2", utils.MetaDefault), - } - - mp := map[string]interface{}{ - "field_extr1": "val_extr1", - "fieldextr2": "valextr2", - utils.CGRID: cdr.CGRID, - utils.RunID: utils.MetaDefault, - utils.OrderID: cdr.OrderID, - utils.OriginHost: "192.168.1.1", - utils.Source: utils.UnitTest, - utils.OriginID: "dsafdsaf", - utils.ToR: utils.MetaVoice, - utils.RequestType: utils.MetaRated, - utils.Tenant: "cgrates.org", - utils.Category: "call", - utils.AccountField: "1002", - utils.Subject: "1001", - utils.Destination: "+4986517174963", - utils.SetupTime: time.Date(2013, 11, 7, 8, 42, 20, 0, time.UTC), - utils.AnswerTime: time.Date(2013, 11, 7, 8, 42, 26, 0, time.UTC), - utils.Usage: 10 * time.Second, - utils.CostSource: cdr.CostSource, - utils.Cost: 1.01, - utils.PreRated: false, - utils.Partial: false, - utils.ExtraInfo: cdr.ExtraInfo, - utils.CostDetails: cdr.CostDetails, - } - if cdrMp := cdr.AsMapStringIface(); !reflect.DeepEqual(mp, cdrMp) { - t.Errorf("Expecting: %+v, received: %+v", mp, cdrMp) - } -} - -func TestCDRAsExportRecord(t *testing.T) { - cc := &CallCost{ - Category: "generic", - Tenant: "cgrates.org", - Subject: "1001", - Account: "1001", - Destination: "data", - ToR: "*data", - Cost: 0, - AccountSummary: &AccountSummary{ - Tenant: "cgrates.org", - ID: "AccountFromAccountSummary", - }, - } - eventCost := NewEventCostFromCallCost(cc, "TestCDRTestCDRAsMapStringIface2", utils.MetaDefault) - eventCost.RatingFilters = RatingFilters{ - "3d99c91": RatingMatchedFilters{ - "DestinationID": "CustomDestination", - "DestinationPrefix": "26377", - "RatingPlanID": "RP_ZW_v1", - }, - } - - cdr := &CDR{ - CGRID: utils.Sha1("dsafdsaf", - time.Unix(1383813745, 0).UTC().String()), - ToR: utils.MetaVoice, OriginID: "dsafdsaf", - OriginHost: "192.168.1.1", - RequestType: utils.MetaRated, - Tenant: "cgrates.org", - Category: "call", - Account: "1001", - Subject: "1001", - Destination: "+4986517174963", - SetupTime: time.Unix(1383813745, 0).UTC(), - AnswerTime: time.Unix(1383813746, 0).UTC(), - Usage: 10 * time.Second, - RunID: utils.MetaDefault, Cost: 1.01, - ExtraFields: map[string]string{"stop_time": "2014-06-11 19:19:00 +0000 UTC", "fieldextr2": "valextr2"}, - CostDetails: eventCost, - } - - prsr := config.NewRSRParsersMustCompile(utils.DynamicDataPrefix+utils.MetaReq+utils.NestingSep+utils.Destination, utils.InfieldSep) - cfgCdrFld := &config.FCTemplate{ - Tag: "destination", - Path: "*exp.Destination", - Type: utils.MetaComposed, - Value: prsr, - Timezone: "UTC", - } - if expRecord, err := cdr.AsExportRecord([]*config.FCTemplate{cfgCdrFld}, nil, nil); err != nil { - t.Error(err) - } else if expRecord[0] != cdr.Destination { - t.Errorf("Expecting:\n%s\nReceived:\n%s", cdr.Destination, expRecord) - } - if err := dm.SetReverseDestination("MASKED_DESTINATIONS", []string{"+4986517174963"}, - utils.NonTransactional); err != nil { - t.Error(err) - } - - cfgCdrFld = &config.FCTemplate{ - Tag: "Destination", - Path: "*exp.Destination", - Type: utils.MetaComposed, - Value: prsr, - MaskDestID: "MASKED_DESTINATIONS", - MaskLen: 3, - } - eDst := "+4986517174***" - if expRecord, err := cdr.AsExportRecord([]*config.FCTemplate{cfgCdrFld}, nil, nil); err != nil { - t.Error(err) - } else if expRecord[0] != eDst { - t.Errorf("Expecting:\n%s\nReceived:\n%s", eDst, expRecord[0]) - } - - cfgCdrFld = &config.FCTemplate{ - Tag: "MaskedDest", - Path: "*exp.MaskedDest", - Type: utils.MetaMaskedDestination, - Value: prsr, - MaskDestID: "MASKED_DESTINATIONS", - } - if expRecord, err := cdr.AsExportRecord([]*config.FCTemplate{cfgCdrFld}, nil, nil); err != nil { - t.Error(err) - } else if expRecord[0] != "1" { - t.Errorf("Expecting:\n%s\nReceived:\n%s", "1", expRecord[0]) - } - defaultCfg := config.NewDefaultCGRConfig() - data := NewInternalDB(nil, nil, true) - dmForCDR := NewDataManager(data, config.CgrConfig().CacheCfg(), nil) - cfgCdrFld = &config.FCTemplate{ - Tag: "destination", - Path: "*exp.Destination", - Type: utils.MetaComposed, - Value: prsr, - Filters: []string{"*string:~*req.Tenant:itsyscom.com"}, - Timezone: "UTC", - } - if rcrd, err := cdr.AsExportRecord([]*config.FCTemplate{cfgCdrFld}, nil, &FilterS{dm: dmForCDR, cfg: defaultCfg}); err != nil { - t.Error(err) - } else if len(rcrd) != 0 { - t.Error("failed using filter") - } - - // Test MetaDateTime - prsr = config.NewRSRParsersMustCompile("~*req.stop_time", utils.InfieldSep) - layout := "2006-01-02 15:04:05" - cfgCdrFld = &config.FCTemplate{ - Tag: "stop_time", - Type: utils.MetaDateTime, - Path: "*exp.stop_time", - Value: prsr, - Layout: layout, - Timezone: "UTC", - } - if expRecord, err := cdr.AsExportRecord([]*config.FCTemplate{cfgCdrFld}, nil, &FilterS{dm: dmForCDR, cfg: defaultCfg}); err != nil { - t.Error(err) - } else if expRecord[0] != "2014-06-11 19:19:00" { - t.Error("Expecting: 2014-06-11 19:19:00, got: ", expRecord[0]) - } - - // Test filter - cfgCdrFld = &config.FCTemplate{ - Tag: "stop_time", - Type: utils.MetaDateTime, - Path: "*exp.stop_time", - Value: prsr, - Filters: []string{"*string:~*req.Tenant:itsyscom.com"}, - Layout: layout, - Timezone: "UTC", - } - if rcrd, err := cdr.AsExportRecord([]*config.FCTemplate{cfgCdrFld}, nil, &FilterS{dm: dmForCDR, cfg: defaultCfg}); err != nil { - t.Error(err) - } else if len(rcrd) != 0 { - t.Error("failed using filter") - } - - prsr = config.NewRSRParsersMustCompile("~*req.fieldextr2", utils.InfieldSep) - cfgCdrFld = &config.FCTemplate{ - Tag: "stop_time", - Type: utils.MetaDateTime, - Path: "*exp.stop_time", - Value: prsr, - Layout: layout, - Timezone: "UTC"} - // Test time parse error - if _, err := cdr.AsExportRecord([]*config.FCTemplate{cfgCdrFld}, nil, nil); err == nil { - t.Error("Should give error here, got none.") - } - - prsr = config.NewRSRParsersMustCompile("~*req.CostDetails.CGRID", utils.InfieldSep) - cfgCdrFld = &config.FCTemplate{ - Tag: "CGRIDFromCostDetails", - Type: utils.MetaComposed, - Path: "*exp.CGRIDFromCostDetails", - Value: prsr, - } - if expRecord, err := cdr.AsExportRecord([]*config.FCTemplate{cfgCdrFld}, nil, nil); err != nil { - t.Error(err) - } else if expRecord[0] != cdr.CostDetails.CGRID { - t.Errorf("Expecting:\n%s\nReceived:\n%s", cdr.CostDetails.CGRID, expRecord) - } - prsr = config.NewRSRParsersMustCompile("~*req.CostDetails.AccountSummary.ID", utils.InfieldSep) - cfgCdrFld = &config.FCTemplate{ - Tag: "AccountID", - Type: utils.MetaComposed, - Path: "*exp.CustomAccountID", - Value: prsr, - } - if expRecord, err := cdr.AsExportRecord([]*config.FCTemplate{cfgCdrFld}, nil, nil); err != nil { - t.Error(err) - } else if expRecord[0] != cdr.CostDetails.AccountSummary.ID { - t.Errorf("Expecting:\n%s\nReceived:\n%s", cdr.CostDetails.AccountSummary.ID, expRecord) - } - - expected := `{"3d99c91":{"DestinationID":"CustomDestination","DestinationPrefix":"26377","RatingPlanID":"RP_ZW_v1"}}` - prsr = config.NewRSRParsersMustCompile("~*req.CostDetails.RatingFilters", utils.InfieldSep) - cfgCdrFld = &config.FCTemplate{ - Tag: "DestinationID", - Type: utils.MetaComposed, - Path: "*exp.CustomDestinationID", - Value: prsr, - } - if expRecord, err := cdr.AsExportRecord([]*config.FCTemplate{cfgCdrFld}, nil, nil); err != nil { - t.Error(err) - } else if expRecord[0] != expected { - t.Errorf("Expecting: <%q>,\n Received: <%q>", expected, expRecord[0]) - } - - expected = "RP_ZW_v1" - prsr = config.NewRSRParsersMustCompile("~*req.CostDetails.RatingFilters:s/RatingPlanID\"\\s?\\:\\s?\"([^\"]*)\".*/$1/", utils.InfieldSep) - cfgCdrFld = &config.FCTemplate{ - Tag: "DestinationID", - Type: utils.MetaComposed, - Path: "*exp.CustomDestinationID", - Value: prsr, - } - if expRecord, err := cdr.AsExportRecord([]*config.FCTemplate{cfgCdrFld}, nil, nil); err != nil { - t.Error(err) - } else if expRecord[0] != expected { - t.Errorf("Expecting: <%q>,\n Received: <%q>", expected, expRecord[0]) - } - - expected = "CustomDestination" - prsr = config.NewRSRParsersMustCompile("~*req.CostDetails.RatingFilters:s/DestinationID\"\\s?\\:\\s?\"([^\"]*)\".*/$1/", utils.InfieldSep) - cfgCdrFld = &config.FCTemplate{ - Tag: "DestinationID", - Type: utils.MetaComposed, - Path: "*exp.CustomDestinationID", - Value: prsr, - } - if expRecord, err := cdr.AsExportRecord([]*config.FCTemplate{cfgCdrFld}, nil, nil); err != nil { - t.Error(err) - } else if expRecord[0] != expected { - t.Errorf("Expecting: <%q>,\n Received: <%q>", expected, expRecord[0]) - } - - expected = "26377" - prsr = config.NewRSRParsersMustCompile("~*req.CostDetails.RatingFilters:s/DestinationPrefix\"\\s?\\:\\s?\"([^\"]*)\".*/$1/", utils.InfieldSep) - cfgCdrFld = &config.FCTemplate{ - Tag: "DestinationID", - Type: utils.MetaComposed, - Path: "*exp.CustomDestinationID", - Value: prsr, - } - if expRecord, err := cdr.AsExportRecord([]*config.FCTemplate{cfgCdrFld}, nil, nil); err != nil { - t.Error(err) - } else if expRecord[0] != expected { - t.Errorf("Expecting: <%q>,\n Received: <%q>", expected, expRecord[0]) - } - -} - -func TestCDRAsCDRsql(t *testing.T) { - cdr := &CDR{CGRID: utils.Sha1("dsafdsaf", time.Date(2013, 11, 7, 8, 42, 26, 0, time.UTC).String()), - OrderID: 123, - ToR: utils.MetaVoice, - OriginID: "dsafdsaf", - OriginHost: "192.168.1.1", - Source: utils.UnitTest, - RequestType: utils.MetaRated, - Tenant: "cgrates.org", - Category: "call", - Account: "1001", - Subject: "1001", - Destination: "+4986517174963", - SetupTime: time.Date(2013, 11, 7, 8, 42, 20, 0, time.UTC), - AnswerTime: time.Date(2013, 11, 7, 8, 42, 26, 0, time.UTC), - RunID: utils.MetaDefault, - Usage: 10 * time.Second, - Cost: 1.01, - ExtraFields: map[string]string{"field_extr1": "val_extr1", "fieldextr2": "valextr2"}, - } - eCDR := cdr.AsCDRsql() - eCDRSql := &CDRsql{ - Cgrid: cdr.CGRID, - RunID: cdr.RunID, - OriginID: "dsafdsaf", - TOR: utils.MetaVoice, - Source: utils.UnitTest, - Tenant: "cgrates.org", - Category: "call", - Account: "1001", - Subject: "1001", - Destination: "+4986517174963", - SetupTime: time.Date(2013, 11, 7, 8, 42, 20, 0, time.UTC), - AnswerTime: time.Date(2013, 11, 7, 8, 42, 26, 0, time.UTC), - Usage: cdr.Usage.Nanoseconds(), - Cost: cdr.Cost, - ExtraFields: utils.ToJSON(cdr.ExtraFields), - RequestType: cdr.RequestType, - OriginHost: cdr.OriginHost, - CostDetails: utils.ToJSON(cdr.CostDetails), - CreatedAt: eCDR.CreatedAt, - } - if !reflect.DeepEqual(eCDR, eCDRSql) { - t.Errorf("Expecting: %+v, received: %+v", eCDR, eCDRSql) - } - -} - func TestCDRNewCDRFromSQL(t *testing.T) { extraFields := map[string]string{"field_extr1": "val_extr1", "fieldextr2": "valextr2"} cdrSQL := &CDRsql{ diff --git a/engine/chargers_test.go b/engine/chargers_test.go index ed744978e..b7d0caa57 100755 --- a/engine/chargers_test.go +++ b/engine/chargers_test.go @@ -27,6 +27,8 @@ import ( "github.com/cgrates/cgrates/utils" ) +var err error + func TestChargerSetChargerProfiles(t *testing.T) { var dmCharger *DataManager cPPs := ChargerProfiles{ diff --git a/engine/filters_test.go b/engine/filters_test.go index 6b9395615..8935d508c 100644 --- a/engine/filters_test.go +++ b/engine/filters_test.go @@ -26,370 +26,6 @@ import ( "github.com/cgrates/cgrates/utils" ) -func TestFilterPassString(t *testing.T) { - cd := &CallDescriptor{ - Category: "call", - Tenant: "cgrates.org", - Subject: "dan", - Destination: "+4986517174963", - TimeStart: time.Date(2013, time.October, 7, 14, 50, 0, 0, time.UTC), - TimeEnd: time.Date(2013, time.October, 7, 14, 52, 12, 0, time.UTC), - DurationIndex: 132 * time.Second, - ExtraFields: map[string]string{"navigation": "off"}, - } - rf := &FilterRule{Type: utils.MetaString, - Element: "~Category", Values: []string{"call"}} - if err := rf.CompileValues(); err != nil { - t.Fatal(err) - } - if passes, err := rf.passString(cd); err != nil { - t.Error(err) - } else if !passes { - t.Error("Not passes filter") - } - - rf = &FilterRule{Type: utils.MetaString, - Element: "~Category", Values: []string{"cal"}} - if err := rf.CompileValues(); err != nil { - t.Fatal(err) - } - if passes, err := rf.passString(cd); err != nil { - t.Error(err) - } else if passes { - t.Error("Filter passes") - } - //not - rf = &FilterRule{Type: utils.MetaNotString, - Element: "~Category", Values: []string{"call"}} - if err := rf.CompileValues(); err != nil { - t.Fatal(err) - } - if passes, err := rf.Pass(cd); err != nil { - t.Error(err) - } else if passes { - t.Error("Filter passes") - } - rf = &FilterRule{Type: utils.MetaNotString, - Element: "~Category", Values: []string{"cal"}} - if err := rf.CompileValues(); err != nil { - t.Fatal(err) - } - if passes, err := rf.Pass(cd); err != nil { - t.Error(err) - } else if !passes { - t.Error("Not passes filter") - } -} - -func TestFilterPassEmpty(t *testing.T) { - cd := &CallDescriptor{ - Category: "", - Tenant: "cgrates.org", - Subject: "dan", - Destination: "+4986517174963", - TimeStart: time.Date(2013, time.October, 7, 14, 50, 0, 0, time.UTC), - TimeEnd: time.Date(2013, time.October, 7, 14, 52, 12, 0, time.UTC), - DurationIndex: 132 * time.Second, - ExtraFields: map[string]string{"navigation": "off"}, - } - rf := &FilterRule{Type: utils.MetaEmpty, Element: "~Category", Values: []string{}} - if err := rf.CompileValues(); err != nil { - t.Fatal(err) - } - if passes, err := rf.passEmpty(cd); err != nil { - t.Error(err) - } else if !passes { - t.Error("Not passes filter") - } - rf = &FilterRule{Type: utils.MetaEmpty, Element: "~ExtraFields", Values: []string{}} - if err := rf.CompileValues(); err != nil { - t.Fatal(err) - } - if passes, err := rf.passEmpty(cd); err != nil { - t.Error(err) - } else if passes { - t.Error("Filter passes") - } - cd.ExtraFields = map[string]string{} - rf = &FilterRule{Type: utils.MetaEmpty, Element: "~ExtraFields", Values: []string{}} - if err := rf.CompileValues(); err != nil { - t.Fatal(err) - } - if passes, err := rf.passEmpty(cd); err != nil { - t.Error(err) - } else if !passes { - t.Error("Not passes filter") - } - //not - rf = &FilterRule{Type: utils.MetaNotEmpty, Element: "~Category", Values: []string{}} - if err := rf.CompileValues(); err != nil { - t.Fatal(err) - } - if passes, err := rf.Pass(cd); err != nil { - t.Error(err) - } else if passes { - t.Error("Filter passes") - } -} - -func TestFilterPassExists(t *testing.T) { - cd := &CallDescriptor{ - Category: "", - Tenant: "cgrates.org", - Subject: "dan", - Destination: "+4986517174963", - TimeStart: time.Date(2013, time.October, 7, 14, 50, 0, 0, time.UTC), - TimeEnd: time.Date(2013, time.October, 7, 14, 52, 12, 0, time.UTC), - DurationIndex: 132 * time.Second, - ExtraFields: map[string]string{"navigation": "off"}, - } - rf := &FilterRule{Type: utils.MetaExists, Element: "~Category", Values: []string{}} - if err := rf.CompileValues(); err != nil { - t.Fatal(err) - } - if passes, err := rf.passExists(cd); err != nil { - t.Error(err) - } else if !passes { - t.Error("Not passes filter") - } - rf = &FilterRule{Type: utils.MetaExists, Element: "~ExtraFields1", Values: []string{}} - if err := rf.CompileValues(); err != nil { - t.Fatal(err) - } - if passes, err := rf.passExists(cd); err != nil { - t.Error(err) - } else if passes { - t.Error("Filter passes") - } - cd.ExtraFields = map[string]string{} - rf = &FilterRule{Type: utils.MetaExists, Element: "~ExtraFields", Values: []string{}} - if err := rf.CompileValues(); err != nil { - t.Fatal(err) - } - if passes, err := rf.passExists(cd); err != nil { - t.Error(err) - } else if !passes { - t.Error("Not passes filter") - } - //not - rf = &FilterRule{Type: utils.MetaNotExists, Element: "~Category1", Values: []string{}} - if err := rf.CompileValues(); err != nil { - t.Fatal(err) - } - if passes, err := rf.Pass(cd); err != nil { - t.Error(err) - } else if !passes { - t.Error("Not passes filter") - } -} - -func TestFilterPassStringPrefix(t *testing.T) { - cd := &CallDescriptor{ - Category: "call", - Tenant: "cgrates.org", - Subject: "dan", - Destination: "+4986517174963", - TimeStart: time.Date(2013, time.October, 7, 14, 50, 0, 0, time.UTC), - TimeEnd: time.Date(2013, time.October, 7, 14, 52, 12, 0, time.UTC), - DurationIndex: 132 * time.Second, - ExtraFields: map[string]string{"navigation": "off"}, - } - rf := &FilterRule{Type: utils.MetaPrefix, Element: "~Category", Values: []string{"call"}} - if err := rf.CompileValues(); err != nil { - t.Fatal(err) - } - if passes, err := rf.passStringPrefix(cd); err != nil { - t.Error(err) - } else if !passes { - t.Error("Not passes filter") - } - rf = &FilterRule{Type: utils.MetaPrefix, Element: "~Category", Values: []string{"premium"}} - if err := rf.CompileValues(); err != nil { - t.Fatal(err) - } - if err := rf.CompileValues(); err != nil { - t.Fatal(err) - } - if passes, err := rf.passStringPrefix(cd); err != nil { - t.Error(err) - } else if passes { - t.Error("Passes filter") - } - rf = &FilterRule{Type: utils.MetaPrefix, Element: "~Destination", Values: []string{"+49"}} - if err := rf.CompileValues(); err != nil { - t.Fatal(err) - } - if passes, err := rf.passStringPrefix(cd); err != nil { - t.Error(err) - } else if !passes { - t.Error("Not passes filter") - } - rf = &FilterRule{Type: utils.MetaPrefix, Element: "~Destination", Values: []string{"+499"}} - if err := rf.CompileValues(); err != nil { - t.Fatal(err) - } - if passes, err := rf.passStringPrefix(cd); err != nil { - t.Error(err) - } else if passes { - t.Error("Passes filter") - } - rf = &FilterRule{Type: utils.MetaPrefix, Element: "~navigation", Values: []string{"off"}} - if err := rf.CompileValues(); err != nil { - t.Fatal(err) - } - if passes, err := rf.passStringPrefix(cd); err != nil { - t.Error(err) - } else if !passes { - t.Error("Not passes filter") - } - rf = &FilterRule{Type: utils.MetaPrefix, Element: "~nonexisting", Values: []string{"off"}} - if err := rf.CompileValues(); err != nil { - t.Fatal(err) - } - if passing, err := rf.passStringPrefix(cd); err != nil { - t.Error(err) - } else if passing { - t.Error("Passes filter") - } - //not - rf = &FilterRule{Type: utils.MetaNotPrefix, Element: "~Category", Values: []string{"premium"}} - if err := rf.CompileValues(); err != nil { - t.Fatal(err) - } - if passes, err := rf.Pass(cd); err != nil { - t.Error(err) - } else if !passes { - t.Error("Not passes filter") - } -} - -func TestFilterPassStringSuffix(t *testing.T) { - cd := &CallDescriptor{ - Category: "call", - Tenant: "cgrates.org", - Subject: "dan", - Destination: "+4986517174963", - TimeStart: time.Date(2013, time.October, 7, 14, 50, 0, 0, time.UTC), - TimeEnd: time.Date(2013, time.October, 7, 14, 52, 12, 0, time.UTC), - DurationIndex: 132 * time.Second, - ExtraFields: map[string]string{"navigation": "off"}, - } - rf := &FilterRule{Type: utils.MetaSuffix, Element: "~Category", Values: []string{"call"}} - if err := rf.CompileValues(); err != nil { - t.Fatal(err) - } - if passes, err := rf.passStringSuffix(cd); err != nil { - t.Error(err) - } else if !passes { - t.Error("Not passes filter") - } - rf = &FilterRule{Type: utils.MetaSuffix, Element: "~Category", Values: []string{"premium"}} - if err := rf.CompileValues(); err != nil { - t.Fatal(err) - } - if passes, err := rf.passStringSuffix(cd); err != nil { - t.Error(err) - } else if passes { - t.Error("Passes filter") - } - rf = &FilterRule{Type: utils.MetaSuffix, Element: "~Destination", Values: []string{"963"}} - if err := rf.CompileValues(); err != nil { - t.Fatal(err) - } - if passes, err := rf.passStringSuffix(cd); err != nil { - t.Error(err) - } else if !passes { - t.Error("Not passes filter") - } - rf = &FilterRule{Type: utils.MetaSuffix, Element: "~Destination", Values: []string{"4966"}} - if err := rf.CompileValues(); err != nil { - t.Fatal(err) - } - if passes, err := rf.passStringSuffix(cd); err != nil { - t.Error(err) - } else if passes { - t.Error("Passes filter") - } - rf = &FilterRule{Type: utils.MetaSuffix, Element: "~navigation", Values: []string{"off"}} - if err := rf.CompileValues(); err != nil { - t.Fatal(err) - } - if passes, err := rf.passStringSuffix(cd); err != nil { - t.Error(err) - } else if !passes { - t.Error("Not passes filter") - } - rf = &FilterRule{Type: utils.MetaSuffix, Element: "~nonexisting", Values: []string{"off"}} - if err := rf.CompileValues(); err != nil { - t.Fatal(err) - } - if passing, err := rf.passStringSuffix(cd); err != nil { - t.Error(err) - } else if passing { - t.Error("Passes filter") - } - //not - rf = &FilterRule{Type: utils.MetaNotSuffix, Element: "~Destination", Values: []string{"963"}} - if err := rf.CompileValues(); err != nil { - t.Fatal(err) - } - if passes, err := rf.Pass(cd); err != nil { - t.Error(err) - } else if passes { - t.Error("Passes filter") - } -} - -func TestFilterPassRSRFields(t *testing.T) { - cd := &CallDescriptor{ - Category: "call", - Tenant: "cgrates.org", - Subject: "dan", - Destination: "+4986517174963", - TimeStart: time.Date(2013, time.October, 7, 14, 50, 0, 0, time.UTC), - TimeEnd: time.Date(2013, time.October, 7, 14, 52, 12, 0, time.UTC), - DurationIndex: 132 * time.Second, - ExtraFields: map[string]string{"navigation": "off"}, - } - rf, err := NewFilterRule(utils.MetaRSR, "~Tenant", []string{"~^cgr.*\\.org$"}) - if err != nil { - t.Error(err) - } - if passes, err := rf.passRSR(cd); err != nil { - t.Error(err) - } else if !passes { - t.Error("Not passing") - } - rf, err = NewFilterRule(utils.MetaRSR, "~navigation", []string{"on"}) - if err != nil { - t.Error(err) - } - if passes, err := rf.passRSR(cd); err != nil { - t.Error(err) - } else if passes { - t.Error("Passing") - } - rf, err = NewFilterRule(utils.MetaRSR, "~navigation", []string{"off"}) - if err != nil { - t.Error(err) - } - if passes, err := rf.passRSR(cd); err != nil { - t.Error(err) - } else if !passes { - t.Error("Not passing") - } - //not - rf, err = NewFilterRule(utils.MetaNotRSR, "~navigation", []string{"off"}) - if err != nil { - t.Error(err) - } - if passes, err := rf.Pass(cd); err != nil { - t.Error(err) - } else if passes { - t.Error("Passing") - } -} - func TestFilterPassGreaterThan(t *testing.T) { rf, err := NewFilterRule(utils.MetaLessThan, "~ASR", []string{"40"}) if err != nil { @@ -1071,175 +707,6 @@ func TestPassFilterMissingField(t *testing.T) { } } -func TestEventCostFilter(t *testing.T) { - cfg := config.NewDefaultCGRConfig() - data := NewInternalDB(nil, nil, true) - dmFilterPass := NewDataManager(data, config.CgrConfig().CacheCfg(), nil) - filterS := FilterS{ - cfg: cfg, - dm: dmFilterPass, - } - cd := &EventCost{ - Cost: utils.Float64Pointer(0.264933), - CGRID: "d8534def2b7067f4f5ad4f7ec7bbcc94bb46111a", - Rates: ChargedRates{ - "3db483c": RateGroups{ - { - Value: 0.1574, - RateUnit: 60000000000, - RateIncrement: 30000000000, - GroupIntervalStart: 0, - }, - { - Value: 0.1574, - RateUnit: 60000000000, - RateIncrement: 1000000000, - GroupIntervalStart: 30000000000, - }, - }, - }, - RunID: "*default", - Usage: utils.DurationPointer(101 * time.Second), - Rating: Rating{ - "7f3d423": &RatingUnit{ - MaxCost: 40, - RatesID: "3db483c", - TimingID: "128e970", - ConnectFee: 0, - RoundingMethod: "*up", - MaxCostStrategy: "*disconnect", - RatingFiltersID: "f8e95f2", - RoundingDecimals: 4, - }, - }, - Charges: []*ChargingInterval{ - { - RatingID: "7f3d423", - Increments: []*ChargingIncrement{ - { - Cost: 0.0787, - Usage: 30000000000, - AccountingID: "fee8a3a", - CompressFactor: 1, - }, - }, - CompressFactor: 1, - }, - { - RatingID: "7f3d423", - Increments: []*ChargingIncrement{ - { - Cost: 0.002623, - Usage: 1000000000, - AccountingID: "3463957", - CompressFactor: 71, - }, - }, - CompressFactor: 1, - }, - }, - Timings: ChargedTimings{ - "128e970": &ChargedTiming{ - StartTime: "00:00:00", - }, - }, - StartTime: time.Date(2019, 12, 06, 11, 57, 32, 0, time.UTC), - Accounting: Accounting{ - "3463957": &BalanceCharge{ - Units: 0.002623, - RatingID: "", - AccountID: "cgrates.org:1001", - BalanceUUID: "154419f2-45e0-4629-a203-06034ccb493f", - ExtraChargeID: "", - }, - "fee8a3a": &BalanceCharge{ - Units: 0.0787, - RatingID: "", - AccountID: "cgrates.org:1001", - BalanceUUID: "154419f2-45e0-4629-a203-06034ccb493f", - ExtraChargeID: "", - }, - }, - RatingFilters: RatingFilters{ - "f8e95f2": RatingMatchedFilters{ - "Subject": "*out:cgrates.org:mo_call_UK_Mobile_O2_GBRCN:*any", - "RatingPlanID": "RP_MO_CALL_44800", - "DestinationID": "DST_44800", - "DestinationPrefix": "44800", - }, - }, - AccountSummary: &AccountSummary{ - ID: "234189200129930", - Tenant: "cgrates.org", - Disabled: false, - AllowNegative: false, - BalanceSummaries: BalanceSummaries{ - &BalanceSummary{ - ID: "MOBILE_DATA", - Type: "*data", - UUID: "08a05723-5849-41b9-b6a9-8ee362539280", - Value: 3221225472, - Disabled: false, - }, - &BalanceSummary{ - ID: "MOBILE_SMS", - Type: "*sms", - UUID: "06a87f20-3774-4eeb-826e-a79c5f175fd3", - Value: 247, - Disabled: false, - }, - &BalanceSummary{ - ID: "MOBILE_VOICE", - Type: "*voice", - UUID: "4ad16621-6e22-4e35-958e-5e1ff93ad7b7", - Value: 14270000000000, - Disabled: false, - }, - &BalanceSummary{ - ID: "MONETARY_POSTPAID", - Type: "*monetary", - UUID: "154419f2-45e0-4629-a203-06034ccb493f", - Value: 50, - Disabled: false, - }, - }, - }, - } - cd.initCache() - cgrDp := utils.MapStorage{utils.MetaEC: cd} - - if pass, err := filterS.Pass("cgrates.org", - []string{"*string:~*ec.Charges[0].Increments[0].Accounting.Balance.Value:50"}, cgrDp); err != nil { - t.Errorf(err.Error()) - } else if !pass { - t.Errorf("Expecting: true , received: %+v", pass) - } - if pass, err := filterS.Pass("cgrates.org", - []string{"*string:~*ec.Charges[0].Increments[0].Accounting.AccountID:cgrates.org:1001"}, cgrDp); err != nil { - t.Errorf(err.Error()) - } else if !pass { - t.Errorf("Expecting: true , received: %+v", pass) - } - if pass, err := filterS.Pass("cgrates.org", - []string{"*string:~*ec.Charges[0].Rating.Rates[0].Value:0.1574"}, cgrDp); err != nil { - t.Errorf(err.Error()) - } else if !pass { - t.Errorf("Expecting: true , received: %+v", pass) - } - if pass, err := filterS.Pass("cgrates.org", - []string{"*string:~*ec.Charges[0].Increments[0].Accounting.Balance.ID:MONETARY_POSTPAID"}, cgrDp); err != nil { - t.Errorf(err.Error()) - } else if !pass { - t.Errorf("Expecting: true , received: %+v", pass) - } - if pass, err := filterS.Pass("cgrates.org", - []string{"*lt:~*ec.AccountSummary.BalanceSummaries.MONETARY_POSTPAID.Value:60"}, cgrDp); err != nil { - t.Errorf(err.Error()) - } else if !pass { - t.Errorf("Expecting: true , received: %+v", pass) - } -} - func TestVerifyPrefixes(t *testing.T) { rf, err := NewFilterRule(utils.MetaString, "~*req.Account", []string{"1001"}) if err != nil { diff --git a/engine/loader_csv_test.go b/engine/loader_csv_test.go index 6ffbc2a1b..40cf9a595 100644 --- a/engine/loader_csv_test.go +++ b/engine/loader_csv_test.go @@ -38,10 +38,10 @@ func init() { var err error csvr, err = NewTpReader(dm.dataDB, NewStringCSVStorage(utils.CSVSep, DestinationsCSVContent, TimingsCSVContent, - ActionsCSVContent, ActionPlansCSVContent, ActionTriggersCSVContent, AccountActionsCSVContent, + ActionsCSVContent, ResourcesCSVContent, StatsCSVContent, ThresholdsCSVContent, FiltersCSVContent, RoutesCSVContent, AttributesCSVContent, ChargersCSVContent, DispatcherCSVContent, - DispatcherHostCSVContent, RateProfileCSVContent, ActionProfileCSVContent, AccountProfileCSVContent), testTPID, "", nil, nil, false) + DispatcherHostCSVContent, RateProfileCSVContent, ActionProfileCSVContent), testTPID, "", nil, nil, false) if err != nil { log.Print("error when creating TpReader:", err) } @@ -51,24 +51,6 @@ func init() { if err := csvr.LoadTimings(); err != nil { log.Print("error in LoadTimings:", err) } - if err := csvr.LoadRates(); err != nil { - log.Print("error in LoadRates:", err) - } - if err := csvr.LoadDestinationRates(); err != nil { - log.Print("error in LoadDestRates:", err) - } - if err := csvr.LoadRatingPlans(); err != nil { - log.Print("error in LoadRatingPlans:", err) - } - if err := csvr.LoadRatingProfiles(); err != nil { - log.Print("error in LoadRatingProfiles:", err) - } - if err := csvr.LoadSharedGroups(); err != nil { - log.Print("error in LoadSharedGroups:", err) - } - if err := csvr.LoadActions(); err != nil { - log.Print("error in LoadActions:", err) - } if err := csvr.LoadFilters(); err != nil { log.Print("error in LoadFilter:", err) } @@ -206,734 +188,6 @@ func TestLoadTimimgs(t *testing.T) { } } -func TestLoadRates(t *testing.T) { - if len(csvr.rates) != 15 { - t.Error("Failed to load rates: ", len(csvr.rates)) - } - rate := csvr.rates["R1"].RateSlots[0] - expctRs, err := utils.NewRateSlot(0, 0.2, "60s", "1s", "0s") - if err != nil { - t.Error("Error loading rate: ", rate, err.Error()) - } else if !reflect.DeepEqual(rate, expctRs) || - rate.RateUnitDuration() != expctRs.RateUnitDuration() || - rate.RateIncrementDuration() != expctRs.RateIncrementDuration() || - rate.GroupIntervalStartDuration() != expctRs.GroupIntervalStartDuration() { - t.Error("Error loading rate: ", rate, expctRs) - } - rate = csvr.rates["R2"].RateSlots[0] - if expctRs, err = utils.NewRateSlot(0, 0.1, "60s", "1s", "0s"); err != nil { - t.Error("Error loading rate: ", rate, err.Error()) - } else if !reflect.DeepEqual(rate, expctRs) || - rate.RateUnitDuration() != expctRs.RateUnitDuration() || - rate.RateIncrementDuration() != expctRs.RateIncrementDuration() || - rate.GroupIntervalStartDuration() != expctRs.GroupIntervalStartDuration() { - t.Errorf("Expecting: %+v, received: %+v", expctRs, rate) - } - rate = csvr.rates["R3"].RateSlots[0] - if expctRs, err = utils.NewRateSlot(0, 0.05, "60s", "1s", "0s"); err != nil { - t.Error("Error loading rate: ", rate, err.Error()) - } else if !reflect.DeepEqual(rate, expctRs) || - rate.RateUnitDuration() != expctRs.RateUnitDuration() || - rate.RateIncrementDuration() != expctRs.RateIncrementDuration() || - rate.GroupIntervalStartDuration() != expctRs.GroupIntervalStartDuration() { - t.Error("Error loading rate: ", rate) - } - rate = csvr.rates["R4"].RateSlots[0] - if expctRs, err = utils.NewRateSlot(1, 1.0, "1s", "1s", "0s"); err != nil { - t.Error("Error loading rate: ", rate, err.Error()) - } else if !reflect.DeepEqual(rate, expctRs) || - rate.RateUnitDuration() != expctRs.RateUnitDuration() || - rate.RateIncrementDuration() != expctRs.RateIncrementDuration() || - rate.GroupIntervalStartDuration() != expctRs.GroupIntervalStartDuration() { - t.Error("Error loading rate: ", rate) - } - rate = csvr.rates["R5"].RateSlots[0] - if expctRs, err = utils.NewRateSlot(0, 0.5, "1s", "1s", "0s"); err != nil { - t.Error("Error loading rate: ", rate, err.Error()) - } else if !reflect.DeepEqual(rate, expctRs) || - rate.RateUnitDuration() != expctRs.RateUnitDuration() || - rate.RateIncrementDuration() != expctRs.RateIncrementDuration() || - rate.GroupIntervalStartDuration() != expctRs.GroupIntervalStartDuration() { - t.Error("Error loading rate: ", rate) - } - rate = csvr.rates["LANDLINE_OFFPEAK"].RateSlots[0] - if expctRs, err = utils.NewRateSlot(0, 1, "1s", "60s", "0s"); err != nil { - t.Error("Error loading rate: ", rate, err.Error()) - } else if !reflect.DeepEqual(rate, expctRs) || - rate.RateUnitDuration() != expctRs.RateUnitDuration() || - rate.RateIncrementDuration() != expctRs.RateIncrementDuration() || - rate.GroupIntervalStartDuration() != expctRs.GroupIntervalStartDuration() { - t.Error("Error loading rate: ", rate) - } - rate = csvr.rates["LANDLINE_OFFPEAK"].RateSlots[1] - if expctRs, err = utils.NewRateSlot(0, 1, "1s", "1s", "60s"); err != nil { - t.Error("Error loading rate: ", rate, err.Error()) - } else if !reflect.DeepEqual(rate, expctRs) || - rate.RateUnitDuration() != expctRs.RateUnitDuration() || - rate.RateIncrementDuration() != expctRs.RateIncrementDuration() || - rate.GroupIntervalStartDuration() != expctRs.GroupIntervalStartDuration() { - t.Error("Error loading rate: ", rate) - } -} - -func TestLoadDestinationRates(t *testing.T) { - if len(csvr.destinationRates) != 15 { - t.Error("Failed to load destinationrates: ", len(csvr.destinationRates)) - } - drs := csvr.destinationRates["RT_STANDARD"] - dr := &utils.TPDestinationRate{ - TPid: testTPID, - ID: "RT_STANDARD", - DestinationRates: []*utils.DestinationRate{ - { - DestinationId: "GERMANY", - RateId: "R1", - Rate: csvr.rates["R1"], - RoundingMethod: utils.MetaRoundingMiddle, - RoundingDecimals: 4, - }, - { - DestinationId: "GERMANY_O2", - RateId: "R2", - Rate: csvr.rates["R2"], - RoundingMethod: utils.MetaRoundingMiddle, - RoundingDecimals: 4, - }, - { - DestinationId: "GERMANY_PREMIUM", - RateId: "R2", - Rate: csvr.rates["R2"], - RoundingMethod: utils.MetaRoundingMiddle, - RoundingDecimals: 4, - }, - }, - } - if !reflect.DeepEqual(drs, dr) { - t.Errorf("Error loading destination rate: \n%+v \n%+v", drs.DestinationRates[0], dr.DestinationRates[0]) - } - drs = csvr.destinationRates["RT_DEFAULT"] - if !reflect.DeepEqual(drs, &utils.TPDestinationRate{ - TPid: testTPID, - ID: "RT_DEFAULT", - DestinationRates: []*utils.DestinationRate{ - { - DestinationId: "ALL", - RateId: "R2", - Rate: csvr.rates["R2"], - RoundingMethod: utils.MetaRoundingMiddle, - RoundingDecimals: 4, - }, - }, - }) { - t.Errorf("Error loading destination rate: %+v", drs.DestinationRates[0]) - } - drs = csvr.destinationRates["RT_STD_WEEKEND"] - if !reflect.DeepEqual(drs, &utils.TPDestinationRate{ - TPid: testTPID, - ID: "RT_STD_WEEKEND", - DestinationRates: []*utils.DestinationRate{ - { - DestinationId: "GERMANY", - RateId: "R2", - Rate: csvr.rates["R2"], - RoundingMethod: utils.MetaRoundingMiddle, - RoundingDecimals: 4, - }, - { - DestinationId: "GERMANY_O2", - RateId: "R3", - Rate: csvr.rates["R3"], - RoundingMethod: utils.MetaRoundingMiddle, - RoundingDecimals: 4, - }, - }, - }) { - t.Error("Error loading destination rate: ", drs) - } - drs = csvr.destinationRates["P1"] - if !reflect.DeepEqual(drs, &utils.TPDestinationRate{ - TPid: testTPID, - ID: "P1", - DestinationRates: []*utils.DestinationRate{ - { - DestinationId: "NAT", - RateId: "R4", - Rate: csvr.rates["R4"], - RoundingMethod: utils.MetaRoundingMiddle, - RoundingDecimals: 4, - }, - }, - }) { - t.Error("Error loading destination rate: ", drs) - } - drs = csvr.destinationRates["P2"] - if !reflect.DeepEqual(drs, &utils.TPDestinationRate{ - TPid: testTPID, - ID: "P2", - DestinationRates: []*utils.DestinationRate{ - { - DestinationId: "NAT", - RateId: "R5", - Rate: csvr.rates["R5"], - RoundingMethod: utils.MetaRoundingMiddle, - RoundingDecimals: 4, - }, - }, - }) { - t.Error("Error loading destination rate: ", drs) - } - drs = csvr.destinationRates["T1"] - if !reflect.DeepEqual(drs, &utils.TPDestinationRate{ - TPid: testTPID, - ID: "T1", - DestinationRates: []*utils.DestinationRate{ - { - DestinationId: "NAT", - RateId: "LANDLINE_OFFPEAK", - Rate: csvr.rates["LANDLINE_OFFPEAK"], - RoundingMethod: utils.MetaRoundingMiddle, - RoundingDecimals: 4, - }, - }, - }) { - t.Error("Error loading destination rate: ", drs) - } - drs = csvr.destinationRates["T2"] - if !reflect.DeepEqual(drs, &utils.TPDestinationRate{ - TPid: testTPID, - ID: "T2", - DestinationRates: []*utils.DestinationRate{ - { - DestinationId: "GERMANY", - RateId: "GBP_72", - Rate: csvr.rates["GBP_72"], - RoundingMethod: utils.MetaRoundingMiddle, - RoundingDecimals: 4, - }, - { - DestinationId: "GERMANY_O2", - RateId: "GBP_70", - Rate: csvr.rates["GBP_70"], - RoundingMethod: utils.MetaRoundingMiddle, - RoundingDecimals: 4, - }, - { - DestinationId: "GERMANY_PREMIUM", - RateId: "GBP_71", - Rate: csvr.rates["GBP_71"], - RoundingMethod: utils.MetaRoundingMiddle, - RoundingDecimals: 4, - }, - }, - }) { - t.Error("Error loading destination rate: ", drs) - } -} - -func TestLoadRatingPlans(t *testing.T) { - if len(csvr.ratingPlans) != 14 { - t.Error("Failed to load rating plans: ", len(csvr.ratingPlans)) - } - rplan := csvr.ratingPlans["STANDARD"] - expected := &RatingPlan{ - Id: "STANDARD", - Timings: map[string]*RITiming{ - "59a981b9": { - Years: utils.Years{}, - Months: utils.Months{}, - MonthDays: utils.MonthDays{}, - WeekDays: utils.WeekDays{1, 2, 3, 4, 5}, - StartTime: "00:00:00", - tag: "WORKDAYS_00", - }, - "2d9ca6c4": { - Years: utils.Years{}, - Months: utils.Months{}, - MonthDays: utils.MonthDays{}, - WeekDays: utils.WeekDays{1, 2, 3, 4, 5}, - StartTime: "18:00:00", - tag: "WORKDAYS_18", - }, - "ec8ed374": { - Years: utils.Years{}, - Months: utils.Months{}, - MonthDays: utils.MonthDays{}, - WeekDays: utils.WeekDays{time.Saturday, time.Sunday}, - StartTime: "00:00:00", - tag: "WEEKENDS", - }, - "83429156": { - Years: utils.Years{}, - Months: utils.Months{}, - MonthDays: utils.MonthDays{}, - WeekDays: utils.WeekDays{}, - StartTime: "00:00:00", - tag: "*any", - }, - }, - Ratings: map[string]*RIRate{ - "ebefae11": { - ConnectFee: 0, - Rates: []*RGRate{ - { - GroupIntervalStart: 0, - Value: 0.2, - RateIncrement: time.Second, - RateUnit: time.Minute, - }, - }, - RoundingMethod: utils.MetaRoundingMiddle, - RoundingDecimals: 4, - tag: "R1", - }, - "fac0138e": { - ConnectFee: 0, - Rates: []*RGRate{ - { - GroupIntervalStart: 0, - Value: 0.1, - RateIncrement: time.Second, - RateUnit: time.Minute, - }, - }, - RoundingMethod: utils.MetaRoundingMiddle, - RoundingDecimals: 4, - tag: "R2", - }, - "781bfa03": { - ConnectFee: 0, - Rates: []*RGRate{ - { - GroupIntervalStart: 0, - Value: 0.05, - RateIncrement: time.Second, - RateUnit: time.Minute, - }, - }, - RoundingMethod: utils.MetaRoundingMiddle, - RoundingDecimals: 4, - tag: "R3", - }, - "f692daa4": { - ConnectFee: 0, - Rates: []*RGRate{ - { - GroupIntervalStart: 0, - Value: 0, - RateIncrement: time.Second, - RateUnit: time.Second, - }, - }, - RoundingMethod: utils.MetaRoundingMiddle, - RoundingDecimals: 4, - tag: "R_URG", - }, - }, - DestinationRates: map[string]RPRateList{ - "GERMANY": []*RPRate{ - { - Timing: "ec8ed374", - Rating: "ebefae11", - Weight: 10, - }, - { - Timing: "83429156", - Rating: "fac0138e", - Weight: 10, - }, - { - Timing: "a60bfb13", - Rating: "fac0138e", - Weight: 10, - }, - }, - "GERMANY_O2": []*RPRate{ - { - Timing: "ec8ed374", - Rating: "fac0138e", - Weight: 10, - }, - { - Timing: "83429156", - Rating: "781bfa03", - Weight: 10, - }, - { - Timing: "a60bfb13", - Rating: "781bfa03", - Weight: 10, - }, - }, - "GERMANY_PREMIUM": []*RPRate{ - { - Timing: "ec8ed374", - Rating: "16e9ee19", - Weight: 10, - }, - }, - "URG": []*RPRate{ - { - Timing: "2d9ca64", - Rating: "f692daa4", - Weight: 20, - }, - }, - }, - } - if !reflect.DeepEqual(rplan.Ratings, expected.Ratings) { - /*for tag, key := range rplan.Ratings { - log.Print(tag, key) - }*/ - t.Errorf("Expecting:\n%s\nReceived:\n%s", utils.ToIJSON(expected.Ratings), utils.ToIJSON(rplan.Ratings)) - } - anyTiming := &RITiming{ - ID: utils.MetaAny, - Years: utils.Years{}, - Months: utils.Months{}, - MonthDays: utils.MonthDays{}, - WeekDays: utils.WeekDays{}, - StartTime: "00:00:00", - EndTime: "", - cronString: "", - tag: utils.MetaAny, - } - - if !reflect.DeepEqual(csvr.ratingPlans["ANY_PLAN"].Timings["b9b78731"], anyTiming) { - t.Errorf("Error using *any timing in rating plans: %+v : %+v", csvr.ratingPlans["ANY_PLAN"].Timings["b9b78731"], anyTiming) - } -} - -func TestLoadRatingProfiles(t *testing.T) { - if len(csvr.ratingProfiles) != 24 { - t.Error("Failed to load rating profiles: ", len(csvr.ratingProfiles), csvr.ratingProfiles) - } - rp := csvr.ratingProfiles["*out:test:0:trp"] - expected := &RatingProfile{ - Id: "*out:test:0:trp", - RatingPlanActivations: RatingPlanActivations{ - &RatingPlanActivation{ - ActivationTime: time.Date(2013, 10, 1, 0, 0, 0, 0, time.UTC), - RatingPlanId: "TDRT", - FallbackKeys: []string{"*out:test:0:danb", "*out:test:0:rif"}, - }}, - } - if !reflect.DeepEqual(rp, expected) { - t.Errorf("Error loading rating profile: %+v", rp.RatingPlanActivations[0]) - } -} - -func TestLoadActions(t *testing.T) { - if len(csvr.actions) != 16 { - t.Error("Failed to load actions: ", len(csvr.actions)) - } - as1 := csvr.actions["MINI"] - expected := []*Action{ - { - Id: "MINI", - ActionType: utils.MetaTopUpReset, - ExpirationString: utils.MetaUnlimited, - ExtraParameters: "", - Weight: 10, - Balance: &BalanceFilter{ - Type: utils.StringPointer(utils.MetaMonetary), - Uuid: as1[0].Balance.Uuid, - Value: &utils.ValueFormula{Static: 10}, - Weight: utils.Float64Pointer(10), - DestinationIDs: nil, - TimingIDs: nil, - SharedGroups: nil, - Categories: nil, - Disabled: utils.BoolPointer(false), - Blocker: utils.BoolPointer(false), - }, - }, - { - Id: "MINI", - ActionType: utils.MetaTopUp, - ExpirationString: utils.MetaUnlimited, - ExtraParameters: "", - Weight: 10, - Balance: &BalanceFilter{ - Type: utils.StringPointer(utils.MetaVoice), - Uuid: as1[1].Balance.Uuid, - Value: &utils.ValueFormula{Static: 100 * float64(time.Second)}, - Weight: utils.Float64Pointer(10), - RatingSubject: utils.StringPointer("test"), - DestinationIDs: utils.StringMapPointer(utils.NewStringMap("NAT")), - TimingIDs: nil, - SharedGroups: nil, - Categories: nil, - Disabled: utils.BoolPointer(false), - Blocker: utils.BoolPointer(false), - }, - }, - } - if !reflect.DeepEqual(as1, expected) { - t.Errorf("expecting: %s received: %s", - utils.ToIJSON(expected), utils.ToIJSON(as1)) - } - as2 := csvr.actions["SHARED"] - expected = []*Action{ - { - Id: "SHARED", - ActionType: utils.MetaTopUp, - ExpirationString: utils.MetaUnlimited, - Weight: 10, - Balance: &BalanceFilter{ - Type: utils.StringPointer(utils.MetaMonetary), - DestinationIDs: nil, - Uuid: as2[0].Balance.Uuid, - Value: &utils.ValueFormula{Static: 100}, - Weight: utils.Float64Pointer(10), - SharedGroups: utils.StringMapPointer(utils.NewStringMap("SG1")), - TimingIDs: nil, - Categories: nil, - Disabled: utils.BoolPointer(false), - Blocker: utils.BoolPointer(false), - }, - }, - } - if !reflect.DeepEqual(as2, expected) { - t.Errorf("Error loading action: %s", utils.ToIJSON(as2)) - } - as3 := csvr.actions["DEFEE"] - expected = []*Action{ - { - Id: "DEFEE", - ActionType: utils.CDRLog, - ExtraParameters: `{"Category":"^ddi","MediationRunId":"^did_run"}`, - Weight: 10, - Balance: &BalanceFilter{ - Uuid: as3[0].Balance.Uuid, - DestinationIDs: nil, - TimingIDs: nil, - Categories: nil, - SharedGroups: nil, - Blocker: utils.BoolPointer(false), - Disabled: utils.BoolPointer(false), - }, - }, - } - if !reflect.DeepEqual(as3, expected) { - t.Errorf("Error loading action: %+v", as3[0].Balance) - } - asGnrc := csvr.actions["TOPUP_RST_GNR_1000"] - //TOPUP_RST_GNR_1000,*topup_reset,"{""*voice"": 60.0,""*data"":1024.0,""*sms"":1.0}",,,*generic,*out,,*any,,,*unlimited,,1000,20,false,false,10 - expected = []*Action{ - { - Id: "TOPUP_RST_GNR_1000", - ActionType: utils.MetaTopUpReset, - ExtraParameters: `{"*voice": 60.0,"*data":1024.0,"*sms":1.0}`, - Weight: 10, - ExpirationString: utils.MetaUnlimited, - Balance: &BalanceFilter{ - Uuid: asGnrc[0].Balance.Uuid, - Type: utils.StringPointer(utils.MetaGeneric), - Value: &utils.ValueFormula{Static: 1000}, - Weight: utils.Float64Pointer(20), - Disabled: utils.BoolPointer(false), - Blocker: utils.BoolPointer(false), - }, - }, - } - if !reflect.DeepEqual(asGnrc, expected) { - t.Errorf("Expecting: %+v, received: %+v", expected[0].Balance, asGnrc[0].Balance) - } -} - -func TestLoadSharedGroups(t *testing.T) { - if len(csvr.sharedGroups) != 3 { - t.Error("Failed to shared groups: ", csvr.sharedGroups) - } - - sg1 := csvr.sharedGroups["SG1"] - expected := &SharedGroup{ - Id: "SG1", - AccountParameters: map[string]*SharingParameters{ - "*any": { - Strategy: "*lowest", - RatingSubject: "", - }, - }, - } - if !reflect.DeepEqual(sg1, expected) { - t.Errorf("Expected: %s, received %s ", utils.ToJSON(expected), utils.ToJSON(sg1)) - } - sg2 := csvr.sharedGroups["SG2"] - expected = &SharedGroup{ - Id: "SG2", - AccountParameters: map[string]*SharingParameters{ - "*any": { - Strategy: "*lowest", - RatingSubject: "one", - }, - }, - } - if !reflect.DeepEqual(sg2, expected) { - t.Errorf("Expected: %s, received %s ", utils.ToJSON(expected), utils.ToJSON(sg2)) - } - /*sg, _ := dataStorage.GetSharedGroup("SG1", false) - if len(sg.Members) != 0 { - t.Errorf("Memebers should be empty: %+v", sg) - } - - // execute action timings to fill memebers - atm := csvr.actionPlans["MORE_MINUTES"][1] - atm.Execute() - atm.actions, atm.stCache = nil, time.Time{} - - sg, _ = dataStorage.GetSharedGroup("SG1", false) - if len(sg.Members) != 1 { - t.Errorf("Memebers should not be empty: %+v", sg) - }*/ -} - -func TestLoadActionTimings(t *testing.T) { - if len(csvr.actionPlans) != 9 { - t.Error("Failed to load action timings: ", len(csvr.actionPlans)) - } - atm := csvr.actionPlans["MORE_MINUTES"] - expected := &ActionPlan{ - Id: "MORE_MINUTES", - AccountIDs: utils.StringMap{}, - ActionTimings: []*ActionTiming{ - { - Uuid: atm.ActionTimings[0].Uuid, - Timing: &RateInterval{ - Timing: &RITiming{ - ID: "ONE_TIME_RUN", - Years: utils.Years{2012}, - Months: utils.Months{}, - MonthDays: utils.MonthDays{}, - WeekDays: utils.WeekDays{}, - StartTime: utils.MetaASAP, - }, - }, - Weight: 10, - ActionsID: "MINI", - }, - { - Uuid: atm.ActionTimings[1].Uuid, - Timing: &RateInterval{ - Timing: &RITiming{ - ID: "ONE_TIME_RUN", - Years: utils.Years{2012}, - Months: utils.Months{}, - MonthDays: utils.MonthDays{}, - WeekDays: utils.WeekDays{}, - StartTime: utils.MetaASAP, - }, - }, - Weight: 10, - ActionsID: "SHARED", - }, - }, - } - if !reflect.DeepEqual(atm, expected) { - t.Errorf("Error loading action timing:\n%+v", utils.ToJSON(atm)) - } -} - -func TestLoadActionTriggers(t *testing.T) { - if len(csvr.actionsTriggers) != 2 { - t.Error("Failed to load action triggers: ", len(csvr.actionsTriggers)) - } - atr := csvr.actionsTriggers["STANDARD_TRIGGER"][0] - expected := &ActionTrigger{ - ID: "STANDARD_TRIGGER", - UniqueID: "st0", - ThresholdType: utils.TriggerMinEventCounter, - ThresholdValue: 10, - Balance: &BalanceFilter{ - ID: nil, - Type: utils.StringPointer(utils.MetaVoice), - DestinationIDs: utils.StringMapPointer(utils.NewStringMap("GERMANY_O2")), - Categories: nil, - TimingIDs: nil, - SharedGroups: nil, - Disabled: nil, - Blocker: nil, - }, - Weight: 10, - ActionsID: "SOME_1", - Executed: false, - } - if !reflect.DeepEqual(atr, expected) { - t.Errorf("Expected: %+v, received %+v", utils.ToJSON(expected), utils.ToJSON(atr)) - } - atr = csvr.actionsTriggers["STANDARD_TRIGGER"][1] - expected = &ActionTrigger{ - ID: "STANDARD_TRIGGER", - UniqueID: "st1", - ThresholdType: utils.TriggerMaxBalance, - ThresholdValue: 200, - Balance: &BalanceFilter{ - Type: utils.StringPointer(utils.MetaVoice), - DestinationIDs: utils.StringMapPointer(utils.NewStringMap("GERMANY")), - Categories: nil, - TimingIDs: nil, - SharedGroups: nil, - }, - Weight: 10, - ActionsID: "SOME_2", - Executed: false, - } - if !reflect.DeepEqual(atr, expected) { - t.Errorf("Error loading action trigger: %+v", atr) - } -} - -func TestLoadAccountActions(t *testing.T) { - if len(csvr.accountActions) != 17 { - t.Error("Failed to load account actions: ", len(csvr.accountActions)) - } - aa := csvr.accountActions["vdf:minitsboy"] - expected := &Account{ - ID: "vdf:minitsboy", - UnitCounters: UnitCounters{ - utils.MetaVoice: []*UnitCounter{ - { - CounterType: "*event", - Counters: CounterFilters{ - &CounterFilter{ - Value: 0, - Filter: &BalanceFilter{ - ID: utils.StringPointer("st0"), - Type: utils.StringPointer(utils.MetaVoice), - DestinationIDs: utils.StringMapPointer(utils.NewStringMap("GERMANY_O2")), - SharedGroups: nil, - Categories: nil, - TimingIDs: nil, - }, - }, - }, - }, - }, - }, - ActionTriggers: csvr.actionsTriggers["STANDARD_TRIGGER"], - } - // set propper uuid - for i, atr := range aa.ActionTriggers { - csvr.actionsTriggers["STANDARD_TRIGGER"][i].ID = atr.ID - } - for i, b := range aa.UnitCounters[utils.MetaVoice][0].Counters { - expected.UnitCounters[utils.MetaVoice][0].Counters[i].Filter.ID = b.Filter.ID - } - if !reflect.DeepEqual(aa.UnitCounters[utils.MetaVoice][0].Counters[0], expected.UnitCounters[utils.MetaVoice][0].Counters[0]) { - t.Errorf("Error loading account action: %+v", utils.ToIJSON(aa.UnitCounters[utils.MetaVoice][0].Counters[0].Filter)) - } - // test that it does not overwrite balances - existing, err := dm.GetAccount(aa.ID) - if err != nil || len(existing.BalanceMap) != 2 { - t.Errorf("The account was not set before load: %+v", existing) - } - dm.SetAccount(aa) - existing, err = dm.GetAccount(aa.ID) - if err != nil || len(existing.BalanceMap) != 2 { - t.Errorf("The set account altered the balances: %+v", existing) - } -} - func TestLoadResourceProfiles(t *testing.T) { eResProfiles := map[utils.TenantID]*utils.TPResourceProfile{ {Tenant: "cgrates.org", ID: "ResGroup21"}: { diff --git a/engine/mapevent_test.go b/engine/mapevent_test.go index 0d3e975bf..9483ffffc 100644 --- a/engine/mapevent_test.go +++ b/engine/mapevent_test.go @@ -23,7 +23,6 @@ import ( "testing" "time" - "github.com/cgrates/cgrates/config" "github.com/cgrates/cgrates/utils" ) @@ -308,362 +307,6 @@ func TestMapEventAsMapString(t *testing.T) { } } -func TestMapEventAsCDR(t *testing.T) { - me := NewMapEvent(nil) - expected := &CDR{Cost: -1.0, ExtraFields: make(map[string]string)} - if rply, err := me.AsCDR(nil, utils.EmptyString, utils.EmptyString); err != nil { - t.Error(err) - } else if !reflect.DeepEqual(expected, rply) { - t.Errorf("Expecting %+v, received: %+v", expected, rply) - } - cfg := config.NewDefaultCGRConfig() - - expected = &CDR{ - CGRID: "da39a3ee5e6b4b0d3255bfef95601890afd80709", - Cost: -1.0, - RunID: utils.MetaDefault, - ToR: utils.MetaVoice, - RequestType: cfg.GeneralCfg().DefaultReqType, - Tenant: cfg.GeneralCfg().DefaultTenant, - Category: cfg.GeneralCfg().DefaultCategory, - ExtraFields: make(map[string]string), - } - if rply, err := me.AsCDR(cfg, utils.EmptyString, utils.EmptyString); err != nil { - t.Error(err) - } else if !reflect.DeepEqual(expected, rply) { - t.Errorf("Expecting %+v, received: %+v", expected, rply) - } - me = MapEvent{"SetupTime": "clearly not time string"} - if _, err := me.AsCDR(nil, utils.EmptyString, utils.EmptyString); err == nil { - t.Errorf("Expecting not null error, received: null error") - } - me = MapEvent{"AnswerTime": "clearly not time string"} - if _, err := me.AsCDR(nil, utils.EmptyString, utils.EmptyString); err == nil { - t.Errorf("Expecting not null error, received: null error") - } - me = MapEvent{"Usage": "clearly not duration string"} - if _, err := me.AsCDR(nil, utils.EmptyString, utils.EmptyString); err == nil { - t.Errorf("Expecting not null error, received: null error") - } - me = MapEvent{"Partial": "clearly not bool string"} - if _, err := me.AsCDR(nil, utils.EmptyString, utils.EmptyString); err == nil { - t.Errorf("Expecting not null error, received: null error") - } - me = MapEvent{"PreRated": "clearly not bool string"} - if _, err := me.AsCDR(nil, utils.EmptyString, utils.EmptyString); err == nil { - t.Errorf("Expecting not null error, received: null error") - } - me = MapEvent{"Cost": "clearly not float64 string"} - if _, err := me.AsCDR(nil, utils.EmptyString, utils.EmptyString); err == nil { - t.Errorf("Expecting not null error, received: null error") - } - me = MapEvent{"CostDetails": "clearly not CostDetails string"} - if _, err := me.AsCDR(nil, utils.EmptyString, utils.EmptyString); err == nil { - t.Errorf("Expecting not null error, received: null error") - } - me = MapEvent{"OrderID": "clearly not int64 string"} - if _, err := me.AsCDR(nil, utils.EmptyString, utils.EmptyString); err == nil { - t.Errorf("Expecting not null error, received: null error") - } - - me = MapEvent{"ExtraField1": 5, "ExtraField2": "extra"} - expected = &CDR{ - Cost: -1.0, - ExtraFields: map[string]string{ - "ExtraField1": "5", - "ExtraField2": "extra", - }} - if rply, err := me.AsCDR(nil, utils.EmptyString, utils.EmptyString); err != nil { - t.Error(err) - } else if !reflect.DeepEqual(expected, rply) { - t.Errorf("Expecting %+v, received: %+v", expected, rply) - } - me = MapEvent{ - "ExtraField1": 5, - "Source": 1001, - "CostSource": "1002", - "ExtraField2": "extra", - "ExtraInfo": "ACCOUNT_NOT_FOUND", - } - expected = &CDR{ - CGRID: "da39a3ee5e6b4b0d3255bfef95601890afd80709", - Cost: -1.0, - Source: "1001", - CostSource: "1002", - ExtraFields: map[string]string{ - "ExtraField1": "5", - "ExtraField2": "extra", - }, - RunID: utils.MetaDefault, - ToR: utils.MetaVoice, - RequestType: cfg.GeneralCfg().DefaultReqType, - Tenant: cfg.GeneralCfg().DefaultTenant, - Category: cfg.GeneralCfg().DefaultCategory, - ExtraInfo: "ACCOUNT_NOT_FOUND", - } - if rply, err := me.AsCDR(cfg, utils.EmptyString, utils.EmptyString); err != nil { - t.Error(err) - } else if !reflect.DeepEqual(expected, rply) { - t.Errorf("Expecting %+v, received: %+v", expected, rply) - } - me = MapEvent{ - utils.CGRID: "da39a3ee5e6b4b0d3255bfef95601890afd80709", - utils.RunID: utils.MetaDefault, - utils.OriginHost: utils.FreeSWITCHAgent, - utils.OriginID: "127.0.0.1", - utils.ToR: utils.MetaVoice, - utils.RequestType: utils.MetaPrepaid, - utils.Tenant: "cgrates.org", - utils.Category: utils.Call, - utils.AccountField: "10010", - utils.Subject: "10010", - utils.Destination: "10012", - "ExtraField1": 5, - "Source": 1001, - "CostSource": "1002", - "ExtraField2": "extra", - "ExtraInfo": "ACCOUNT_NOT_FOUND", - } - expected = &CDR{ - CGRID: "da39a3ee5e6b4b0d3255bfef95601890afd80709", - RunID: utils.MetaDefault, - OriginHost: utils.FreeSWITCHAgent, - OriginID: "127.0.0.1", - ToR: utils.MetaVoice, - RequestType: utils.MetaPrepaid, - Tenant: "cgrates.org", - Category: utils.Call, - Account: "10010", - Subject: "10010", - Destination: "10012", - Cost: -1.0, - Source: "1001", - CostSource: "1002", - ExtraFields: map[string]string{ - "ExtraField1": "5", - "ExtraField2": "extra", - }, - ExtraInfo: "ACCOUNT_NOT_FOUND", - } - if rply, err := me.AsCDR(cfg, utils.EmptyString, utils.EmptyString); err != nil { - t.Error(err) - } else if !reflect.DeepEqual(expected, rply) { - t.Errorf("Expecting %+v, received: %+v", expected, rply) - } - ec1 := &EventCost{ - CGRID: "164b0422fdc6a5117031b427439482c6a4f90e41", - RunID: utils.MetaDefault, - StartTime: time.Date(2017, 1, 9, 16, 18, 21, 0, time.UTC), - Charges: []*ChargingInterval{ - { - RatingID: "c1a5ab9", - Increments: []*ChargingIncrement{ - { - Usage: 0, - Cost: 0.1, - AccountingID: "9bdad10", - CompressFactor: 1, - }, - { - Usage: time.Second, - Cost: 0, - AccountingID: "3455b83", - CompressFactor: 10, - }, - { - Usage: 10 * time.Second, - Cost: 0.01, - AccountingID: "a012888", - CompressFactor: 2, - }, - { - Usage: time.Second, - Cost: 0.005, - AccountingID: "44d6c02", - CompressFactor: 30, - }, - }, - CompressFactor: 1, - }, - { - RatingID: "c1a5ab9", - Increments: []*ChargingIncrement{ - { - Usage: time.Second, - Cost: 0.01, - AccountingID: "a012888", - CompressFactor: 60, - }, - }, - CompressFactor: 4, - }, - { - RatingID: "c1a5ab9", - Increments: []*ChargingIncrement{ - { - Usage: time.Second, - Cost: 0, - AccountingID: "3455b83", - CompressFactor: 10, - }, - { - Usage: 10 * time.Second, - Cost: 0.01, - AccountingID: "a012888", - CompressFactor: 2, - }, - { - Usage: time.Second, - Cost: 0.005, - AccountingID: "44d6c02", - CompressFactor: 30, - }, - }, - CompressFactor: 5, - }, - }, - AccountSummary: &AccountSummary{ - Tenant: "cgrates.org", - ID: "dan", - BalanceSummaries: []*BalanceSummary{ - { - Type: "*monetary", - Value: 50, - Disabled: false}, - { - ID: "4b8b53d7-c1a1-4159-b845-4623a00a0165", - Type: "*monetary", - Value: 25, - Disabled: false}, - { - Type: "*voice", - Value: 200, - Disabled: false, - }, - }, - AllowNegative: false, - Disabled: false, - }, - Rating: Rating{ - "3cd6425": &RatingUnit{ - RoundingMethod: "*up", - RoundingDecimals: 5, - TimingID: "7f324ab", - RatesID: "4910ecf", - RatingFiltersID: "43e77dc", - }, - "c1a5ab9": &RatingUnit{ - ConnectFee: 0.1, - RoundingMethod: "*up", - RoundingDecimals: 5, - TimingID: "7f324ab", - RatesID: "ec1a177", - RatingFiltersID: "43e77dc", - }, - }, - Accounting: Accounting{ - "a012888": &BalanceCharge{ - AccountID: "cgrates.org:dan", - BalanceUUID: "8c54a9e9-d610-4c82-bcb5-a315b9a65010", - Units: 0.01, - }, - "188bfa6": &BalanceCharge{ - AccountID: "cgrates.org:dan", - BalanceUUID: "8c54a9e9-d610-4c82-bcb5-a315b9a65010", - Units: 0.005, - }, - "9bdad10": &BalanceCharge{ - AccountID: "cgrates.org:dan", - BalanceUUID: "8c54a9e9-d610-4c82-bcb5-a315b9a65010", - Units: 0.1, - }, - "44d6c02": &BalanceCharge{ - AccountID: "cgrates.org:dan", - BalanceUUID: "7a54a9e9-d610-4c82-bcb5-a315b9a65010", - RatingID: "3cd6425", - Units: 1, - ExtraChargeID: "188bfa6", - }, - "3455b83": &BalanceCharge{ - AccountID: "cgrates.org:dan", - BalanceUUID: "9d54a9e9-d610-4c82-bcb5-a315b9a65089", - Units: 1, - ExtraChargeID: "*none", - }, - }, - RatingFilters: RatingFilters{ - "43e77dc": RatingMatchedFilters{ - "DestinationID": "GERMANY", - "DestinationPrefix": "+49", - "RatingPlanID": "RPL_RETAIL1", - "Subject": "*out:cgrates.org:call:*any", - }, - }, - Rates: ChargedRates{ - "ec1a177": RateGroups{ - &RGRate{ - GroupIntervalStart: 0, - Value: 0.01, - RateIncrement: time.Minute, - RateUnit: time.Second}, - }, - "4910ecf": RateGroups{ - &RGRate{ - GroupIntervalStart: 0, - Value: 0.005, - RateIncrement: time.Second, - RateUnit: time.Second}, - &RGRate{ - GroupIntervalStart: 60 * time.Second, - Value: 0.005, - RateIncrement: time.Second, - RateUnit: time.Second}, - }, - }, - Timings: ChargedTimings{ - "7f324ab": &ChargedTiming{ - StartTime: "00:00:00", - }, - }, - } - ec1.initCache() - me = MapEvent{ - "ExtraField1": 5, - "Source": 1001, - "CostSource": "1002", - "ExtraField2": "extra", - "SetupTime": "2009-11-10T23:00:00Z", - "Usage": "42s", - "PreRated": "True", - "Cost": "42.3", - "CostDetails": utils.ToJSON(ec1), - } - expected = &CDR{ - CGRID: "da39a3ee5e6b4b0d3255bfef95601890afd80709", - Tenant: "itsyscom.com", - Cost: 42.3, - Source: "1001", - CostSource: "1002", - PreRated: true, - Usage: 42 * time.Second, - SetupTime: time.Date(2009, 11, 10, 23, 0, 0, 0, time.UTC), - ExtraFields: map[string]string{ - "ExtraField1": "5", - "ExtraField2": "extra", - }, - RunID: utils.MetaDefault, - ToR: utils.MetaVoice, - RequestType: cfg.GeneralCfg().DefaultReqType, - Category: cfg.GeneralCfg().DefaultCategory, - CostDetails: ec1, - } - if rply, err := me.AsCDR(cfg, "itsyscom.com", utils.EmptyString); err != nil { - t.Error(err) - } else if !reflect.DeepEqual(expected, rply) { - t.Errorf("Expecting %+v, received: %+v", expected, rply) - } -} - func TestMapEventGetTInt64(t *testing.T) { if rply, err := mapEv.GetTInt64("test2"); err != nil { t.Error(err) diff --git a/engine/model_helpers_test.go b/engine/model_helpers_test.go index 259dcc090..cf876e5cb 100644 --- a/engine/model_helpers_test.go +++ b/engine/model_helpers_test.go @@ -339,220 +339,6 @@ func TestApierTPTimingAsExportSlice(t *testing.T) { } } -func TestTPActionsAsExportSlice(t *testing.T) { - tpActs := &utils.TPActions{ - TPid: "TEST_TPID", - ID: "TEST_ACTIONS", - Actions: []*utils.TPAction{ - { - Identifier: "*topup_reset", - BalanceType: "*monetary", - Units: "5.0", - ExpiryTime: "*never", - DestinationIds: "*any", - RatingSubject: "special1", - Categories: "call", - SharedGroups: "GROUP1", - BalanceWeight: "10.0", - ExtraParameters: "", - Weight: 10.0}, - { - Identifier: "*http_post", - BalanceType: "", - Units: "0.0", - ExpiryTime: "", - DestinationIds: "", - RatingSubject: "", - Categories: "", - SharedGroups: "", - BalanceWeight: "0.0", - ExtraParameters: "http://localhost/¶m1=value1", - Weight: 20.0}, - }, - } - expectedSlc := [][]string{ - {"TEST_ACTIONS", "*topup_reset", "", "", "", "*monetary", "call", "*any", "special1", "GROUP1", "*never", "", "5.0", "10.0", "", "", "10"}, - {"TEST_ACTIONS", "*http_post", "http://localhost/¶m1=value1", "", "", "", "", "", "", "", "", "", "0.0", "0.0", "", "", "20"}, - } - - ms := APItoModelAction(tpActs) - var slc [][]string - for _, m := range ms { - lc, err := CsvDump(m) - if err != nil { - t.Error("Error dumping to csv: ", err) - } - slc = append(slc, lc) - } - - if !reflect.DeepEqual(expectedSlc, slc) { - t.Errorf("Expecting: \n%+v, received: \n%+v", expectedSlc, slc) - } -} - -func TestAPItoModelAction(t *testing.T) { - var as *utils.TPActions - if rcv := APItoModelAction(as); rcv != nil { - t.Errorf("Expecting: nil, received: %+v", rcv) - } - as = &utils.TPActions{ - TPid: "TEST_TPID", - ID: "TEST_ACTIONS", - } - eOut := ActionMdls{ - ActionMdl{ - Tpid: "TEST_TPID", - Tag: "TEST_ACTIONS", - }, - } - if rcv := APItoModelAction(as); !reflect.DeepEqual(eOut, rcv) { - t.Errorf("Expecting: %+v, received: %+v", utils.ToJSON(eOut), utils.ToJSON(rcv)) - } - as = &utils.TPActions{ - TPid: "TEST_TPID", - ID: "TEST_ACTIONS", - Actions: []*utils.TPAction{ - { - Identifier: "*topup_reset", - BalanceType: "*monetary", - Units: "5.0", - ExpiryTime: "*never", - DestinationIds: "*any", - RatingSubject: "special1", - Categories: "call", - SharedGroups: "GROUP1", - BalanceWeight: "10.0", - ExtraParameters: "", - Weight: 10.0}, - { - Identifier: "*http_post", - BalanceType: "", - Units: "0.0", - ExpiryTime: "", - DestinationIds: "", - RatingSubject: "", - Categories: "", - SharedGroups: "", - BalanceWeight: "0.0", - ExtraParameters: "http://localhost/¶m1=value1", - Weight: 20.0}, - }, - } - eOut = ActionMdls{ - ActionMdl{ - Tpid: "TEST_TPID", - Tag: "TEST_ACTIONS", - BalanceType: "*monetary", - Categories: "call", - DestinationTags: "*any", - RatingSubject: "special1", - SharedGroups: "GROUP1", - ExpiryTime: "*never", - Units: "5.0", - BalanceWeight: "10.0", - Weight: 10, - Action: "*topup_reset", - }, - ActionMdl{ - Tpid: "TEST_TPID", - Tag: "TEST_ACTIONS", - Action: "*http_post", - ExtraParameters: "http://localhost/\u0026param1=value1", - Units: "0.0", - BalanceWeight: "0.0", - Weight: 20, - }, - } - if rcv := APItoModelAction(as); !reflect.DeepEqual(eOut, rcv) { - t.Errorf("Expecting: %+v,\nreceived: %+v", utils.ToJSON(eOut), utils.ToJSON(rcv)) - } -} - -func TestAPItoModelActions(t *testing.T) { - var as []*utils.TPActions - if rcv := APItoModelActions(as); rcv != nil { - t.Errorf("Expecting: nil, received: %+v", rcv) - } - as = []*utils.TPActions{ - { - TPid: "TEST_TPID", - ID: "TEST_ACTIONS", - }, - { - TPid: "TEST_TPID2", - ID: "TEST_ACTIONS2", - }, - } - eOut := ActionMdls{ - ActionMdl{ - Tpid: "TEST_TPID", - Tag: "TEST_ACTIONS", - }, - ActionMdl{ - Tpid: "TEST_TPID2", - Tag: "TEST_ACTIONS2", - }, - } - if rcv := APItoModelActions(as); !reflect.DeepEqual(eOut, rcv) { - t.Errorf("Expecting: %+v,\nreceived: %+v", utils.ToJSON(eOut), utils.ToJSON(rcv)) - } - as = []*utils.TPActions{ - { - TPid: "TEST_TPID", - ID: "TEST_ACTIONS", - Actions: []*utils.TPAction{ - { - Identifier: "*topup_reset", - BalanceType: "*monetary", - Units: "5.0", - ExpiryTime: "*never", - DestinationIds: "*any", - RatingSubject: "special1", - Categories: "call", - SharedGroups: "GROUP1", - BalanceWeight: "10.0", - ExtraParameters: "", - Weight: 10.0}, - { - Identifier: "*http_post", - BalanceType: "", - Units: "0.0", - BalanceWeight: "0.0", - ExtraParameters: "http://localhost/¶m1=value1", - Weight: 20.0}, - }, - }, - } - eOut = ActionMdls{ - ActionMdl{ - Tpid: "TEST_TPID", - Tag: "TEST_ACTIONS", - BalanceType: "*monetary", - Categories: "call", - DestinationTags: "*any", - RatingSubject: "special1", - SharedGroups: "GROUP1", - ExpiryTime: "*never", - Units: "5.0", - BalanceWeight: "10.0", - Weight: 10, - Action: "*topup_reset", - }, - ActionMdl{ - Tpid: "TEST_TPID", - Tag: "TEST_ACTIONS", - Action: "*http_post", - ExtraParameters: "http://localhost/\u0026param1=value1", - Units: "0.0", - BalanceWeight: "0.0", - Weight: 20, - }, - } - if rcv := APItoModelActions(as); !reflect.DeepEqual(eOut, rcv) { - t.Errorf("Expecting: %+v,\nreceived: %+v", utils.ToJSON(eOut), utils.ToJSON(rcv)) - } -} - func TestTpResourcesAsTpResources(t *testing.T) { tps := []*ResourceMdl{ { @@ -993,52 +779,6 @@ func TestTPThresholdsAsTPThreshold(t *testing.T) { } } -func TestAPItoModelAccountActions(t *testing.T) { - var aas []*utils.TPAccountActions - if rcv := APItoModelAccountActions(aas); rcv != nil { - t.Errorf("Expecting: nil , Received: %+v", utils.ToIJSON(rcv)) - } - aas = []*utils.TPAccountActions{ - { - TPid: "TEST_TPID", - LoadId: "TEST_LOADID", - Tenant: "cgrates.org", - Account: "1001", - ActionPlanId: "PACKAGE_10_SHARED_A_5", - ActionTriggersId: "STANDARD_TRIGGERS", - }, - { - TPid: "TEST_TPID2", - LoadId: "TEST_LOADID2", - Tenant: "cgrates.org", - Account: "1001", - ActionPlanId: "PACKAGE_10_SHARED_A_5", - ActionTriggersId: "STANDARD_TRIGGERS", - }, - } - eOut := AccountActionMdls{ - AccountActionMdl{ - Tpid: "TEST_TPID", - Loadid: "TEST_LOADID", - Tenant: "cgrates.org", - Account: "1001", - ActionPlanTag: "PACKAGE_10_SHARED_A_5", - ActionTriggersTag: "STANDARD_TRIGGERS", - }, - AccountActionMdl{ - Tpid: "TEST_TPID2", - Loadid: "TEST_LOADID2", - Tenant: "cgrates.org", - Account: "1001", - ActionPlanTag: "PACKAGE_10_SHARED_A_5", - ActionTriggersTag: "STANDARD_TRIGGERS", - }, - } - if rcv := APItoModelAccountActions(aas); !reflect.DeepEqual(eOut, rcv) { - t.Errorf("Expecting: %+v, received: %+v", utils.ToJSON(eOut), utils.ToJSON(rcv)) - } -} - func TestCSVHeader(t *testing.T) { var tps ResourceMdls eOut := []string{ @@ -3702,23 +3442,6 @@ func TestModelHelpersCsvDumpError(t *testing.T) { } } -func TestModelHelpersAsMapRatesError(t *testing.T) { - tps := RateMdls{{RateUnit: "true"}} - _, err := tps.AsMapRates() - if err == nil || err.Error() != "time: invalid duration \"true\"" { - t.Errorf("Expecting: ,\n Received: <%+v>", err) - } -} - -func TestModelHelpersAsTPRatesError(t *testing.T) { - tps := RateMdls{{RateUnit: "true"}} - _, err := tps.AsTPRates() - if err == nil || err.Error() != "time: invalid duration \"true\"" { - t.Errorf("Expecting: ,\n Received: <%+v>", err) - } - -} - func TestAPItoModelTPRoutesCase1(t *testing.T) { structTest := &utils.TPRouteProfile{} structTest2 := RouteMdls{} @@ -4440,7 +4163,7 @@ func TestThresholdMdlsCSVHeader(t *testing.T) { } expStruct := []string{"#" + utils.Tenant, utils.ID, utils.FilterIDs, utils.ActivationIntervalString, utils.MaxHits, utils.MinHits, utils.MinSleep, - utils.Blocker, utils.Weight, utils.ActionIDs, utils.Async} + utils.Blocker, utils.Weight, utils.ActionProfileIDs, utils.Async} result := testStruct.CSVHeader() if !reflect.DeepEqual(result, expStruct) { t.Errorf("\nExpecting <%+v>,\n Received <%+v>", utils.ToJSON(expStruct), utils.ToJSON(result)) @@ -5539,150 +5262,6 @@ func TestTpResourcesAsTpResources2(t *testing.T) { } } -func TestModelHelpersMapTPAccountActionsError(t *testing.T) { - testStruct := []*utils.TPAccountActions{ - { - TPid: "ee", - LoadId: "ee", - Tenant: "", - Account: "", - ActionPlanId: "", - ActionTriggersId: "", - AllowNegative: false, - Disabled: false, - }, - { - TPid: "ee", - LoadId: "ee", - Tenant: "", - Account: "", - ActionPlanId: "", - ActionTriggersId: "", - AllowNegative: false, - Disabled: false, - }, - } - - _, err := MapTPAccountActions(testStruct) - if err == nil || err.Error() != "Non unique ID :" { - t.Errorf("\nExpecting ,\n Received <%+v>", err) - } -} - -func TestModelHelpersMapTPSharedGroup2(t *testing.T) { - testStruct := []*utils.TPSharedGroups{ - { - TPid: "", - ID: "2", - SharedGroups: []*utils.TPSharedGroup{ - { - Account: "", - Strategy: "", - RatingSubject: "", - }, - }, - }, - { - TPid: "", - ID: "2", - SharedGroups: []*utils.TPSharedGroup{ - { - Account: "", - Strategy: "", - RatingSubject: "", - }, - }, - }, - } - expStruct := map[string][]*utils.TPSharedGroup{ - "2": []*utils.TPSharedGroup{ - { - Account: "", - Strategy: "", - RatingSubject: "", - }, - { - Account: "", - Strategy: "", - RatingSubject: "", - }, - }, - } - result := MapTPSharedGroup(testStruct) - if !reflect.DeepEqual(result, expStruct) { - t.Errorf("\nExpecting <%+v>,\n Received <%+v>", utils.ToJSON(expStruct), utils.ToJSON(result)) - } - -} - -func TestSharedGroupMdlsAsMapTPSharedGroups2(t *testing.T) { - testStruct := SharedGroupMdls{ - { - Id: 2, - Tpid: "2", - Tag: "", - Account: "", - Strategy: "", - RatingSubject: "", - }, - { - Id: 2, - Tpid: "2", - Tag: "", - Account: "", - Strategy: "", - RatingSubject: "", - }, - } - expStruct := map[string]*utils.TPSharedGroups{ - "": &utils.TPSharedGroups{ - TPid: "2", - ID: "", - SharedGroups: []*utils.TPSharedGroup{ - { - Account: "", - Strategy: "", - RatingSubject: "", - }, - { - Account: "", - Strategy: "", - RatingSubject: "", - }, - }, - }, - } - result := testStruct.AsMapTPSharedGroups() - if !reflect.DeepEqual(result, expStruct) { - t.Errorf("\nExpecting <%+v>,\n Received <%+v>", utils.ToJSON(expStruct), utils.ToJSON(result)) - } -} - -func TestModelHelpersMapTPRatingProfilesError(t *testing.T) { - testStruct := []*utils.TPRatingProfile{ - { - TPid: "2", - LoadId: "", - Tenant: "", - Category: "", - Subject: "", - RatingPlanActivations: nil, - }, - { - TPid: "2", - LoadId: "", - Tenant: "", - Category: "", - Subject: "", - RatingPlanActivations: nil, - }, - } - _, err := MapTPRatingProfiles(testStruct) - if err == nil || err.Error() != "Non unique id :*out:::" { - t.Errorf("\nExpecting ,\n Received <%+v>", err) - } -} - func TestModelHelpersCSVLoadErrorInt(t *testing.T) { type testStruct struct { Id int64 diff --git a/engine/models_test.go b/engine/models_test.go index 7b889f262..da589e4f5 100644 --- a/engine/models_test.go +++ b/engine/models_test.go @@ -42,129 +42,3 @@ func TestModelsDestinationMdlTableName(t *testing.T) { t.Errorf("\nExpected <%+v>,\nreceived <%+v>", exp, result) } } - -func TestModelsRateMdlTableName(t *testing.T) { - testStruct := RateMdl{} - exp := utils.TBLTPRates - result := testStruct.TableName() - if !reflect.DeepEqual(exp, result) { - t.Errorf("\nExpected <%+v>,\nreceived <%+v>", exp, result) - } -} - -func TestModelsDestinationRateMdlTableName(t *testing.T) { - testStruct := DestinationRateMdl{} - exp := utils.TBLTPDestinationRates - result := testStruct.TableName() - if !reflect.DeepEqual(exp, result) { - t.Errorf("\nExpected <%+v>,\nreceived <%+v>", exp, result) - } -} - -func TestModelsRatingPlanMdlTableName(t *testing.T) { - testStruct := RatingPlanMdl{} - exp := utils.TBLTPRatingPlans - result := testStruct.TableName() - if !reflect.DeepEqual(exp, result) { - t.Errorf("\nExpected <%+v>,\nreceived <%+v>", exp, result) - } -} - -func TestModelsRatingProfileMdlTableName(t *testing.T) { - testStruct := RatingProfileMdl{} - exp := utils.TBLTPRatingProfiles - result := testStruct.TableName() - if !reflect.DeepEqual(exp, result) { - t.Errorf("\nExpected <%+v>,\nreceived <%+v>", exp, result) - } -} - -func TestModelsActionMdlTableName(t *testing.T) { - testStruct := ActionMdl{} - exp := utils.TBLTPActions - result := testStruct.TableName() - if !reflect.DeepEqual(exp, result) { - t.Errorf("\nExpected <%+v>,\nreceived <%+v>", exp, result) - } -} - -func TestModelsActionPlanMdlTableName(t *testing.T) { - testStruct := ActionPlanMdl{} - exp := utils.TBLTPActionPlans - result := testStruct.TableName() - if !reflect.DeepEqual(exp, result) { - t.Errorf("\nExpected <%+v>,\nreceived <%+v>", exp, result) - } -} - -func TestModelsActionTriggerMdlTableName(t *testing.T) { - testStruct := ActionTriggerMdl{} - exp := utils.TBLTPActionTriggers - result := testStruct.TableName() - if !reflect.DeepEqual(exp, result) { - t.Errorf("\nExpected <%+v>,\nreceived <%+v>", exp, result) - } -} - -func TestModelsAccountActionMdlTableName(t *testing.T) { - testStruct := AccountActionMdl{} - exp := utils.TBLTPAccountActions - result := testStruct.TableName() - if !reflect.DeepEqual(exp, result) { - t.Errorf("\nExpected <%+v>,\nreceived <%+v>", exp, result) - } -} - -func TestModelsSetAccountActionId(t *testing.T) { - testStruct := &AccountActionMdl{ - Id: 0, - Loadid: "", - Tenant: "", - Account: "", - } - - err := testStruct.SetAccountActionId("id1:id2:id3") - if err != nil { - t.Errorf("\nExpected <%+v>,\nreceived <%+v>", nil, err) - } - if !reflect.DeepEqual("id1", testStruct.Loadid) { - t.Errorf("\nExpected <%+v>,\nreceived <%+v>", "id1", testStruct.Loadid) - } - if !reflect.DeepEqual("id2", testStruct.Tenant) { - t.Errorf("\nExpected <%+v>,\nreceived <%+v>", "id2", testStruct.Tenant) - } - if !reflect.DeepEqual("id3", testStruct.Account) { - t.Errorf("\nExpected <%+v>,\nreceived <%+v>", "id3", testStruct.Account) - } - -} - -func TestModelsSetAccountActionIdError(t *testing.T) { - testStruct := &AccountActionMdl{ - Id: 0, - Loadid: "", - Tenant: "", - Account: "", - } - - err := testStruct.SetAccountActionId("id1;id2;id3") - if err == nil || err.Error() != "Wrong TP Account Action Id: id1;id2;id3" { - t.Errorf("\nExpected ,\nreceived <%+v>", err) - } - -} - -func TestModelGetAccountActionId(t *testing.T) { - testStruct := &AccountActionMdl{ - Id: 0, - Tpid: "", - Loadid: "", - Tenant: "id1", - Account: "id2", - } - result := testStruct.GetAccountActionId() - exp := utils.ConcatenatedKey(testStruct.Tenant, testStruct.Account) - if !reflect.DeepEqual(exp, result) { - t.Errorf("\nExpected <%+v> ,\nreceived <%+v>", exp, result) - } -} diff --git a/engine/storage_test.go b/engine/storage_test.go index f7e44c73b..01463bb43 100644 --- a/engine/storage_test.go +++ b/engine/storage_test.go @@ -96,34 +96,6 @@ func TestStorageDestinationContainsPrefixNotExisting(t *testing.T) { } } -/* -func TestStorageCacheRefresh(t *testing.T) { - dm.SetDestination(&Destination{"T11", []string{"0"}}, utils.NonTransactional) - dm.GetDestination("T11", false, utils.NonTransactional) - dm.SetDestination(&Destination{"T11", []string{"1"}}, utils.NonTransactional) - t.Log("Test cache refresh") - err := dm.LoadDataDBCache(GetDefaultEmptyArgCachePrefix()) - if err != nil { - t.Error("Error cache rating: ", err) - } - d, err := dm.GetDestination("T11", false, utils.NonTransactional) - p := d.containsPrefix("1") - if err != nil || p == 0 { - t.Error("Error refreshing cache:", d) - } -} -*/ - -func TestStorageDisabledAccount(t *testing.T) { - acc, err := dm.GetAccount("cgrates.org:alodis") - if err != nil || acc == nil { - t.Error("Error loading disabled user account: ", err, acc) - } - if acc.Disabled != true || acc.AllowNegative != true { - t.Errorf("Error loading user account properties: %+v", acc) - } -} - // Install fails to detect them and starting server will panic, these tests will fix this func TestStoreInterfaces(t *testing.T) { rds := new(RedisStorage) @@ -131,234 +103,3 @@ func TestStoreInterfaces(t *testing.T) { sql := new(SQLStorage) var _ CdrStorage = sql } - -func TestDifferentUuid(t *testing.T) { - a1, err := dm.GetAccount("cgrates.org:12345") - if err != nil { - t.Error("Error getting account: ", err) - } - a2, err := dm.GetAccount("cgrates.org:123456") - if err != nil { - t.Error("Error getting account: ", err) - } - if a1.BalanceMap[utils.MetaVoice][0].Uuid == a2.BalanceMap[utils.MetaVoice][0].Uuid || - a1.BalanceMap[utils.MetaMonetary][0].Uuid == a2.BalanceMap[utils.MetaMonetary][0].Uuid { - t.Errorf("Identical uuids in different accounts: %+v <-> %+v", a1.BalanceMap[utils.MetaVoice][0], a1.BalanceMap[utils.MetaMonetary][0]) - } - -} - -func TestStorageTask(t *testing.T) { - // clean previous unused tasks - for i := 0; i < 21; i++ { - dm.DataDB().PopTask() - } - - if err := dm.DataDB().PushTask(&Task{Uuid: "1"}); err != nil { - t.Error("Error pushing task: ", err) - } - if err := dm.DataDB().PushTask(&Task{Uuid: "2"}); err != nil { - t.Error("Error pushing task: ", err) - } - if err := dm.DataDB().PushTask(&Task{Uuid: "3"}); err != nil { - t.Error("Error pushing task: ", err) - } - if err := dm.DataDB().PushTask(&Task{Uuid: "4"}); err != nil { - t.Error("Error pushing task: ", err) - } - if task, err := dm.DataDB().PopTask(); err != nil && task.Uuid != "1" { - t.Error("Error poping task: ", task, err) - } - if task, err := dm.DataDB().PopTask(); err != nil && task.Uuid != "2" { - t.Error("Error poping task: ", task, err) - } - if task, err := dm.DataDB().PopTask(); err != nil && task.Uuid != "3" { - t.Error("Error poping task: ", task, err) - } - if task, err := dm.DataDB().PopTask(); err != nil && task.Uuid != "4" { - t.Error("Error poping task: ", task, err) - } - if task, err := dm.DataDB().PopTask(); err == nil && task != nil { - t.Errorf("Error poping task %+v, %v ", task, err) - } -} - -/************************** Benchmarks *****************************/ - -func GetUB() *Account { - uc := &UnitCounter{ - Counters: CounterFilters{&CounterFilter{Value: 1}, &CounterFilter{Filter: &BalanceFilter{Weight: utils.Float64Pointer(20), DestinationIDs: utils.StringMapPointer(utils.NewStringMap("NAT"))}}, &CounterFilter{Filter: &BalanceFilter{Weight: utils.Float64Pointer(10), DestinationIDs: utils.StringMapPointer(utils.NewStringMap("RET"))}}}, - } - at := &ActionTrigger{ - ID: "some_uuid", - ThresholdValue: 100.0, - Balance: &BalanceFilter{ - Type: utils.StringPointer(utils.MetaMonetary), - DestinationIDs: utils.StringMapPointer(utils.NewStringMap("NAT")), - }, - Weight: 10.0, - ActionsID: "Commando", - } - var zeroTime time.Time - zeroTime = zeroTime.UTC() // for deep equal to find location - ub := &Account{ - ID: "rif", - AllowNegative: true, - BalanceMap: map[string]Balances{ - utils.MetaSMS: {&Balance{Value: 14, ExpirationDate: zeroTime}}, - utils.MetaData: {&Balance{Value: 1024, ExpirationDate: zeroTime}}, - utils.MetaVoice: {&Balance{Weight: 20, DestinationIDs: utils.NewStringMap("NAT")}, - &Balance{Weight: 10, DestinationIDs: utils.NewStringMap("RET")}}}, - UnitCounters: UnitCounters{utils.MetaSMS: []*UnitCounter{uc, uc}}, - ActionTriggers: ActionTriggers{at, at, at}, - } - return ub -} - -func BenchmarkMarshallerJSONStoreRestore(b *testing.B) { - b.StopTimer() - i := &RateInterval{ - Timing: &RITiming{ - Months: []time.Month{time.February}, - MonthDays: []int{1}, - WeekDays: []time.Weekday{time.Wednesday, time.Thursday}, - StartTime: "14:30:00", - EndTime: "15:00:00"}} - ap := &RatingPlan{Id: "test"} - ap.AddRateInterval("NAT", i) - ub := GetUB() - - ap1 := RatingPlan{} - ub1 := &Account{} - b.StartTimer() - ms := new(JSONMarshaler) - for i := 0; i < b.N; i++ { - result, _ := ms.Marshal(ap) - ms.Unmarshal(result, ap1) - result, _ = ms.Marshal(ub) - ms.Unmarshal(result, ub1) - } -} - -func BenchmarkMarshallerBSONStoreRestore(b *testing.B) { - b.StopTimer() - i := &RateInterval{ - Timing: &RITiming{ - Months: []time.Month{time.February}, - MonthDays: []int{1}, - WeekDays: []time.Weekday{time.Wednesday, time.Thursday}, - StartTime: "14:30:00", - EndTime: "15:00:00"}} - ap := &RatingPlan{Id: "test"} - ap.AddRateInterval("NAT", i) - ub := GetUB() - - ap1 := RatingPlan{} - ub1 := &Account{} - b.StartTimer() - ms := new(BSONMarshaler) - for i := 0; i < b.N; i++ { - result, _ := ms.Marshal(ap) - ms.Unmarshal(result, ap1) - result, _ = ms.Marshal(ub) - ms.Unmarshal(result, ub1) - } -} - -func BenchmarkMarshallerJSONBufStoreRestore(b *testing.B) { - b.StopTimer() - i := &RateInterval{ - Timing: &RITiming{Months: []time.Month{time.February}, - MonthDays: []int{1}, - WeekDays: []time.Weekday{time.Wednesday, time.Thursday}, - StartTime: "14:30:00", - EndTime: "15:00:00"}} - ap := &RatingPlan{Id: "test"} - ap.AddRateInterval("NAT", i) - ub := GetUB() - - ap1 := RatingPlan{} - ub1 := &Account{} - b.StartTimer() - ms := new(JSONBufMarshaler) - for i := 0; i < b.N; i++ { - result, _ := ms.Marshal(ap) - ms.Unmarshal(result, ap1) - result, _ = ms.Marshal(ub) - ms.Unmarshal(result, ub1) - } -} - -func BenchmarkMarshallerGOBStoreRestore(b *testing.B) { - b.StopTimer() - i := &RateInterval{ - Timing: &RITiming{Months: []time.Month{time.February}, - MonthDays: []int{1}, - WeekDays: []time.Weekday{time.Wednesday, time.Thursday}, - StartTime: "14:30:00", - EndTime: "15:00:00"}} - ap := &RatingPlan{Id: "test"} - ap.AddRateInterval("NAT", i) - ub := GetUB() - - ap1 := RatingPlan{} - ub1 := &Account{} - b.StartTimer() - ms := new(GOBMarshaler) - for i := 0; i < b.N; i++ { - result, _ := ms.Marshal(ap) - ms.Unmarshal(result, ap1) - result, _ = ms.Marshal(ub) - ms.Unmarshal(result, ub1) - } -} - -func BenchmarkMarshallerCodecMsgpackStoreRestore(b *testing.B) { - b.StopTimer() - i := &RateInterval{ - Timing: &RITiming{ - Months: []time.Month{time.February}, - MonthDays: []int{1}, - WeekDays: []time.Weekday{time.Wednesday, time.Thursday}, - StartTime: "14:30:00", - EndTime: "15:00:00"}} - ap := &RatingPlan{Id: "test"} - ap.AddRateInterval("NAT", i) - ub := GetUB() - - ap1 := RatingPlan{} - ub1 := &Account{} - b.StartTimer() - ms := NewCodecMsgpackMarshaler() - for i := 0; i < b.N; i++ { - result, _ := ms.Marshal(ap) - ms.Unmarshal(result, ap1) - result, _ = ms.Marshal(ub) - ms.Unmarshal(result, ub1) - } -} - -func BenchmarkMarshallerBincStoreRestore(b *testing.B) { - b.StopTimer() - i := &RateInterval{ - Timing: &RITiming{ - Months: []time.Month{time.February}, - MonthDays: []int{1}, - WeekDays: []time.Weekday{time.Wednesday, time.Thursday}, - StartTime: "14:30:00", - EndTime: "15:00:00"}} - ap := &RatingPlan{Id: "test"} - ap.AddRateInterval("NAT", i) - ub := GetUB() - - ap1 := RatingPlan{} - ub1 := &Account{} - b.StartTimer() - ms := NewBincMarshaler() - for i := 0; i < b.N; i++ { - result, _ := ms.Marshal(ap) - ms.Unmarshal(result, ap1) - result, _ = ms.Marshal(ub) - ms.Unmarshal(result, ub1) - } -} diff --git a/engine/units_counter.go b/engine/units_counter.go deleted file mode 100644 index 79cea1745..000000000 --- a/engine/units_counter.go +++ /dev/null @@ -1,104 +0,0 @@ -/* -Real-time Online/Offline Charging System (OCS) 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 -*/ - -package engine - -// Amount of a trafic of a certain type -type UnitCounter struct { - CounterType string // *event or *balance - Counters CounterFilters // first balance is the general one (no destination) -} - -type CounterFilter struct { - Value float64 - Filter *BalanceFilter -} - -type CounterFilters []*CounterFilter - -func (cfs CounterFilters) HasCounter(cf *CounterFilter) bool { - for _, c := range cfs { - if c.Filter.Equal(cf.Filter) { - return true - } - } - return false -} - -// Clone clones *UnitCounter -func (uc *UnitCounter) Clone() (newUnit *UnitCounter) { - if uc == nil { - return - } - newUnit = &UnitCounter{ - CounterType: uc.CounterType, - } - if uc.Counters != nil { - newUnit.Counters = make(CounterFilters, len(uc.Counters)) - for i, counter := range uc.Counters { - newUnit.Counters[i] = counter.Clone() - } - } - return newUnit -} - -// Clone clones *CounterFilter -func (cfs *CounterFilter) Clone() *CounterFilter { - if cfs == nil { - return nil - } - return &CounterFilter{ - Value: cfs.Value, - Filter: cfs.Filter.Clone(), - } -} - -// Clone clones UnitCounters -func (ucs UnitCounters) Clone() UnitCounters { - if ucs == nil { - return nil - } - newUnitCounters := make(UnitCounters) - for key, unitCounter := range ucs { - newal := make([]*UnitCounter, len(unitCounter)) - for i, uc := range unitCounter { - newal[i] = uc.Clone() - } - newUnitCounters[key] = newal - } - return newUnitCounters -} - -// Returns true if the counters were of the same type -// Copies the value from old balances -func (uc *UnitCounter) CopyCounterValues(oldUc *UnitCounter) bool { - if uc.CounterType != oldUc.CounterType { // type check - return false - } - for _, c := range uc.Counters { - for _, oldC := range oldUc.Counters { - if c.Filter.Equal(oldC.Filter) { - c.Value = oldC.Value - break - } - } - } - return true -} - -type UnitCounters map[string][]*UnitCounter diff --git a/engine/units_counter_test.go b/engine/units_counter_test.go deleted file mode 100644 index 599cb56a1..000000000 --- a/engine/units_counter_test.go +++ /dev/null @@ -1,591 +0,0 @@ -/* -Real-time Online/Offline Charging System (OCS) 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 -*/ -package engine - -import ( - "reflect" - "testing" - - "github.com/cgrates/cgrates/utils" -) - -func TestUnitCounterClone(t *testing.T) { - var uc *UnitCounter - if rcv := uc.Clone(); rcv != nil { - t.Errorf("Expecting nil, received: %s", utils.ToJSON(rcv)) - } - uc = &UnitCounter{} - eOut := &UnitCounter{} - if rcv := uc.Clone(); !reflect.DeepEqual(eOut, rcv) { - t.Errorf("Expecting: %s, received %s", utils.ToJSON(eOut), utils.ToJSON(rcv)) - } - - uc = &UnitCounter{ - CounterType: "testCounterType", - Counters: []*CounterFilter{ - {Value: 0.7}, - {Value: 0.8}, - }, - } - eOut = &UnitCounter{ - CounterType: "testCounterType", - Counters: []*CounterFilter{ - {Value: 0.7}, - {Value: 0.8}, - }, - } - if rcv := uc.Clone(); !reflect.DeepEqual(eOut, rcv) { - t.Errorf("Expecting: %s, received %s", utils.ToJSON(eOut), utils.ToJSON(rcv)) - } -} - -func TestCounterFilterClone(t *testing.T) { - var cfs *CounterFilter - if rcv := cfs.Clone(); rcv != nil { - t.Errorf("Expecting nil, received: %s", utils.ToJSON(rcv)) - } - cfs = &CounterFilter{} - eOut := &CounterFilter{} - if rcv := cfs.Clone(); !reflect.DeepEqual(eOut, rcv) { - t.Errorf("Expecting: %s, received %s", utils.ToJSON(eOut), utils.ToJSON(rcv)) - } - cfs = &CounterFilter{ - Value: 0.7, - Filter: &BalanceFilter{ - Uuid: utils.StringPointer("testUuid"), - }, - } - eOut = &CounterFilter{ - Value: 0.7, - Filter: &BalanceFilter{ - Uuid: utils.StringPointer("testUuid"), - }, - } - if rcv := cfs.Clone(); !reflect.DeepEqual(eOut, rcv) { - t.Errorf("Expecting: %s, received %s", utils.ToJSON(eOut), utils.ToJSON(rcv)) - } - -} - -func TestUnitCountersClone(t *testing.T) { - var ucs UnitCounters - if rcv := ucs.Clone(); rcv != nil { - t.Errorf("Expecting nil, received: %s", utils.ToJSON(rcv)) - } - ucs = UnitCounters{} - eOut := UnitCounters{} - if rcv := ucs.Clone(); !reflect.DeepEqual(eOut, rcv) { - t.Errorf("Expecting: %s, received %s", utils.ToJSON(eOut), utils.ToJSON(rcv)) - } - ucs = UnitCounters{ - "string1": []*UnitCounter{ - { - CounterType: "testCounterType1.1", - }, - { - CounterType: "testCounterType1.2", - }, - }, - "string2": []*UnitCounter{ - { - CounterType: "testCounterType2.1", - }, - { - CounterType: "testCounterType2.2", - }, - }, - } - eOut = UnitCounters{ - "string1": []*UnitCounter{ - { - CounterType: "testCounterType1.1", - }, - { - CounterType: "testCounterType1.2", - }, - }, - "string2": []*UnitCounter{ - { - CounterType: "testCounterType2.1", - }, - { - CounterType: "testCounterType2.2", - }, - }, - } - rcv := ucs.Clone() - if !reflect.DeepEqual(eOut, rcv) { - t.Errorf("Expecting: %s, received %s", utils.ToJSON(eOut), utils.ToJSON(rcv)) - } - rcv["string1"][0].CounterType = "modified" - if ucs["string1"][0].CounterType == "modified" { - t.Error("Original struct was modified") - } -} - -func TestUnitsCounterAddBalance(t *testing.T) { - uc := &UnitCounter{ - Counters: CounterFilters{&CounterFilter{Value: 1}, - &CounterFilter{Filter: &BalanceFilter{Weight: utils.Float64Pointer(20), - DestinationIDs: utils.StringMapPointer(utils.NewStringMap("NAT"))}}, - &CounterFilter{Filter: &BalanceFilter{Weight: utils.Float64Pointer(10), - DestinationIDs: utils.StringMapPointer(utils.NewStringMap("RET"))}}}, - } - UnitCounters{utils.MetaSMS: []*UnitCounter{uc}}.addUnits(20, utils.MetaSMS, - &CallCost{Destination: "test"}, nil) - if len(uc.Counters) != 3 { - t.Error("Error adding minute bucket: ", uc.Counters) - } -} - -func TestUnitsCounterAddBalanceExists(t *testing.T) { - uc := &UnitCounter{ - Counters: CounterFilters{&CounterFilter{Value: 1}, &CounterFilter{Value: 10, - Filter: &BalanceFilter{Weight: utils.Float64Pointer(20), - DestinationIDs: utils.StringMapPointer(utils.NewStringMap("NAT"))}}, - &CounterFilter{Filter: &BalanceFilter{Weight: utils.Float64Pointer(10), - DestinationIDs: utils.StringMapPointer(utils.NewStringMap("RET"))}}}, - } - UnitCounters{utils.MetaSMS: []*UnitCounter{uc}}.addUnits(5, - utils.MetaSMS, &CallCost{Destination: "0723"}, nil) - if len(uc.Counters) != 3 || uc.Counters[1].Value != 15 { - t.Error("Error adding minute bucket!") - } -} - -func TestUnitCountersCountAllMonetary(t *testing.T) { - a := &Account{ - ActionTriggers: ActionTriggers{ - &ActionTrigger{ - UniqueID: "TestTR1", - ThresholdType: utils.TriggerMaxEventCounter, - Balance: &BalanceFilter{ - Type: utils.StringPointer(utils.MetaMonetary), - Weight: utils.Float64Pointer(10), - }, - }, - &ActionTrigger{ - UniqueID: "TestTR11", - ThresholdType: utils.TriggerMaxEventCounter, - Balance: &BalanceFilter{ - Type: utils.StringPointer(utils.MetaMonetary), - Weight: utils.Float64Pointer(10), - }, - }, - &ActionTrigger{ - UniqueID: "TestTR2", - ThresholdType: utils.TriggerMaxEventCounter, - Balance: &BalanceFilter{ - Type: utils.StringPointer(utils.MetaVoice), - Weight: utils.Float64Pointer(10), - }, - }, - &ActionTrigger{ - UniqueID: "TestTR3", - ThresholdType: utils.TriggerMaxBalanceCounter, - Balance: &BalanceFilter{ - Type: utils.StringPointer(utils.MetaVoice), - Weight: utils.Float64Pointer(10), - }, - }, - &ActionTrigger{ - UniqueID: "TestTR4", - ThresholdType: utils.TriggerMaxBalanceCounter, - Balance: &BalanceFilter{ - Type: utils.StringPointer(utils.MetaSMS), - Weight: utils.Float64Pointer(10), - }, - }, - &ActionTrigger{ - UniqueID: "TestTR5", - ThresholdType: utils.TriggerMaxBalance, - Balance: &BalanceFilter{ - Type: utils.StringPointer(utils.MetaSMS), - Weight: utils.Float64Pointer(10), - }, - }, - }, - } - a.InitCounters() - a.UnitCounters.addUnits(10, utils.MetaMonetary, &CallCost{}, nil) - - if len(a.UnitCounters) != 3 || - len(a.UnitCounters[utils.MetaMonetary][0].Counters) != 2 || - a.UnitCounters[utils.MetaMonetary][0].Counters[0].Value != 10 || - a.UnitCounters[utils.MetaMonetary][0].Counters[1].Value != 10 { - for key, counters := range a.UnitCounters { - t.Log(key) - for _, uc := range counters { - t.Logf("UC: %+v", uc) - for _, b := range uc.Counters { - t.Logf("B: %+v", b) - } - } - } - t.Errorf("Error Initializing adding unit counters: %v", len(a.UnitCounters)) - } -} - -func TestUnitCountersCountAllMonetaryId(t *testing.T) { - a := &Account{ - ActionTriggers: ActionTriggers{ - &ActionTrigger{ - UniqueID: "TestTR1", - ThresholdType: utils.TriggerMaxBalanceCounter, - Balance: &BalanceFilter{ - Type: utils.StringPointer(utils.MetaMonetary), - Weight: utils.Float64Pointer(10), - }, - }, - &ActionTrigger{ - UniqueID: "TestTR11", - ThresholdType: utils.TriggerMaxBalanceCounter, - Balance: &BalanceFilter{ - Type: utils.StringPointer(utils.MetaMonetary), - Weight: utils.Float64Pointer(20), - }, - }, - &ActionTrigger{ - UniqueID: "TestTR2", - ThresholdType: utils.TriggerMaxEventCounter, - Balance: &BalanceFilter{ - Type: utils.StringPointer(utils.MetaVoice), - Weight: utils.Float64Pointer(10), - }, - }, - &ActionTrigger{ - UniqueID: "TestTR3", - ThresholdType: utils.TriggerMaxBalanceCounter, - Balance: &BalanceFilter{ - Type: utils.StringPointer(utils.MetaVoice), - Weight: utils.Float64Pointer(10), - }, - }, - &ActionTrigger{ - UniqueID: "TestTR4", - ThresholdType: utils.TriggerMaxBalanceCounter, - Balance: &BalanceFilter{ - Type: utils.StringPointer(utils.MetaSMS), - Weight: utils.Float64Pointer(10), - }, - }, - &ActionTrigger{ - UniqueID: "TestTR5", - ThresholdType: utils.TriggerMaxBalance, - Balance: &BalanceFilter{ - Type: utils.StringPointer(utils.MetaSMS), - Weight: utils.Float64Pointer(10), - }, - }, - }, - } - a.InitCounters() - a.UnitCounters.addUnits(10, utils.MetaMonetary, nil, &Balance{Weight: 20}) - if len(a.UnitCounters) != 3 || - len(a.UnitCounters[utils.MetaMonetary][0].Counters) != 2 || - a.UnitCounters[utils.MetaMonetary][0].Counters[0].Value != 0 || - a.UnitCounters[utils.MetaMonetary][0].Counters[1].Value != 10 { - for key, counters := range a.UnitCounters { - t.Log(key) - for _, uc := range counters { - t.Logf("UC: %+v", uc) - for _, b := range uc.Counters { - t.Logf("B: %+v", b) - } - } - } - t.Errorf("Error adding unit counters: %v", len(a.UnitCounters)) - } -} - -func TestUnitCountersCountAllVoiceDestinationEvent(t *testing.T) { - a := &Account{ - ActionTriggers: ActionTriggers{ - &ActionTrigger{ - UniqueID: "TestTR1", - ThresholdType: utils.TriggerMaxBalanceCounter, - Balance: &BalanceFilter{ - Type: utils.StringPointer(utils.MetaMonetary), - Weight: utils.Float64Pointer(10), - }, - }, - &ActionTrigger{ - UniqueID: "TestTR11", - ThresholdType: utils.TriggerMaxBalanceCounter, - Balance: &BalanceFilter{ - Type: utils.StringPointer(utils.MetaMonetary), - Weight: utils.Float64Pointer(20), - }, - }, - &ActionTrigger{ - UniqueID: "TestTR2", - ThresholdType: utils.TriggerMaxEventCounter, - Balance: &BalanceFilter{ - Type: utils.StringPointer(utils.MetaVoice), - DestinationIDs: utils.StringMapPointer(utils.NewStringMap("NAT")), - Weight: utils.Float64Pointer(10), - }, - }, - &ActionTrigger{ - UniqueID: "TestTR22", - ThresholdType: utils.TriggerMaxEventCounter, - Balance: &BalanceFilter{ - Type: utils.StringPointer(utils.MetaVoice), - DestinationIDs: utils.StringMapPointer(utils.NewStringMap("RET")), - Weight: utils.Float64Pointer(10), - }, - }, - &ActionTrigger{ - UniqueID: "TestTR3", - ThresholdType: utils.TriggerMaxBalanceCounter, - Balance: &BalanceFilter{ - Type: utils.StringPointer(utils.MetaVoice), - Weight: utils.Float64Pointer(10), - }, - }, - &ActionTrigger{ - UniqueID: "TestTR4", - ThresholdType: utils.TriggerMaxBalanceCounter, - Balance: &BalanceFilter{ - Type: utils.StringPointer(utils.MetaSMS), - Weight: utils.Float64Pointer(10), - }, - }, - &ActionTrigger{ - UniqueID: "TestTR5", - ThresholdType: utils.TriggerMaxBalance, - Balance: &BalanceFilter{ - Type: utils.StringPointer(utils.MetaSMS), - Weight: utils.Float64Pointer(10), - }, - }, - }, - } - a.InitCounters() - a.UnitCounters.addUnits(10, utils.MetaVoice, &CallCost{Destination: "0723045326"}, nil) - - if len(a.UnitCounters) != 3 || - len(a.UnitCounters[utils.MetaVoice][0].Counters) != 2 || - a.UnitCounters[utils.MetaVoice][0].Counters[0].Value != 10 || - a.UnitCounters[utils.MetaVoice][0].Counters[1].Value != 10 { - for key, counters := range a.UnitCounters { - t.Log(key) - for _, uc := range counters { - t.Logf("UC: %+v", uc) - for _, b := range uc.Counters { - t.Logf("B: %+v", b) - } - } - } - t.Errorf("Error adding unit counters: %v", len(a.UnitCounters)) - } -} - -func TestUnitCountersKeepValuesAfterInit(t *testing.T) { - a := &Account{ - ActionTriggers: ActionTriggers{ - &ActionTrigger{ - UniqueID: "TestTR1", - ThresholdType: utils.TriggerMaxBalanceCounter, - Balance: &BalanceFilter{ - Type: utils.StringPointer(utils.MetaMonetary), - Weight: utils.Float64Pointer(10), - }, - }, - &ActionTrigger{ - UniqueID: "TestTR11", - ThresholdType: utils.TriggerMaxBalanceCounter, - Balance: &BalanceFilter{ - Type: utils.StringPointer(utils.MetaMonetary), - Weight: utils.Float64Pointer(20), - }, - }, - &ActionTrigger{ - UniqueID: "TestTR2", - ThresholdType: utils.TriggerMaxEventCounter, - Balance: &BalanceFilter{ - Type: utils.StringPointer(utils.MetaVoice), - DestinationIDs: utils.StringMapPointer(utils.NewStringMap("NAT")), - Weight: utils.Float64Pointer(10), - }, - }, - &ActionTrigger{ - UniqueID: "TestTR22", - ThresholdType: utils.TriggerMaxEventCounter, - Balance: &BalanceFilter{ - Type: utils.StringPointer(utils.MetaVoice), - DestinationIDs: utils.StringMapPointer(utils.NewStringMap("RET")), - Weight: utils.Float64Pointer(10), - }, - }, - &ActionTrigger{ - UniqueID: "TestTR3", - ThresholdType: utils.TriggerMaxBalanceCounter, - Balance: &BalanceFilter{ - Type: utils.StringPointer(utils.MetaVoice), - Weight: utils.Float64Pointer(10), - }, - }, - &ActionTrigger{ - UniqueID: "TestTR4", - ThresholdType: utils.TriggerMaxBalanceCounter, - Balance: &BalanceFilter{ - Type: utils.StringPointer(utils.MetaSMS), - Weight: utils.Float64Pointer(10), - }, - }, - &ActionTrigger{ - UniqueID: "TestTR5", - ThresholdType: utils.TriggerMaxBalance, - Balance: &BalanceFilter{ - Type: utils.StringPointer(utils.MetaSMS), - Weight: utils.Float64Pointer(10), - }, - }, - }, - } - a.InitCounters() - a.UnitCounters.addUnits(10, utils.MetaVoice, &CallCost{Destination: "0723045326"}, nil) - - if len(a.UnitCounters) != 3 || - len(a.UnitCounters[utils.MetaVoice][0].Counters) != 2 || - a.UnitCounters[utils.MetaVoice][0].Counters[0].Value != 10 || - a.UnitCounters[utils.MetaVoice][0].Counters[1].Value != 10 { - for key, counters := range a.UnitCounters { - t.Log(key) - for _, uc := range counters { - t.Logf("UC: %+v", uc) - for _, b := range uc.Counters { - t.Logf("B: %+v", b) - } - } - } - t.Errorf("Error adding unit counters: %v", len(a.UnitCounters)) - } - a.InitCounters() - - if len(a.UnitCounters) != 3 || - len(a.UnitCounters[utils.MetaVoice][0].Counters) != 2 || - a.UnitCounters[utils.MetaVoice][0].Counters[0].Value != 10 || - a.UnitCounters[utils.MetaVoice][0].Counters[1].Value != 10 { - for key, counters := range a.UnitCounters { - t.Log(key) - for _, uc := range counters { - t.Logf("UC: %+v", uc) - for _, b := range uc.Counters { - t.Logf("B: %+v", b) - } - } - } - t.Errorf("Error keeping counter values after init: %v", len(a.UnitCounters)) - } -} - -func TestUnitCountersResetCounterById(t *testing.T) { - a := &Account{ - ActionTriggers: ActionTriggers{ - &ActionTrigger{ - UniqueID: "TestTR1", - ThresholdType: utils.TriggerMaxEventCounter, - Balance: &BalanceFilter{ - Type: utils.StringPointer(utils.MetaMonetary), - Weight: utils.Float64Pointer(10), - }, - }, - &ActionTrigger{ - UniqueID: "TestTR11", - ThresholdType: utils.TriggerMaxEventCounter, - Balance: &BalanceFilter{ - Type: utils.StringPointer(utils.MetaMonetary), - Weight: utils.Float64Pointer(10), - }, - }, - &ActionTrigger{ - UniqueID: "TestTR2", - ThresholdType: utils.TriggerMaxEventCounter, - Balance: &BalanceFilter{ - Type: utils.StringPointer(utils.MetaVoice), - Weight: utils.Float64Pointer(10), - }, - }, - &ActionTrigger{ - UniqueID: "TestTR3", - ThresholdType: utils.TriggerMaxBalanceCounter, - Balance: &BalanceFilter{ - Type: utils.StringPointer(utils.MetaVoice), - Weight: utils.Float64Pointer(10), - }, - }, - &ActionTrigger{ - UniqueID: "TestTR4", - ThresholdType: utils.TriggerMaxBalanceCounter, - Balance: &BalanceFilter{ - Type: utils.StringPointer(utils.MetaSMS), - Weight: utils.Float64Pointer(10), - }, - }, - &ActionTrigger{ - UniqueID: "TestTR5", - ThresholdType: utils.TriggerMaxBalance, - Balance: &BalanceFilter{ - Type: utils.StringPointer(utils.MetaSMS), - Weight: utils.Float64Pointer(10), - }, - }, - }, - } - a.InitCounters() - a.UnitCounters.addUnits(10, utils.MetaMonetary, &CallCost{}, nil) - - if len(a.UnitCounters) != 3 || - len(a.UnitCounters[utils.MetaMonetary][0].Counters) != 2 || - a.UnitCounters[utils.MetaMonetary][0].Counters[0].Value != 10 || - a.UnitCounters[utils.MetaMonetary][0].Counters[1].Value != 10 { - for key, counters := range a.UnitCounters { - t.Log(key) - for _, uc := range counters { - t.Logf("UC: %+v", uc) - for _, b := range uc.Counters { - t.Logf("B: %+v", b) - } - } - } - t.Errorf("Error Initializing adding unit counters: %v", len(a.UnitCounters)) - } - a.UnitCounters.resetCounters(&Action{ - Balance: &BalanceFilter{ - Type: utils.StringPointer(utils.MetaMonetary), - ID: utils.StringPointer("TestTR11"), - }, - }) - if len(a.UnitCounters) != 3 || - len(a.UnitCounters[utils.MetaMonetary][0].Counters) != 2 || - a.UnitCounters[utils.MetaMonetary][0].Counters[0].Value != 10 || - a.UnitCounters[utils.MetaMonetary][0].Counters[1].Value != 0 { - for key, counters := range a.UnitCounters { - t.Log(key) - for _, uc := range counters { - t.Logf("UC: %+v", uc) - for _, b := range uc.Counters { - t.Logf("B: %+v", b) - } - } - } - t.Errorf("Error Initializing adding unit counters: %v", len(a.UnitCounters)) - } -} diff --git a/general_tests/acntacts_test.go b/general_tests/acntacts_test.go deleted file mode 100644 index 73152e772..000000000 --- a/general_tests/acntacts_test.go +++ /dev/null @@ -1,114 +0,0 @@ -/* -Real-time Online/Offline Charging System (OCS) 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 -*/ -package general_tests - -import ( - "reflect" - "testing" - - "github.com/cgrates/cgrates/config" - "github.com/cgrates/cgrates/engine" - "github.com/cgrates/cgrates/utils" -) - -var dbAcntActs *engine.DataManager - -func TestAcntActsSetStorage(t *testing.T) { - dataDB := engine.NewInternalDB(nil, nil, true) - dbAcntActs = engine.NewDataManager(dataDB, config.CgrConfig().CacheCfg(), nil) - engine.SetDataStorage(dbAcntActs) -} - -func TestAcntActsLoadCsv(t *testing.T) { - timings := `ASAP,*any,*any,*any,*any,*asap` - destinations := `` - rates := `` - destinationRates := `` - ratingPlans := `` - ratingProfiles := `` - sharedGroups := `` - actions := `TOPUP10_AC,*topup_reset,,,,*voice,,*any,,,*unlimited,,10s,10,false,false,10 -DISABLE_ACNT,*disable_account,,,,,,,,,,,,,false,false,10 -ENABLE_ACNT,*enable_account,,,,,,,,,,,,,false,false,10` - actionPlans := `TOPUP10_AT,TOPUP10_AC,ASAP,10` - actionTriggers := `` - accountActions := `cgrates.org,1,TOPUP10_AT,,,` - resLimits := `` - stats := `` - thresholds := `` - filters := `` - suppliers := `` - attrProfiles := `` - chargerProfiles := `` - csvr, err := engine.NewTpReader(dbAcntActs.DataDB(), engine.NewStringCSVStorage(utils.CSVSep, destinations, timings, - rates, destinationRates, ratingPlans, ratingProfiles, sharedGroups, - actions, actionPlans, actionTriggers, accountActions, - resLimits, stats, thresholds, filters, suppliers, attrProfiles, chargerProfiles, ``, "", utils.EmptyString, utils.EmptyString, utils.EmptyString), "", "", nil, nil, false) - if err != nil { - t.Error(err) - } - if err := csvr.LoadAll(); err != nil { - t.Fatal(err) - } - csvr.WriteToDatabase(false, false) - - dbAcntActs.LoadDataDBCache(engine.GetDefaultEmptyArgCachePrefix()) - - expectAcnt := &engine.Account{ID: "cgrates.org:1"} - if acnt, err := dbAcntActs.GetAccount("cgrates.org:1"); err != nil { - t.Error(err) - } else if acnt == nil { - t.Error("No account created") - } else if !reflect.DeepEqual(expectAcnt.ActionTriggers, acnt.ActionTriggers) { - t.Errorf("Expecting: %+v, received: %+v", expectAcnt, acnt) - } -} - -func TestAcntActsDisableAcnt(t *testing.T) { - acnt1Tag := "cgrates.org:1" - at := &engine.ActionTiming{ - ActionsID: "DISABLE_ACNT", - } - at.SetAccountIDs(utils.StringMap{acnt1Tag: true}) - if err := at.Execute(nil, nil); err != nil { - t.Error(err) - } - expectAcnt := &engine.Account{ID: "cgrates.org:1", Disabled: true} - if acnt, err := dbAcntActs.GetAccount(acnt1Tag); err != nil { - t.Error(err) - } else if !reflect.DeepEqual(expectAcnt, acnt) { - t.Errorf("Expecting: %+v, received: %+v", utils.ToJSON(expectAcnt), utils.ToJSON(acnt)) - } -} - -func TestAcntActsEnableAcnt(t *testing.T) { - acnt1Tag := "cgrates.org:1" - at := &engine.ActionTiming{ - ActionsID: "ENABLE_ACNT", - } - at.SetAccountIDs(utils.StringMap{acnt1Tag: true}) - if err := at.Execute(nil, nil); err != nil { - t.Error(err) - } - expectAcnt := &engine.Account{ID: "cgrates.org:1", Disabled: false} - if acnt, err := dbAcntActs.GetAccount(acnt1Tag); err != nil { - t.Error(err) - } else if !reflect.DeepEqual(expectAcnt, acnt) { - t.Errorf("Expecting: %+v, received: %+v", expectAcnt, acnt) - } -} diff --git a/general_tests/auth_test.go b/general_tests/auth_test.go deleted file mode 100644 index 502dcf023..000000000 --- a/general_tests/auth_test.go +++ /dev/null @@ -1,173 +0,0 @@ -/* -Real-time Online/Offline Charging System (OCS) 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 -*/ -package general_tests - -import ( - "testing" - "time" - - "github.com/cgrates/cgrates/config" - "github.com/cgrates/cgrates/engine" - "github.com/cgrates/cgrates/utils" -) - -var dbAuth *engine.DataManager -var rsponder *engine.Responder - -func TestAuthSetStorage(t *testing.T) { - config.CgrConfig().CacheCfg().Partitions[utils.CacheRatingPlans].Precache = true // precache rating plan - dataDB := engine.NewInternalDB(nil, nil, true) - dbAuth = engine.NewDataManager(dataDB, config.CgrConfig().CacheCfg(), nil) - engine.SetDataStorage(dbAuth) - rsponder = &engine.Responder{ - MaxComputedUsage: config.CgrConfig().RalsCfg().MaxComputedUsage} - engine.Cache.Clear(nil) -} - -func TestAuthLoadCsvError(t *testing.T) { - timings := `` - destinations := `` - rates := `` - destinationRates := `` - ratingPlans := `` - ratingProfiles := `` - sharedGroups := `` - actions := `` - actionPlans := `` - actionTriggers := `` - accountActions := `` - resLimits := `` - stats := `` - thresholds := `` - filters := `` - suppliers := `` - attrProfiles := `cgrates.org,ATTR_1,*any,*string~*req.RunID:route1,,,*req.Info,*constant,1001,false,10` - chargerProfiles := `` - csvr, err := engine.NewTpReader(dbAuth.DataDB(), engine.NewStringCSVStorage(utils.CSVSep, destinations, timings, rates, destinationRates, - ratingPlans, ratingProfiles, sharedGroups, actions, actionPlans, actionTriggers, accountActions, - resLimits, stats, thresholds, filters, suppliers, attrProfiles, chargerProfiles, ``, "", utils.EmptyString, utils.EmptyString, utils.EmptyString), "", "", nil, nil, false) - if err != nil { - t.Error(err) - } - if err := csvr.LoadAll(); err == nil { - t.Fatal("Expected error received nil") - } -} - -func TestAuthLoadCsv(t *testing.T) { - timings := `` - destinations := `DST_GERMANY_LANDLINE,49` - rates := `RT_1CENTWITHCF,0.02,0.01,60s,60s,0s` - destinationRates := `DR_GERMANY,DST_GERMANY_LANDLINE,RT_1CENTWITHCF,*up,8,, -DR_ANY_1CNT,*any,RT_1CENTWITHCF,*up,8,,` - ratingPlans := `RP_1,DR_GERMANY,*any,10 -RP_ANY,DR_ANY_1CNT,*any,10` - ratingProfiles := `cgrates.org,call,testauthpostpaid1,2013-01-06T00:00:00Z,RP_1, -cgrates.org,call,testauthpostpaid2,2013-01-06T00:00:00Z,RP_1,*any -cgrates.org,call,*any,2013-01-06T00:00:00Z,RP_ANY,` - sharedGroups := `` - actions := `TOPUP10_AC,*topup_reset,,,,*monetary,,*any,,,*unlimited,,0,10,false,false,10` - actionPlans := `TOPUP10_AT,TOPUP10_AC,*asap,10` - actionTriggers := `` - accountActions := `cgrates.org,testauthpostpaid1,TOPUP10_AT,,,` - resLimits := `` - stats := `` - thresholds := `` - filters := `` - suppliers := `` - attrProfiles := `` - chargerProfiles := `` - csvr, err := engine.NewTpReader(dbAuth.DataDB(), engine.NewStringCSVStorage(utils.CSVSep, destinations, timings, rates, destinationRates, - ratingPlans, ratingProfiles, sharedGroups, actions, actionPlans, actionTriggers, accountActions, - resLimits, stats, thresholds, filters, suppliers, attrProfiles, chargerProfiles, ``, "", utils.EmptyString, utils.EmptyString, utils.EmptyString), "", "", nil, nil, false) - if err != nil { - t.Error(err) - } - if err := csvr.LoadAll(); err != nil { - t.Fatal(err) - } - csvr.WriteToDatabase(false, false) - if acnt, err := dbAuth.GetAccount("cgrates.org:testauthpostpaid1"); err != nil { - t.Error(err) - } else if acnt == nil { - t.Error("No account saved") - } - - dbAuth.LoadDataDBCache(engine.GetDefaultEmptyArgCachePrefix()) - - if cachedDests := len(engine.Cache.GetItemIDs(utils.CacheDestinations, "")); cachedDests != 1 { - t.Error("Wrong number of cached destinations found", cachedDests) - } - if cachedRPlans := len(engine.Cache.GetItemIDs(utils.CacheRatingPlans, "")); cachedRPlans != 2 { - t.Error("Wrong number of cached rating plans found", cachedRPlans) - } - if cachedRProfiles := len(engine.Cache.GetItemIDs(utils.CacheRatingProfiles, "")); cachedRProfiles != 3 { - t.Error("Wrong number of cached rating profiles found", cachedRProfiles) - } - if cachedActions := len(engine.Cache.GetItemIDs(utils.CacheActions, "")); cachedActions != 1 { - t.Error("Wrong number of cached actions found", cachedActions) - } -} - -func TestAuthPostpaidNoAcnt(t *testing.T) { - cdr := &engine.UsageRecord{ToR: utils.MetaVoice, RequestType: utils.MetaPrepaid, Tenant: "cgrates.org", - Category: "call", Account: "nonexistent", Subject: "testauthpostpaid1", - Destination: "4986517174963", SetupTime: time.Date(2015, 8, 27, 11, 26, 0, 0, time.UTC).String()} - cd, err := cdr.AsCallDescriptor("", false) - if err != nil { - t.Error(err) - } - var maxSessionTime time.Duration - if err := rsponder.GetMaxSessionTime(&engine.CallDescriptorWithAPIOpts{CallDescriptor: cd}, &maxSessionTime); err != utils.ErrAccountNotFound { - t.Error(err) - } -} - -func TestAuthPostpaidFallbackDest(t *testing.T) { - // Test subject which has fallback for destination - cdr := &engine.UsageRecord{ToR: utils.MetaVoice, RequestType: utils.MetaPostpaid, Tenant: "cgrates.org", - Category: "call", Account: "testauthpostpaid1", Subject: "testauthpostpaid2", - Destination: "441231234", SetupTime: time.Date(2015, 8, 27, 11, 26, 0, 0, time.UTC).String()} - cd, err := cdr.AsCallDescriptor("", false) - if err != nil { - t.Error(err) - } - var maxSessionTime time.Duration - if err = rsponder.GetMaxSessionTime(&engine.CallDescriptorWithAPIOpts{CallDescriptor: cd}, &maxSessionTime); err != nil { - t.Error(err) - } else if maxSessionTime != 0 { - t.Error("Unexpected maxSessionTime received: ", maxSessionTime) - } -} - -func TestAuthPostpaidWithDestination(t *testing.T) { - // Test subject which does not have destination attached - cdr := &engine.UsageRecord{ToR: utils.MetaVoice, RequestType: utils.MetaPostpaid, Tenant: "cgrates.org", - Category: "call", Account: "testauthpostpaid1", Subject: "testauthpostpaid1", - Destination: "4986517174963", SetupTime: time.Date(2015, 8, 27, 11, 26, 0, 0, time.UTC).String()} - cd, err := cdr.AsCallDescriptor("", false) - if err != nil { - t.Error(err) - } - var maxSessionTime time.Duration - if err := rsponder.GetMaxSessionTime(&engine.CallDescriptorWithAPIOpts{CallDescriptor: cd}, &maxSessionTime); err != nil { - t.Error(err) - } else if maxSessionTime != 0 { - t.Error("Unexpected maxSessionTime received: ", maxSessionTime) - } -} diff --git a/general_tests/costs1_test.go b/general_tests/costs1_test.go deleted file mode 100644 index e5822f742..000000000 --- a/general_tests/costs1_test.go +++ /dev/null @@ -1,153 +0,0 @@ -/* -Real-time Online/Offline Charging System (OCS) 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 -*/ -package general_tests - -import ( - "testing" - - "github.com/cgrates/cgrates/config" - "github.com/cgrates/cgrates/engine" - "github.com/cgrates/cgrates/utils" -) - -func TestCosts1SetStorage(t *testing.T) { - config.CgrConfig().CacheCfg().Partitions[utils.CacheRatingPlans].Precache = true // precache rating plan - dataDBInt := engine.NewInternalDB(nil, nil, true) - dataDB = engine.NewDataManager(dataDBInt, config.CgrConfig().CacheCfg(), nil) - engine.SetDataStorage(dataDB) - engine.Cache.Clear(nil) -} - -func TestCosts1LoadCsvTp(t *testing.T) { - timings := `ALWAYS,*any,*any,*any,*any,00:00:00 -ASAP,*any,*any,*any,*any,*asap` - dests := `GERMANY,+49 -GERMANY_MOBILE,+4915 -GERMANY_MOBILE,+4916 -GERMANY_MOBILE,+4917` - rates := `RT_1CENT,0,1,1s,1s,0s -RT_DATA_2c,0,0.002,10,10,0 -RT_SMS_5c,0,0.005,1,1,0` - destinationRates := `DR_RETAIL,GERMANY,RT_1CENT,*up,4,0, -DR_RETAIL,GERMANY_MOBILE,RT_1CENT,*up,4,0, -DR_DATA_1,*any,RT_DATA_2c,*up,4,0, -DR_SMS_1,*any,RT_SMS_5c,*up,4,0,` - ratingPlans := `RP_RETAIL,DR_RETAIL,ALWAYS,10 -RP_DATA1,DR_DATA_1,ALWAYS,10 -RP_SMS1,DR_SMS_1,ALWAYS,10` - ratingProfiles := `cgrates.org,call,*any,2012-01-01T00:00:00Z,RP_RETAIL, -cgrates.org,data,*any,2012-01-01T00:00:00Z,RP_DATA1, -cgrates.org,sms,*any,2012-01-01T00:00:00Z,RP_SMS1,` - csvr, err := engine.NewTpReader(dataDB.DataDB(), engine.NewStringCSVStorage(utils.CSVSep, dests, timings, - rates, destinationRates, ratingPlans, ratingProfiles, - utils.EmptyString, utils.EmptyString, utils.EmptyString, - utils.EmptyString, utils.EmptyString, utils.EmptyString, - utils.EmptyString, utils.EmptyString, utils.EmptyString, - utils.EmptyString, utils.EmptyString, utils.EmptyString, - utils.EmptyString, utils.EmptyString, utils.EmptyString, utils.EmptyString, utils.EmptyString), - utils.EmptyString, utils.EmptyString, nil, nil, false) - if err != nil { - t.Error(err) - } - if err := csvr.LoadTimings(); err != nil { - t.Fatal(err) - } - if err := csvr.LoadDestinations(); err != nil { - t.Fatal(err) - } - if err := csvr.LoadRates(); err != nil { - t.Fatal(err) - } - if err := csvr.LoadDestinationRates(); err != nil { - t.Fatal(err) - } - if err := csvr.LoadRatingPlans(); err != nil { - t.Fatal(err) - } - if err := csvr.LoadRatingProfiles(); err != nil { - t.Fatal(err) - } - csvr.WriteToDatabase(false, false) - dataDB.LoadDataDBCache(engine.GetDefaultEmptyArgCachePrefix()) - - if cachedRPlans := len(engine.Cache.GetItemIDs(utils.CacheRatingPlans, utils.EmptyString)); cachedRPlans != 3 { - t.Error("Wrong number of cached rating plans found", cachedRPlans) - } - if cachedRProfiles := len(engine.Cache.GetItemIDs(utils.CacheRatingProfiles, utils.EmptyString)); cachedRProfiles != 3 { - t.Error("Wrong number of cached rating profiles found", cachedRProfiles) - } -} - -func TestCosts1GetCost1(t *testing.T) { - tStart, _ := utils.ParseTimeDetectLayout("2013-08-07T17:30:00Z", utils.EmptyString) - tEnd, _ := utils.ParseTimeDetectLayout("2013-08-07T17:31:30Z", utils.EmptyString) - cd := &engine.CallDescriptor{ - Category: "call", - Tenant: "cgrates.org", - Subject: "1001", - Account: "1001", - Destination: "+4986517174963", - TimeStart: tStart, - TimeEnd: tEnd, - } - if cc, err := cd.GetCost(); err != nil { - t.Error(err) - } else if cc.Cost != 90 { - t.Error("Wrong cost returned: ", cc.Cost) - } -} - -func TestCosts1GetCostZeroDuration(t *testing.T) { - tStart, _ := utils.ParseTimeDetectLayout("2013-08-07T17:30:00Z", utils.EmptyString) - tEnd, _ := utils.ParseTimeDetectLayout("2013-08-07T17:30:00Z", utils.EmptyString) - cd := &engine.CallDescriptor{ - Category: "call", - Tenant: "cgrates.org", - Subject: "1001", - Account: "1001", - Destination: "+4986517174963", - TimeStart: tStart, - TimeEnd: tEnd, - } - if cc, err := cd.GetCost(); err != nil { - t.Error(err) - } else if cc.Cost != 0 { - t.Error("Wrong cost returned: ", cc.Cost) - } -} - -/* FixMe -func TestCosts1GetCost2(t *testing.T) { - tStart, _ := utils.ParseTimeDetectLayout("2004-06-04T00:00:01Z") - tEnd, _ := utils.ParseTimeDetectLayout("2004-06-04T00:01:01Z") - cd := &engine.CallDescriptor{ - Category: "call", - Tenant: "cgrates.org", - Subject: "1001", - Account: "1001", - Destination: "+4986517174963", - TimeStart: tStart, - TimeEnd: tEnd, - } - if cc, err := cd.GetCost(); err != nil { - t.Error(err) - } else if cc.Cost != 90 { - t.Error("Wrong cost returned: ", cc.Cost) - } -} -*/ diff --git a/general_tests/datachrg1_test.go b/general_tests/datachrg1_test.go deleted file mode 100644 index 2c18a2994..000000000 --- a/general_tests/datachrg1_test.go +++ /dev/null @@ -1,146 +0,0 @@ -/* -Real-time Online/Offline Charging System (OCS) 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 -*/ -package general_tests - -import ( - "testing" - "time" - - "github.com/cgrates/cgrates/config" - "github.com/cgrates/cgrates/engine" - "github.com/cgrates/cgrates/utils" -) - -func TestSetStorageDtChrg1(t *testing.T) { - dataDBInt := engine.NewInternalDB(nil, nil, true) - dataDB = engine.NewDataManager(dataDBInt, config.CgrConfig().CacheCfg(), nil) - engine.SetDataStorage(dataDB) - engine.Cache.Clear(nil) -} - -func TestLoadCsvTpDtChrg1(t *testing.T) { - timings := `TM1,*any,*any,*any,*any,00:00:00 -TM2,*any,*any,*any,*any,01:00:00` - rates := `RT_DATA_2c,0,0.002,10s,10s,0 -RT_DATA_1c,0,0.001,10,10,0` - destinationRates := `DR_DATA_1,*any,RT_DATA_2c,*up,4,0, -DR_DATA_2,*any,RT_DATA_1c,*up,4,0,` - ratingPlans := `RP_DATA1,DR_DATA_1,TM1,10 -RP_DATA1,DR_DATA_2,TM2,10` - ratingProfiles := `cgrates.org,data,*any,2012-01-01T00:00:00Z,RP_DATA1,` - csvr, err := engine.NewTpReader(dataDB.DataDB(), engine.NewStringCSVStorage(utils.CSVSep, - utils.EmptyString, timings, rates, destinationRates, ratingPlans, ratingProfiles, - utils.EmptyString, utils.EmptyString, utils.EmptyString, utils.EmptyString, utils.EmptyString, - utils.EmptyString, utils.EmptyString, utils.EmptyString, utils.EmptyString, utils.EmptyString, - utils.EmptyString, utils.EmptyString, utils.EmptyString, utils.EmptyString, utils.EmptyString, utils.EmptyString, utils.EmptyString), - utils.EmptyString, utils.EmptyString, nil, nil, false) - if err != nil { - t.Error(err) - } - if err := csvr.LoadTimings(); err != nil { - t.Fatal(err) - } - if err := csvr.LoadRates(); err != nil { - t.Fatal(err) - } - if err := csvr.LoadDestinationRates(); err != nil { - t.Fatal(err) - } - if err := csvr.LoadRatingPlans(); err != nil { - t.Fatal(err) - } - if err := csvr.LoadRatingProfiles(); err != nil { - t.Fatal(err) - } - csvr.WriteToDatabase(false, false) - dataDB.LoadDataDBCache(engine.GetDefaultEmptyArgCachePrefix()) - - if cachedRPlans := len(engine.Cache.GetItemIDs(utils.CacheRatingPlans, utils.EmptyString)); cachedRPlans != 1 { - t.Error("Wrong number of cached rating plans found", cachedRPlans) - } - if cachedRProfiles := len(engine.Cache.GetItemIDs(utils.CacheRatingProfiles, utils.EmptyString)); cachedRProfiles != 1 { - t.Error("Wrong number of cached rating profiles found", cachedRProfiles) - } -} - -func TestGetDataCostDtChrg1(t *testing.T) { - usedData := 20 - usageDur := time.Duration(usedData) * time.Second - timeStart := time.Date(2014, 3, 4, 0, 0, 0, 0, time.Local) - cd := &engine.CallDescriptor{ - Category: "data", - Tenant: "cgrates.org", - Subject: "12345", - Account: "12345", - TimeStart: timeStart, - TimeEnd: timeStart.Add(usageDur), - DurationIndex: usageDur, - ToR: utils.MetaData, - } - if cc, err := cd.GetCost(); err != nil { - t.Error(err) - } else if cc.Cost != 0.004 { - t.Error("Wrong cost returned: ", cc.Cost) - } -} - -func TestGetDataCostSecondIntDtChrg1(t *testing.T) { - usedData := 20 - usageDur := time.Duration(usedData) - timeStart := time.Date(2014, 3, 4, 1, 0, 0, 0, time.Local) - cd := &engine.CallDescriptor{ - Category: "data", - Tenant: "cgrates.org", - Subject: "12345", - Account: "12345", - TimeStart: timeStart, - TimeEnd: timeStart.Add(usageDur), - DurationIndex: usageDur, - ToR: utils.MetaData, - } - if cc, err := cd.GetCost(); err != nil { - t.Error(err) - } else if cc.Cost != 0.002 { - t.Error("Wrong cost returned: ", cc.Cost) - } -} - -func TestGetDataBetweenCostDtChrg1(t *testing.T) { - usedData := 20 - usageDur := time.Duration(usedData) * time.Second - timeStart := time.Date(2014, 3, 4, 0, 59, 50, 0, time.Local) - cd := &engine.CallDescriptor{ - Category: "data", - Tenant: "cgrates.org", - Subject: "12345", - Account: "12345", - TimeStart: timeStart, - TimeEnd: timeStart.Add(usageDur), - DurationIndex: usageDur, - ToR: utils.MetaData, - } - if cc, err := cd.GetCost(); err != nil { - t.Error(err) - } else if cc.Cost != 0.004 { - //t.Logf("%+v", cc.Timespans[1].RateInterval.Timing) - for _, ts := range cc.Timespans { - t.Logf("TS: %+v", ts) - } - t.Error("Wrong cost returned: ", cc.Cost) - } -} diff --git a/general_tests/ddazmbl1_test.go b/general_tests/ddazmbl1_test.go deleted file mode 100644 index f2676990c..000000000 --- a/general_tests/ddazmbl1_test.go +++ /dev/null @@ -1,172 +0,0 @@ -/* -Real-time Online/Offline Charging System (OCS) 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 -*/ -package general_tests - -import ( - "testing" - "time" - - "github.com/cgrates/cgrates/config" - "github.com/cgrates/cgrates/engine" - "github.com/cgrates/cgrates/utils" -) - -var dataDB *engine.DataManager - -func TestDZ1SetStorage(t *testing.T) { - data := engine.NewInternalDB(nil, nil, true) - dataDB = engine.NewDataManager(data, config.CgrConfig().CacheCfg(), nil) - engine.SetDataStorage(dataDB) - engine.Cache.Clear(nil) -} - -func TestDZ1LoadCsvTp(t *testing.T) { - timings := `ALWAYS,*any,*any,*any,*any,00:00:00 -ASAP,*any,*any,*any,*any,*asap` - destinations := `DST_UK_Mobile_BIG5,447596 -DST_UK_Mobile_BIG5,447956` - rates := `RT_UK_Mobile_BIG5_PKG,0.01,0,20s,20s,0s -RT_UK_Mobile_BIG5,0.01,0.10,1s,1s,0s` - destinationRates := `DR_UK_Mobile_BIG5_PKG,DST_UK_Mobile_BIG5,RT_UK_Mobile_BIG5_PKG,*up,8,0, -DR_UK_Mobile_BIG5,DST_UK_Mobile_BIG5,RT_UK_Mobile_BIG5,*up,8,0,` - ratingPlans := `RP_UK_Mobile_BIG5_PKG,DR_UK_Mobile_BIG5_PKG,ALWAYS,10 -RP_UK,DR_UK_Mobile_BIG5,ALWAYS,10` - ratingProfiles := `cgrates.org,call,*any,2013-01-06T00:00:00Z,RP_UK, -cgrates.org,call,discounted_minutes,2013-01-06T00:00:00Z,RP_UK_Mobile_BIG5_PKG,` - sharedGroups := `` - actions := `TOPUP10_AC,*topup_reset,,,,*monetary,,*any,,,*unlimited,,10,10,false,false,10 -TOPUP10_AC1,*topup_reset,,,,*voice,,DST_UK_Mobile_BIG5,discounted_minutes,,*unlimited,,40000000000,10,false,false,10` - actionPlans := `TOPUP10_AT,TOPUP10_AC,ASAP,10 -TOPUP10_AT,TOPUP10_AC1,ASAP,10` - actionTriggers := `` - accountActions := `cgrates.org,12344,TOPUP10_AT,,,` - resLimits := `` - stats := `` - thresholds := `` - filters := `` - suppliers := `` - attrProfiles := `` - chargerProfiles := `` - csvr, err := engine.NewTpReader(dataDB.DataDB(), - engine.NewStringCSVStorage(utils.CSVSep, destinations, timings, rates, - destinationRates, ratingPlans, ratingProfiles, - sharedGroups, actions, actionPlans, actionTriggers, accountActions, - resLimits, stats, thresholds, filters, suppliers, - attrProfiles, chargerProfiles, ``, "", utils.EmptyString, utils.EmptyString, utils.EmptyString), "", "", nil, nil, false) - if err != nil { - t.Error(err) - } - if err := csvr.LoadDestinations(); err != nil { - t.Fatal(err) - } - if err := csvr.LoadTimings(); err != nil { - t.Fatal(err) - } - if err := csvr.LoadRates(); err != nil { - t.Fatal(err) - } - if err := csvr.LoadDestinationRates(); err != nil { - t.Fatal(err) - } - if err := csvr.LoadRatingPlans(); err != nil { - t.Fatal(err) - } - if err := csvr.LoadRatingProfiles(); err != nil { - t.Fatal(err) - } - if err := csvr.LoadSharedGroups(); err != nil { - t.Fatal(err) - } - if err := csvr.LoadActions(); err != nil { - t.Fatal(err) - } - if err := csvr.LoadActionPlans(); err != nil { - t.Fatal(err) - } - if err := csvr.LoadActionTriggers(); err != nil { - t.Fatal(err) - } - if err := csvr.LoadAccountActions(); err != nil { - t.Fatal(err) - } - csvr.WriteToDatabase(false, false) - if acnt, err := dataDB.GetAccount("cgrates.org:12344"); err != nil { - t.Error(err) - } else if acnt == nil { - t.Error("No account saved") - } - - dataDB.LoadDataDBCache(engine.GetDefaultEmptyArgCachePrefix()) - - if cachedDests := len(engine.Cache.GetItemIDs(utils.CacheDestinations, "")); cachedDests != 1 { - t.Error("Wrong number of cached destinations found", cachedDests) - } - if cachedRPlans := len(engine.Cache.GetItemIDs(utils.CacheRatingPlans, "")); cachedRPlans != 2 { - t.Error("Wrong number of cached rating plans found", cachedRPlans) - } - if cachedRProfiles := len(engine.Cache.GetItemIDs(utils.CacheRatingProfiles, "")); cachedRProfiles != 2 { - t.Error("Wrong number of cached rating profiles found", cachedRProfiles) - } - if cachedActions := len(engine.Cache.GetItemIDs(utils.CacheActions, "")); cachedActions != 2 { - t.Error("Wrong number of cached actions found", cachedActions) - } -} - -func TestDZ1ExecuteActions(t *testing.T) { - time.Sleep(10 * time.Millisecond) - if acnt, err := dataDB.GetAccount("cgrates.org:12344"); err != nil { - t.Error(err) - } else if len(acnt.BalanceMap) != 2 { - t.Error("Account does not have enough balances: ", acnt.BalanceMap) - } else if acnt.BalanceMap[utils.MetaVoice][0].Value != 40000000000 { - t.Error("Account does not have enough minutes in balance", - acnt.BalanceMap[utils.MetaVoice][0].Value) - } else if acnt.BalanceMap[utils.MetaMonetary][0].Value != 10 { - t.Error("Account does not have enough monetary balance", - acnt.BalanceMap[utils.MetaMonetary][0].Value) - } -} - -func TestDZ1Debit(t *testing.T) { - cd := &engine.CallDescriptor{ - Category: "call", - Tenant: "cgrates.org", - Subject: "12344", - Account: "12344", - Destination: "447956933443", - TimeStart: time.Date(2014, 3, 4, 6, 0, 0, 0, time.UTC), - TimeEnd: time.Date(2014, 3, 4, 6, 0, 10, 0, time.UTC), - } - if cc, err := cd.Debit(); err != nil { - t.Error(err) - } else if cc.Cost != 0.01 { - t.Error("Wrong cost returned: ", cc.Cost) - } - acnt, err := dataDB.GetAccount("cgrates.org:12344") - if err != nil { - t.Fatal(err) - } - if acnt.BalanceMap[utils.MetaVoice][0].Value != 20000000000 { - t.Error("Account does not have expected *voice units in balance", - acnt.BalanceMap[utils.MetaVoice][0].Value) - } - if acnt.BalanceMap[utils.MetaMonetary][0].Value != 9.99 { - t.Error("Account does not have expected *monetary units in balance", - acnt.BalanceMap[utils.MetaMonetary][0].Value) - } -} diff --git a/general_tests/ddazmbl2_test.go b/general_tests/ddazmbl2_test.go deleted file mode 100644 index e8ddc8371..000000000 --- a/general_tests/ddazmbl2_test.go +++ /dev/null @@ -1,175 +0,0 @@ -/* -Real-time Online/Offline Charging System (OCS) 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 -*/ -package general_tests - -import ( - "testing" - "time" - - "github.com/cgrates/cgrates/config" - "github.com/cgrates/cgrates/engine" - "github.com/cgrates/cgrates/scheduler" - "github.com/cgrates/cgrates/utils" -) - -var dataDB2 *engine.DataManager - -func TestSetStorage2(t *testing.T) { - data := engine.NewInternalDB(nil, nil, true) - dataDB2 = engine.NewDataManager(data, config.CgrConfig().CacheCfg(), nil) - engine.SetDataStorage(dataDB2) - engine.Cache.Clear(nil) -} - -func TestLoadCsvTp2(t *testing.T) { - timings := `ALWAYS,*any,*any,*any,*any,00:00:00 -ASAP,*any,*any,*any,*any,*asap` - destinations := `DST_UK_Mobile_BIG5,447596 -DST_UK_Mobile_BIG5,447956` - rates := `RT_UK_Mobile_BIG5_PKG,0.01,0,20s,20s,0s -RT_UK_Mobile_BIG5,0.01,0.10,1s,1s,0s` - destinationRates := `DR_UK_Mobile_BIG5_PKG,DST_UK_Mobile_BIG5,RT_UK_Mobile_BIG5_PKG,*up,8,0, -DR_UK_Mobile_BIG5,DST_UK_Mobile_BIG5,RT_UK_Mobile_BIG5,*up,8,0,` - ratingPlans := `RP_UK_Mobile_BIG5_PKG,DR_UK_Mobile_BIG5_PKG,ALWAYS,10 -RP_UK,DR_UK_Mobile_BIG5,ALWAYS,10` - ratingProfiles := `cgrates.org,call,*any,2013-01-06T00:00:00Z,RP_UK, -cgrates.org,call,discounted_minutes,2013-01-06T00:00:00Z,RP_UK_Mobile_BIG5_PKG,` - sharedGroups := `` - actions := `TOPUP10_AC,*topup_reset,,,,*monetary,,*any,,,*unlimited,,0,10,false,false,10 -TOPUP10_AC1,*topup_reset,,,,*voice,,DST_UK_Mobile_BIG5,discounted_minutes,,*unlimited,,40s,10,false,false,10` - actionPlans := `TOPUP10_AT,TOPUP10_AC,ASAP,10 -TOPUP10_AT,TOPUP10_AC1,ASAP,10` - actionTriggers := `` - accountActions := `cgrates.org,12345,TOPUP10_AT,,,` - resLimits := `` - stats := `` - thresholds := `` - filters := `` - suppliers := `` - attrProfiles := `` - chargerProfiles := `` - csvr, err := engine.NewTpReader(dataDB2.DataDB(), engine.NewStringCSVStorage(utils.CSVSep, destinations, timings, - rates, destinationRates, ratingPlans, ratingProfiles, sharedGroups, actions, actionPlans, - actionTriggers, accountActions, resLimits, - stats, thresholds, filters, suppliers, attrProfiles, chargerProfiles, ``, "", utils.EmptyString, utils.EmptyString, utils.EmptyString), "", "", nil, nil, false) - if err != nil { - t.Error(err) - } - if err := csvr.LoadDestinations(); err != nil { - t.Fatal(err) - } - if err := csvr.LoadTimings(); err != nil { - t.Fatal(err) - } - if err := csvr.LoadRates(); err != nil { - t.Fatal(err) - } - if err := csvr.LoadDestinationRates(); err != nil { - t.Fatal(err) - } - if err := csvr.LoadRatingPlans(); err != nil { - t.Fatal(err) - } - if err := csvr.LoadRatingProfiles(); err != nil { - t.Fatal(err) - } - if err := csvr.LoadSharedGroups(); err != nil { - t.Fatal(err) - } - if err := csvr.LoadActions(); err != nil { - t.Fatal(err) - } - if err := csvr.LoadActionPlans(); err != nil { - t.Fatal(err) - } - if err := csvr.LoadActionTriggers(); err != nil { - t.Fatal(err) - } - if err := csvr.LoadAccountActions(); err != nil { - t.Fatal(err) - } - csvr.WriteToDatabase(false, false) - if acnt, err := dataDB2.GetAccount("cgrates.org:12345"); err != nil { - t.Error(err) - } else if acnt == nil { - t.Error("No account saved") - } - dataDB2.LoadDataDBCache(engine.GetDefaultEmptyArgCachePrefix()) - - if cachedDests := len(engine.Cache.GetItemIDs(utils.CacheDestinations, "")); cachedDests != 1 { - t.Error("Wrong number of cached destinations found", cachedDests) - } - if cachedRPlans := len(engine.Cache.GetItemIDs(utils.CacheRatingPlans, "")); cachedRPlans != 2 { - t.Error("Wrong number of cached rating plans found", cachedRPlans) - } - if cachedRProfiles := len(engine.Cache.GetItemIDs(utils.CacheRatingProfiles, "")); cachedRProfiles != 2 { - t.Error("Wrong number of cached rating profiles found", cachedRProfiles) - } - if cachedActions := len(engine.Cache.GetItemIDs(utils.CacheActions, "")); cachedActions != 2 { - t.Error("Wrong number of cached actions found", cachedActions) - } -} - -func TestExecuteActions2(t *testing.T) { - scheduler.NewScheduler(dataDB2, config.CgrConfig(), - engine.NewFilterS(config.CgrConfig(), nil, dataDB)).Reload() - time.Sleep(10 * time.Millisecond) // Give time to scheduler to topup the account - if acnt, err := dataDB2.GetAccount("cgrates.org:12345"); err != nil { - t.Error(err) - } else if len(acnt.BalanceMap) != 2 { - t.Error("Account does not have enough balances: ", acnt.BalanceMap) - } else if acnt.BalanceMap[utils.MetaVoice][0].Value != 40*float64(time.Second) { - t.Error("Account does not have enough minutes in balance", acnt.BalanceMap[utils.MetaVoice][0].Value) - } else if acnt.BalanceMap[utils.MetaMonetary][0].Value != 0 { - t.Error("Account does not have enough monetary balance", acnt.BalanceMap[utils.MetaMonetary][0].Value) - } -} - -func TestDebit2(t *testing.T) { - cd := &engine.CallDescriptor{ - Category: "call", - Tenant: "cgrates.org", - Subject: "12345", - Account: "12345", - Destination: "447956933443", - TimeStart: time.Date(2014, 3, 4, 6, 0, 0, 0, time.UTC), - TimeEnd: time.Date(2014, 3, 4, 6, 0, 10, 0, time.UTC), - } - if cc, err := cd.Debit(); err != nil { - t.Error(err) - } else if cc.Cost != 0.01 { - t.Error("Wrong cost returned: ", cc.Cost) - } - acnt, err := dataDB2.GetAccount("cgrates.org:12345") - if err != nil { - t.Error(err) - } - if len(acnt.BalanceMap) != 2 { - t.Error("Wrong number of user balances found", acnt.BalanceMap) - } - if acnt.BalanceMap[utils.MetaVoice][0].Value != 20*float64(time.Second) { - t.Error("Account does not have expected minutes in balance", acnt.BalanceMap[utils.MetaVoice][0].Value) - } - for _, blnc := range acnt.BalanceMap[utils.MetaMonetary] { // Test negative balance for default one - if blnc.Weight == 10 && blnc.Value != 0 { - t.Errorf("Balance with weight: %f, having value: %f ", blnc.Weight, blnc.Value) - } else if blnc.Weight == 0 && blnc.Value != -0.01 { - t.Errorf("Balance with weight: %f, having value: %f ", blnc.Weight, blnc.Value) - } - } -} diff --git a/general_tests/ddazmbl3_test.go b/general_tests/ddazmbl3_test.go deleted file mode 100644 index bb46f442a..000000000 --- a/general_tests/ddazmbl3_test.go +++ /dev/null @@ -1,168 +0,0 @@ -/* -Real-time Online/Offline Charging System (OCS) 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 -*/ -package general_tests - -import ( - "testing" - "time" - - "github.com/cgrates/cgrates/config" - "github.com/cgrates/cgrates/engine" - "github.com/cgrates/cgrates/scheduler" - "github.com/cgrates/cgrates/utils" -) - -var dataDB3 *engine.DataManager - -func TestSetStorage3(t *testing.T) { - data := engine.NewInternalDB(nil, nil, true) - dataDB3 = engine.NewDataManager(data, config.CgrConfig().CacheCfg(), nil) - engine.SetDataStorage(dataDB3) - engine.Cache.Clear(nil) -} - -func TestLoadCsvTp3(t *testing.T) { - timings := `ALWAYS,*any,*any,*any,*any,00:00:00 -ASAP,*any,*any,*any,*any,*asap` - destinations := `DST_UK_Mobile_BIG5,447596 -DST_UK_Mobile_BIG5,447956` - rates := `RT_UK_Mobile_BIG5_PKG,0.01,0,20s,20s,0s -RT_UK_Mobile_BIG5,0.01,0.10,1s,1s,0s` - destinationRates := `DR_UK_Mobile_BIG5_PKG,DST_UK_Mobile_BIG5,RT_UK_Mobile_BIG5_PKG,*up,8,0, -DR_UK_Mobile_BIG5,DST_UK_Mobile_BIG5,RT_UK_Mobile_BIG5,*up,8,0,` - ratingPlans := `RP_UK_Mobile_BIG5_PKG,DR_UK_Mobile_BIG5_PKG,ALWAYS,10 -RP_UK,DR_UK_Mobile_BIG5,ALWAYS,10` - ratingProfiles := `cgrates.org,call,*any,2013-01-06T00:00:00Z,RP_UK, -cgrates.org,call,discounted_minutes,2013-01-06T00:00:00Z,RP_UK_Mobile_BIG5_PKG,` - sharedGroups := `` - actions := `TOPUP10_AC1,*topup_reset,,,,*voice,,DST_UK_Mobile_BIG5,discounted_minutes,,*unlimited,,40s,10,false,false,10` - actionPlans := `TOPUP10_AT,TOPUP10_AC1,ASAP,10` - actionTriggers := `` - accountActions := `cgrates.org,12346,TOPUP10_AT,,,` - resLimits := `` - stats := `` - thresholds := `` - filters := `` - suppliers := `` - attrProfiles := `` - chargerProfiles := `` - csvr, err := engine.NewTpReader(dataDB3.DataDB(), engine.NewStringCSVStorage(utils.CSVSep, destinations, timings, rates, - destinationRates, ratingPlans, ratingProfiles, sharedGroups, actions, actionPlans, actionTriggers, - accountActions, resLimits, stats, - thresholds, filters, suppliers, attrProfiles, chargerProfiles, ``, "", utils.EmptyString, utils.EmptyString, utils.EmptyString), "", "", nil, nil, false) - if err != nil { - t.Error(err) - } - if err := csvr.LoadDestinations(); err != nil { - t.Fatal(err) - } - if err := csvr.LoadTimings(); err != nil { - t.Fatal(err) - } - if err := csvr.LoadRates(); err != nil { - t.Fatal(err) - } - if err := csvr.LoadDestinationRates(); err != nil { - t.Fatal(err) - } - if err := csvr.LoadRatingPlans(); err != nil { - t.Fatal(err) - } - if err := csvr.LoadRatingProfiles(); err != nil { - t.Fatal(err) - } - if err := csvr.LoadSharedGroups(); err != nil { - t.Fatal(err) - } - if err := csvr.LoadActions(); err != nil { - t.Fatal(err) - } - if err := csvr.LoadActionPlans(); err != nil { - t.Fatal(err) - } - if err := csvr.LoadActionTriggers(); err != nil { - t.Fatal(err) - } - if err := csvr.LoadAccountActions(); err != nil { - t.Fatal(err) - } - - csvr.WriteToDatabase(false, false) - if acnt, err := dataDB3.GetAccount("cgrates.org:12346"); err != nil { - t.Error(err) - } else if acnt == nil { - t.Error("No account saved") - } - dataDB3.LoadDataDBCache(engine.GetDefaultEmptyArgCachePrefix()) - - if cachedDests := len(engine.Cache.GetItemIDs(utils.CacheDestinations, "")); cachedDests != 1 { - t.Error("Wrong number of cached destinations found", cachedDests) - } - if cachedRPlans := len(engine.Cache.GetItemIDs(utils.CacheRatingPlans, "")); cachedRPlans != 2 { - t.Error("Wrong number of cached rating plans found", cachedRPlans) - } - if cachedRProfiles := len(engine.Cache.GetItemIDs(utils.CacheRatingProfiles, "")); cachedRProfiles != 2 { - t.Error("Wrong number of cached rating profiles found", cachedRProfiles) - } - if cachedActions := len(engine.Cache.GetItemIDs(utils.CacheActions, "")); cachedActions != 1 { - t.Error("Wrong number of cached actions found", cachedActions) - } -} - -func TestExecuteActions3(t *testing.T) { - scheduler.NewScheduler(dataDB3, config.CgrConfig(), - engine.NewFilterS(config.CgrConfig(), nil, dataDB)).Reload() - time.Sleep(10 * time.Millisecond) // Give time to scheduler to topup the account - if acnt, err := dataDB3.GetAccount("cgrates.org:12346"); err != nil { - t.Error(err) - } else if len(acnt.BalanceMap) != 1 { - t.Error("Account does not have enough balances: ", acnt.BalanceMap) - } else if acnt.BalanceMap[utils.MetaVoice][0].Value != 40*float64(time.Second) { - t.Error("Account does not have enough minutes in balance", acnt.BalanceMap[utils.MetaVoice][0].Value) - } -} - -func TestDebit3(t *testing.T) { - cd := &engine.CallDescriptor{ - Category: "call", - Tenant: "cgrates.org", - Subject: "12346", - Account: "12346", - Destination: "447956933443", - TimeStart: time.Date(2014, 3, 4, 6, 0, 0, 0, time.UTC), - TimeEnd: time.Date(2014, 3, 4, 6, 0, 10, 0, time.UTC), - } - if cc, err := cd.Debit(); err != nil { - t.Error(err) - } else if cc.Cost != 0.01 { - t.Error("Wrong cost returned: ", cc.Cost) - } - acnt, err := dataDB3.GetAccount("cgrates.org:12346") - if err != nil { - t.Error(err) - } - if len(acnt.BalanceMap) != 2 { - t.Error("Wrong number of user balances found", acnt.BalanceMap) - } - if acnt.BalanceMap[utils.MetaVoice][0].Value != 20*float64(time.Second) { - t.Error("Account does not have expected minutes in balance", acnt.BalanceMap[utils.MetaVoice][0].Value) - } - if acnt.BalanceMap[utils.MetaMonetary][0].Value != -0.01 { - t.Error("Account does not have expected monetary balance", acnt.BalanceMap[utils.MetaMonetary][0].Value) - } -} diff --git a/general_tests/filters_test.go b/general_tests/filters_test.go index 24beb29d2..35f554023 100644 --- a/general_tests/filters_test.go +++ b/general_tests/filters_test.go @@ -43,15 +43,15 @@ func TestFilterPassDestinations(t *testing.T) { dm := engine.NewDataManager(data, config.CgrConfig().CacheCfg(), connMgr) internalAPIerSv1Chan <- &v1.APIerSv1{DataManager: dm} engine.SetConnManager(connMgr) - cd := &engine.CallDescriptor{ - Category: "call", - Tenant: "cgrates.org", - Subject: "dan", - Destination: "+4986517174963", - TimeStart: time.Date(2013, time.October, 7, 14, 50, 0, 0, time.UTC), - TimeEnd: time.Date(2013, time.October, 7, 14, 52, 12, 0, time.UTC), - DurationIndex: 132 * time.Second, - ExtraFields: map[string]string{"navigation": "off"}, + cd := &utils.MapStorage{ + utils.Category: "call", + utils.Tenant: "cgrates.org", + utils.Subject: "dan", + utils.Destination: "+4986517174963", + utils.TimeStart: time.Date(2013, time.October, 7, 14, 50, 0, 0, time.UTC), + utils.TimeEnd: time.Date(2013, time.October, 7, 14, 52, 12, 0, time.UTC), + utils.DurationIndex: 132 * time.Second, + utils.ExtraFields: map[string]string{"navigation": "off"}, } rf, err := engine.NewFilterRule(utils.MetaDestinations, "~Destination", []string{"DE"}) if err != nil { diff --git a/general_tests/objectdp_test.go b/general_tests/objectdp_test.go deleted file mode 100644 index 808da06a6..000000000 --- a/general_tests/objectdp_test.go +++ /dev/null @@ -1,86 +0,0 @@ -/* -Real-time Online/Offline Charging System (OCS) 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 -*/ -package general_tests - -import ( - "testing" - - "github.com/cgrates/cgrates/config" - "github.com/cgrates/cgrates/engine" - "github.com/cgrates/cgrates/utils" -) - -func TestAccountNewObjectDPFieldAsInterface(t *testing.T) { - acc := &engine.Account{ - ID: "cgrates.org:1001", - BalanceMap: map[string]engine.Balances{ - utils.MetaMonetary: []*engine.Balance{ - { - Value: 20, - Weight: 10, - }, - }, - }, - } - accDP := config.NewObjectDP(acc) - if data, err := accDP.FieldAsInterface([]string{"BalanceMap", "*monetary[0]", "Value"}); err != nil { - t.Error(err) - } else if data != 20. { - t.Errorf("Expected: %+v ,received: %+v", 20., data) - } - if _, err := accDP.FieldAsInterface([]string{"BalanceMap", "*monetary[1]", "Value"}); err == nil || - err.Error() != "index out of range" { - t.Error(err) - } - if _, err := accDP.FieldAsInterface([]string{"BalanceMap", "*monetary[0]", "InexistentField"}); err == nil || - err != utils.ErrNotFound { - t.Error(err) - } -} - -func TestAccountNewObjectDPFieldAsInterfaceFromCache(t *testing.T) { - acc := &engine.Account{ - ID: "cgrates.org:1001", - BalanceMap: map[string]engine.Balances{ - utils.MetaMonetary: []*engine.Balance{ - { - Value: 20, - Weight: 10, - }, - }, - }, - } - accDP := config.NewObjectDP(acc) - - if data, err := accDP.FieldAsInterface([]string{"BalanceMap", "*monetary[0]", "Value"}); err != nil { - t.Error(err) - } else if data != 20. { - t.Errorf("Expected: %+v ,received: %+v", 20., data) - } - // the value should be taken from cache - if data, err := accDP.FieldAsInterface([]string{"BalanceMap", "*monetary[0]", "Value"}); err != nil { - t.Error(err) - } else if data != 20. { - t.Errorf("Expected: %+v ,received: %+v", 20., data) - } - if data, err := accDP.FieldAsInterface([]string{"BalanceMap", "*monetary[0]"}); err != nil { - t.Error(err) - } else if data != acc.BalanceMap[utils.MetaMonetary][0] { - t.Errorf("Expected: %+v ,received: %+v", acc.BalanceMap[utils.MetaMonetary][0], data) - } -} diff --git a/general_tests/sessions_race_test.go b/general_tests/sessions_race_test.go deleted file mode 100644 index 3b4ad942f..000000000 --- a/general_tests/sessions_race_test.go +++ /dev/null @@ -1,181 +0,0 @@ -// +build race - -/* -Real-time Online/Offline Charging System (OCS) 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 -*/ - -package general_tests - -import ( - "fmt" - "testing" - "time" - - v1 "github.com/cgrates/cgrates/apier/v1" - "github.com/cgrates/cgrates/config" - "github.com/cgrates/cgrates/engine" - "github.com/cgrates/cgrates/sessions" - "github.com/cgrates/cgrates/utils" - "github.com/cgrates/rpcclient" -) - -var ( - sS *sessions.SessionS - cfg *config.CGRConfig - chrS *engine.ChargerService - filterS *engine.FilterS - connMgr *engine.ConnManager - dm *engine.DataManager - resp *engine.Responder -) - -// this structure will iplement rpcclient.ClientConnector -// and will read forever the Event map -type raceConn struct{} - -func (_ raceConn) Call(serviceMethod string, args interface{}, reply interface{}) (err error) { - cgrev := args.(*engine.ThresholdsArgsProcessEvent) - for { - for k := range cgrev.CGREvent.Event { - if _, has := cgrev.CGREvent.Event[k]; !has { - fmt.Println(1) - } - } - } -} - -// small test to detect races in sessions -func TestSessionSRace(t *testing.T) { - // config - var err error - cfg = config.NewDefaultCGRConfig() - cfg.SessionSCfg().Enabled = true - cfg.SessionSCfg().ThreshSConns = []string{utils.ConcatenatedKey(utils.MetaInternal, utils.MetaThresholds)} - cfg.SessionSCfg().ChargerSConns = []string{utils.ConcatenatedKey(utils.MetaInternal, utils.MetaChargers)} - cfg.SessionSCfg().RALsConns = []string{utils.ConcatenatedKey(utils.MetaInternal, utils.MetaResponder)} - cfg.SessionSCfg().DebitInterval = 10 - cfg.ChargerSCfg().Enabled = true - - cfg.CacheCfg().Partitions[utils.CacheChargerProfiles].Limit = -1 - cfg.CacheCfg().Partitions[utils.CacheAccounts].Limit = -1 - // cfg.GeneralCfg().ReplyTimeout = 30 * time.Second - - utils.Logger.SetLogLevel(7) - // connManager - raceChan := make(chan rpcclient.ClientConnector, 1) - chargerSChan := make(chan rpcclient.ClientConnector, 1) - respChan := make(chan rpcclient.ClientConnector, 1) - raceChan <- new(raceConn) - connMgr = engine.NewConnManager(cfg, map[string]chan rpcclient.ClientConnector{ - utils.ConcatenatedKey(utils.MetaInternal, utils.MetaThresholds): raceChan, - utils.ConcatenatedKey(utils.MetaInternal, utils.MetaChargers): chargerSChan, - utils.ConcatenatedKey(utils.MetaInternal, utils.MetaResponder): respChan, - }) - - // dataManager - db := engine.NewInternalDB(nil, nil, true) - dm := engine.NewDataManager(db, cfg.CacheCfg(), connMgr) - engine.SetDataStorage(dm) - - // resp - resp = &engine.Responder{ - ShdChan: utils.NewSyncedChan(), - MaxComputedUsage: cfg.RalsCfg().MaxComputedUsage, - } - respChan <- resp - - // filterS - filterS = engine.NewFilterS(cfg, connMgr, dm) - - // chargerS - chrS = engine.NewChargerService(dm, filterS, cfg, connMgr) - - chargerSChan <- v1.NewChargerSv1(chrS) - - // addCharger - if err = dm.SetChargerProfile(&engine.ChargerProfile{ - Tenant: "cgrates.org", - ID: "Default", - RunID: utils.MetaDefault, - AttributeIDs: []string{"*none"}, - Weight: 20, - }, true); err != nil { - t.Fatal(err) - } - - // set account - if err = dm.SetAccount(&engine.Account{ - ID: utils.ConcatenatedKey("cgrates.org", "1001"), - // AllowNegative: true, - BalanceMap: map[string]engine.Balances{utils.MetaVoice: {{Value: float64(0 * time.Second), Weight: 10}}}}); err != nil { - t.Fatal(err) - } - - // sessionS - sS = sessions.NewSessionS(cfg, dm, connMgr) - - // the race2 - rply := new(sessions.V1InitSessionReply) - if err = sS.BiRPCv1InitiateSession(nil, &sessions.V1InitSessionArgs{ - InitSession: true, - ProcessThresholds: true, - CGREvent: &utils.CGREvent{ - Tenant: "cgrates.org", - ID: "testSSv1ItProcessEventInitiateSession", - Event: map[string]interface{}{ - utils.Tenant: "cgrates.org", - utils.ToR: utils.MetaVoice, - utils.OriginID: "testSSv1ItProcessEvent", - utils.RequestType: utils.MetaPrepaid, - utils.AccountField: "1001", - // utils.RatingSubject: "*zero1ms", - utils.CGRDebitInterval: 10, - utils.Destination: "1002", - utils.SetupTime: time.Date(2018, time.January, 7, 16, 60, 0, 0, time.UTC), - utils.AnswerTime: time.Date(2018, time.January, 7, 16, 60, 10, 0, time.UTC), - utils.Usage: 0, - }, - }, - }, rply); err != utils.ErrPartiallyExecuted { - t.Fatal(err) - } - // the race1 - rply2 := new(sessions.V1ProcessEventReply) - if err = sS.BiRPCv1ProcessEvent(nil, &sessions.V1ProcessEventArgs{ - Flags: []string{utils.ConcatenatedKey(utils.MetaRALs, utils.MetaInitiate), - utils.MetaThresholds}, - CGREvent: &utils.CGREvent{ - Tenant: "cgrates.org", - ID: "testSSv1ItProcessEventInitiateSession", - Event: map[string]interface{}{ - utils.Tenant: "cgrates.org", - utils.ToR: utils.MetaVoice, - utils.OriginID: "testSSv1ItProcessEvent", - utils.RequestType: utils.MetaPrepaid, - utils.AccountField: "1001", - // utils.RatingSubject: "*zero1ms", - utils.CGRDebitInterval: 10, - utils.Destination: "1002", - utils.SetupTime: time.Date(2018, time.January, 7, 16, 60, 0, 0, time.UTC), - utils.AnswerTime: time.Date(2018, time.January, 7, 16, 60, 10, 0, time.UTC), - utils.Usage: 0, - }, - }, - }, rply2); err != utils.ErrPartiallyExecuted { - t.Fatal(err) - } -} diff --git a/general_tests/smschrg1_test.go b/general_tests/smschrg1_test.go deleted file mode 100644 index 31bb039e5..000000000 --- a/general_tests/smschrg1_test.go +++ /dev/null @@ -1,100 +0,0 @@ -/* -Real-time Online/Offline Charging System (OCS) 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 -*/ -package general_tests - -import ( - "testing" - "time" - - "github.com/cgrates/cgrates/config" - "github.com/cgrates/cgrates/engine" - "github.com/cgrates/cgrates/utils" -) - -func TestSMSSetStorageSmsChrg1(t *testing.T) { - dflt := config.NewDefaultCGRConfig() - config.SetCgrConfig(dflt) - config.CgrConfig().CacheCfg().Partitions[utils.CacheRatingPlans].Precache = true // precache rating plan - data := engine.NewInternalDB(nil, nil, true) - dataDB = engine.NewDataManager(data, config.CgrConfig().CacheCfg(), nil) - engine.SetDataStorage(dataDB) - engine.Cache.Clear(nil) -} - -func TestSMSLoadCsvTpSmsChrg1(t *testing.T) { - timings := `ALWAYS,*any,*any,*any,*any,00:00:00` - rates := `RT_SMS_5c,0,0.005,1,1,0` - destinationRates := `DR_SMS_1,*any,RT_SMS_5c,*up,4,0,` - ratingPlans := `RP_SMS1,DR_SMS_1,ALWAYS,10` - ratingProfiles := `cgrates.org,sms,*any,2012-01-01T00:00:00Z,RP_SMS1,` - csvr, err := engine.NewTpReader(dataDB.DataDB(), engine.NewStringCSVStorage(utils.CSVSep, - utils.EmptyString, timings, rates, destinationRates, ratingPlans, ratingProfiles, - utils.EmptyString, utils.EmptyString, utils.EmptyString, utils.EmptyString, - utils.EmptyString, utils.EmptyString, utils.EmptyString, utils.EmptyString, - utils.EmptyString, utils.EmptyString, utils.EmptyString, utils.EmptyString, - utils.EmptyString, utils.EmptyString, utils.EmptyString, utils.EmptyString, utils.EmptyString), utils.EmptyString, - utils.EmptyString, nil, nil, false) - if err != nil { - t.Error(err) - } - if err := csvr.LoadTimings(); err != nil { - t.Fatal(err) - } - if err := csvr.LoadRates(); err != nil { - t.Fatal(err) - } - if err := csvr.LoadDestinationRates(); err != nil { - t.Fatal(err) - } - if err := csvr.LoadRatingPlans(); err != nil { - t.Fatal(err) - } - if err := csvr.LoadRatingProfiles(); err != nil { - t.Fatal(err) - } - csvr.WriteToDatabase(false, false) - dataDB.LoadDataDBCache(engine.GetDefaultEmptyArgCachePrefix()) - - if cachedRPlans := len(engine.Cache.GetItemIDs(utils.CacheRatingPlans, utils.EmptyString)); cachedRPlans != 1 { - t.Error("Wrong number of cached rating plans found", cachedRPlans) - } - if cachedRProfiles := len(engine.Cache.GetItemIDs(utils.CacheRatingProfiles, utils.EmptyString)); cachedRProfiles != 1 { - t.Error("Wrong number of cached rating profiles found", cachedRProfiles) - } -} - -func TestSMSGetDataCostSmsChrg1(t *testing.T) { - usageDur := time.Nanosecond - timeStart := time.Date(2014, 3, 4, 0, 0, 0, 0, time.Local) - cd := &engine.CallDescriptor{ - Category: "sms", - Tenant: "cgrates.org", - Subject: "12345", - Account: "12345", - Destination: "+4917621621391", - TimeStart: timeStart, - TimeEnd: timeStart.Add(usageDur), - DurationIndex: usageDur, - ToR: utils.MetaSMS, - } - if cc, err := cd.GetCost(); err != nil { - t.Error(err) - } else if cc.Cost != 0.005 { - t.Error("Wrong cost returned: ", cc.Cost) - } -} diff --git a/general_tests/tutorial_calls_test.go b/general_tests/tutorial_calls_test.go index 02ad464b4..c9a1ee8ed 100755 --- a/general_tests/tutorial_calls_test.go +++ b/general_tests/tutorial_calls_test.go @@ -20,24 +20,7 @@ along with this program. If not, see package general_tests -import ( - "flag" - "net/rpc" - "net/rpc/jsonrpc" - "os" - "path" - "reflect" - "sort" - "strings" - "testing" - "time" - - "github.com/cgrates/cgrates/config" - "github.com/cgrates/cgrates/engine" - "github.com/cgrates/cgrates/sessions" - "github.com/cgrates/cgrates/utils" -) - +/* var tutorialCallsCfg *config.CGRConfig var tutorialCallsRpc *rpc.Client var tutorialCallsPjSuaListener *os.File @@ -852,3 +835,4 @@ func testCallStopFS(t *testing.T) { t.Errorf("Unsuported format") } } +*/ diff --git a/sessions/session_test.go b/sessions/session_test.go index 128ad08b8..223c42b4b 100644 --- a/sessions/session_test.go +++ b/sessions/session_test.go @@ -83,16 +83,12 @@ func TestSessionClone(t *testing.T) { DebitInterval: 18, SRuns: []*SRun{ {Event: engine.NewMapEvent(nil), - CD: &engine.CallDescriptor{Category: "test"}, - EventCost: &engine.EventCost{CGRID: "testCGRID"}, ExtraDuration: 1, LastUsage: 2, TotalUsage: 3, NextAutoDebit: &tTime, }, {Event: engine.NewMapEvent(nil), - CD: &engine.CallDescriptor{Category: "test2"}, - EventCost: &engine.EventCost{CGRID: "testCGRID2"}, ExtraDuration: 4, LastUsage: 5, TotalUsage: 6, @@ -109,16 +105,12 @@ func TestSessionClone(t *testing.T) { DebitInterval: 18, SRuns: []*SRun{ {Event: engine.NewMapEvent(nil), - CD: &engine.CallDescriptor{Category: "test"}, - EventCost: &engine.EventCost{CGRID: "testCGRID"}, ExtraDuration: 1, LastUsage: 2, TotalUsage: 3, NextAutoDebit: &tTime, }, {Event: engine.NewMapEvent(nil), - CD: &engine.CallDescriptor{Category: "test2"}, - EventCost: &engine.EventCost{CGRID: "testCGRID2"}, ExtraDuration: 4, LastUsage: 5, TotalUsage: 6, @@ -498,14 +490,7 @@ func TestSessionAsExternalSessions2(t *testing.T) { SRuns: []*SRun{{ Event: engine.NewMapEvent(ev), TotalUsage: 2 * time.Second, - CD: &engine.CallDescriptor{ - LoopIndex: 10, - DurationIndex: 3 * time.Second, - MaxRate: 11, - MaxRateUnit: 30 * time.Second, - MaxCostSoFar: 20, - }}, - }, + }}, } exp := []*ExternalSession{{ CGRID: "RandomCGRID", @@ -582,15 +567,8 @@ func TestSessionAsExternalSessions3(t *testing.T) { EventStart: engine.NewMapEvent(startEv), DebitInterval: time.Second, SRuns: []*SRun{{ - Event: engine.NewMapEvent(ev), - TotalUsage: 2 * time.Second, - CD: &engine.CallDescriptor{ - LoopIndex: 10, - DurationIndex: 3 * time.Second, - MaxRate: 11, - MaxRateUnit: 30 * time.Second, - MaxCostSoFar: 20, - }, + Event: engine.NewMapEvent(ev), + TotalUsage: 2 * time.Second, NextAutoDebit: &tTime, }}, } @@ -651,8 +629,6 @@ func TestSessiontotalUsage(t *testing.T) { SRuns: []*SRun{ { Event: engine.NewMapEvent(nil), - CD: &engine.CallDescriptor{Category: "test"}, - EventCost: &engine.EventCost{CGRID: "testCGRID"}, ExtraDuration: 1, LastUsage: 2, TotalUsage: 5, @@ -660,8 +636,6 @@ func TestSessiontotalUsage(t *testing.T) { }, { Event: engine.NewMapEvent(nil), - CD: &engine.CallDescriptor{Category: "test2"}, - EventCost: &engine.EventCost{CGRID: "testCGRID2"}, ExtraDuration: 4, LastUsage: 5, TotalUsage: 6, @@ -744,13 +718,6 @@ func TestUpdateSRuns(t *testing.T) { SRuns: []*SRun{{ Event: engine.NewMapEvent(ev), TotalUsage: 2 * time.Second, - CD: &engine.CallDescriptor{ - LoopIndex: 10, - DurationIndex: 3 * time.Second, - MaxRate: 11, - MaxRateUnit: 30 * time.Second, - MaxCostSoFar: 20, - }, }}, } updEv := map[string]interface{}{ diff --git a/sessions/sessions.go b/sessions/sessions.go index 7cc18954a..77c50ed4b 100644 --- a/sessions/sessions.go +++ b/sessions/sessions.go @@ -106,7 +106,6 @@ func (sS *SessionS) ListenAndServe(stopChan chan struct{}) { } } } - return } // Shutdown is called by engine to clear states @@ -605,7 +604,6 @@ func (sS *SessionS) replicateSessions(cgrID string, psv bool, connIDs []string) utils.SessionS, sCln.CGRID, err.Error())) } } - return } // registerSession will register an active or passive Session @@ -697,7 +695,6 @@ func (sS *SessionS) indexSession(s *Session, pSessions bool) { ssRIdx[s.CGRID] = append(ssRIdx[s.CGRID], &riFieldNameVal{fieldName: fieldName, fieldValue: fieldVal}) } } - return } // unindexASession removes an active or passive session from indexes diff --git a/sessions/sessions_bench_test.go b/sessions/sessions_bench_test.go deleted file mode 100644 index 36eed1194..000000000 --- a/sessions/sessions_bench_test.go +++ /dev/null @@ -1,249 +0,0 @@ -/* -Real-time Online/Offline Charging System (OCS) 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 -*/ - -package sessions - -import ( - "flag" - "fmt" - "log" - "net/rpc" - "net/rpc/jsonrpc" - "path" - "sync" - "testing" - "time" - - "github.com/cgrates/cgrates/config" - "github.com/cgrates/cgrates/engine" - "github.com/cgrates/cgrates/utils" -) - -var ( - sBenchCfg *config.CGRConfig - sBenchRPC *rpc.Client - connOnce sync.Once - initRuns = flag.Int("runs", 25000, "number of loops to run in init") - cps = flag.Int("cps", 2000, "number of loops to run in init") - maxCps = make(chan struct{}, *cps) -) - -func startRPC() { - var err error - sBenchCfg, err = config.NewCGRConfigFromPath( - path.Join(*dataDir, "conf", "samples", "tutmongo")) - if err != nil { - log.Fatal(err) - } - if sBenchRPC, err = jsonrpc.Dial(utils.TCP, sBenchCfg.ListenCfg().RPCJSONListen); err != nil { - log.Fatalf("Error at dialing rcp client:%v\n", err) - } -} - -func loadTP() { - for i := 0; i < *cps; i++ { // init CPS limitation - maxCps <- struct{}{} - } - if err := engine.InitDataDb(sBenchCfg); err != nil { - log.Fatal(err) - } - attrs := &utils.AttrLoadTpFromFolder{ - FolderPath: path.Join(*dataDir, "tariffplans", "tutorial")} - var tpLoadInst utils.LoadInstance - if err := sBenchRPC.Call(utils.APIerSv2LoadTariffPlanFromFolder, - attrs, &tpLoadInst); err != nil { - log.Fatal(err) - } - time.Sleep(100 * time.Millisecond) // Give time for scheduler to execute topups -} - -func addBalance(sBenchRPC *rpc.Client, sraccount string) { - attrSetBalance := utils.AttrSetBalance{ - Tenant: "cgrates.org", - Account: sraccount, - BalanceType: utils.MetaVoice, - Value: 5 * float64(time.Hour), - Balance: map[string]interface{}{ - utils.ID: "TestDynamicDebitBalance", - }, - } - var reply string - if err := sBenchRPC.Call(utils.APIerSv2SetBalance, - attrSetBalance, &reply); err != nil { - log.Fatal(err) - } -} - -func addAccouns() { - var wg sync.WaitGroup - for i := 0; i < *initRuns; i++ { - wg.Add(1) - go func(i int) { - oneCps := <-maxCps // queue here for maxCps - defer func() { maxCps <- oneCps }() - addBalance(sBenchRPC, fmt.Sprintf("1001%v", i)) - wg.Done() - }(i) - } - wg.Wait() -} - -func initSession(i int) { - oneCps := <-maxCps // queue here for maxCps - defer func() { maxCps <- oneCps }() - initArgs := &V1InitSessionArgs{ - InitSession: true, - CGREvent: &utils.CGREvent{ - Tenant: "cgrates.org", - ID: "", - Event: map[string]interface{}{ - utils.EventName: "TEST_EVENT", - utils.ToR: utils.MetaVoice, - utils.Category: "call", - utils.Tenant: "cgrates.org", - utils.RequestType: utils.MetaPrepaid, - utils.AnswerTime: time.Date(2016, time.January, 5, 18, 31, 05, 0, time.UTC), - }, - }, - } - initArgs.ID = utils.UUIDSha1Prefix() - initArgs.Event[utils.OriginID] = utils.UUIDSha1Prefix() - initArgs.Event[utils.AccountField] = fmt.Sprintf("1001%v", i) - initArgs.Event[utils.Subject] = "1001" //initArgs.Event[utils.AccountField] - initArgs.Event[utils.Destination] = fmt.Sprintf("1002%v", i) - - var initRpl *V1InitSessionReply - if err := sBenchRPC.Call(utils.SessionSv1InitiateSession, - initArgs, &initRpl); err != nil { - // log.Fatal(err) - } -} - -func sendInitx10(r int) { - var wg sync.WaitGroup - for i := r; i < r+10; i++ { - wg.Add(1) - go func(i int) { - initSession(i) - wg.Done() - - }(i) - } - wg.Wait() -} - -func sendInit() { - var wg sync.WaitGroup - for i := 0; i < *initRuns; i++ { - wg.Add(1) - go func(i int) { - initSession(i) - wg.Done() - - }(i) - } - wg.Wait() -} - -func getCount() int { - var count int - if err := sBenchRPC.Call(utils.SessionSv1GetActiveSessionsCount, utils.SessionFilter{ - Filters: []string{"*string:~*req.ToR:*voice"}, - }, &count); err != nil { - log.Fatal(err) - } - return count -} - -func BenchmarkSendInitSession(b *testing.B) { - connOnce.Do(func() { - startRPC() - loadTP() - addAccouns() - sendInit() - // time.Sleep(3 * time.Minute) - }) - b.ResetTimer() - for i := 0; i < b.N; i++ { - _ = getCount() - } -} - -func BenchmarkEncodingJSON(b *testing.B) { - maxCps = make(chan struct{}, *cps) - for i := 0; i < *cps; i++ { // init CPS limitation - maxCps <- struct{}{} - } - var err error - sBenchCfg, err = config.NewCGRConfigFromPath( - path.Join(*dataDir, "conf", "samples", "tutmongo")) - if err != nil { - log.Fatal(err) - } - - if sBenchRPC, err = jsonrpc.Dial(utils.TCP, sBenchCfg.ListenCfg().RPCJSONListen); err != nil { - log.Fatalf("Error at dialing rcp client:%v\n", err) - } - b.ResetTimer() - for i := 0; i < b.N; i++ { - initSession(i) - } - -} - -func BenchmarkEncodingGOB(b *testing.B) { - maxCps = make(chan struct{}, *cps) - for i := 0; i < *cps; i++ { // init CPS limitation - maxCps <- struct{}{} - } - var err error - sBenchCfg, err = config.NewCGRConfigFromPath( - path.Join(*dataDir, "conf", "samples", "tutmongo")) - if err != nil { - log.Fatal(err) - } - - if sBenchRPC, err = rpc.Dial(utils.TCP, sBenchCfg.ListenCfg().RPCGOBListen); err != nil { - log.Fatalf("Error at dialing rcp client:%v\n", err) - } - b.ResetTimer() - for i := 0; i < b.N; i++ { - initSession(i) - } - -} - -func benchmarkSendInitSessionx10(b *testing.B) { - connOnce.Do(func() { - startRPC() - loadTP() - addAccouns() - // time.Sleep(3 * time.Minute) - }) - b.ResetTimer() - for i := 0; i < *initRuns/10; i++ { - sendInitx10(i * 10) - tStart := time.Now() - _ = getCount() - if tDur := time.Now().Sub(tStart); tDur > 100*time.Millisecond && tDur < time.Second { - fmt.Printf("Expected answer in less than %v receved answer after %v for %v sessions\n", 100*time.Millisecond, tDur, i*10+10) - } else if tDur >= time.Second { - b.Fatalf("Fatal:Expected answer in less than %v receved answer after %v for %v sessions", time.Second, tDur, i*10+10) - } - } -} diff --git a/sessions/sessions_test.go b/sessions/sessions_test.go index a1f498f53..94408f226 100644 --- a/sessions/sessions_test.go +++ b/sessions/sessions_test.go @@ -171,9 +171,6 @@ func TestSessionSIndexAndUnindexSessions(t *testing.T) { SRuns: []*SRun{ { Event: sEv, - CD: &engine.CallDescriptor{ - RunID: utils.MetaDefault, - }, }, }, } @@ -240,9 +237,6 @@ func TestSessionSIndexAndUnindexSessions(t *testing.T) { SRuns: []*SRun{ { Event: sSEv2, - CD: &engine.CallDescriptor{ - RunID: utils.MetaDefault, - }, }, }, } @@ -261,9 +255,6 @@ func TestSessionSIndexAndUnindexSessions(t *testing.T) { SRuns: []*SRun{ { Event: sSEv3, - CD: &engine.CallDescriptor{ - RunID: utils.MetaDefault, - }, }, }, } @@ -486,9 +477,6 @@ func TestSessionSRegisterAndUnregisterASessions(t *testing.T) { SRuns: []*SRun{ { Event: sSEv, - CD: &engine.CallDescriptor{ - RunID: utils.MetaDefault, - }, }, }, } @@ -544,9 +532,6 @@ func TestSessionSRegisterAndUnregisterASessions(t *testing.T) { SRuns: []*SRun{ { Event: sSEv2, - CD: &engine.CallDescriptor{ - RunID: utils.MetaDefault, - }, }, }, } @@ -611,9 +596,6 @@ func TestSessionSRegisterAndUnregisterASessions(t *testing.T) { SRuns: []*SRun{ { Event: sSEv3, - CD: &engine.CallDescriptor{ - RunID: utils.MetaDefault, - }, }, }, } @@ -704,9 +686,6 @@ func TestSessionSRegisterAndUnregisterPSessions(t *testing.T) { SRuns: []*SRun{ { Event: sSEv, - CD: &engine.CallDescriptor{ - RunID: utils.MetaDefault, - }, }, }, } @@ -765,9 +744,6 @@ func TestSessionSRegisterAndUnregisterPSessions(t *testing.T) { SRuns: []*SRun{ { Event: sSEv2, - CD: &engine.CallDescriptor{ - RunID: utils.MetaDefault, - }, }, }, } @@ -832,7 +808,6 @@ func TestSessionSRegisterAndUnregisterPSessions(t *testing.T) { SRuns: []*SRun{ { Event: sSEv3, - CD: &engine.CallDescriptor{}, }, }, } @@ -1858,9 +1833,6 @@ func TestSessionSgetSessionIDsMatchingIndexes(t *testing.T) { SRuns: []*SRun{ { Event: sEv, - CD: &engine.CallDescriptor{ - RunID: "RunID", - }, }, }, } @@ -1897,17 +1869,11 @@ func TestSessionSgetSessionIDsMatchingIndexes(t *testing.T) { session.SRuns = []*SRun{ { Event: sEv, - CD: &engine.CallDescriptor{ - RunID: "RunID", - }, }, { Event: engine.NewMapEvent(map[string]interface{}{ utils.EventName: "TEST_EVENT", utils.ToR: "*voice"}), - CD: &engine.CallDescriptor{ - RunID: "RunID2", - }, }, } sSCfg.SessionSCfg().SessionIndexes = utils.StringSet{ @@ -2160,9 +2126,6 @@ func TestSessionSgetSession(t *testing.T) { SRuns: []*SRun{ { Event: sSEv, - CD: &engine.CallDescriptor{ - RunID: utils.MetaDefault, - }, }, }, } @@ -2213,15 +2176,9 @@ func TestSessionSfilterSessions(t *testing.T) { SRuns: []*SRun{ { Event: sEv, - CD: &engine.CallDescriptor{ - RunID: "RunID", - }, }, { Event: sr2, - CD: &engine.CallDescriptor{ - RunID: "RunID2", - }, }, }, } @@ -2389,15 +2346,9 @@ func TestSessionSfilterSessionsCount(t *testing.T) { SRuns: []*SRun{ { Event: sEv, - CD: &engine.CallDescriptor{ - RunID: "RunID", - }, }, { Event: sr2, - CD: &engine.CallDescriptor{ - RunID: "RunID2", - }, }, }, } diff --git a/sessions/sessionscover_test.go b/sessions/sessionscover_test.go index 2e4d00a0d..bdaad8281 100644 --- a/sessions/sessionscover_test.go +++ b/sessions/sessionscover_test.go @@ -18,23 +18,7 @@ along with this program. If not, see package sessions -import ( - "bytes" - "fmt" - "io" - "log" - "os" - "reflect" - "strings" - "testing" - "time" - - "github.com/cgrates/cgrates/config" - "github.com/cgrates/cgrates/engine" - "github.com/cgrates/cgrates/utils" - "github.com/cgrates/rpcclient" -) - +/* func TestSetSTerminator(t *testing.T) { log.SetOutput(io.Discard) cfg := config.NewDefaultCGRConfig() @@ -252,8 +236,6 @@ func TestForceSTerminatorManualTermination(t *testing.T) { DebitInterval: 18, SRuns: []*SRun{ {Event: engine.NewMapEvent(nil), - CD: &engine.CallDescriptor{Category: "test"}, - EventCost: &engine.EventCost{CGRID: "testCGRID"}, ExtraDuration: 1, LastUsage: 2, TotalUsage: 3, @@ -294,8 +276,6 @@ func TestForceSTerminatorPostCDRs(t *testing.T) { Event: map[string]interface{}{ utils.RequestType: utils.MetaPostpaid, }, - CD: &engine.CallDescriptor{Category: "test"}, - EventCost: &engine.EventCost{CGRID: "testCGRID"}, ExtraDuration: 1, LastUsage: 2, TotalUsage: 3, @@ -332,8 +312,6 @@ func TestForceSTerminatorReleaseSession(t *testing.T) { Event: map[string]interface{}{ utils.RequestType: utils.MetaPostpaid, }, - CD: &engine.CallDescriptor{Category: "test"}, - EventCost: &engine.EventCost{CGRID: "testCGRID"}, ExtraDuration: 1, LastUsage: 2, TotalUsage: 3, @@ -382,8 +360,6 @@ func TestForceSTerminatorClientCall(t *testing.T) { Event: map[string]interface{}{ utils.RequestType: utils.MetaPostpaid, }, - CD: &engine.CallDescriptor{Category: "test"}, - EventCost: &engine.EventCost{CGRID: "testCGRID"}, ExtraDuration: 1, LastUsage: 2, TotalUsage: 3, @@ -416,8 +392,6 @@ func TestDebitSession(t *testing.T) { Event: map[string]interface{}{ utils.RequestType: utils.MetaPostpaid, }, - CD: &engine.CallDescriptor{Category: "test"}, - EventCost: &engine.EventCost{CGRID: "testCGRID"}, ExtraDuration: 1, LastUsage: 2, TotalUsage: 3, @@ -467,17 +441,17 @@ func TestDebitSessionResponderMaxDebit(t *testing.T) { engine.Cache.Clear(nil) testMock1 := &testMockClients{ calls: map[string]func(args interface{}, reply interface{}) error{ - utils.ResponderMaxDebit: func(args interface{}, reply interface{}) error { - callCost := new(engine.CallCost) - callCost.Timespans = []*engine.TimeSpan{ - { - TimeStart: time.Date(2020, 07, 21, 5, 0, 0, 0, time.UTC), - TimeEnd: time.Date(2020, 07, 21, 10, 0, 0, 0, time.UTC), - }, - } - *(reply.(*engine.CallCost)) = *callCost - return nil - }, + // utils.ResponderMaxDebit: func(args interface{}, reply interface{}) error { + // callCost := new(engine.CallCost) + // callCost.Timespans = []*engine.TimeSpan{ + // { + // TimeStart: time.Date(2020, 07, 21, 5, 0, 0, 0, time.UTC), + // TimeEnd: time.Date(2020, 07, 21, 10, 0, 0, 0, time.UTC), + // }, + // } + // *(reply.(*engine.CallCost)) = *callCost + // return nil + // }, }, } @@ -502,11 +476,6 @@ func TestDebitSessionResponderMaxDebit(t *testing.T) { Event: map[string]interface{}{ utils.RequestType: utils.MetaPostpaid, }, - CD: &engine.CallDescriptor{ - Category: "test", - LoopIndex: 12, - }, - EventCost: &engine.EventCost{CGRID: "testCGRID"}, ExtraDuration: time.Minute, LastUsage: time.Minute, TotalUsage: 3 * time.Minute, @@ -523,7 +492,6 @@ func TestDebitSessionResponderMaxDebit(t *testing.T) { t.Errorf("Expected %+v, received %+v", time.Minute, maxDur) } - ss.SRuns[0].EventCost = nil if _, err := sessions.debitSession(ss, 0, 5*time.Minute, utils.DurationPointer(time.Minute)); err != nil { t.Error(err) @@ -540,12 +508,12 @@ func TestDebitSessionResponderMaxDebitError(t *testing.T) { engine.Cache.Clear(nil) sMock := &testMockClients{ calls: map[string]func(args interface{}, reply interface{}) error{ - utils.ResponderMaxDebit: func(args interface{}, reply interface{}) error { - return utils.ErrAccountNotFound - }, - utils.SchedulerSv1ExecuteActionPlans: func(args interface{}, reply interface{}) error { - return nil - }, + // utils.ResponderMaxDebit: func(args interface{}, reply interface{}) error { + // return utils.ErrAccountNotFound + // }, + // utils.SchedulerSv1ExecuteActionPlans: func(args interface{}, reply interface{}) error { + // return nil + // }, }, } @@ -553,11 +521,11 @@ func TestDebitSessionResponderMaxDebitError(t *testing.T) { internalRpcChan <- sMock cfg := config.NewDefaultCGRConfig() cfg.SessionSCfg().RALsConns = []string{utils.ConcatenatedKey(utils.MetaInternal, utils.MetaRALs)} - cfg.SessionSCfg().SchedulerConns = []string{utils.ConcatenatedKey(utils.MetaInternal, utils.MetaScheduler)} + // cfg.SessionSCfg().SchedulerConns = []string{utils.ConcatenatedKey(utils.MetaInternal, utils.MetaActions)} data := engine.NewInternalDB(nil, nil, true) connMgr := engine.NewConnManager(cfg, map[string]chan rpcclient.ClientConnector{ - utils.ConcatenatedKey(utils.MetaInternal, utils.MetaRALs): internalRpcChan, - utils.ConcatenatedKey(utils.MetaInternal, utils.MetaScheduler): internalRpcChan}) + utils.ConcatenatedKey(utils.MetaInternal, utils.MetaRALs): internalRpcChan, + utils.ConcatenatedKey(utils.MetaInternal, utils.MetaActions): internalRpcChan}) dm := engine.NewDataManager(data, cfg.CacheCfg(), connMgr) sessions := NewSessionS(cfg, dm, connMgr) @@ -570,8 +538,8 @@ func TestDebitSessionResponderMaxDebitError(t *testing.T) { Event: map[string]interface{}{ utils.RequestType: utils.MetaDynaprepaid, }, - CD: &engine.CallDescriptor{Category: "test"}, - EventCost: &engine.EventCost{CGRID: "testCGRID"}, + // CD: &engine.CallDescriptor{Category: "test"}, + // EventCost: &engine.EventCost{CGRID: "testCGRID"}, ExtraDuration: 1, LastUsage: time.Minute, TotalUsage: 3 * time.Minute, @@ -589,14 +557,14 @@ func TestDebitSessionResponderMaxDebitError(t *testing.T) { } engine.Cache.Clear(nil) - sMock.calls[utils.SchedulerSv1ExecuteActionPlans] = func(args interface{}, reply interface{}) error { - return utils.ErrNotImplemented - } + // sMock.calls[utils.SchedulerSv1ExecuteActionPlans] = func(args interface{}, reply interface{}) error { + // return utils.ErrNotImplemented + // } newInternalRpcChan := make(chan rpcclient.ClientConnector, 1) newInternalRpcChan <- sMock connMgr = engine.NewConnManager(cfg, map[string]chan rpcclient.ClientConnector{ - utils.ConcatenatedKey(utils.MetaInternal, utils.MetaRALs): internalRpcChan, - utils.ConcatenatedKey(utils.MetaInternal, utils.MetaScheduler): internalRpcChan}) + utils.ConcatenatedKey(utils.MetaInternal, utils.MetaRALs): internalRpcChan, + utils.ConcatenatedKey(utils.MetaInternal, utils.MetaActions): internalRpcChan}) dm = engine.NewDataManager(data, cfg.CacheCfg(), connMgr) sessions = NewSessionS(cfg, dm, connMgr) @@ -626,8 +594,8 @@ func TestInitSessionDebitLoops(t *testing.T) { Event: map[string]interface{}{ utils.RequestType: utils.MetaPrepaid, }, - CD: &engine.CallDescriptor{Category: "test"}, - EventCost: &engine.EventCost{CGRID: "testCGRID"}, + // CD: &engine.CallDescriptor{Category: "test"}, + // EventCost: &engine.EventCost{CGRID: "testCGRID"}, ExtraDuration: 1, LastUsage: time.Minute, TotalUsage: 3 * time.Minute, @@ -657,7 +625,7 @@ func TestDebitLoopSessionErrorDebiting(t *testing.T) { cfg.GeneralCfg().NodeID = "ClientConnIdtest" cfg.SessionSCfg().TerminateAttempts = 1 cfg.SessionSCfg().RALsConns = []string{utils.ConcatenatedKey(utils.MetaInternal, utils.MetaRALs)} - cfg.SessionSCfg().SchedulerConns = []string{utils.ConcatenatedKey(utils.MetaInternal, utils.MetaScheduler)} + // cfg.SessionSCfg().SchedulerConns = []string{utils.ConcatenatedKey(utils.MetaInternal, utils.MetaActions)} data := engine.NewInternalDB(nil, nil, true) dm := engine.NewDataManager(data, cfg.CacheCfg(), nil) sessions := NewSessionS(cfg, dm, nil) @@ -673,8 +641,8 @@ func TestDebitLoopSessionErrorDebiting(t *testing.T) { Event: map[string]interface{}{ utils.RequestType: utils.MetaDynaprepaid, }, - CD: &engine.CallDescriptor{Category: "test"}, - EventCost: &engine.EventCost{CGRID: "testCGRID"}, + // CD: &engine.CallDescriptor{Category: "test"}, + // EventCost: &engine.EventCost{CGRID: "testCGRID"}, ExtraDuration: 1, LastUsage: time.Minute, TotalUsage: 3 * time.Minute, @@ -694,19 +662,19 @@ func TestDebitLoopSessionErrorDebiting(t *testing.T) { engine.Cache.Clear(nil) sMock := &testMockClients{ calls: map[string]func(args interface{}, reply interface{}) error{ - utils.ResponderMaxDebit: func(args interface{}, reply interface{}) error { - return utils.ErrAccountNotFound - }, - utils.SchedulerSv1ExecuteActionPlans: func(args interface{}, reply interface{}) error { - return utils.ErrUnauthorizedDestination - }, + // utils.ResponderMaxDebit: func(args interface{}, reply interface{}) error { + // return utils.ErrAccountNotFound + // }, + // utils.SchedulerSv1ExecuteActionPlans: func(args interface{}, reply interface{}) error { + // return utils.ErrUnauthorizedDestination + // }, }, } internalRpcChan := make(chan rpcclient.ClientConnector, 1) internalRpcChan <- sMock connMgr := engine.NewConnManager(cfg, map[string]chan rpcclient.ClientConnector{ - utils.ConcatenatedKey(utils.MetaInternal, utils.MetaRALs): internalRpcChan, - utils.ConcatenatedKey(utils.MetaInternal, utils.MetaScheduler): internalRpcChan}) + utils.ConcatenatedKey(utils.MetaInternal, utils.MetaRALs): internalRpcChan, + utils.ConcatenatedKey(utils.MetaInternal, utils.MetaActions): internalRpcChan}) dm = engine.NewDataManager(data, cfg.CacheCfg(), connMgr) sessions = NewSessionS(cfg, dm, connMgr) @@ -899,7 +867,7 @@ func TestDebitLoopSessionLowBalance(t *testing.T) { //}() //time.Sleep(1 * time.Second) } -*/ +* / func TestDebitLoopSessionWarningSessions(t *testing.T) { log.SetOutput(io.Discard) @@ -4487,6 +4455,6 @@ func TestBiRPCv1GetCost(t *testing.T) { fmt.Printf("%T and %T \n", expectedVal.EventCost.Cost, reply.EventCost.Cost) t.Errorf("Expected %+v \n, received %+v", utils.ToJSON(expectedVal), utils.ToJSON(reply)) } - - */ + * / } +*/