diff --git a/accounts/accounts.go b/accounts/accounts.go index ee83b43bd..042d42286 100644 --- a/accounts/accounts.go +++ b/accounts/accounts.go @@ -62,7 +62,8 @@ func (aS *AccountS) Shutdown() { // matchingAccountsForEvent returns the matched Accounts for the given event // if lked option is passed, each Account will be also locked -// so it becomes responsibility of upper layers to release the lock +// +// so it becomes responsibility of upper layers to release the lock func (aS *AccountS) matchingAccountsForEvent(ctx *context.Context, tnt string, cgrEv *utils.CGREvent, acntIDs []string, ignoreFilters, lked bool) (acnts utils.AccountsWithWeight, err error) { evNm := utils.MapStorage{ diff --git a/agents/agentreq.go b/agents/agentreq.go index 2b1ca8ade..ee55dd5c1 100644 --- a/agents/agentreq.go +++ b/agents/agentreq.go @@ -189,7 +189,7 @@ func (ar *AgentRequest) FieldAsString(fldPath []string) (val string, err error) return utils.IfaceAsString(iface), nil } -//SetFields will populate fields of AgentRequest out of templates +// SetFields will populate fields of AgentRequest out of templates func (ar *AgentRequest) SetFields(tplFlds []*config.FCTemplate) (err error) { ar.tmp = &utils.DataNode{Type: utils.NMMapType, Map: make(map[string]*utils.DataNode)} for _, tplFld := range tplFlds { diff --git a/agents/kamevent.go b/agents/kamevent.go index 8ae02e7cc..882458971 100644 --- a/agents/kamevent.go +++ b/agents/kamevent.go @@ -276,8 +276,8 @@ func (kev KamEvent) AsKamProcessMessageEmptyReply() (kar *KamReply) { return } -//KamReply will be used to send back to kamailio from -//Authrization,ProcessEvent and ProcessEvent empty (pingPong) +// KamReply will be used to send back to kamailio from +// Authrization,ProcessEvent and ProcessEvent empty (pingPong) type KamReply struct { Event string // Kamailio will use this to differentiate between requests and replies TransactionIndex string // Original transaction index diff --git a/agents/libdiam.go b/agents/libdiam.go index 66cee7f80..17974cde4 100644 --- a/agents/libdiam.go +++ b/agents/libdiam.go @@ -210,7 +210,8 @@ func updateAVPLength(avps []*diam.AVP) (l int) { } // messageAddAVPsWithPath will dynamically add AVPs into the message -// append: append to the message, on false overwrite if AVP is single or add to group if AVP is Grouped +// +// append: append to the message, on false overwrite if AVP is single or add to group if AVP is Grouped func messageSetAVPsWithPath(m *diam.Message, pathStr []string, avpValStr string, newBranch bool, tmz string) (err error) { if len(pathStr) == 0 { diff --git a/agents/librad.go b/agents/librad.go index 1ba66d5bb..e05aacc0f 100644 --- a/agents/librad.go +++ b/agents/librad.go @@ -100,7 +100,7 @@ func (pk *radiusDP) FieldAsString(fldPath []string) (data string, err error) { return utils.IfaceAsString(valIface), nil } -//radauthReq is used to authorize a request based on flags +// radauthReq is used to authorize a request based on flags func radauthReq(flags utils.FlagsWithParams, req *radigo.Packet, aReq *AgentRequest, rpl *radigo.Packet) (bool, error) { // try to get UserPassword from Vars as slice of NMItems nmItems, has := aReq.Vars.Map[utils.UserPassword] diff --git a/analyzers/analyzers_it_test.go b/analyzers/analyzers_it_test.go index 8ce38b516..237cea022 100644 --- a/analyzers/analyzers_it_test.go +++ b/analyzers/analyzers_it_test.go @@ -84,7 +84,7 @@ func newRPCClient(cfg *config.ListenCfg) (c *rpc.Client, err error) { } } -//Test start here +// Test start here func TestAnalyzerSIT(t *testing.T) { for _, stest := range sTestsAlsPrf { t.Run("TestAnalyzerSIT", stest) diff --git a/apis/accounts.go b/apis/accounts.go index 4af2741ac..9a9a4d627 100644 --- a/apis/accounts.go +++ b/apis/accounts.go @@ -115,7 +115,7 @@ func (admS *AdminSv1) GetAccountsCount(ctx *context.Context, args *utils.ArgsIte return } -//SetAccount add/update a new Account +// SetAccount add/update a new Account func (admS *AdminSv1) SetAccount(ctx *context.Context, args *utils.AccountWithAPIOpts, reply *string) error { if missing := utils.MissingStructFields(args.Account, []string{utils.ID}); len(missing) != 0 { return utils.NewErrMandatoryIeMissing(missing...) diff --git a/apis/accounts_it_test.go b/apis/accounts_it_test.go index b62c101c2..42b968684 100644 --- a/apis/accounts_it_test.go +++ b/apis/accounts_it_test.go @@ -1953,7 +1953,7 @@ func testAccDebitAbstractWithBlockersOnBalance(t *testing.T) { } } -//Kill the engine when it is about to be finished +// Kill the engine when it is about to be finished func testAccSKillEngine(t *testing.T) { if err := engine.KillEngine(100); err != nil { t.Error(err) diff --git a/apis/actions.go b/apis/actions.go index 1c412cee6..56c3b3b1d 100644 --- a/apis/actions.go +++ b/apis/actions.go @@ -116,7 +116,7 @@ func (admS *AdminSv1) GetActionProfilesCount(ctx *context.Context, args *utils.A return } -//SetActionProfile add/update a new Action Profile +// SetActionProfile add/update a new Action Profile func (admS *AdminSv1) SetActionProfile(ctx *context.Context, ap *engine.ActionProfileWithAPIOpts, reply *string) error { if missing := utils.MissingStructFields(ap.ActionProfile, []string{utils.ID, utils.Actions}); len(missing) != 0 { return utils.NewErrMandatoryIeMissing(missing...) diff --git a/apis/actions_it_test.go b/apis/actions_it_test.go index 06861c651..e7d048284 100644 --- a/apis/actions_it_test.go +++ b/apis/actions_it_test.go @@ -144,7 +144,7 @@ func testActionsRPCConn(t *testing.T) { } } -//Kill the engine when it is about to be finished +// Kill the engine when it is about to be finished func testActionsKillEngine(t *testing.T) { if err := engine.KillEngine(100); err != nil { t.Error(err) diff --git a/apis/attributes.go b/apis/attributes.go index 911952c62..2104db394 100644 --- a/apis/attributes.go +++ b/apis/attributes.go @@ -114,7 +114,7 @@ func (admS *AdminSv1) GetAttributeProfilesCount(ctx *context.Context, args *util return } -//SetAttributeProfile add/update a new Attribute Profile +// SetAttributeProfile add/update a new Attribute Profile func (admS *AdminSv1) SetAttributeProfile(ctx *context.Context, arg *engine.APIAttributeProfileWithAPIOpts, reply *string) error { if missing := utils.MissingStructFields(arg.APIAttributeProfile, []string{utils.ID}); len(missing) != 0 { return utils.NewErrMandatoryIeMissing(missing...) diff --git a/apis/attributes_it_test.go b/apis/attributes_it_test.go index 7145c6616..4f7347ed8 100644 --- a/apis/attributes_it_test.go +++ b/apis/attributes_it_test.go @@ -2183,7 +2183,7 @@ func testAttributeSCheckIndexesRemoveAttributeProfile(t *testing.T) { } } -//Kill the engine when it is about to be finished +// Kill the engine when it is about to be finished func testAttributesKillEngine(t *testing.T) { if err := engine.KillEngine(100); err != nil { t.Error(err) diff --git a/apis/cache_it_test.go b/apis/cache_it_test.go index ff4dc15c7..f87954f92 100644 --- a/apis/cache_it_test.go +++ b/apis/cache_it_test.go @@ -112,7 +112,7 @@ func testCacheSRpcConn(t *testing.T) { } } -//Set an attribute profile and rate profile to test cache's apis +// Set an attribute profile and rate profile to test cache's apis func testCacheSSetAttributeProfile(t *testing.T) { attrPrf := &engine.APIAttributeProfileWithAPIOpts{ APIAttributeProfile: &engine.APIAttributeProfile{ diff --git a/apis/chargers.go b/apis/chargers.go index c80782cda..1d72a6a9d 100644 --- a/apis/chargers.go +++ b/apis/chargers.go @@ -118,7 +118,7 @@ type ChargerWithAPIOpts struct { APIOpts map[string]interface{} } -//SetChargerProfile add/update a new Charger Profile +// SetChargerProfile add/update a new Charger Profile func (adms *AdminSv1) SetChargerProfile(ctx *context.Context, arg *ChargerWithAPIOpts, reply *string) error { if missing := utils.MissingStructFields(arg.ChargerProfile, []string{utils.ID}); len(missing) != 0 { return utils.NewErrMandatoryIeMissing(missing...) @@ -142,7 +142,7 @@ func (adms *AdminSv1) SetChargerProfile(ctx *context.Context, arg *ChargerWithAP return nil } -//RemoveChargerProfile remove a specific Charger Profile +// RemoveChargerProfile remove a specific Charger Profile func (adms *AdminSv1) RemoveChargerProfile(ctx *context.Context, arg *utils.TenantIDWithAPIOpts, reply *string) error { if missing := utils.MissingStructFields(arg, []string{utils.ID}); len(missing) != 0 { //Params missing return utils.NewErrMandatoryIeMissing(missing...) diff --git a/apis/chargers_it_test.go b/apis/chargers_it_test.go index 4994ca4df..48ac256a1 100644 --- a/apis/chargers_it_test.go +++ b/apis/chargers_it_test.go @@ -1005,7 +1005,7 @@ func testChargersBlockerGetChargersForEvent(t *testing.T) { } } -//Kill the engine when it is about to be finished +// Kill the engine when it is about to be finished func testChargersSKillEngine(t *testing.T) { if err := engine.KillEngine(100); err != nil { t.Error(err) diff --git a/apis/dispatchers.go b/apis/dispatchers.go index a994dddaf..f7e8b186e 100644 --- a/apis/dispatchers.go +++ b/apis/dispatchers.go @@ -117,7 +117,7 @@ type DispatcherWithAPIOpts struct { APIOpts map[string]interface{} } -//SetDispatcherProfile add/update a new Dispatcher Profile +// SetDispatcherProfile add/update a new Dispatcher Profile func (admS *AdminSv1) SetDispatcherProfile(ctx *context.Context, args *DispatcherWithAPIOpts, reply *string) error { if missing := utils.MissingStructFields(args.DispatcherProfile, []string{utils.ID}); len(missing) != 0 { return utils.NewErrMandatoryIeMissing(missing...) @@ -141,7 +141,7 @@ func (admS *AdminSv1) SetDispatcherProfile(ctx *context.Context, args *Dispatche return nil } -//RemoveDispatcherProfile remove a specific Dispatcher Profile +// RemoveDispatcherProfile remove a specific Dispatcher Profile func (admS *AdminSv1) RemoveDispatcherProfile(ctx *context.Context, arg *utils.TenantIDWithAPIOpts, reply *string) error { if missing := utils.MissingStructFields(arg, []string{utils.ID}); len(missing) != 0 { //Params missing return utils.NewErrMandatoryIeMissing(missing...) @@ -253,7 +253,7 @@ func (admS *AdminSv1) GetDispatcherHostsCount(ctx *context.Context, args *utils. return } -//SetDispatcherHost add/update a new Dispatcher Host +// SetDispatcherHost add/update a new Dispatcher Host func (admS *AdminSv1) SetDispatcherHost(ctx *context.Context, args *engine.DispatcherHostWithAPIOpts, reply *string) error { if missing := utils.MissingStructFields(args.DispatcherHost, []string{utils.ID}); len(missing) != 0 { return utils.NewErrMandatoryIeMissing(missing...) @@ -277,7 +277,7 @@ func (admS *AdminSv1) SetDispatcherHost(ctx *context.Context, args *engine.Dispa return nil } -//RemoveDispatcherHost remove a specific Dispatcher Host +// RemoveDispatcherHost remove a specific Dispatcher Host func (admS *AdminSv1) RemoveDispatcherHost(ctx *context.Context, arg *utils.TenantIDWithAPIOpts, reply *string) error { if missing := utils.MissingStructFields(arg, []string{utils.ID}); len(missing) != 0 { //Params missing return utils.NewErrMandatoryIeMissing(missing...) diff --git a/apis/filters.go b/apis/filters.go index a465cb608..4dfd7f311 100644 --- a/apis/filters.go +++ b/apis/filters.go @@ -36,7 +36,7 @@ func validateFilterRules(rules []*engine.FilterRule) error { return nil } -//SetFilter add a new Filter +// SetFilter add a new Filter func (adms *AdminSv1) SetFilter(ctx *context.Context, arg *engine.FilterWithAPIOpts, reply *string) (err error) { if missing := utils.MissingStructFields(arg.Filter, []string{utils.ID}); len(missing) != 0 { return utils.NewErrMandatoryIeMissing(missing...) @@ -81,7 +81,7 @@ func (adms *AdminSv1) SetFilter(ctx *context.Context, arg *engine.FilterWithAPIO return } -//GetFilter returns a Filter +// GetFilter returns a Filter func (adms *AdminSv1) GetFilter(ctx *context.Context, arg *utils.TenantIDWithAPIOpts, reply *engine.Filter) error { if missing := utils.MissingStructFields(arg, []string{utils.ID}); len(missing) != 0 { //Params missing return utils.NewErrMandatoryIeMissing(missing...) @@ -147,7 +147,7 @@ func (adms *AdminSv1) GetFilterIDs(ctx *context.Context, args *utils.ArgsItemIDs return } -//RemoveFilter remove a specific filter +// RemoveFilter remove a specific filter func (adms *AdminSv1) RemoveFilter(ctx *context.Context, arg *utils.TenantIDWithAPIOpts, reply *string) error { if missing := utils.MissingStructFields(arg, []string{utils.ID}); len(missing) != 0 { //Params missing return utils.NewErrMandatoryIeMissing(missing...) diff --git a/apis/filters_it_test.go b/apis/filters_it_test.go index 40b45c476..cef1f5f8c 100644 --- a/apis/filters_it_test.go +++ b/apis/filters_it_test.go @@ -742,7 +742,7 @@ func testFiltersFiltersMatchFalse(t *testing.T) { } } -//Kill the engine when it is about to be finished +// Kill the engine when it is about to be finished func testFiltersKillEngine(t *testing.T) { if err := engine.KillEngine(100); err != nil { t.Error(err) diff --git a/apis/indexes_after_load_it_test.go b/apis/indexes_after_load_it_test.go index 87cdfc066..c85a4cc47 100644 --- a/apis/indexes_after_load_it_test.go +++ b/apis/indexes_after_load_it_test.go @@ -179,7 +179,7 @@ func testIdxLoadCheckIndexes(t *testing.T) { } } -//Kill the engine when it is about to be finished +// Kill the engine when it is about to be finished func testIdxLoadKillEngine(t *testing.T) { if err := engine.KillEngine(100); err != nil { t.Error(err) diff --git a/apis/loaders_it_test.go b/apis/loaders_it_test.go index 43506eef8..9e1060975 100644 --- a/apis/loaders_it_test.go +++ b/apis/loaders_it_test.go @@ -137,7 +137,7 @@ func testLoadersRPCConn(t *testing.T) { } } -//Kill the engine when it is about to be finished +// Kill the engine when it is about to be finished func testLoadersKillEngine(t *testing.T) { if err := engine.KillEngine(100); err != nil { t.Error(err) diff --git a/apis/rates_it_test.go b/apis/rates_it_test.go index 454fa1d53..0421900ac 100644 --- a/apis/rates_it_test.go +++ b/apis/rates_it_test.go @@ -2692,7 +2692,7 @@ func testRateSPaginateGetRateProfile3(t *testing.T) { } } -//Kill the engine when it is about to be finished +// Kill the engine when it is about to be finished func testRateSKillEngine(t *testing.T) { if err := engine.KillEngine(100); err != nil { t.Error(err) diff --git a/apis/resources.go b/apis/resources.go index c199d3ae4..59d3550df 100644 --- a/apis/resources.go +++ b/apis/resources.go @@ -112,7 +112,7 @@ func (admS *AdminSv1) GetResourceProfilesCount(ctx *context.Context, args *utils return } -//SetResourceProfile adds a new resource configuration +// SetResourceProfile adds a new resource configuration func (adms *AdminSv1) SetResourceProfile(ctx *context.Context, arg *engine.ResourceProfileWithAPIOpts, reply *string) (err error) { if missing := utils.MissingStructFields(arg.ResourceProfile, []string{utils.ID}); len(missing) != 0 { return utils.NewErrMandatoryIeMissing(missing...) @@ -140,7 +140,7 @@ func (adms *AdminSv1) SetResourceProfile(ctx *context.Context, arg *engine.Resou return nil } -//RemoveResourceProfile remove a specific resource configuration +// RemoveResourceProfile remove a specific resource configuration func (adms *AdminSv1) RemoveResourceProfile(ctx *context.Context, arg *utils.TenantIDWithAPIOpts, reply *string) error { if missing := utils.MissingStructFields(arg, []string{utils.ID}); len(missing) != 0 { //Params missing return utils.NewErrMandatoryIeMissing(missing...) diff --git a/apis/resources_it_test.go b/apis/resources_it_test.go index 5e1c23931..34b0bb2a3 100644 --- a/apis/resources_it_test.go +++ b/apis/resources_it_test.go @@ -138,7 +138,7 @@ func testResourceSRPCConn(t *testing.T) { } } -//Kill the engine when it is about to be finished +// Kill the engine when it is about to be finished func testResourceSKillEngine(t *testing.T) { if err := engine.KillEngine(100); err != nil { t.Error(err) diff --git a/apis/routes.go b/apis/routes.go index 8c316e7e7..8c9afcb39 100644 --- a/apis/routes.go +++ b/apis/routes.go @@ -112,7 +112,7 @@ func (adms *AdminSv1) GetRouteProfilesCount(ctx *context.Context, args *utils.Ar return } -//SetRouteProfile add a new Route configuration +// SetRouteProfile add a new Route configuration func (adms *AdminSv1) SetRouteProfile(ctx *context.Context, args *engine.RouteProfileWithAPIOpts, reply *string) error { if missing := utils.MissingStructFields(args.RouteProfile, []string{utils.ID}); len(missing) != 0 { return utils.NewErrMandatoryIeMissing(missing...) @@ -139,7 +139,7 @@ func (adms *AdminSv1) SetRouteProfile(ctx *context.Context, args *engine.RoutePr return nil } -//RemoveRouteProfile remove a specific Route configuration +// RemoveRouteProfile remove a specific Route configuration func (adms *AdminSv1) RemoveRouteProfile(ctx *context.Context, args *utils.TenantIDWithAPIOpts, reply *string) error { if missing := utils.MissingStructFields(args, []string{utils.ID}); len(missing) != 0 { //Params missing return utils.NewErrMandatoryIeMissing(missing...) diff --git a/apis/routes_it_test.go b/apis/routes_it_test.go index f1545baa7..8810039ce 100644 --- a/apis/routes_it_test.go +++ b/apis/routes_it_test.go @@ -1041,7 +1041,7 @@ func testRoutesBlockerGetRoutes(t *testing.T) { } } -//Kill the engine when it is about to be finished +// Kill the engine when it is about to be finished func testRoutesKillEngine(t *testing.T) { if err := engine.KillEngine(100); err != nil { t.Error(err) diff --git a/apis/stats_it_test.go b/apis/stats_it_test.go index e43ac3fe9..0f2cf8916 100644 --- a/apis/stats_it_test.go +++ b/apis/stats_it_test.go @@ -128,7 +128,7 @@ func testStatsRPCConn(t *testing.T) { } } -//Kill the engine when it is about to be finished +// Kill the engine when it is about to be finished func testStatsKillEngine(t *testing.T) { if err := engine.KillEngine(100); err != nil { t.Error(err) diff --git a/apis/thresholds_it_test.go b/apis/thresholds_it_test.go index 8f821dd0d..20b9f3c40 100644 --- a/apis/thresholds_it_test.go +++ b/apis/thresholds_it_test.go @@ -120,7 +120,7 @@ func testThresholdsRPCConn(t *testing.T) { } } -//Kill the engine when it is about to be finished +// Kill the engine when it is about to be finished func testThresholdsKillEngine(t *testing.T) { if err := engine.KillEngine(100); err != nil { t.Error(err) diff --git a/apis/tpes_it_test.go b/apis/tpes_it_test.go index bb24551dd..2f21f6f5b 100644 --- a/apis/tpes_it_test.go +++ b/apis/tpes_it_test.go @@ -1400,7 +1400,7 @@ func testTPeSExportAfterFlush(t *testing.T) { } } -//Kill the engine when it is about to be finished +// Kill the engine when it is about to be finished func testTPeSKillEngine(t *testing.T) { if err := engine.KillEngine(100); err != nil { t.Error(err) diff --git a/cmd/cgr-loader/cgr-loader_remove_it_test.go b/cmd/cgr-loader/cgr-loader_remove_it_test.go index 18478193d..5ffdeb5b3 100644 --- a/cmd/cgr-loader/cgr-loader_remove_it_test.go +++ b/cmd/cgr-loader/cgr-loader_remove_it_test.go @@ -708,7 +708,7 @@ func testCgrLdrRemoveData(t *testing.T) { } } -//Kill the engine when it is about to be finished +// Kill the engine when it is about to be finished func testCgrLdrKillEngine(t *testing.T) { if err := engine.KillEngine(100); err != nil { t.Error(err) diff --git a/config/apis.go b/config/apis.go index 98b1f6893..95afc83c0 100644 --- a/config/apis.go +++ b/config/apis.go @@ -199,7 +199,7 @@ func (cfg *CGRConfig) V1SetConfig(ctx *context.Context, args *SetConfigArgs, rep return } -//V1GetConfigAsJSON will retrieve from CGRConfig a section as a string +// V1GetConfigAsJSON will retrieve from CGRConfig a section as a string func (cfg *CGRConfig) V1GetConfigAsJSON(ctx *context.Context, args *SectionWithAPIOpts, reply *string) (err error) { var mp map[string]interface{} if err = cfg.V1GetConfig(ctx, args, &mp); err != nil { diff --git a/config/rjreader.go b/config/rjreader.go index ad3dcba01..34752a1d9 100644 --- a/config/rjreader.go +++ b/config/rjreader.go @@ -54,7 +54,7 @@ func isWhiteSpace(c byte) bool { return c == ' ' || c == '\t' || isNewLine(c) || c == 0 } -//ReadEnv reads the enviorment variable +// ReadEnv reads the enviorment variable func ReadEnv(key string) (string, error) { //it shod print a warning not a error if env := os.Getenv(key); env != "" { return env, nil @@ -166,7 +166,7 @@ func (rjr *RjReader) consumeComent(pkbit byte) (bool, error) { return false, nil } -//readFirstNonWhiteSpace reads first non white space byte +// readFirstNonWhiteSpace reads first non white space byte func (rjr *RjReader) readFirstNonWhiteSpace() (bit byte, err error) { for !rjr.isEndOfFile() { bit = rjr.buf[rjr.indx] @@ -233,13 +233,13 @@ func (rjr *RjReader) PeekByteWC() (bit byte, err error) { return 0, io.EOF } -//checkMeta check if char mach with next char from MetaEnv if not reset the counting +// checkMeta check if char mach with next char from MetaEnv if not reset the counting func (rjr *RjReader) checkMeta() bool { return rjr.indx-1+len(utils.MetaEnv) < len(rjr.buf) && utils.MetaEnv == string(rjr.buf[rjr.indx-1:rjr.indx-1+len(utils.MetaEnv)]) } -//readEnvName reads the enviorment key +// readEnvName reads the enviorment key func (rjr *RjReader) readEnvName(indx int) (name []byte, endindx int) { //0 if not set for indx < len(rjr.buf) { //read byte by byte bit := rjr.buf[indx] @@ -252,7 +252,7 @@ func (rjr *RjReader) readEnvName(indx int) (name []byte, endindx int) { //0 if n return name, indx } -//replaceEnv replaces the EnvMeta and enviorment key with enviorment variable value in specific buffer +// replaceEnv replaces the EnvMeta and enviorment key with enviorment variable value in specific buffer func (rjr *RjReader) replaceEnv(startEnv int) error { midEnv := len(utils.MetaEnv) key, endEnv := rjr.readEnvName(startEnv + midEnv) diff --git a/cores/basic_auth.go b/cores/basic_auth.go index 2ff46aa67..31bf342aa 100644 --- a/cores/basic_auth.go +++ b/cores/basic_auth.go @@ -30,9 +30,9 @@ import ( // use provides a cleaner interface for chaining middleware for single routes. // Middleware functions are simple HTTP handlers (w http.ResponseWriter, r *http.Request) // -// r.HandleFunc("/login", use(loginHandler, rateLimit, csrf)) -// r.HandleFunc("/form", use(formHandler, csrf)) -// r.HandleFunc("/about", aboutHandler) +// r.HandleFunc("/login", use(loginHandler, rateLimit, csrf)) +// r.HandleFunc("/form", use(formHandler, csrf)) +// r.HandleFunc("/about", aboutHandler) // // From https://gist.github.com/elithrar/9146306 // See https://gist.github.com/elithrar/7600878#comment-955958 for how to extend it to suit simple http.Handler's diff --git a/data/conf/cgrates/cgrates.json b/data/conf/cgrates/cgrates.json index 3c3d0ba8c..043e03c73 100755 --- a/data/conf/cgrates/cgrates.json +++ b/data/conf/cgrates/cgrates.json @@ -50,7 +50,7 @@ // "opts": { // "kafka_conn": "", // the connection trough kafka // "kafka_topic": "", // the topic from where the events are exported -// "attempts": 1, // number of attempts of connecting +// "kafka_attempts": 1, // number of attempts of connecting // "failed_posts_dir": "/var/spool/cgrates/failed_posts" // path where fail logs are exported // }, // }, @@ -492,8 +492,8 @@ // // SQL // // "sqlMaxIdleConns": 0, // SQLMaxIdleConns // // "sqlMaxOpenConns": 0, // SQLMaxOpenConns -// // "sqlConnMaxLifetime": "0", // SQLConnMaxLifetime -// // "mysqlDSNParams": {}, // DSN params +// // "sqlConnMaxLifetime": "0", // SQLConnMaxLifetime +// // "mysqlDSNParams": {}, // DSN params // // "sqlTableName":"cdrs", // the name of the table from where the events are exported @@ -503,6 +503,8 @@ // // Kafka // // "kafkaTopic": "cgrates", // the topic from where the events are exported +// // "kafkaCAPath": "", // path to certificate authority pem file +// // "kafkaSkipTLSVerify": false, // if set to true it will skip certificate verification // // AMQP @@ -1495,6 +1497,15 @@ // "notexists_indexed_fields": [], // query indexes based on these fields for faster processing // "nested_fields": false, // determines which field is checked when matching indexed filters(true: all; false: only the one on the first level) // "attributes_conns": [], // connections to AttributeS for API authorization, empty to disable auth functionality: <""|*internal|$rpc_conns_id> +// "opts": { // +// // "*dispatcherS": [ +// // { +// // "Tenant": "*any", +// // "FilterIDs": [], +// // "Value": false, +// // }, +// // ], +// }, // }, @@ -1730,7 +1741,7 @@ // "notexists_indexed_fields": [], // query indexes based on these fields for faster processing // "nested_fields": false, // determines which field is checked when matching indexed filters(true: all; false: only the one on the first level) // "dynaprepaid_actionprofile": [], // -// "opts":{ // +// "opts":{ // // "*profileIDs": [ // // { // // "Tenant": "*any", @@ -1738,12 +1749,19 @@ // // "Value": [], // // }, // // ], -// // "*profileIgnoreFilters": [ // ignore the filters for actionProfileIDs +// // "*profileIgnoreFilters": [ // ignore the filters for actionProfileIDs // // { // // "Tenant": "*any", // // "FilterIDs": [], // // "Value": false, // // }, +// // ], +// // "*posterAttempts": [ // poster attempts for HTTPPost action type +// // { +// // "Tenant": "*any", +// // "FilterIDs": [], +// // "Value": 1, +// // }, // // ], // }, // }, diff --git a/data/conf/samples/ees/cgrates.json b/data/conf/samples/ees/cgrates.json index b722c9fcc..e648bb04d 100644 --- a/data/conf/samples/ees/cgrates.json +++ b/data/conf/samples/ees/cgrates.json @@ -515,10 +515,11 @@ { "id": "KafkaExporter", "type": "*kafkaJSONMap", - "export_path": "localhost:9092", + "export_path": "localhost:9093", "concurrent_requests": 0, "opts": { - "kafkaTopic": "cgrates" + "kafkaTopic": "cgrates", + "kafkaCAPath": "/home/kafka/kafka/ssl/ca-cert.pem" }, "timezone": "", "filters": [], diff --git a/dispatchers/accounts_it_test.go b/dispatchers/accounts_it_test.go index e1c724494..5d2579010 100644 --- a/dispatchers/accounts_it_test.go +++ b/dispatchers/accounts_it_test.go @@ -31,7 +31,7 @@ var sTestsDspAccPrf = []func(t *testing.T){ testDspAccPrfPing, } -//Test start here +// Test start here func TestDspAccountSIT(t *testing.T) { var config1, config2, config3 string switch *dbType { diff --git a/dispatchers/actions_it_test.go b/dispatchers/actions_it_test.go index dcd7242cc..53028d0b3 100644 --- a/dispatchers/actions_it_test.go +++ b/dispatchers/actions_it_test.go @@ -31,7 +31,7 @@ var sTestsDspActPrf = []func(t *testing.T){ testDspActPrfPing, } -//Test start here +// Test start here func TestDspActionSIT(t *testing.T) { var config1, config2, config3 string switch *dbType { diff --git a/dispatchers/attributes_it_test.go b/dispatchers/attributes_it_test.go index f87bed051..b285f0526 100644 --- a/dispatchers/attributes_it_test.go +++ b/dispatchers/attributes_it_test.go @@ -48,7 +48,7 @@ var sTestsDspAttr = []func(t *testing.T){ testDspAttrGetAttrInternal, } -//Test start here +// Test start here func TestDspAttributeS(t *testing.T) { var config1, config2, config3 string switch *dbType { diff --git a/dispatchers/caches_it_test.go b/dispatchers/caches_it_test.go index 6f1142ab2..a460189b2 100644 --- a/dispatchers/caches_it_test.go +++ b/dispatchers/caches_it_test.go @@ -44,7 +44,7 @@ var sTestsDspChc = []func(t *testing.T){ testDspChcClear, } -//Test start here +// Test start here func TestDspCacheSv1(t *testing.T) { var config1, config2, config3 string switch *dbType { diff --git a/dispatchers/chargers_it_test.go b/dispatchers/chargers_it_test.go index 1b21ecbf4..672423a08 100644 --- a/dispatchers/chargers_it_test.go +++ b/dispatchers/chargers_it_test.go @@ -41,7 +41,7 @@ var sTestsDspCpp = []func(t *testing.T){ testDspCppTestAuthKey2, } -//Test start here +// Test start here func TestDspChargerST(t *testing.T) { var config1, config2, config3 string switch *dbType { diff --git a/dispatchers/config_it_test.go b/dispatchers/config_it_test.go index 1afdfd88b..821f62118 100644 --- a/dispatchers/config_it_test.go +++ b/dispatchers/config_it_test.go @@ -33,7 +33,7 @@ var sTestsDspConfig = []func(t *testing.T){ testDspConfigSv1GetJSONSection, } -//Test start here +// Test start here func TestDspConfigIT(t *testing.T) { var config1, config2, config3 string switch *dbType { diff --git a/dispatchers/guardian_it_test.go b/dispatchers/guardian_it_test.go index 93b3c9d98..762f7df17 100644 --- a/dispatchers/guardian_it_test.go +++ b/dispatchers/guardian_it_test.go @@ -35,7 +35,7 @@ var sTestsDspGrd = []func(t *testing.T){ testDspGrdLock, } -//Test start here +// Test start here func TestDspGuardianST(t *testing.T) { var config1, config2, config3 string switch *dbType { diff --git a/dispatchers/rates_it_test.go b/dispatchers/rates_it_test.go index 94942951c..dee79af6c 100644 --- a/dispatchers/rates_it_test.go +++ b/dispatchers/rates_it_test.go @@ -34,7 +34,7 @@ var sTestsDspRPrf = []func(t *testing.T){ testDspRPrfCostForEventWithoutFilters, } -//Test start here +// Test start here func TestDspRateSIT(t *testing.T) { var config1, config2, config3 string switch *dbType { diff --git a/dispatchers/replicator_it_test.go b/dispatchers/replicator_it_test.go index 464ad2d92..a65405b24 100644 --- a/dispatchers/replicator_it_test.go +++ b/dispatchers/replicator_it_test.go @@ -49,7 +49,7 @@ var sTestsDspRpl = []func(t *testing.T){ testDspRplActionProfile, } -//Test start here +// Test start here func TestDspReplicator(t *testing.T) { var config1, config2, config3 string switch *dbType { diff --git a/dispatchers/resources_it_test.go b/dispatchers/resources_it_test.go index 567eaca40..79b13ac82 100644 --- a/dispatchers/resources_it_test.go +++ b/dispatchers/resources_it_test.go @@ -38,7 +38,7 @@ var sTestsDspRes = []func(t *testing.T){ testDspResTestAuthKey3, } -//Test start here +// Test start here func TestDspResourceSIT(t *testing.T) { var config1, config2, config3 string switch *dbType { diff --git a/dispatchers/routes_it_test.go b/dispatchers/routes_it_test.go index f3fb35b19..1c62bf4c0 100644 --- a/dispatchers/routes_it_test.go +++ b/dispatchers/routes_it_test.go @@ -44,7 +44,7 @@ var ( } ) -//Test start here +// Test start here func TestDspSupplierS(t *testing.T) { var config1, config2, config3 string switch *dbType { diff --git a/dispatchers/sessions_it_test.go b/dispatchers/sessions_it_test.go index d73f2ad84..1f66ad27a 100644 --- a/dispatchers/sessions_it_test.go +++ b/dispatchers/sessions_it_test.go @@ -31,796 +31,256 @@ import ( ) /* -var sTestsDspSession = []func(t *testing.T){ - testDspSessionAddBalacne, + var sTestsDspSession = []func(t *testing.T){ + testDspSessionAddBalacne, - testDspSessionPingFailover, + testDspSessionPingFailover, - testDspSessionPing, - testDspSessionTestAuthKey, - testDspSessionAuthorize, - testDspSessionInit, - testDspGetSessions, - testDspSessionUpdate, - testDspSessionTerminate, - testDspSessionProcessCDR, - testDspSessionProcessEvent, - testDspSessionProcessEvent2, + testDspSessionPing, + testDspSessionTestAuthKey, + testDspSessionAuthorize, + testDspSessionInit, + testDspGetSessions, + testDspSessionUpdate, + testDspSessionTerminate, + testDspSessionProcessCDR, + testDspSessionProcessEvent, + testDspSessionProcessEvent2, - testDspSessionProcessEvent3, + testDspSessionProcessEvent3, - testDspSessionGetCost, - testDspSessionReplicate, - testDspSessionPassive, + testDspSessionGetCost, + testDspSessionReplicate, + testDspSessionPassive, - testDspSessionSTIRAuthenticate, - testDspSessionSTIRIdentity, - testDspSessionForceDisconect, -} + testDspSessionSTIRAuthenticate, + testDspSessionSTIRIdentity, + testDspSessionForceDisconect, + } //Test start here -func TestDspSessionS(t *testing.T) { - var config1, config2, config3 string - switch *dbType { - case utils.MetaInternal: - t.SkipNow() - case utils.MetaMySQL: - config1 = "all_mysql" - config2 = "all2_mysql" - config3 = "dispatchers_mysql" - case utils.MetaMongo: - config1 = "all_mongo" - config2 = "all2_mongo" - config3 = "dispatchers_mongo" - case utils.MetaPostgres: - t.SkipNow() - default: - t.Fatal("Unknown Database type") + + func TestDspSessionS(t *testing.T) { + var config1, config2, config3 string + switch *dbType { + case utils.MetaInternal: + t.SkipNow() + case utils.MetaMySQL: + config1 = "all_mysql" + config2 = "all2_mysql" + config3 = "dispatchers_mysql" + case utils.MetaMongo: + config1 = "all_mongo" + config2 = "all2_mongo" + config3 = "dispatchers_mongo" + case utils.MetaPostgres: + t.SkipNow() + default: + t.Fatal("Unknown Database type") + } + + dispDIR := "dispatchers" + if *encoding == utils.MetaGOB { + dispDIR += "_gob" + config3 += "_gob" + } + testDsp(t, sTestsDspSession, "TestDspSessionS", config1, config2, config3, "testit", "tutorial", dispDIR) } - dispDIR := "dispatchers" - if *encoding == utils.MetaGOB { - dispDIR += "_gob" - config3 += "_gob" + func testDspSessionAddBalacne(t *testing.T) { + initUsage := 40 * time.Minute + attrSetBalance := utils.AttrSetBalance{ + Tenant: "cgrates.org", + Account: "1001", + BalanceType: utils.MetaVoice, + Value: float64(initUsage), + Balance: map[string]interface{}{ + utils.ID: "SessionBalance", + utils.RatingSubject: "*zero5ms", + }, + } + var reply string + if err := allEngine.RPC.Call(utils.APIerSv2SetBalance, attrSetBalance, &reply); err != nil { + t.Error(err) + } else if reply != utils.OK { + t.Errorf("Received: %s", reply) + } + var acnt *engine.Account + attrs := &utils.AttrGetAccount{ + Tenant: attrSetBalance.Tenant, + Account: attrSetBalance.Account, + } + eAcntVal := float64(initUsage) + if err := allEngine.RPC.Call(utils.APIerSv2GetAccount, attrs, &acnt); err != nil { + t.Error(err) + } else if acnt.BalanceMap[utils.MetaVoice].GetTotalValue() != eAcntVal { + t.Errorf("Expecting: %v, received: %v", + time.Duration(eAcntVal), time.Duration(acnt.BalanceMap[utils.MetaVoice].GetTotalValue())) + } + if err := allEngine2.RPC.Call(utils.APIerSv2SetBalance, attrSetBalance, &reply); err != nil { + t.Error(err) + } else if reply != utils.OK { + t.Errorf("Received: %s", reply) + } + if err := allEngine2.RPC.Call(utils.APIerSv2GetAccount, attrs, &acnt); err != nil { + t.Error(err) + } else if acnt.BalanceMap[utils.MetaVoice].GetTotalValue() != eAcntVal { + t.Errorf("Expecting: %v, received: %v", + time.Duration(eAcntVal), time.Duration(acnt.BalanceMap[utils.MetaVoice].GetTotalValue())) + } } - testDsp(t, sTestsDspSession, "TestDspSessionS", config1, config2, config3, "testit", "tutorial", dispDIR) -} -func testDspSessionAddBalacne(t *testing.T) { - initUsage := 40 * time.Minute - attrSetBalance := utils.AttrSetBalance{ - Tenant: "cgrates.org", - Account: "1001", - BalanceType: utils.MetaVoice, - Value: float64(initUsage), - Balance: map[string]interface{}{ - utils.ID: "SessionBalance", - utils.RatingSubject: "*zero5ms", - }, - } - var reply string - if err := allEngine.RPC.Call(utils.APIerSv2SetBalance, attrSetBalance, &reply); err != nil { - t.Error(err) - } else if reply != utils.OK { - t.Errorf("Received: %s", reply) - } - var acnt *engine.Account - attrs := &utils.AttrGetAccount{ - Tenant: attrSetBalance.Tenant, - Account: attrSetBalance.Account, - } - eAcntVal := float64(initUsage) - if err := allEngine.RPC.Call(utils.APIerSv2GetAccount, attrs, &acnt); err != nil { - t.Error(err) - } else if acnt.BalanceMap[utils.MetaVoice].GetTotalValue() != eAcntVal { - t.Errorf("Expecting: %v, received: %v", - time.Duration(eAcntVal), time.Duration(acnt.BalanceMap[utils.MetaVoice].GetTotalValue())) - } - if err := allEngine2.RPC.Call(utils.APIerSv2SetBalance, attrSetBalance, &reply); err != nil { - t.Error(err) - } else if reply != utils.OK { - t.Errorf("Received: %s", reply) - } - if err := allEngine2.RPC.Call(utils.APIerSv2GetAccount, attrs, &acnt); err != nil { - t.Error(err) - } else if acnt.BalanceMap[utils.MetaVoice].GetTotalValue() != eAcntVal { - t.Errorf("Expecting: %v, received: %v", - time.Duration(eAcntVal), time.Duration(acnt.BalanceMap[utils.MetaVoice].GetTotalValue())) - } -} - -func testDspSessionPing(t *testing.T) { - var reply string - if err := allEngine.RPC.Call(utils.SessionSv1Ping, new(utils.CGREvent), &reply); err != nil { - t.Error(err) - } else if reply != utils.Pong { - t.Errorf("Received: %s", reply) - } - if err := dispEngine.RPC.Call(utils.SessionSv1Ping, &utils.CGREvent{ - Tenant: "cgrates.org", - - APIOpts: map[string]interface{}{ - utils.OptsAPIKey: "ses12345", - }, - }, &reply); err != nil { - t.Error(err) - } else if reply != utils.Pong { - t.Errorf("Received: %s", reply) - } -} - -func testDspSessionPingFailover(t *testing.T) { - var reply string - if err := allEngine.RPC.Call(utils.SessionSv1Ping, new(utils.CGREvent), &reply); err != nil { - t.Error(err) - } else if reply != utils.Pong { - t.Errorf("Received: %s", reply) - } - ev := &utils.CGREvent{ - Tenant: "cgrates.org", - - APIOpts: map[string]interface{}{ - utils.OptsAPIKey: "ses12345", - }, - } - if err := dispEngine.RPC.Call(utils.SessionSv1Ping, &ev, &reply); err != nil { - t.Error(err) - } else if reply != utils.Pong { - t.Errorf("Received: %s", reply) - } - allEngine.stopEngine(t) - if err := dispEngine.RPC.Call(utils.SessionSv1Ping, &ev, &reply); err != nil { - t.Error(err) - } else if reply != utils.Pong { - t.Errorf("Received: %s", reply) - } - allEngine2.stopEngine(t) - if err := dispEngine.RPC.Call(utils.SessionSv1Ping, &ev, &reply); err == nil { - t.Errorf("Expected error but received %v and reply %v\n", err, reply) - } - allEngine.startEngine(t) - allEngine2.startEngine(t) -} - -func testDspSessionTestAuthKey(t *testing.T) { - authUsage := 5 * time.Minute - args := sessions.V1AuthorizeArgs{ - GetMaxUsage: true, - AuthorizeResources: true, - GetRoutes: true, - GetAttributes: true, - CGREvent: &utils.CGREvent{ + func testDspSessionPing(t *testing.T) { + var reply string + if err := allEngine.RPC.Call(utils.SessionSv1Ping, new(utils.CGREvent), &reply); err != nil { + t.Error(err) + } else if reply != utils.Pong { + t.Errorf("Received: %s", reply) + } + if err := dispEngine.RPC.Call(utils.SessionSv1Ping, &utils.CGREvent{ Tenant: "cgrates.org", - ID: "TestSSv1ItAuth", - Event: map[string]interface{}{ - utils.Tenant: "cgrates.org", - utils.Category: "call", - utils.ToR: utils.MetaVoice, - utils.OriginID: "TestSSv1It1", - utils.RequestType: utils.MetaPrepaid, - utils.AccountField: "1001", - utils.Destination: "1002", - utils.SetupTime: time.Date(2018, time.January, 7, 16, 60, 0, 0, time.UTC), - utils.Usage: authUsage, - }, - - APIOpts: map[string]interface{}{ - utils.OptsAPIKey: "12345", - }, - }, - } - var rply sessions.V1AuthorizeReplyWithDigest - if err := dispEngine.RPC.Call(utils.SessionSv1AuthorizeEventWithDigest, - args, &rply); err == nil || err.Error() != utils.ErrUnauthorizedApi.Error() { - t.Error(err) - } -} - -func testDspSessionAuthorize(t *testing.T) { - authUsage := 5 * time.Minute - argsAuth := &sessions.V1AuthorizeArgs{ - GetMaxUsage: true, - AuthorizeResources: true, - GetRoutes: true, - GetAttributes: true, - CGREvent: &utils.CGREvent{ - Tenant: "cgrates.org", - ID: "TestSSv1ItAuth", - Event: map[string]interface{}{ - utils.CGRID: "c87609aa1cb6e9529ab1836cfeeebaab7aa7ebaf", - utils.Tenant: "cgrates.org", - utils.Category: "call", - utils.ToR: utils.MetaVoice, - utils.OriginID: "TestSSv1It1", - utils.RequestType: utils.MetaPrepaid, - utils.AccountField: "1001", - utils.Destination: "1002", - utils.SetupTime: time.Date(2018, time.January, 7, 16, 60, 0, 0, time.UTC), - utils.Usage: authUsage, - }, - - APIOpts: map[string]interface{}{ - utils.OptsAPIKey: "ses12345", - utils.OptsRoutesProfileCount: 1., - }, - }, - } - var rply sessions.V1AuthorizeReplyWithDigest - if err := dispEngine.RPC.Call(utils.SessionSv1AuthorizeEventWithDigest, - argsAuth, &rply); err != nil { - t.Error(err) - return - } - if rply.MaxUsage != authUsage.Seconds() { - t.Errorf("Unexpected MaxUsage: %v", rply.MaxUsage) - } - if *rply.ResourceAllocation == "" { - t.Errorf("Unexpected ResourceAllocation: %s", *rply.ResourceAllocation) - } - eSplrs := "route1,route2" - tp := strings.Split(*rply.RoutesDigest, ",") - sort.Strings(tp) - *rply.RoutesDigest = strings.Join(tp, ",") - if eSplrs != *rply.RoutesDigest { - t.Errorf("expecting: %v, received: %v", eSplrs, *rply.RoutesDigest) - } - eAttrs := "OfficeGroup:Marketing" - if eAttrs != *rply.AttributesDigest { - t.Errorf("expecting: %v, received: %v", eAttrs, *rply.AttributesDigest) - } -} - -func testDspSessionInit(t *testing.T) { - initUsage := 5 * time.Minute - argsInit := &sessions.V1InitSessionArgs{ - InitSession: true, - AllocateResources: true, - GetAttributes: true, - CGREvent: &utils.CGREvent{ - Tenant: "cgrates.org", - ID: "TestSSv1ItInitiateSession", - Event: map[string]interface{}{ - utils.CGRID: "c87609aa1cb6e9529ab1836cfeeebaab7aa7ebaf", - utils.Tenant: "cgrates.org", - utils.Category: "call", - utils.ToR: utils.MetaVoice, - utils.OriginID: "TestSSv1It1", - utils.RequestType: utils.MetaPrepaid, - utils.AccountField: "1001", - 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: initUsage, - }, APIOpts: map[string]interface{}{ utils.OptsAPIKey: "ses12345", }, - }, - } - var rply sessions.V1InitReplyWithDigest - if err := dispEngine.RPC.Call(utils.SessionSv1InitiateSessionWithDigest, - argsInit, &rply); err != nil { - t.Fatal(err) - } - if rply.MaxUsage != initUsage.Seconds() { - t.Errorf("Unexpected MaxUsage: %v", rply.MaxUsage) - } - if *rply.ResourceAllocation != "RES_ACNT_1001" { - t.Errorf("Unexpected ResourceAllocation: %s", *rply.ResourceAllocation) - } -} - -func testDspGetSessions(t *testing.T) { - filtr := utils.SessionFilter{ - APIOpts: map[string]interface{}{ - utils.OptsAPIKey: "ses12345", - }, - Tenant: "cgrates.org", - Filters: []string{}, - } - var reply int - if err := dispEngine.RPC.Call(utils.SessionSv1GetActiveSessionsCount, - &filtr, &reply); err != nil { - t.Fatal(err) - } else if reply != 3 { - t.Errorf("Expected 3 active sessions received %v", reply) - } - var rply []*sessions.ExternalSession - if err := dispEngine.RPC.Call(utils.SessionSv1GetActiveSessions, - &filtr, &rply); err != nil { - t.Fatal(err) - } else if len(rply) != 3 { - t.Errorf("Unexpected number of sessions returned %v :%s", len(rply), utils.ToJSON(rply)) + }, &reply); err != nil { + t.Error(err) + } else if reply != utils.Pong { + t.Errorf("Received: %s", reply) + } } - if err := dispEngine.RPC.Call(utils.SessionSv1GetPassiveSessionsCount, - &filtr, &reply); err != nil { - t.Fatal(err) - } else if reply != 0 { - t.Errorf("Expected no pasive sessions received %v", reply) - } - rply = nil - if err := dispEngine.RPC.Call(utils.SessionSv1GetPassiveSessions, - &filtr, &rply); err == nil || err.Error() != utils.ErrNotFound.Error() { - t.Fatalf("Expected %v received %v with reply %s", utils.ErrNotFound, err, utils.ToJSON(rply)) - } -} - -func testDspSessionUpdate(t *testing.T) { - reqUsage := 5 * time.Minute - argsUpdate := &sessions.V1UpdateSessionArgs{ - GetAttributes: true, - UpdateSession: true, - CGREvent: &utils.CGREvent{ + func testDspSessionPingFailover(t *testing.T) { + var reply string + if err := allEngine.RPC.Call(utils.SessionSv1Ping, new(utils.CGREvent), &reply); err != nil { + t.Error(err) + } else if reply != utils.Pong { + t.Errorf("Received: %s", reply) + } + ev := &utils.CGREvent{ Tenant: "cgrates.org", - ID: "TestSSv1ItUpdateSession", - Event: map[string]interface{}{ - utils.CGRID: "c87609aa1cb6e9529ab1836cfeeebaab7aa7ebaf", - utils.Tenant: "cgrates.org", - utils.Category: "call", - utils.ToR: utils.MetaVoice, - utils.OriginID: "TestSSv1It1", - utils.RequestType: utils.MetaPrepaid, - utils.AccountField: "1001", - 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: reqUsage, - }, APIOpts: map[string]interface{}{ utils.OptsAPIKey: "ses12345", }, - }, + } + if err := dispEngine.RPC.Call(utils.SessionSv1Ping, &ev, &reply); err != nil { + t.Error(err) + } else if reply != utils.Pong { + t.Errorf("Received: %s", reply) + } + allEngine.stopEngine(t) + if err := dispEngine.RPC.Call(utils.SessionSv1Ping, &ev, &reply); err != nil { + t.Error(err) + } else if reply != utils.Pong { + t.Errorf("Received: %s", reply) + } + allEngine2.stopEngine(t) + if err := dispEngine.RPC.Call(utils.SessionSv1Ping, &ev, &reply); err == nil { + t.Errorf("Expected error but received %v and reply %v\n", err, reply) + } + allEngine.startEngine(t) + allEngine2.startEngine(t) } - var rply sessions.V1UpdateSessionReply - if err := dispEngine.RPC.Call(utils.SessionSv1UpdateSession, - argsUpdate, &rply); err != nil { - t.Error(err) - } - eAttrs := &engine.AttrSProcessEventReply{ - MatchedProfiles: []string{"cgrates.org:ATTR_ACNT_1001"}, - AlteredFields: []string{"*req.OfficeGroup"}, - CGREvent: &utils.CGREvent{ - Tenant: "cgrates.org", - ID: "TestSSv1ItUpdateSession", - Event: map[string]interface{}{ - utils.Tenant: "cgrates.org", - utils.Category: "call", - utils.ToR: utils.MetaVoice, - utils.AccountField: "1001", - utils.Destination: "1002", - "OfficeGroup": "Marketing", - utils.OriginID: "TestSSv1It1", - utils.RequestType: utils.MetaPrepaid, - utils.SetupTime: "2018-01-07T17:00:00Z", - utils.AnswerTime: "2018-01-07T17:00:10Z", - utils.Usage: float64(reqUsage), - utils.CGRID: "c87609aa1cb6e9529ab1836cfeeebaab7aa7ebaf", + + func testDspSessionTestAuthKey(t *testing.T) { + authUsage := 5 * time.Minute + args := sessions.V1AuthorizeArgs{ + GetMaxUsage: true, + AuthorizeResources: true, + GetRoutes: true, + GetAttributes: true, + CGREvent: &utils.CGREvent{ + Tenant: "cgrates.org", + ID: "TestSSv1ItAuth", + Event: map[string]interface{}{ + utils.Tenant: "cgrates.org", + utils.Category: "call", + utils.ToR: utils.MetaVoice, + utils.OriginID: "TestSSv1It1", + utils.RequestType: utils.MetaPrepaid, + utils.AccountField: "1001", + utils.Destination: "1002", + utils.SetupTime: time.Date(2018, time.January, 7, 16, 60, 0, 0, time.UTC), + utils.Usage: authUsage, + }, + + APIOpts: map[string]interface{}{ + utils.OptsAPIKey: "12345", + }, }, - APIOpts: map[string]interface{}{ - utils.OptsAPIKey: "ses12345", - utils.Subsys: utils.MetaSessionS, + } + var rply sessions.V1AuthorizeReplyWithDigest + if err := dispEngine.RPC.Call(utils.SessionSv1AuthorizeEventWithDigest, + args, &rply); err == nil || err.Error() != utils.ErrUnauthorizedApi.Error() { + t.Error(err) + } + } + + func testDspSessionAuthorize(t *testing.T) { + authUsage := 5 * time.Minute + argsAuth := &sessions.V1AuthorizeArgs{ + GetMaxUsage: true, + AuthorizeResources: true, + GetRoutes: true, + GetAttributes: true, + CGREvent: &utils.CGREvent{ + Tenant: "cgrates.org", + ID: "TestSSv1ItAuth", + Event: map[string]interface{}{ + utils.CGRID: "c87609aa1cb6e9529ab1836cfeeebaab7aa7ebaf", + utils.Tenant: "cgrates.org", + utils.Category: "call", + utils.ToR: utils.MetaVoice, + utils.OriginID: "TestSSv1It1", + utils.RequestType: utils.MetaPrepaid, + utils.AccountField: "1001", + utils.Destination: "1002", + utils.SetupTime: time.Date(2018, time.January, 7, 16, 60, 0, 0, time.UTC), + utils.Usage: authUsage, + }, + + APIOpts: map[string]interface{}{ + utils.OptsAPIKey: "ses12345", + utils.OptsRoutesProfileCount: 1., + }, }, - }, - } - if *encoding == utils.MetaGOB { // gob maintains the variable type - eAttrs.CGREvent.Event[utils.Usage] = reqUsage - eAttrs.CGREvent.Event[utils.SetupTime] = argsUpdate.CGREvent.Event[utils.SetupTime] - eAttrs.CGREvent.Event[utils.AnswerTime] = argsUpdate.CGREvent.Event[utils.AnswerTime] - } - if !reflect.DeepEqual(eAttrs, rply.Attributes) { - t.Errorf("expecting: %+v, received: %+v", - utils.ToJSON(eAttrs), utils.ToJSON(rply.Attributes)) - } - if rply.MaxUsage == nil || *rply.MaxUsage != reqUsage { - t.Errorf("Unexpected MaxUsage: %v", utils.ToJSON(rply)) - } -} - -func testDspSessionUpdate2(t *testing.T) { - reqUsage := 5 * time.Minute - argsUpdate := &sessions.V1UpdateSessionArgs{ - GetAttributes: true, - UpdateSession: true, - CGREvent: &utils.CGREvent{ - Tenant: "cgrates.org", - ID: "TestSSv1ItUpdateSession", - Event: map[string]interface{}{ - utils.CGRID: "c87609aa1cb6e9529ab1836cfeeebaab7aa7ebaf", - utils.Tenant: "cgrates.org", - utils.Category: "call", - utils.ToR: utils.MetaVoice, - utils.OriginID: "TestSSv1It1", - utils.RequestType: utils.MetaPrepaid, - utils.AccountField: "1001", - 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: reqUsage, - }, - APIOpts: map[string]interface{}{ - utils.OptsAPIKey: "ses12345", - }, - }, - } - var rply sessions.V1UpdateSessionReply - if err := dispEngine.RPC.Call(utils.SessionSv1UpdateSession, - argsUpdate, &rply); err != nil { - t.Fatal(err) - } - eAttrs := &engine.AttrSProcessEventReply{ - MatchedProfiles: []string{"cgrates.org:ATTR_1001_SESSIONAUTH"}, - AlteredFields: []string{"*req.LCRProfile", "*req.Password", "*req.RequestType", "*req.PaypalAccount"}, - - CGREvent: &utils.CGREvent{ - Tenant: "cgrates.org", - ID: "TestSSv1ItUpdateSession", - Event: map[string]interface{}{ - utils.CGRID: "c87609aa1cb6e9529ab1836cfeeebaab7aa7ebaf", - utils.Tenant: "cgrates.org", - utils.Category: "call", - utils.ToR: utils.MetaVoice, - utils.AccountField: "1001", - utils.Destination: "1002", - "LCRProfile": "premium_cli", - "Password": "CGRateS.org", - "PaypalAccount": "cgrates@paypal.com", - utils.OriginID: "TestSSv1It1", - utils.RequestType: utils.MetaPrepaid, - utils.SetupTime: "2018-01-07T17:00:00Z", - utils.AnswerTime: "2018-01-07T17:00:10Z", - utils.Usage: float64(reqUsage), - }, - APIOpts: map[string]interface{}{ - utils.OptsAPIKey: "ses12345", - utils.Subsys: utils.MetaSessionS, - }, - }, - } - sort.Strings(eAttrs.AlteredFields) - if *encoding == utils.MetaGOB { // gob maintains the variable type - eAttrs.CGREvent.Event[utils.Usage] = reqUsage - eAttrs.CGREvent.Event[utils.SetupTime] = argsUpdate.CGREvent.Event[utils.SetupTime] - eAttrs.CGREvent.Event[utils.AnswerTime] = argsUpdate.CGREvent.Event[utils.AnswerTime] - } - if rply.Attributes != nil && rply.Attributes.AlteredFields != nil { - sort.Strings(rply.Attributes.AlteredFields) - } - if !reflect.DeepEqual(eAttrs, rply.Attributes) { - t.Errorf("expecting: %+v, received: %+v", - utils.ToJSON(eAttrs), utils.ToJSON(rply.Attributes)) - } - if rply.MaxUsage == nil || *rply.MaxUsage != reqUsage { - t.Errorf("Unexpected MaxUsage: %v", utils.ToJSON(rply)) - } -} - -func testDspSessionTerminate(t *testing.T) { - args := &sessions.V1TerminateSessionArgs{ - TerminateSession: true, - ReleaseResources: true, - - CGREvent: &utils.CGREvent{ - Tenant: "cgrates.org", - ID: "TestSSv1ItUpdateSession", - Event: map[string]interface{}{ - utils.CGRID: "c87609aa1cb6e9529ab1836cfeeebaab7aa7ebaf", - utils.Tenant: "cgrates.org", - utils.Category: "call", - utils.ToR: utils.MetaVoice, - utils.OriginID: "TestSSv1It1", - utils.RequestType: utils.MetaPrepaid, - utils.AccountField: "1001", - 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: 10 * time.Minute, - }, - - APIOpts: map[string]interface{}{ - utils.OptsAPIKey: "ses12345", - }, - }, - } - var rply string - if err := dispEngine.RPC.Call(utils.SessionSv1TerminateSession, - args, &rply); err != nil { - t.Error(err) - } - if rply != utils.OK { - t.Errorf("Unexpected reply: %s", rply) - } -} - -func testDspSessionProcessCDR(t *testing.T) { - args := utils.CGREvent{ - Tenant: "cgrates.org", - ID: "TestSSv1ItProcessCDR", - Event: map[string]interface{}{ - utils.Tenant: "cgrates.org", - utils.Category: "call", - utils.ToR: utils.MetaVoice, - utils.OriginID: "TestSSv1It1", - utils.RequestType: utils.MetaPostpaid, - utils.AccountField: "1001", - 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: 10 * time.Minute, - }, - APIOpts: map[string]interface{}{ - utils.OptsAPIKey: "ses12345", - }, + } + var rply sessions.V1AuthorizeReplyWithDigest + if err := dispEngine.RPC.Call(utils.SessionSv1AuthorizeEventWithDigest, + argsAuth, &rply); err != nil { + t.Error(err) + return + } + if rply.MaxUsage != authUsage.Seconds() { + t.Errorf("Unexpected MaxUsage: %v", rply.MaxUsage) + } + if *rply.ResourceAllocation == "" { + t.Errorf("Unexpected ResourceAllocation: %s", *rply.ResourceAllocation) + } + eSplrs := "route1,route2" + tp := strings.Split(*rply.RoutesDigest, ",") + sort.Strings(tp) + *rply.RoutesDigest = strings.Join(tp, ",") + if eSplrs != *rply.RoutesDigest { + t.Errorf("expecting: %v, received: %v", eSplrs, *rply.RoutesDigest) + } + eAttrs := "OfficeGroup:Marketing" + if eAttrs != *rply.AttributesDigest { + t.Errorf("expecting: %v, received: %v", eAttrs, *rply.AttributesDigest) + } } - var rply string - if err := dispEngine.RPC.Call(utils.SessionSv1ProcessCDR, - args, &rply); err != nil { - t.Fatal(err) - } - if rply != utils.OK { - t.Errorf("Unexpected reply: %s", rply) - } -} - -func testDspSessionProcessEvent(t *testing.T) { - initUsage := 5 * time.Minute - args := sessions.V1ProcessMessageArgs{ - AllocateResources: true, - Debit: true, - GetAttributes: true, - CGREvent: &utils.CGREvent{ - Tenant: "cgrates.org", - ID: "TestSSv1ItProcessEvent", - Event: map[string]interface{}{ - utils.CGRID: "c87609aa1cb6e9529ab1836cfeeebaab7aa7ebac", - utils.Tenant: "cgrates.org", - utils.Category: "call", - utils.ToR: utils.MetaVoice, - utils.OriginHost: "disp", - utils.OriginID: "TestSSv1It2", - utils.RequestType: utils.MetaPrepaid, - utils.AccountField: "1001", - 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: initUsage, - }, - - APIOpts: map[string]interface{}{ - utils.OptsAPIKey: "ses12345", - }, - }, - } - var rply sessions.V1ProcessMessageReply - if err := dispEngine.RPC.Call(utils.SessionSv1ProcessMessage, - args, &rply); err != nil { - t.Fatal(err) - } - if rply.MaxUsage == nil || *rply.MaxUsage != initUsage { - t.Errorf("Unexpected MaxUsage: %v", rply.MaxUsage) - } - if *rply.ResourceAllocation != "RES_ACNT_1001" { - t.Errorf("Unexpected ResourceAllocation: %s", *rply.ResourceAllocation) - } - eAttrs := &engine.AttrSProcessEventReply{ - MatchedProfiles: []string{"cgrates.org:ATTR_ACNT_1001"}, - AlteredFields: []string{"*req.OfficeGroup"}, - - CGREvent: &utils.CGREvent{ - Tenant: "cgrates.org", - ID: "TestSSv1ItProcessEvent", - Event: map[string]interface{}{ - utils.CGRID: "c87609aa1cb6e9529ab1836cfeeebaab7aa7ebac", - utils.Tenant: "cgrates.org", - utils.Category: "call", - utils.ToR: utils.MetaVoice, - utils.AccountField: "1001", - utils.Destination: "1002", - "OfficeGroup": "Marketing", - utils.OriginHost: "disp", - utils.OriginID: "TestSSv1It2", - utils.RequestType: utils.MetaPrepaid, - utils.SetupTime: "2018-01-07T17:00:00Z", - utils.AnswerTime: "2018-01-07T17:00:10Z", - utils.Usage: 300000000000.0, - }, - APIOpts: map[string]interface{}{ - utils.OptsAPIKey: "ses12345", - utils.Subsys: utils.MetaSessionS, - }, - }, - } - if *encoding == utils.MetaGOB { // gob maintains the variable type - eAttrs.CGREvent.Event[utils.Usage] = initUsage - eAttrs.CGREvent.Event[utils.SetupTime] = args.CGREvent.Event[utils.SetupTime] - eAttrs.CGREvent.Event[utils.AnswerTime] = args.CGREvent.Event[utils.AnswerTime] - } - if !reflect.DeepEqual(eAttrs, rply.Attributes) { - t.Errorf("expecting: %+v, received: %+v", - utils.ToJSON(eAttrs), utils.ToJSON(rply.Attributes)) - } -} - -func testDspSessionProcessEvent2(t *testing.T) { - initUsage := 5 * time.Minute - args := sessions.V1ProcessMessageArgs{ - AllocateResources: true, - Debit: true, - GetAttributes: true, - CGREvent: &utils.CGREvent{ - Tenant: "cgrates.org", - ID: "TestSSv1ItProcessEvent", - Event: map[string]interface{}{ - utils.CGRID: "c87609aa1cb6e9529ab1836cfeeebaab7aa7ebaf", - utils.Tenant: "cgrates.org", - utils.Category: "call", - utils.ToR: utils.MetaVoice, - utils.OriginID: "TestSSv1It2", - utils.RequestType: utils.MetaPrepaid, - utils.AccountField: "1001", - 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: initUsage, - utils.EventName: "Internal", - }, - - APIOpts: map[string]interface{}{ - utils.OptsAPIKey: "pse12345", - }, - }, - } - var rply sessions.V1ProcessMessageReply - if err := dispEngine.RPC.Call(utils.SessionSv1ProcessMessage, - args, &rply); err != nil { - t.Fatal(err) - } - if rply.MaxUsage == nil || *rply.MaxUsage != initUsage { - t.Errorf("Unexpected MaxUsage: %v", rply.MaxUsage) - } - if *rply.ResourceAllocation != "RES_ACNT_1001" { - t.Errorf("Unexpected ResourceAllocation: %s", *rply.ResourceAllocation) - } - eAttrs := &engine.AttrSProcessEventReply{ - MatchedProfiles: []string{"cgrates.org:ATTR_1001_SIMPLEAUTH"}, - AlteredFields: []string{"*req.EventName", "*req.Password"}, - - CGREvent: &utils.CGREvent{ - Tenant: "cgrates.org", - ID: "TestSSv1ItProcessEvent", - Event: map[string]interface{}{ - utils.CGRID: "c87609aa1cb6e9529ab1836cfeeebaab7aa7ebaf", - utils.Tenant: "cgrates.org", - utils.Category: "call", - utils.ToR: utils.MetaVoice, - utils.AccountField: "1001", - utils.Destination: "1002", - "Password": "CGRateS.org", - utils.OriginID: "TestSSv1It2", - utils.RequestType: utils.MetaPrepaid, - utils.SetupTime: "2018-01-07T17:00:00Z", - utils.AnswerTime: "2018-01-07T17:00:10Z", - utils.Usage: 300000000000.0, - }, - APIOpts: map[string]interface{}{ - utils.OptsAPIKey: "pse12345", - utils.Subsys: utils.MetaSessionS, - }, - }, - } - if *encoding == utils.MetaGOB { // gob maintains the variable type - eAttrs.CGREvent.Event[utils.Usage] = initUsage - eAttrs.CGREvent.Event[utils.SetupTime] = args.CGREvent.Event[utils.SetupTime] - eAttrs.CGREvent.Event[utils.AnswerTime] = args.CGREvent.Event[utils.AnswerTime] - } - sort.Strings(rply.Attributes.AlteredFields) - if !reflect.DeepEqual(eAttrs, rply.Attributes) { - t.Errorf("expecting: %+v, received: %+v", - utils.ToJSON(eAttrs), utils.ToJSON(rply.Attributes)) - } -} - -func testDspSessionReplicate(t *testing.T) { - allEngine.initDataDb(t) - - var reply string - // reload cache in order to corectly cahce the indexes - if err := allEngine.RPC.Call(utils.CacheSv1Clear, &utils.AttrCacheIDsWithAPIOpts{ - CacheIDs: nil, - }, &reply); err != nil { - t.Error(err) - } else if reply != utils.OK { - t.Error("Reply: ", reply) - } - allEngine.loadData(t, path.Join(*dataDir, "tariffplans", "testit")) - testDspSessionAddBalacne(t) - testDspSessionAuthorize(t) - testDspSessionInit(t) - - if err := dispEngine.RPC.Call(utils.SessionSv1ReplicateSessions, &ArgsReplicateSessionsWithAPIOpts{ - APIOpts: map[string]interface{}{ - utils.OptsAPIKey: "ses12345", - }, - Tenant: "cgrates.org", - ArgsReplicateSessions: sessions.ArgsReplicateSessions{ - CGRID: "c87609aa1cb6e9529ab1836cfeeebaab7aa7ebaf", - Passive: false, - ConnIDs: []string{"rplConn"}, - }, - }, &reply); err != nil { - t.Fatal(err) - } else if reply != utils.OK { - t.Errorf("Unexpected reply %s", reply) - } - - var repl int - time.Sleep(10 * time.Millisecond) - if err := allEngine2.RPC.Call(utils.SessionSv1GetPassiveSessionsCount, - new(utils.SessionFilter), &repl); err != nil { - t.Fatal(err) - } else if repl != 3 { - t.Errorf("Expected 3 sessions received %v", repl) - } -} - -func testDspSessionPassive(t *testing.T) { - allEngine.stopEngine(t) - testDspSessionUpdate2(t) - var repl int - filtr := utils.SessionFilter{ - APIOpts: map[string]interface{}{ - utils.OptsAPIKey: "ses12345", - }, - Tenant: "cgrates.org", - Filters: []string{}, - } - time.Sleep(10 * time.Millisecond) - if err := dispEngine.RPC.Call(utils.SessionSv1GetPassiveSessionsCount, - filtr, &repl); err != nil { - t.Fatal(err) - } else if repl != 0 { - t.Errorf("Expected no passive sessions received %v", repl) - } - if err := dispEngine.RPC.Call(utils.SessionSv1GetActiveSessionsCount, - filtr, &repl); err != nil { - t.Fatal(err) - } else if repl != 3 { - t.Errorf("Expected 3 active sessions received %v", repl) - } - - var rply []*sessions.ExternalSession - if err := dispEngine.RPC.Call(utils.SessionSv1GetActiveSessions, - &filtr, &rply); err != nil { - t.Fatal(err) - } else if len(rply) != 3 { - t.Errorf("Unexpected number of sessions returned %v :%s", len(rply), utils.ToJSON(rply)) - } - - var reply string - if err := dispEngine.RPC.Call(utils.SessionSv1SetPassiveSession, sessions.Session{ - CGRID: rply[0].CGRID, - Tenant: rply[0].Tenant, - ResourceID: "TestSSv1It1", - EventStart: engine.NewMapEvent(map[string]interface{}{ - utils.CGRID: "c87609aa1cb6e9529ab1836cfeeebaab7aa7ebaf", - utils.Tenant: "cgrates.org", - utils.Category: "call", - utils.ToR: utils.MetaVoice, - utils.OriginID: "TestSSv1It1", - utils.RequestType: utils.MetaPrepaid, - utils.AccountField: "1001", - 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: 5 * time.Minute, - }), - SRuns: []*sessions.SRun{ - { - Event: engine.NewMapEvent(map[string]interface{}{ - "RunID": "CustomerCharges", + func testDspSessionInit(t *testing.T) { + initUsage := 5 * time.Minute + argsInit := &sessions.V1InitSessionArgs{ + InitSession: true, + AllocateResources: true, + GetAttributes: true, + CGREvent: &utils.CGREvent{ + Tenant: "cgrates.org", + ID: "TestSSv1ItInitiateSession", + Event: map[string]interface{}{ utils.CGRID: "c87609aa1cb6e9529ab1836cfeeebaab7aa7ebaf", utils.Tenant: "cgrates.org", utils.Category: "call", @@ -831,141 +291,682 @@ func testDspSessionPassive(t *testing.T) { 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: 5 * time.Minute, - }), - CD: &engine.CallDescriptor{}, - EventCost: &engine.EventCost{}, + utils.Usage: initUsage, + }, - LastUsage: 5 * time.Minute, - TotalUsage: 10 * time.Minute, + APIOpts: map[string]interface{}{ + utils.OptsAPIKey: "ses12345", + }, }, - }, - OptsStart: map[string]interface{}{ - utils.OptsAPIKey: "ses12345", - }, - }, &reply); err != nil { - t.Fatal(err) - } else if reply != utils.OK { - t.Errorf("Unexpected reply %s", reply) - } - time.Sleep(10 * time.Millisecond) - if err := dispEngine.RPC.Call(utils.SessionSv1GetPassiveSessionsCount, - filtr, &repl); err != nil { - t.Fatal(err) - } else if repl != 1 { - t.Errorf("Expected 1 passive sessions received %v", repl) - } - if err := dispEngine.RPC.Call(utils.SessionSv1GetActiveSessionsCount, - filtr, &repl); err != nil { - t.Fatal(err) - } else if repl != 0 { - t.Errorf("Expected no active sessions received %v", repl) - } -} - -func testDspSessionForceDisconect(t *testing.T) { - allEngine.startEngine(t) - allEngine.initDataDb(t) - - allEngine.loadData(t, path.Join(*dataDir, "tariffplans", "testit")) - testDspSessionAddBalacne(t) - testDspSessionAuthorize(t) - testDspSessionInit(t) - var repl int - filtr := utils.SessionFilter{ - APIOpts: map[string]interface{}{ - utils.OptsAPIKey: "ses12345", - }, - Tenant: "cgrates.org", - Filters: []string{}, - } - time.Sleep(10 * time.Millisecond) - if err := dispEngine.RPC.Call(utils.SessionSv1GetPassiveSessionsCount, - filtr, &repl); err != nil { - t.Fatal(err) - } else if repl != 0 { - t.Errorf("Expected no passive sessions received %v", repl) - } - if err := dispEngine.RPC.Call(utils.SessionSv1GetActiveSessionsCount, - filtr, &repl); err != nil { - t.Fatal(err) - } else if repl != 3 { - t.Errorf("Expected 3 active sessions received %v", repl) + } + var rply sessions.V1InitReplyWithDigest + if err := dispEngine.RPC.Call(utils.SessionSv1InitiateSessionWithDigest, + argsInit, &rply); err != nil { + t.Fatal(err) + } + if rply.MaxUsage != initUsage.Seconds() { + t.Errorf("Unexpected MaxUsage: %v", rply.MaxUsage) + } + if *rply.ResourceAllocation != "RES_ACNT_1001" { + t.Errorf("Unexpected ResourceAllocation: %s", *rply.ResourceAllocation) + } } - var rply []*sessions.ExternalSession - if err := dispEngine.RPC.Call(utils.SessionSv1GetActiveSessions, - &filtr, &rply); err != nil { - t.Fatal(err) - } else if len(rply) != 3 { - t.Errorf("Unexpected number of sessions returned %v :%s", len(rply), utils.ToJSON(rply)) - } - - var reply string - if err := dispEngine.RPC.Call(utils.SessionSv1ForceDisconnect, &filtr, &reply); err != nil { - t.Fatal(err) - } else if reply != utils.OK { - t.Errorf("Unexpected reply %s", reply) - } - time.Sleep(10 * time.Millisecond) - if err := dispEngine.RPC.Call(utils.SessionSv1GetPassiveSessionsCount, - filtr, &repl); err != nil { - t.Fatal(err) - } else if repl != 0 { - t.Errorf("Expected 1 passive sessions received %v", repl) - } - if err := dispEngine.RPC.Call(utils.SessionSv1GetActiveSessionsCount, - filtr, &repl); err != nil { - t.Fatal(err) - } else if repl != 0 { - t.Errorf("Expected no active sessions received %v", repl) - } -} - -func testDspSessionProcessEvent3(t *testing.T) { - args := &sessions.V1ProcessEventArgs{ - Flags: []string{"*rals:*terminate", "*resources:*release"}, - CGREvent: &utils.CGREvent{ - Tenant: "cgrates.org", - ID: "testSSv1ItProcessEventTerminateSession", - Event: map[string]interface{}{ - utils.Tenant: "cgrates.org", - utils.ToR: utils.MetaVoice, - utils.OriginID: "TestSSv1It2", - utils.RequestType: utils.MetaPrepaid, - utils.AccountField: "1001", - utils.Subject: "ANY2CNT", - 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: 10 * time.Minute, - }, - - APIOpts: map[string]interface{}{ - utils.OptsAPIKey: "pse12345", - }, - }, - } - var rply sessions.V1ProcessEventReply - if err := dispEngine.RPC.Call(utils.SessionSv1ProcessEvent, - args, &rply); err != nil { - t.Error(err) - } - - var repl int - if err := dispEngine.RPC.Call(utils.SessionSv1GetActiveSessionsCount, - utils.SessionFilter{ + func testDspGetSessions(t *testing.T) { + filtr := utils.SessionFilter{ APIOpts: map[string]interface{}{ utils.OptsAPIKey: "ses12345", }, Tenant: "cgrates.org", Filters: []string{}, - }, &repl); err != nil { - t.Fatal(err) - } else if repl != 0 { - t.Errorf("Expected no active sessions received %v", repl) + } + var reply int + if err := dispEngine.RPC.Call(utils.SessionSv1GetActiveSessionsCount, + &filtr, &reply); err != nil { + t.Fatal(err) + } else if reply != 3 { + t.Errorf("Expected 3 active sessions received %v", reply) + } + var rply []*sessions.ExternalSession + if err := dispEngine.RPC.Call(utils.SessionSv1GetActiveSessions, + &filtr, &rply); err != nil { + t.Fatal(err) + } else if len(rply) != 3 { + t.Errorf("Unexpected number of sessions returned %v :%s", len(rply), utils.ToJSON(rply)) + } + + if err := dispEngine.RPC.Call(utils.SessionSv1GetPassiveSessionsCount, + &filtr, &reply); err != nil { + t.Fatal(err) + } else if reply != 0 { + t.Errorf("Expected no pasive sessions received %v", reply) + } + rply = nil + if err := dispEngine.RPC.Call(utils.SessionSv1GetPassiveSessions, + &filtr, &rply); err == nil || err.Error() != utils.ErrNotFound.Error() { + t.Fatalf("Expected %v received %v with reply %s", utils.ErrNotFound, err, utils.ToJSON(rply)) + } + } + + func testDspSessionUpdate(t *testing.T) { + reqUsage := 5 * time.Minute + argsUpdate := &sessions.V1UpdateSessionArgs{ + GetAttributes: true, + UpdateSession: true, + CGREvent: &utils.CGREvent{ + Tenant: "cgrates.org", + ID: "TestSSv1ItUpdateSession", + Event: map[string]interface{}{ + utils.CGRID: "c87609aa1cb6e9529ab1836cfeeebaab7aa7ebaf", + utils.Tenant: "cgrates.org", + utils.Category: "call", + utils.ToR: utils.MetaVoice, + utils.OriginID: "TestSSv1It1", + utils.RequestType: utils.MetaPrepaid, + utils.AccountField: "1001", + 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: reqUsage, + }, + + APIOpts: map[string]interface{}{ + utils.OptsAPIKey: "ses12345", + }, + }, + } + var rply sessions.V1UpdateSessionReply + if err := dispEngine.RPC.Call(utils.SessionSv1UpdateSession, + argsUpdate, &rply); err != nil { + t.Error(err) + } + eAttrs := &engine.AttrSProcessEventReply{ + MatchedProfiles: []string{"cgrates.org:ATTR_ACNT_1001"}, + AlteredFields: []string{"*req.OfficeGroup"}, + CGREvent: &utils.CGREvent{ + Tenant: "cgrates.org", + ID: "TestSSv1ItUpdateSession", + Event: map[string]interface{}{ + utils.Tenant: "cgrates.org", + utils.Category: "call", + utils.ToR: utils.MetaVoice, + utils.AccountField: "1001", + utils.Destination: "1002", + "OfficeGroup": "Marketing", + utils.OriginID: "TestSSv1It1", + utils.RequestType: utils.MetaPrepaid, + utils.SetupTime: "2018-01-07T17:00:00Z", + utils.AnswerTime: "2018-01-07T17:00:10Z", + utils.Usage: float64(reqUsage), + utils.CGRID: "c87609aa1cb6e9529ab1836cfeeebaab7aa7ebaf", + }, + APIOpts: map[string]interface{}{ + utils.OptsAPIKey: "ses12345", + utils.Subsys: utils.MetaSessionS, + }, + }, + } + if *encoding == utils.MetaGOB { // gob maintains the variable type + eAttrs.CGREvent.Event[utils.Usage] = reqUsage + eAttrs.CGREvent.Event[utils.SetupTime] = argsUpdate.CGREvent.Event[utils.SetupTime] + eAttrs.CGREvent.Event[utils.AnswerTime] = argsUpdate.CGREvent.Event[utils.AnswerTime] + } + if !reflect.DeepEqual(eAttrs, rply.Attributes) { + t.Errorf("expecting: %+v, received: %+v", + utils.ToJSON(eAttrs), utils.ToJSON(rply.Attributes)) + } + if rply.MaxUsage == nil || *rply.MaxUsage != reqUsage { + t.Errorf("Unexpected MaxUsage: %v", utils.ToJSON(rply)) + } + } + + func testDspSessionUpdate2(t *testing.T) { + reqUsage := 5 * time.Minute + argsUpdate := &sessions.V1UpdateSessionArgs{ + GetAttributes: true, + UpdateSession: true, + CGREvent: &utils.CGREvent{ + Tenant: "cgrates.org", + ID: "TestSSv1ItUpdateSession", + Event: map[string]interface{}{ + utils.CGRID: "c87609aa1cb6e9529ab1836cfeeebaab7aa7ebaf", + utils.Tenant: "cgrates.org", + utils.Category: "call", + utils.ToR: utils.MetaVoice, + utils.OriginID: "TestSSv1It1", + utils.RequestType: utils.MetaPrepaid, + utils.AccountField: "1001", + 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: reqUsage, + }, + APIOpts: map[string]interface{}{ + utils.OptsAPIKey: "ses12345", + }, + }, + } + var rply sessions.V1UpdateSessionReply + if err := dispEngine.RPC.Call(utils.SessionSv1UpdateSession, + argsUpdate, &rply); err != nil { + t.Fatal(err) + } + eAttrs := &engine.AttrSProcessEventReply{ + MatchedProfiles: []string{"cgrates.org:ATTR_1001_SESSIONAUTH"}, + AlteredFields: []string{"*req.LCRProfile", "*req.Password", "*req.RequestType", "*req.PaypalAccount"}, + + CGREvent: &utils.CGREvent{ + Tenant: "cgrates.org", + ID: "TestSSv1ItUpdateSession", + Event: map[string]interface{}{ + utils.CGRID: "c87609aa1cb6e9529ab1836cfeeebaab7aa7ebaf", + utils.Tenant: "cgrates.org", + utils.Category: "call", + utils.ToR: utils.MetaVoice, + utils.AccountField: "1001", + utils.Destination: "1002", + "LCRProfile": "premium_cli", + "Password": "CGRateS.org", + "PaypalAccount": "cgrates@paypal.com", + utils.OriginID: "TestSSv1It1", + utils.RequestType: utils.MetaPrepaid, + utils.SetupTime: "2018-01-07T17:00:00Z", + utils.AnswerTime: "2018-01-07T17:00:10Z", + utils.Usage: float64(reqUsage), + }, + APIOpts: map[string]interface{}{ + utils.OptsAPIKey: "ses12345", + utils.Subsys: utils.MetaSessionS, + }, + }, + } + sort.Strings(eAttrs.AlteredFields) + if *encoding == utils.MetaGOB { // gob maintains the variable type + eAttrs.CGREvent.Event[utils.Usage] = reqUsage + eAttrs.CGREvent.Event[utils.SetupTime] = argsUpdate.CGREvent.Event[utils.SetupTime] + eAttrs.CGREvent.Event[utils.AnswerTime] = argsUpdate.CGREvent.Event[utils.AnswerTime] + } + if rply.Attributes != nil && rply.Attributes.AlteredFields != nil { + sort.Strings(rply.Attributes.AlteredFields) + } + if !reflect.DeepEqual(eAttrs, rply.Attributes) { + t.Errorf("expecting: %+v, received: %+v", + utils.ToJSON(eAttrs), utils.ToJSON(rply.Attributes)) + } + if rply.MaxUsage == nil || *rply.MaxUsage != reqUsage { + t.Errorf("Unexpected MaxUsage: %v", utils.ToJSON(rply)) + } + } + + func testDspSessionTerminate(t *testing.T) { + args := &sessions.V1TerminateSessionArgs{ + TerminateSession: true, + ReleaseResources: true, + + CGREvent: &utils.CGREvent{ + Tenant: "cgrates.org", + ID: "TestSSv1ItUpdateSession", + Event: map[string]interface{}{ + utils.CGRID: "c87609aa1cb6e9529ab1836cfeeebaab7aa7ebaf", + utils.Tenant: "cgrates.org", + utils.Category: "call", + utils.ToR: utils.MetaVoice, + utils.OriginID: "TestSSv1It1", + utils.RequestType: utils.MetaPrepaid, + utils.AccountField: "1001", + 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: 10 * time.Minute, + }, + + APIOpts: map[string]interface{}{ + utils.OptsAPIKey: "ses12345", + }, + }, + } + var rply string + if err := dispEngine.RPC.Call(utils.SessionSv1TerminateSession, + args, &rply); err != nil { + t.Error(err) + } + if rply != utils.OK { + t.Errorf("Unexpected reply: %s", rply) + } + } + + func testDspSessionProcessCDR(t *testing.T) { + args := utils.CGREvent{ + Tenant: "cgrates.org", + ID: "TestSSv1ItProcessCDR", + Event: map[string]interface{}{ + utils.Tenant: "cgrates.org", + utils.Category: "call", + utils.ToR: utils.MetaVoice, + utils.OriginID: "TestSSv1It1", + utils.RequestType: utils.MetaPostpaid, + utils.AccountField: "1001", + 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: 10 * time.Minute, + }, + APIOpts: map[string]interface{}{ + utils.OptsAPIKey: "ses12345", + }, + } + + var rply string + if err := dispEngine.RPC.Call(utils.SessionSv1ProcessCDR, + args, &rply); err != nil { + t.Fatal(err) + } + if rply != utils.OK { + t.Errorf("Unexpected reply: %s", rply) + } + } + + func testDspSessionProcessEvent(t *testing.T) { + initUsage := 5 * time.Minute + args := sessions.V1ProcessMessageArgs{ + AllocateResources: true, + Debit: true, + GetAttributes: true, + CGREvent: &utils.CGREvent{ + Tenant: "cgrates.org", + ID: "TestSSv1ItProcessEvent", + Event: map[string]interface{}{ + utils.CGRID: "c87609aa1cb6e9529ab1836cfeeebaab7aa7ebac", + utils.Tenant: "cgrates.org", + utils.Category: "call", + utils.ToR: utils.MetaVoice, + utils.OriginHost: "disp", + utils.OriginID: "TestSSv1It2", + utils.RequestType: utils.MetaPrepaid, + utils.AccountField: "1001", + 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: initUsage, + }, + + APIOpts: map[string]interface{}{ + utils.OptsAPIKey: "ses12345", + }, + }, + } + var rply sessions.V1ProcessMessageReply + if err := dispEngine.RPC.Call(utils.SessionSv1ProcessMessage, + args, &rply); err != nil { + t.Fatal(err) + } + if rply.MaxUsage == nil || *rply.MaxUsage != initUsage { + t.Errorf("Unexpected MaxUsage: %v", rply.MaxUsage) + } + if *rply.ResourceAllocation != "RES_ACNT_1001" { + t.Errorf("Unexpected ResourceAllocation: %s", *rply.ResourceAllocation) + } + eAttrs := &engine.AttrSProcessEventReply{ + MatchedProfiles: []string{"cgrates.org:ATTR_ACNT_1001"}, + AlteredFields: []string{"*req.OfficeGroup"}, + + CGREvent: &utils.CGREvent{ + Tenant: "cgrates.org", + ID: "TestSSv1ItProcessEvent", + Event: map[string]interface{}{ + utils.CGRID: "c87609aa1cb6e9529ab1836cfeeebaab7aa7ebac", + utils.Tenant: "cgrates.org", + utils.Category: "call", + utils.ToR: utils.MetaVoice, + utils.AccountField: "1001", + utils.Destination: "1002", + "OfficeGroup": "Marketing", + utils.OriginHost: "disp", + utils.OriginID: "TestSSv1It2", + utils.RequestType: utils.MetaPrepaid, + utils.SetupTime: "2018-01-07T17:00:00Z", + utils.AnswerTime: "2018-01-07T17:00:10Z", + utils.Usage: 300000000000.0, + }, + APIOpts: map[string]interface{}{ + utils.OptsAPIKey: "ses12345", + utils.Subsys: utils.MetaSessionS, + }, + }, + } + if *encoding == utils.MetaGOB { // gob maintains the variable type + eAttrs.CGREvent.Event[utils.Usage] = initUsage + eAttrs.CGREvent.Event[utils.SetupTime] = args.CGREvent.Event[utils.SetupTime] + eAttrs.CGREvent.Event[utils.AnswerTime] = args.CGREvent.Event[utils.AnswerTime] + } + if !reflect.DeepEqual(eAttrs, rply.Attributes) { + t.Errorf("expecting: %+v, received: %+v", + utils.ToJSON(eAttrs), utils.ToJSON(rply.Attributes)) + } + } + + func testDspSessionProcessEvent2(t *testing.T) { + initUsage := 5 * time.Minute + args := sessions.V1ProcessMessageArgs{ + AllocateResources: true, + Debit: true, + GetAttributes: true, + CGREvent: &utils.CGREvent{ + Tenant: "cgrates.org", + ID: "TestSSv1ItProcessEvent", + Event: map[string]interface{}{ + utils.CGRID: "c87609aa1cb6e9529ab1836cfeeebaab7aa7ebaf", + utils.Tenant: "cgrates.org", + utils.Category: "call", + utils.ToR: utils.MetaVoice, + utils.OriginID: "TestSSv1It2", + utils.RequestType: utils.MetaPrepaid, + utils.AccountField: "1001", + 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: initUsage, + utils.EventName: "Internal", + }, + + APIOpts: map[string]interface{}{ + utils.OptsAPIKey: "pse12345", + }, + }, + } + var rply sessions.V1ProcessMessageReply + if err := dispEngine.RPC.Call(utils.SessionSv1ProcessMessage, + args, &rply); err != nil { + t.Fatal(err) + } + if rply.MaxUsage == nil || *rply.MaxUsage != initUsage { + t.Errorf("Unexpected MaxUsage: %v", rply.MaxUsage) + } + if *rply.ResourceAllocation != "RES_ACNT_1001" { + t.Errorf("Unexpected ResourceAllocation: %s", *rply.ResourceAllocation) + } + eAttrs := &engine.AttrSProcessEventReply{ + MatchedProfiles: []string{"cgrates.org:ATTR_1001_SIMPLEAUTH"}, + AlteredFields: []string{"*req.EventName", "*req.Password"}, + + CGREvent: &utils.CGREvent{ + Tenant: "cgrates.org", + ID: "TestSSv1ItProcessEvent", + Event: map[string]interface{}{ + utils.CGRID: "c87609aa1cb6e9529ab1836cfeeebaab7aa7ebaf", + utils.Tenant: "cgrates.org", + utils.Category: "call", + utils.ToR: utils.MetaVoice, + utils.AccountField: "1001", + utils.Destination: "1002", + "Password": "CGRateS.org", + utils.OriginID: "TestSSv1It2", + utils.RequestType: utils.MetaPrepaid, + utils.SetupTime: "2018-01-07T17:00:00Z", + utils.AnswerTime: "2018-01-07T17:00:10Z", + utils.Usage: 300000000000.0, + }, + APIOpts: map[string]interface{}{ + utils.OptsAPIKey: "pse12345", + utils.Subsys: utils.MetaSessionS, + }, + }, + } + if *encoding == utils.MetaGOB { // gob maintains the variable type + eAttrs.CGREvent.Event[utils.Usage] = initUsage + eAttrs.CGREvent.Event[utils.SetupTime] = args.CGREvent.Event[utils.SetupTime] + eAttrs.CGREvent.Event[utils.AnswerTime] = args.CGREvent.Event[utils.AnswerTime] + } + sort.Strings(rply.Attributes.AlteredFields) + if !reflect.DeepEqual(eAttrs, rply.Attributes) { + t.Errorf("expecting: %+v, received: %+v", + utils.ToJSON(eAttrs), utils.ToJSON(rply.Attributes)) + } + } + + func testDspSessionReplicate(t *testing.T) { + allEngine.initDataDb(t) + + var reply string + // reload cache in order to corectly cahce the indexes + if err := allEngine.RPC.Call(utils.CacheSv1Clear, &utils.AttrCacheIDsWithAPIOpts{ + CacheIDs: nil, + }, &reply); err != nil { + t.Error(err) + } else if reply != utils.OK { + t.Error("Reply: ", reply) + } + allEngine.loadData(t, path.Join(*dataDir, "tariffplans", "testit")) + testDspSessionAddBalacne(t) + testDspSessionAuthorize(t) + testDspSessionInit(t) + + if err := dispEngine.RPC.Call(utils.SessionSv1ReplicateSessions, &ArgsReplicateSessionsWithAPIOpts{ + APIOpts: map[string]interface{}{ + utils.OptsAPIKey: "ses12345", + }, + Tenant: "cgrates.org", + ArgsReplicateSessions: sessions.ArgsReplicateSessions{ + CGRID: "c87609aa1cb6e9529ab1836cfeeebaab7aa7ebaf", + Passive: false, + ConnIDs: []string{"rplConn"}, + }, + }, &reply); err != nil { + t.Fatal(err) + } else if reply != utils.OK { + t.Errorf("Unexpected reply %s", reply) + } + + var repl int + time.Sleep(10 * time.Millisecond) + if err := allEngine2.RPC.Call(utils.SessionSv1GetPassiveSessionsCount, + new(utils.SessionFilter), &repl); err != nil { + t.Fatal(err) + } else if repl != 3 { + t.Errorf("Expected 3 sessions received %v", repl) + } + } + + func testDspSessionPassive(t *testing.T) { + allEngine.stopEngine(t) + testDspSessionUpdate2(t) + var repl int + filtr := utils.SessionFilter{ + APIOpts: map[string]interface{}{ + utils.OptsAPIKey: "ses12345", + }, + Tenant: "cgrates.org", + Filters: []string{}, + } + time.Sleep(10 * time.Millisecond) + if err := dispEngine.RPC.Call(utils.SessionSv1GetPassiveSessionsCount, + filtr, &repl); err != nil { + t.Fatal(err) + } else if repl != 0 { + t.Errorf("Expected no passive sessions received %v", repl) + } + if err := dispEngine.RPC.Call(utils.SessionSv1GetActiveSessionsCount, + filtr, &repl); err != nil { + t.Fatal(err) + } else if repl != 3 { + t.Errorf("Expected 3 active sessions received %v", repl) + } + + var rply []*sessions.ExternalSession + if err := dispEngine.RPC.Call(utils.SessionSv1GetActiveSessions, + &filtr, &rply); err != nil { + t.Fatal(err) + } else if len(rply) != 3 { + t.Errorf("Unexpected number of sessions returned %v :%s", len(rply), utils.ToJSON(rply)) + } + + var reply string + if err := dispEngine.RPC.Call(utils.SessionSv1SetPassiveSession, sessions.Session{ + CGRID: rply[0].CGRID, + Tenant: rply[0].Tenant, + ResourceID: "TestSSv1It1", + EventStart: engine.NewMapEvent(map[string]interface{}{ + utils.CGRID: "c87609aa1cb6e9529ab1836cfeeebaab7aa7ebaf", + utils.Tenant: "cgrates.org", + utils.Category: "call", + utils.ToR: utils.MetaVoice, + utils.OriginID: "TestSSv1It1", + utils.RequestType: utils.MetaPrepaid, + utils.AccountField: "1001", + 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: 5 * time.Minute, + }), + SRuns: []*sessions.SRun{ + { + Event: engine.NewMapEvent(map[string]interface{}{ + "RunID": "CustomerCharges", + utils.CGRID: "c87609aa1cb6e9529ab1836cfeeebaab7aa7ebaf", + utils.Tenant: "cgrates.org", + utils.Category: "call", + utils.ToR: utils.MetaVoice, + utils.OriginID: "TestSSv1It1", + utils.RequestType: utils.MetaPrepaid, + utils.AccountField: "1001", + 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: 5 * time.Minute, + }), + CD: &engine.CallDescriptor{}, + EventCost: &engine.EventCost{}, + + LastUsage: 5 * time.Minute, + TotalUsage: 10 * time.Minute, + }, + }, + OptsStart: map[string]interface{}{ + utils.OptsAPIKey: "ses12345", + }, + }, &reply); err != nil { + t.Fatal(err) + } else if reply != utils.OK { + t.Errorf("Unexpected reply %s", reply) + } + time.Sleep(10 * time.Millisecond) + if err := dispEngine.RPC.Call(utils.SessionSv1GetPassiveSessionsCount, + filtr, &repl); err != nil { + t.Fatal(err) + } else if repl != 1 { + t.Errorf("Expected 1 passive sessions received %v", repl) + } + if err := dispEngine.RPC.Call(utils.SessionSv1GetActiveSessionsCount, + filtr, &repl); err != nil { + t.Fatal(err) + } else if repl != 0 { + t.Errorf("Expected no active sessions received %v", repl) + } + } + + func testDspSessionForceDisconect(t *testing.T) { + allEngine.startEngine(t) + allEngine.initDataDb(t) + + allEngine.loadData(t, path.Join(*dataDir, "tariffplans", "testit")) + testDspSessionAddBalacne(t) + testDspSessionAuthorize(t) + testDspSessionInit(t) + var repl int + filtr := utils.SessionFilter{ + APIOpts: map[string]interface{}{ + utils.OptsAPIKey: "ses12345", + }, + Tenant: "cgrates.org", + Filters: []string{}, + } + time.Sleep(10 * time.Millisecond) + if err := dispEngine.RPC.Call(utils.SessionSv1GetPassiveSessionsCount, + filtr, &repl); err != nil { + t.Fatal(err) + } else if repl != 0 { + t.Errorf("Expected no passive sessions received %v", repl) + } + if err := dispEngine.RPC.Call(utils.SessionSv1GetActiveSessionsCount, + filtr, &repl); err != nil { + t.Fatal(err) + } else if repl != 3 { + t.Errorf("Expected 3 active sessions received %v", repl) + } + + var rply []*sessions.ExternalSession + if err := dispEngine.RPC.Call(utils.SessionSv1GetActiveSessions, + &filtr, &rply); err != nil { + t.Fatal(err) + } else if len(rply) != 3 { + t.Errorf("Unexpected number of sessions returned %v :%s", len(rply), utils.ToJSON(rply)) + } + + var reply string + if err := dispEngine.RPC.Call(utils.SessionSv1ForceDisconnect, &filtr, &reply); err != nil { + t.Fatal(err) + } else if reply != utils.OK { + t.Errorf("Unexpected reply %s", reply) + } + time.Sleep(10 * time.Millisecond) + if err := dispEngine.RPC.Call(utils.SessionSv1GetPassiveSessionsCount, + filtr, &repl); err != nil { + t.Fatal(err) + } else if repl != 0 { + t.Errorf("Expected 1 passive sessions received %v", repl) + } + if err := dispEngine.RPC.Call(utils.SessionSv1GetActiveSessionsCount, + filtr, &repl); err != nil { + t.Fatal(err) + } else if repl != 0 { + t.Errorf("Expected no active sessions received %v", repl) + } + } + + func testDspSessionProcessEvent3(t *testing.T) { + args := &sessions.V1ProcessEventArgs{ + Flags: []string{"*rals:*terminate", "*resources:*release"}, + CGREvent: &utils.CGREvent{ + Tenant: "cgrates.org", + ID: "testSSv1ItProcessEventTerminateSession", + Event: map[string]interface{}{ + utils.Tenant: "cgrates.org", + utils.ToR: utils.MetaVoice, + utils.OriginID: "TestSSv1It2", + utils.RequestType: utils.MetaPrepaid, + utils.AccountField: "1001", + utils.Subject: "ANY2CNT", + 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: 10 * time.Minute, + }, + + APIOpts: map[string]interface{}{ + utils.OptsAPIKey: "pse12345", + }, + }, + } + var rply sessions.V1ProcessEventReply + if err := dispEngine.RPC.Call(utils.SessionSv1ProcessEvent, + args, &rply); err != nil { + t.Error(err) + } + + var repl int + if err := dispEngine.RPC.Call(utils.SessionSv1GetActiveSessionsCount, + utils.SessionFilter{ + APIOpts: map[string]interface{}{ + utils.OptsAPIKey: "ses12345", + }, + Tenant: "cgrates.org", + Filters: []string{}, + }, &repl); err != nil { + t.Fatal(err) + } else if repl != 0 { + t.Errorf("Expected no active sessions received %v", repl) + } } -} func testDspSessionGetCost(t *testing.T) { @@ -1007,24 +1008,24 @@ func testDspSessionGetCost(t *testing.T) { } -func testDspSessionSTIRAuthenticate(t *testing.T) { - var rply string - if err := dispEngine.RPC.Call(utils.SessionSv1STIRAuthenticate, - &sessions.V1STIRAuthenticateArgs{ - Attest: []string{"A"}, - PayloadMaxDuration: "-1", - DestinationTn: "1002", - Identity: "eyJhbGciOiJFUzI1NiIsInBwdCI6InNoYWtlbiIsInR5cCI6InBhc3Nwb3J0IiwieDV1IjoiL3Vzci9zaGFyZS9jZ3JhdGVzL3N0aXIvc3Rpcl9wdWJrZXkucGVtIn0.eyJhdHRlc3QiOiJBIiwiZGVzdCI6eyJ0biI6WyIxMDAyIl19LCJpYXQiOjE1ODcwMzg4MDIsIm9yaWciOnsidG4iOiIxMDAxIn0sIm9yaWdpZCI6IjEyMzQ1NiJ9.cMEMlFnfyTu8uxfeU4RoZTamA7ifFT9Ibwrvi1_LKwL2xAU6fZ_CSIxKbtyOpNhM_sV03x7CfA_v0T4sHkifzg;info=;ppt=shaken", - OriginatorTn: "1001", - APIOpts: map[string]interface{}{ - utils.OptsAPIKey: "ses12345", - }, - }, &rply); err != nil { - t.Fatal(err) - } else if rply != utils.OK { - t.Errorf("Expected: %s ,received: %s", utils.OK, rply) + func testDspSessionSTIRAuthenticate(t *testing.T) { + var rply string + if err := dispEngine.RPC.Call(utils.SessionSv1STIRAuthenticate, + &sessions.V1STIRAuthenticateArgs{ + Attest: []string{"A"}, + PayloadMaxDuration: "-1", + DestinationTn: "1002", + Identity: "eyJhbGciOiJFUzI1NiIsInBwdCI6InNoYWtlbiIsInR5cCI6InBhc3Nwb3J0IiwieDV1IjoiL3Vzci9zaGFyZS9jZ3JhdGVzL3N0aXIvc3Rpcl9wdWJrZXkucGVtIn0.eyJhdHRlc3QiOiJBIiwiZGVzdCI6eyJ0biI6WyIxMDAyIl19LCJpYXQiOjE1ODcwMzg4MDIsIm9yaWciOnsidG4iOiIxMDAxIn0sIm9yaWdpZCI6IjEyMzQ1NiJ9.cMEMlFnfyTu8uxfeU4RoZTamA7ifFT9Ibwrvi1_LKwL2xAU6fZ_CSIxKbtyOpNhM_sV03x7CfA_v0T4sHkifzg;info=;ppt=shaken", + OriginatorTn: "1001", + APIOpts: map[string]interface{}{ + utils.OptsAPIKey: "ses12345", + }, + }, &rply); err != nil { + t.Fatal(err) + } else if rply != utils.OK { + t.Errorf("Expected: %s ,received: %s", utils.OK, rply) + } } -} */ func testDspSessionSTIRIdentity(t *testing.T) { payload := &utils.PASSporTPayload{ diff --git a/dispatchers/stats_it_test.go b/dispatchers/stats_it_test.go index 57422e879..abb79091e 100644 --- a/dispatchers/stats_it_test.go +++ b/dispatchers/stats_it_test.go @@ -40,7 +40,7 @@ var sTestsDspSts = []func(t *testing.T){ testDspStsTestAuthKey3, } -//Test start here +// Test start here func TestDspStatS(t *testing.T) { var config1, config2, config3 string switch *dbType { diff --git a/dispatchers/thresholds_it_test.go b/dispatchers/thresholds_it_test.go index 34d262c16..5f89ebea0 100644 --- a/dispatchers/thresholds_it_test.go +++ b/dispatchers/thresholds_it_test.go @@ -40,7 +40,7 @@ var sTestsDspTh = []func(t *testing.T){ testDspThTestAuthKey3, } -//Test start here +// Test start here func TestDspThresholdS(t *testing.T) { var config1, config2, config3 string switch *dbType { diff --git a/ees/ee_test.go b/ees/ee_test.go index a9ff1a321..942dec38c 100644 --- a/ees/ee_test.go +++ b/ees/ee_test.go @@ -194,7 +194,7 @@ func TestNewEventExporterDefaultCase(t *testing.T) { } } -//Test for Case 7 +// Test for Case 7 func TestNewEventExporterCase7(t *testing.T) { cgrCfg := config.NewDefaultCGRConfig() cgrCfg.EEsCfg().Exporters[0].Type = utils.MetaElastic @@ -225,7 +225,7 @@ func TestNewEventExporterCase7(t *testing.T) { } } -//Test for Case 8 +// Test for Case 8 func TestNewEventExporterCase8(t *testing.T) { cgrCfg := config.NewDefaultCGRConfig() cgrCfg.EEsCfg().Exporters[0].Type = utils.MetaSQL @@ -238,7 +238,7 @@ func TestNewEventExporterCase8(t *testing.T) { } } -//Test for invalid "dc" +// Test for invalid "dc" func TestNewEventExporterDcCase(t *testing.T) { cgrCfg := config.NewDefaultCGRConfig() cgrCfg.GeneralCfg().DefaultTimezone = "invalid_timezone" diff --git a/ees/kafka_it_test.go b/ees/kafka_it_test.go index 5cc4e2cd7..94b37ea16 100644 --- a/ees/kafka_it_test.go +++ b/ees/kafka_it_test.go @@ -48,14 +48,14 @@ var ( testKafkaLoadConfig, testKafkaResetDataDB, - testKafkaStartEngine, + // testKafkaStartEngine, testKafkaRPCConn, - testKafkaCreateTopic, + // testKafkaCreateTopic, testKafkaExportEvent, testKafkaVerifyExport, - testKafkaDeleteTopic, - testStopCgrEngine, - testCleanDirectory, + // testKafkaDeleteTopic, + // testStopCgrEngine, + // testCleanDirectory, } ) diff --git a/ees/poster_it_test.go b/ees/poster_it_test.go index cdc18e97b..7be032be8 100644 --- a/ees/poster_it_test.go +++ b/ees/poster_it_test.go @@ -61,77 +61,77 @@ type TestContent struct { } /* -func TestHttpJsonPoster(t *testing.T) { - SetFailedPostCacheTTL(time.Millisecond) - content := &TestContent{Var1: "Val1", Var2: "Val2"} - jsn, _ := json.Marshal(content) - pstr, err := NewHTTPjsonMapEE(&config.EventExporterCfg{ - ExportPath: "http://localhost:8080/invalid", - Attempts: 3, - FailedPostsDir: "/tmp", - Opts: &config.EventExporterOpts{}, - }, config.CgrConfig(), nil, nil) - if err != nil { - t.Error(err) - } - if err = ExportWithAttempts(context.Background(), pstr, &HTTPPosterRequest{Body: jsn, Header: make(http.Header)}, ""); err == nil { - t.Error("Expected error") - } - AddFailedPost("/tmp", "http://localhost:8080/invalid", utils.MetaHTTPjsonMap, "test1", jsn, &config.EventExporterOpts{}) - time.Sleep(5 * time.Millisecond) - fs, err := filepath.Glob("/tmp/test1*") - if err != nil { - t.Fatal(err) - } else if len(fs) == 0 { - t.Fatal("Expected at least one file") + func TestHttpJsonPoster(t *testing.T) { + SetFailedPostCacheTTL(time.Millisecond) + content := &TestContent{Var1: "Val1", Var2: "Val2"} + jsn, _ := json.Marshal(content) + pstr, err := NewHTTPjsonMapEE(&config.EventExporterCfg{ + ExportPath: "http://localhost:8080/invalid", + Attempts: 3, + FailedPostsDir: "/tmp", + Opts: &config.EventExporterOpts{}, + }, config.CgrConfig(), nil, nil) + if err != nil { + t.Error(err) + } + if err = ExportWithAttempts(context.Background(), pstr, &HTTPPosterRequest{Body: jsn, Header: make(http.Header)}, ""); err == nil { + t.Error("Expected error") + } + AddFailedPost("/tmp", "http://localhost:8080/invalid", utils.MetaHTTPjsonMap, "test1", jsn, &config.EventExporterOpts{}) + time.Sleep(5 * time.Millisecond) + fs, err := filepath.Glob("/tmp/test1*") + if err != nil { + t.Fatal(err) + } else if len(fs) == 0 { + t.Fatal("Expected at least one file") + } + + ev, err := NewExportEventsFromFile(fs[0]) + if err != nil { + t.Fatal(err) + } else if len(ev.Events) == 0 { + t.Fatal("Expected at least one event") + } + if !reflect.DeepEqual(jsn, ev.Events[0]) { + t.Errorf("Expecting: %q, received: %q", string(jsn), ev.Events[0]) + } } - ev, err := NewExportEventsFromFile(fs[0]) - if err != nil { - t.Fatal(err) - } else if len(ev.Events) == 0 { - t.Fatal("Expected at least one event") + func TestHttpBytesPoster(t *testing.T) { + SetFailedPostCacheTTL(time.Millisecond) + content := []byte(`Test + Test2 + `) + pstr, err := NewHTTPjsonMapEE(&config.EventExporterCfg{ + ExportPath: "http://localhost:8080/invalid", + Attempts: 3, + FailedPostsDir: "/tmp", + Opts: &config.EventExporterOpts{}, + }, config.CgrConfig(), nil, nil) + if err != nil { + t.Error(err) + } + if err = ExportWithAttempts(context.Background(), pstr, &HTTPPosterRequest{Body: content, Header: make(http.Header)}, ""); err == nil { + t.Error("Expected error") + } + AddFailedPost("/tmp", "http://localhost:8080/invalid", utils.ContentJSON, "test2", content, &config.EventExporterOpts{}) + time.Sleep(5 * time.Millisecond) + fs, err := filepath.Glob("/tmp/test2*") + if err != nil { + t.Fatal(err) + } else if len(fs) == 0 { + t.Fatal("Expected at least one file") + } + ev, err := NewExportEventsFromFile(fs[0]) + if err != nil { + t.Fatal(err) + } else if len(ev.Events) == 0 { + t.Fatal("Expected at least one event") + } + if !reflect.DeepEqual(content, ev.Events[0]) { + t.Errorf("Expecting: %q, received: %q", string(content), ev.Events[0]) + } } - if !reflect.DeepEqual(jsn, ev.Events[0]) { - t.Errorf("Expecting: %q, received: %q", string(jsn), ev.Events[0]) - } -} - -func TestHttpBytesPoster(t *testing.T) { - SetFailedPostCacheTTL(time.Millisecond) - content := []byte(`Test - Test2 - `) - pstr, err := NewHTTPjsonMapEE(&config.EventExporterCfg{ - ExportPath: "http://localhost:8080/invalid", - Attempts: 3, - FailedPostsDir: "/tmp", - Opts: &config.EventExporterOpts{}, - }, config.CgrConfig(), nil, nil) - if err != nil { - t.Error(err) - } - if err = ExportWithAttempts(context.Background(), pstr, &HTTPPosterRequest{Body: content, Header: make(http.Header)}, ""); err == nil { - t.Error("Expected error") - } - AddFailedPost("/tmp", "http://localhost:8080/invalid", utils.ContentJSON, "test2", content, &config.EventExporterOpts{}) - time.Sleep(5 * time.Millisecond) - fs, err := filepath.Glob("/tmp/test2*") - if err != nil { - t.Fatal(err) - } else if len(fs) == 0 { - t.Fatal("Expected at least one file") - } - ev, err := NewExportEventsFromFile(fs[0]) - if err != nil { - t.Fatal(err) - } else if len(ev.Events) == 0 { - t.Fatal("Expected at least one event") - } - if !reflect.DeepEqual(content, ev.Events[0]) { - t.Errorf("Expecting: %q, received: %q", string(content), ev.Events[0]) - } -} */ func TestSQSPoster(t *testing.T) { if !*itTestSQS { diff --git a/engine/caches.go b/engine/caches.go index 26e3b7645..b76a503f1 100644 --- a/engine/caches.go +++ b/engine/caches.go @@ -371,7 +371,7 @@ func (chS *CacheS) cacheDataFromDB(ctx *context.Context, attrs *utils.AttrReload return } -//populateCacheLoadIDs populate cacheLoadIDs based on attrs +// populateCacheLoadIDs populate cacheLoadIDs based on attrs func populateCacheLoadIDs(loadIDs map[string]int64, attrs map[string][]string) (cacheLoadIDs map[string]int64) { cacheLoadIDs = make(map[string]int64) //based on IDs of each type populate cacheLoadIDs and add into cache diff --git a/engine/datadbmock.go b/engine/datadbmock.go index 9f6537de7..262da4ced 100644 --- a/engine/datadbmock.go +++ b/engine/datadbmock.go @@ -72,7 +72,7 @@ type DataDBMock struct { RemoveDispatcherHostDrvF func(*context.Context, string, string) error } -//Storage methods +// Storage methods func (dbM *DataDBMock) Close() {} func (dbM *DataDBMock) Flush(string) error { @@ -106,7 +106,7 @@ func (dbM *DataDBMock) IsDBEmpty() (resp bool, err error) { return false, utils.ErrNotImplemented } -//DataDB methods +// DataDB methods func (dbM *DataDBMock) HasDataDrv(*context.Context, string, string, string) (bool, error) { return false, utils.ErrNotImplemented } diff --git a/engine/exportrequest.go b/engine/exportrequest.go index fb8576582..88413d0b9 100644 --- a/engine/exportrequest.go +++ b/engine/exportrequest.go @@ -95,7 +95,7 @@ func (eeR *ExportRequest) FieldAsString(fldPath []string) (val string, err error return utils.IfaceAsString(iface), nil } -//SetFields will populate fields of AgentRequest out of templates +// SetFields will populate fields of AgentRequest out of templates func (eeR *ExportRequest) SetFields(ctx *context.Context, tplFlds []*config.FCTemplate) (err error) { for _, tplFld := range tplFlds { if pass, err := eeR.filterS.Pass(ctx, eeR.tnt, diff --git a/engine/filters.go b/engine/filters.go index 1afb161c1..c7eddd2d2 100644 --- a/engine/filters.go +++ b/engine/filters.go @@ -80,7 +80,7 @@ func (fS *FilterS) Pass(ctx *context.Context, tenant string, filterIDs []string, return } -//checkPrefix verify if the value has as prefix one of the prefixes +// checkPrefix verify if the value has as prefix one of the prefixes func checkPrefix(value string, prefixes []string) (hasPrefix bool) { for _, prefix := range prefixes { if strings.HasPrefix(value, prefix) { @@ -94,7 +94,7 @@ func checkPrefix(value string, prefixes []string) (hasPrefix bool) { return } -//verifyPrefixes verify the Element and the Values from FilterRule if has as prefix one of the prefixes +// verifyPrefixes verify the Element and the Values from FilterRule if has as prefix one of the prefixes func verifyPrefixes(rule *FilterRule, prefixes []string) (hasPrefix bool) { if strings.HasPrefix(rule.Element, utils.DynamicDataPrefix) { if hasPrefix = checkPrefix(rule.Element, prefixes); !hasPrefix { @@ -112,8 +112,8 @@ func verifyPrefixes(rule *FilterRule, prefixes []string) (hasPrefix bool) { return true } -//LazyPass is almost the same as Pass except that it verify if the -//Element of the Values from FilterRules has as prefix one of the pathPrfxs +// LazyPass is almost the same as Pass except that it verify if the +// Element of the Values from FilterRules has as prefix one of the pathPrfxs func (fS *FilterS) LazyPass(ctx *context.Context, tenant string, filterIDs []string, ev utils.DataProvider, pathPrfxs []string) (pass bool, lazyCheckRules []*FilterRule, err error) { if len(filterIDs) == 0 { diff --git a/engine/libindex.go b/engine/libindex.go index 841752c46..70186178f 100644 --- a/engine/libindex.go +++ b/engine/libindex.go @@ -212,7 +212,8 @@ func removeItemFromFilterIndex(ctx *context.Context, dm *DataManager, idxItmType // oldFilterIds - the filtersIDs that the old object had; this is optional if the object did not exist // newFilterIDs - the filtersIDs for the object that will be set // useGrp - in case of subindexes(e.g. Rate from RateProfiles) need to add the grp to the itemID when reverse filter indexes are set -// used when updating the filters +// +// used when updating the filters func updatedIndexes(ctx *context.Context, dm *DataManager, idxItmType, tnt, grp, itemID string, oldFilterIds *[]string, newFilterIDs []string, useGrp bool) (err error) { itmGrp := itemID if useGrp { diff --git a/engine/libroutes.go b/engine/libroutes.go index 8432b7318..c307e4fc6 100644 --- a/engine/libroutes.go +++ b/engine/libroutes.go @@ -285,7 +285,7 @@ func (lps RouteProfilesWithWeight) Sort() { sort.Slice(lps, func(i, j int) bool { return lps[i].Weight > lps[j].Weight }) } -//routeLazyPass filters the route based on +// routeLazyPass filters the route based on func routeLazyPass(ctx *context.Context, filters []*FilterRule, ev *utils.CGREvent, data utils.MapStorage, resConns, statConns, acntConns []string) (pass bool, err error) { if len(filters) == 0 { diff --git a/engine/libroutes_test.go b/engine/libroutes_test.go index 563b0376c..e16bef737 100644 --- a/engine/libroutes_test.go +++ b/engine/libroutes_test.go @@ -394,7 +394,7 @@ func TestLibRoutesSortHighestCost(t *testing.T) { } } -//sort based on *acd and *tcd +// sort based on *acd and *tcd func TestLibRoutesSortQOS(t *testing.T) { sSpls := &SortedRoutes{ Routes: []*SortedRoute{ @@ -463,7 +463,7 @@ func TestLibRoutesSortQOS(t *testing.T) { } } -//sort based on *acd and *tcd +// sort based on *acd and *tcd func TestLibRoutesSortQOS2(t *testing.T) { sSpls := &SortedRoutes{ Routes: []*SortedRoute{ @@ -527,7 +527,7 @@ func TestLibRoutesSortQOS2(t *testing.T) { } } -//sort based on *pdd +// sort based on *pdd func TestLibRoutesSortQOS3(t *testing.T) { sSpls := &SortedRoutes{ Routes: []*SortedRoute{ diff --git a/engine/model_helpers.go b/engine/model_helpers.go index 6723780dc..d3fa41794 100644 --- a/engine/model_helpers.go +++ b/engine/model_helpers.go @@ -91,7 +91,7 @@ func csvLoad(s interface{}, values []string) (interface{}, error) { return elem.Interface(), nil } -//CsvDump receive and interface and convert it to a slice of string +// CsvDump receive and interface and convert it to a slice of string func CsvDump(s interface{}) ([]string, error) { fieldIndexMap := make(map[string]int) st := reflect.ValueOf(s) diff --git a/engine/model_helpers_test.go b/engine/model_helpers_test.go index 8814b22f5..f6603f9a8 100644 --- a/engine/model_helpers_test.go +++ b/engine/model_helpers_test.go @@ -1399,7 +1399,7 @@ func TestChargerProfileToAPI(t *testing.T) { } } -//Number of FilterIDs and AttributeIDs are equal +// Number of FilterIDs and AttributeIDs are equal func TestAPItoModelTPCharger(t *testing.T) { tpCharger := &utils.TPChargerProfile{ TPid: "TP1", @@ -1441,7 +1441,7 @@ func TestAPItoModelTPCharger(t *testing.T) { } } -//Number of FilterIDs is smaller than AttributeIDs +// Number of FilterIDs is smaller than AttributeIDs func TestAPItoModelTPCharger2(t *testing.T) { tpCharger := &utils.TPChargerProfile{ TPid: "TP1", @@ -1476,7 +1476,7 @@ func TestAPItoModelTPCharger2(t *testing.T) { } } -//Number of FilterIDs is greater than AttributeIDs +// Number of FilterIDs is greater than AttributeIDs func TestAPItoModelTPCharger3(t *testing.T) { tpCharger := &utils.TPChargerProfile{ TPid: "TP1", @@ -1516,7 +1516,7 @@ func TestAPItoModelTPCharger3(t *testing.T) { } } -//len(AttributeIDs) is 0 +// len(AttributeIDs) is 0 func TestAPItoModelTPCharger4(t *testing.T) { tpCharger := &utils.TPChargerProfile{ TPid: "TP1", @@ -1550,7 +1550,7 @@ func TestAPItoModelTPCharger4(t *testing.T) { } } -//len(FilterIDs) is 0 +// len(FilterIDs) is 0 func TestAPItoModelTPCharger5(t *testing.T) { tpCharger := &utils.TPChargerProfile{ TPid: "TP1", @@ -1578,7 +1578,7 @@ func TestAPItoModelTPCharger5(t *testing.T) { } } -//both len(AttributeIDs) and len(FilterIDs) are 0 +// both len(AttributeIDs) and len(FilterIDs) are 0 func TestAPItoModelTPCharger6(t *testing.T) { tpCharger := &utils.TPChargerProfile{ TPid: "TP1", diff --git a/engine/thresholds_test.go b/engine/thresholds_test.go index 2429bfb38..308f10acc 100644 --- a/engine/thresholds_test.go +++ b/engine/thresholds_test.go @@ -415,632 +415,633 @@ func TestThresholdsmatchingThresholdsForEvent(t *testing.T) { } /* -func TestThresholdsProcessEvent(t *testing.T) { - var dmTH *DataManager - var thServ *ThresholdService - var tPrfls = []*ThresholdProfile{ - { + func TestThresholdsProcessEvent(t *testing.T) { + var dmTH *DataManager + var thServ *ThresholdService + var tPrfls = []*ThresholdProfile{ + { + Tenant: "cgrates.org", + ID: "TH_1", + FilterIDs: []string{"FLTR_TH_1"}, + MaxHits: 12, + Blocker: false, + Weight: 20.0, + ActionProfileIDs: []string{"ACT_1", "ACT_2"}, + Async: false, + }, + { + Tenant: "cgrates.org", + ID: "TH_2", + FilterIDs: []string{"FLTR_TH_2"}, + MaxHits: 12, + MinSleep: 5 * time.Minute, + Blocker: false, + Weight: 20.0, + ActionProfileIDs: []string{"ACT_1", "ACT_2"}, + Async: false, + }, + { + Tenant: "cgrates.org", + ID: "TH_3", + FilterIDs: []string{"FLTR_TH_3"}, + MaxHits: 12, + MinSleep: 5 * time.Minute, + Blocker: false, + Weight: 20.0, + ActionProfileIDs: []string{"ACT_1", "ACT_2"}, + Async: false, + }, + } + ths := Thresholds{ + &Threshold{ + Tenant: "cgrates.org", + ID: "TH_1", + Hits: 0, + }, + &Threshold{ + Tenant: "cgrates.org", + ID: "TH_2", + Hits: 0, + }, + &Threshold{ + Tenant: "cgrates.org", + ID: "TH_3", + Hits: 0, + }, + } + argsGetThresholds := []*utils.CGREvent{ + { + Tenant: "cgrates.org", + ID: "Ev1", + Event: map[string]interface{}{ + "Threshold": "TH_1", + "Weight": "10.0", + }, + }, + { + Tenant: "cgrates.org", + ID: "Ev1", + Event: map[string]interface{}{ + "Threshold": "TH_2", + "Weight": "20.0", + }, + }, + { + Tenant: "cgrates.org", + ID: "Ev1", + Event: map[string]interface{}{ + "Threshold": "ThresholdPrefix123", + }, + }, + } + + cfg := config.NewDefaultCGRConfig() + data := NewInternalDB(nil, nil, cfg.DataDbCfg().Items) + dmTH = NewDataManager(data, config.CgrConfig().CacheCfg(), nil) + cfg.ThresholdSCfg().StoreInterval = 0 + cfg.ThresholdSCfg().StringIndexedFields = nil + cfg.ThresholdSCfg().PrefixIndexedFields = nil + thServ = NewThresholdService(dmTH, cfg, &FilterS{dm: dmTH, cfg: cfg}) + if err != nil { + t.Errorf("Error: %+v", err) + } + fltrTh1 := &Filter{ + Tenant: config.CgrConfig().GeneralCfg().DefaultTenant, + ID: "FLTR_TH_1", + Rules: []*FilterRule{ + { + Type: utils.MetaString, + Element: "~*req.Threshold", + Values: []string{"TH_1"}, + }, + { + Type: utils.MetaGreaterOrEqual, + Element: utils.DynamicDataPrefix + utils.MetaReq + utils.NestingSep + utils.Weight, + Values: []string{"9.0"}, + }, + }, + } + dmTH.SetFilter(context.TODO(), fltrTh1, true) + fltrTh2 := &Filter{ + Tenant: config.CgrConfig().GeneralCfg().DefaultTenant, + ID: "FLTR_TH_2", + Rules: []*FilterRule{ + { + Type: utils.MetaString, + Element: "~*req.Threshold", + Values: []string{"TH_2"}, + }, + { + Type: utils.MetaGreaterOrEqual, + Element: utils.DynamicDataPrefix + utils.MetaReq + utils.NestingSep + utils.Weight, + Values: []string{"15.0"}, + }, + }, + } + dmTH.SetFilter(context.TODO(), fltrTh2, true) + fltrTh3 := &Filter{ + Tenant: config.CgrConfig().GeneralCfg().DefaultTenant, + ID: "FLTR_TH_3", + Rules: []*FilterRule{ + { + Type: utils.MetaPrefix, + Element: "~*req.Threshold", + Values: []string{"ThresholdPrefix"}, + }, + }, + } + dmTH.SetFilter(context.TODO(), fltrTh3, true) + for _, th := range tPrfls { + if err = dmTH.SetThresholdProfile(context.Background(),th, true); err != nil { + t.Errorf("Error: %+v", err) + } + } + //Test each threshold profile from cache + for _, th := range tPrfls { + if temptTh, err := dmTH.GetThresholdProfile(context.Background(),th.Tenant, + th.ID, true, false, utils.NonTransactional); err != nil { + t.Errorf("Error: %+v", err) + } else if !reflect.DeepEqual(th, temptTh) { + t.Errorf("Expecting: %+v, received: %+v", th, temptTh) + } + } + for _, th := range ths { + if err = dmTH.SetThreshold(context.Background(),th); err != nil { + t.Errorf("Error: %+v", err) + } + } + //Test each threshold profile from cache + for _, th := range ths { + if temptTh, err := dmTH.GetThreshold(context.Background(),th.Tenant, + th.ID, true, false, utils.NonTransactional); err != nil { + t.Errorf("Error: %+v", err) + } else if !reflect.DeepEqual(th, temptTh) { + t.Errorf("Expecting: %+v, received: %+v", th, temptTh) + } + } + thIDs := []string{"TH_1"} + if thMatched, err := thServ.processEvent(context.Background(),argsGetThresholds[0].Tenant, argsGetThresholds[0]); err != utils.ErrPartiallyExecuted { + t.Errorf("Error: %+v", err) + } else if !reflect.DeepEqual(thIDs, thMatched) { + t.Errorf("Expecting: %+v, received: %+v", thIDs, thMatched) + } + + thIDs = []string{"TH_2"} + if thMatched, err := thServ.processEvent(context.Background(),argsGetThresholds[1].Tenant, argsGetThresholds[1]); err != utils.ErrPartiallyExecuted { + t.Errorf("Error: %+v", err) + } else if !reflect.DeepEqual(thIDs, thMatched) { + t.Errorf("Expecting: %+v, received: %+v", thIDs, thMatched) + } + + thIDs = []string{"TH_3"} + if thMatched, err := thServ.processEvent(context.Background(),argsGetThresholds[2].Tenant, argsGetThresholds[2]); err != utils.ErrPartiallyExecuted { + t.Errorf("Error: %+v", err) + } else if !reflect.DeepEqual(thIDs, thMatched) { + t.Errorf("Expecting: %+v, received: %+v", thIDs, thMatched) + } + } + + func TestThresholdsVerifyIfExecuted(t *testing.T) { + var dmTH *DataManager + var thServ *ThresholdService + var tPrfls = []*ThresholdProfile{ + { + Tenant: "cgrates.org", + ID: "TH_1", + FilterIDs: []string{"FLTR_TH_1"}, + MaxHits: 12, + Blocker: false, + Weight: 20.0, + ActionProfileIDs: []string{"ACT_1", "ACT_2"}, + Async: false, + }, + { + Tenant: "cgrates.org", + ID: "TH_2", + FilterIDs: []string{"FLTR_TH_2"}, + MaxHits: 12, + MinSleep: 5 * time.Minute, + Blocker: false, + Weight: 20.0, + ActionProfileIDs: []string{"ACT_1", "ACT_2"}, + Async: false, + }, + { + Tenant: "cgrates.org", + ID: "TH_3", + FilterIDs: []string{"FLTR_TH_3"}, + MaxHits: 12, + MinSleep: 5 * time.Minute, + Blocker: false, + Weight: 20.0, + ActionProfileIDs: []string{"ACT_1", "ACT_2"}, + Async: false, + }, + } + ths := Thresholds{ + &Threshold{ + Tenant: "cgrates.org", + ID: "TH_1", + Hits: 0, + }, + &Threshold{ + Tenant: "cgrates.org", + ID: "TH_2", + Hits: 0, + }, + &Threshold{ + Tenant: "cgrates.org", + ID: "TH_3", + Hits: 0, + }, + } + argsGetThresholds := []*utils.CGREvent{ + { + Tenant: "cgrates.org", + ID: "Ev1", + Event: map[string]interface{}{ + "Threshold": "TH_1", + "Weight": "10.0", + }, + }, + { + Tenant: "cgrates.org", + ID: "Ev1", + Event: map[string]interface{}{ + "Threshold": "TH_2", + "Weight": "20.0", + }, + }, + { + Tenant: "cgrates.org", + ID: "Ev1", + Event: map[string]interface{}{ + "Threshold": "ThresholdPrefix123", + }, + }, + } + + cfg := config.NewDefaultCGRConfig() + data := NewInternalDB(nil, nil, cfg.DataDbCfg().Items) + dmTH = NewDataManager(data, config.CgrConfig().CacheCfg(), nil) + cfg.ThresholdSCfg().StoreInterval = 0 + cfg.ThresholdSCfg().StringIndexedFields = nil + cfg.ThresholdSCfg().PrefixIndexedFields = nil + thServ = NewThresholdService(dmTH, cfg, &FilterS{dm: dmTH, cfg: cfg}) + if err != nil { + t.Errorf("Error: %+v", err) + } + fltrTh1 := &Filter{ + Tenant: config.CgrConfig().GeneralCfg().DefaultTenant, + ID: "FLTR_TH_1", + Rules: []*FilterRule{ + { + Type: utils.MetaString, + Element: "~*req.Threshold", + Values: []string{"TH_1"}, + }, + { + Type: utils.MetaGreaterOrEqual, + Element: utils.DynamicDataPrefix + utils.MetaReq + utils.NestingSep + utils.Weight, + Values: []string{"9.0"}, + }, + }, + } + dmTH.SetFilter(context.TODO(), fltrTh1, true) + fltrTh2 := &Filter{ + Tenant: config.CgrConfig().GeneralCfg().DefaultTenant, + ID: "FLTR_TH_2", + Rules: []*FilterRule{ + { + Type: utils.MetaString, + Element: "~*req.Threshold", + Values: []string{"TH_2"}, + }, + { + Type: utils.MetaGreaterOrEqual, + Element: utils.DynamicDataPrefix + utils.MetaReq + utils.NestingSep + utils.Weight, + Values: []string{"15.0"}, + }, + }, + } + dmTH.SetFilter(context.TODO(), fltrTh2, true) + fltrTh3 := &Filter{ + Tenant: config.CgrConfig().GeneralCfg().DefaultTenant, + ID: "FLTR_TH_3", + Rules: []*FilterRule{ + { + Type: utils.MetaPrefix, + Element: "~*req.Threshold", + Values: []string{"ThresholdPrefix"}, + }, + }, + } + dmTH.SetFilter(context.TODO(), fltrTh3, true) + for _, th := range tPrfls { + if err = dmTH.SetThresholdProfile(context.Background(),th, true); err != nil { + t.Errorf("Error: %+v", err) + } + } + //Test each threshold profile from cache + for _, th := range tPrfls { + if temptTh, err := dmTH.GetThresholdProfile(context.Background(),th.Tenant, + th.ID, true, false, utils.NonTransactional); err != nil { + t.Errorf("Error: %+v", err) + } else if !reflect.DeepEqual(th, temptTh) { + t.Errorf("Expecting: %+v, received: %+v", th, temptTh) + } + } + for _, th := range ths { + if err = dmTH.SetThreshold(context.Background(),th); err != nil { + t.Errorf("Error: %+v", err) + } + } + thIDs := []string{"TH_1"} + if thMatched, err := thServ.processEvent(context.Background(),argsGetThresholds[0].Tenant, argsGetThresholds[0]); err != utils.ErrPartiallyExecuted { + t.Errorf("Error: %+v", err) + } else if !reflect.DeepEqual(thIDs, thMatched) { + t.Errorf("Expecting: %+v, received: %+v", thIDs, thMatched) + } + + thIDs = []string{"TH_2"} + if thMatched, err := thServ.processEvent(context.Background(),argsGetThresholds[1].Tenant, argsGetThresholds[1]); err != utils.ErrPartiallyExecuted { + t.Errorf("Error: %+v", err) + } else if !reflect.DeepEqual(thIDs, thMatched) { + t.Errorf("Expecting: %+v, received: %+v", thIDs, thMatched) + } + + thIDs = []string{"TH_3"} + if thMatched, err := thServ.processEvent(context.Background(),argsGetThresholds[2].Tenant, argsGetThresholds[2]); err != utils.ErrPartiallyExecuted { + t.Errorf("Error: %+v", err) + } else if !reflect.DeepEqual(thIDs, thMatched) { + t.Errorf("Expecting: %+v, received: %+v", thIDs, thMatched) + } + thMatched, err := thServ.matchingThresholdsForEvent(argsGetThresholds[0].Tenant, argsGetThresholds[0]) + if err != nil { + t.Errorf("Error: %+v", err) + } + thMatched.unlock() + if !reflect.DeepEqual(ths[0].Tenant, thMatched[0].Tenant) { + t.Errorf("Expecting: %+v, received: %+v", ths[0].Tenant, thMatched[0].Tenant) + } else if !reflect.DeepEqual(ths[0].ID, thMatched[0].ID) { + t.Errorf("Expecting: %+v, received: %+v", ths[0].ID, thMatched[0].ID) + } else if thMatched[0].Hits != 1 { + t.Errorf("Expecting: 1, received: %+v", thMatched[0].Hits) + } + + thMatched, err = thServ.matchingThresholdsForEvent(argsGetThresholds[1].Tenant, argsGetThresholds[1]) + if err != nil { + t.Errorf("Error: %+v", err) + } + thMatched.unlock() + if !reflect.DeepEqual(ths[1].Tenant, thMatched[0].Tenant) { + t.Errorf("Expecting: %+v, received: %+v", ths[1].Tenant, thMatched[0].Tenant) + } else if !reflect.DeepEqual(ths[1].ID, thMatched[0].ID) { + t.Errorf("Expecting: %+v, received: %+v", ths[1].ID, thMatched[0].ID) + } else if thMatched[0].Hits != 1 { + t.Errorf("Expecting: 1, received: %+v", thMatched[0].Hits) + } + + thMatched, err = thServ.matchingThresholdsForEvent(argsGetThresholds[2].Tenant, argsGetThresholds[2]) + if err != nil { + t.Errorf("Error: %+v", err) + } + thMatched.unlock() + if !reflect.DeepEqual(ths[2].Tenant, thMatched[0].Tenant) { + t.Errorf("Expecting: %+v, received: %+v", ths[2].Tenant, thMatched[0].Tenant) + } else if !reflect.DeepEqual(ths[2].ID, thMatched[0].ID) { + t.Errorf("Expecting: %+v, received: %+v", ths[2].ID, thMatched[0].ID) + } else if thMatched[0].Hits != 1 { + t.Errorf("Expecting: 1, received: %+v", thMatched[0].Hits) + } + } + + func TestThresholdsProcessEvent2(t *testing.T) { + var dmTH *DataManager + var thServ *ThresholdService + tPrfls := []*ThresholdProfile{ + { + Tenant: "cgrates.org", + ID: "TH_1", + FilterIDs: []string{"FLTR_TH_1"}, + MaxHits: 12, + Blocker: false, + Weight: 20.0, + ActionProfileIDs: []string{"ACT_1", "ACT_2"}, + Async: false, + }, + { + Tenant: "cgrates.org", + ID: "TH_2", + FilterIDs: []string{"FLTR_TH_2"}, + MaxHits: 12, + MinSleep: 5 * time.Minute, + Blocker: false, + Weight: 20.0, + ActionProfileIDs: []string{"ACT_1", "ACT_2"}, + Async: false, + }, + { + Tenant: "cgrates.org", + ID: "TH_3", + FilterIDs: []string{"FLTR_TH_3"}, + MaxHits: 12, + MinSleep: 5 * time.Minute, + Blocker: false, + Weight: 20.0, + ActionProfileIDs: []string{"ACT_1", "ACT_2"}, + Async: false, + }, + } + ths := Thresholds{ + &Threshold{ + Tenant: "cgrates.org", + ID: "TH_1", + Hits: 0, + }, + &Threshold{ + Tenant: "cgrates.org", + ID: "TH_2", + Hits: 0, + }, + &Threshold{ + Tenant: "cgrates.org", + ID: "TH_3", + Hits: 0, + }, + } + argsGetThresholds := []*utils.CGREvent{ + { + Tenant: "cgrates.org", + ID: "Ev1", + Event: map[string]interface{}{ + "Threshold": "TH_1", + "Weight": "10.0", + }, + }, + { + Tenant: "cgrates.org", + ID: "Ev1", + Event: map[string]interface{}{ + "Threshold": "TH_2", + "Weight": "20.0", + }, + }, + { + Tenant: "cgrates.org", + ID: "Ev1", + Event: map[string]interface{}{ + "Threshold": "ThresholdPrefix123", + }, + }, + } + + cfg := config.NewDefaultCGRConfig() + data := NewInternalDB(nil, nil, cfg.DataDbCfg().Items) + dmTH = NewDataManager(data, config.CgrConfig().CacheCfg(), nil) + cfg.ThresholdSCfg().StoreInterval = 0 + cfg.ThresholdSCfg().StringIndexedFields = nil + cfg.ThresholdSCfg().PrefixIndexedFields = nil + thServ = NewThresholdService(dmTH, cfg, &FilterS{dm: dmTH, cfg: cfg}) + if err != nil { + t.Errorf("Error: %+v", err) + } + + fltrTh1 := &Filter{ + Tenant: config.CgrConfig().GeneralCfg().DefaultTenant, + ID: "FLTR_TH_1", + Rules: []*FilterRule{ + { + Type: utils.MetaString, + Element: "~*req.Threshold", + Values: []string{"TH_1"}, + }, + { + Type: utils.MetaGreaterOrEqual, + Element: utils.DynamicDataPrefix + utils.MetaReq + utils.NestingSep + utils.Weight, + Values: []string{"9.0"}, + }, + }, + } + dmTH.SetFilter(context.TODO(), fltrTh1, true) + fltrTh2 := &Filter{ + Tenant: config.CgrConfig().GeneralCfg().DefaultTenant, + ID: "FLTR_TH_2", + Rules: []*FilterRule{ + { + Type: utils.MetaString, + Element: "~*req.Threshold", + Values: []string{"TH_2"}, + }, + { + Type: utils.MetaGreaterOrEqual, + Element: utils.DynamicDataPrefix + utils.MetaReq + utils.NestingSep + utils.Weight, + Values: []string{"15.0"}, + }, + }, + } + dmTH.SetFilter(context.TODO(), fltrTh2, true) + fltrTh3 := &Filter{ + Tenant: config.CgrConfig().GeneralCfg().DefaultTenant, + ID: "FLTR_TH_3", + Rules: []*FilterRule{ + { + Type: utils.MetaPrefix, + Element: "~*req.Threshold", + Values: []string{"ThresholdPrefix"}, + }, + }, + } + dmTH.SetFilter(context.TODO(), fltrTh3, true) + + for _, th := range tPrfls { + if err = dmTH.SetThresholdProfile(context.Background(),th, true); err != nil { + t.Errorf("Error: %+v", err) + } + } + //Test each threshold profile from cache + for _, th := range tPrfls { + if temptTh, err := dmTH.GetThresholdProfile(context.Background(),th.Tenant, + th.ID, true, false, utils.NonTransactional); err != nil { + t.Errorf("Error: %+v", err) + } else if !reflect.DeepEqual(th, temptTh) { + t.Errorf("Expecting: %+v, received: %+v", th, temptTh) + } + } + for _, th := range ths { + if err = dmTH.SetThreshold(context.Background(),th); err != nil { + t.Errorf("Error: %+v", err) + } + } + //Test each threshold profile from cache + for _, th := range ths { + if temptTh, err := dmTH.GetThreshold(context.Background(),th.Tenant, + th.ID, true, false, utils.NonTransactional); err != nil { + t.Errorf("Error: %+v", err) + } else if !reflect.DeepEqual(th, temptTh) { + t.Errorf("Expecting: %+v, received: %+v", th, temptTh) + } + } + + thPrf := &ThresholdProfile{ Tenant: "cgrates.org", - ID: "TH_1", + ID: "TH_4", FilterIDs: []string{"FLTR_TH_1"}, MaxHits: 12, Blocker: false, Weight: 20.0, ActionProfileIDs: []string{"ACT_1", "ACT_2"}, Async: false, - }, - { - Tenant: "cgrates.org", - ID: "TH_2", - FilterIDs: []string{"FLTR_TH_2"}, - MaxHits: 12, - MinSleep: 5 * time.Minute, - Blocker: false, - Weight: 20.0, - ActionProfileIDs: []string{"ACT_1", "ACT_2"}, - Async: false, - }, - { - Tenant: "cgrates.org", - ID: "TH_3", - FilterIDs: []string{"FLTR_TH_3"}, - MaxHits: 12, - MinSleep: 5 * time.Minute, - Blocker: false, - Weight: 20.0, - ActionProfileIDs: []string{"ACT_1", "ACT_2"}, - Async: false, - }, - } - ths := Thresholds{ - &Threshold{ + } + th := &Threshold{ Tenant: "cgrates.org", - ID: "TH_1", + ID: "TH_4", Hits: 0, - }, - &Threshold{ - Tenant: "cgrates.org", - ID: "TH_2", - Hits: 0, - }, - &Threshold{ - Tenant: "cgrates.org", - ID: "TH_3", - Hits: 0, - }, - } - argsGetThresholds := []*utils.CGREvent{ - { - Tenant: "cgrates.org", - ID: "Ev1", - Event: map[string]interface{}{ - "Threshold": "TH_1", - "Weight": "10.0", - }, - }, - { - Tenant: "cgrates.org", - ID: "Ev1", - Event: map[string]interface{}{ - "Threshold": "TH_2", - "Weight": "20.0", - }, - }, - { - Tenant: "cgrates.org", - ID: "Ev1", - Event: map[string]interface{}{ - "Threshold": "ThresholdPrefix123", - }, - }, - } - - cfg := config.NewDefaultCGRConfig() - data := NewInternalDB(nil, nil, cfg.DataDbCfg().Items) - dmTH = NewDataManager(data, config.CgrConfig().CacheCfg(), nil) - cfg.ThresholdSCfg().StoreInterval = 0 - cfg.ThresholdSCfg().StringIndexedFields = nil - cfg.ThresholdSCfg().PrefixIndexedFields = nil - thServ = NewThresholdService(dmTH, cfg, &FilterS{dm: dmTH, cfg: cfg}) - if err != nil { - t.Errorf("Error: %+v", err) - } - fltrTh1 := &Filter{ - Tenant: config.CgrConfig().GeneralCfg().DefaultTenant, - ID: "FLTR_TH_1", - Rules: []*FilterRule{ - { - Type: utils.MetaString, - Element: "~*req.Threshold", - Values: []string{"TH_1"}, - }, - { - Type: utils.MetaGreaterOrEqual, - Element: utils.DynamicDataPrefix + utils.MetaReq + utils.NestingSep + utils.Weight, - Values: []string{"9.0"}, - }, - }, - } - dmTH.SetFilter(context.TODO(), fltrTh1, true) - fltrTh2 := &Filter{ - Tenant: config.CgrConfig().GeneralCfg().DefaultTenant, - ID: "FLTR_TH_2", - Rules: []*FilterRule{ - { - Type: utils.MetaString, - Element: "~*req.Threshold", - Values: []string{"TH_2"}, - }, - { - Type: utils.MetaGreaterOrEqual, - Element: utils.DynamicDataPrefix + utils.MetaReq + utils.NestingSep + utils.Weight, - Values: []string{"15.0"}, - }, - }, - } - dmTH.SetFilter(context.TODO(), fltrTh2, true) - fltrTh3 := &Filter{ - Tenant: config.CgrConfig().GeneralCfg().DefaultTenant, - ID: "FLTR_TH_3", - Rules: []*FilterRule{ - { - Type: utils.MetaPrefix, - Element: "~*req.Threshold", - Values: []string{"ThresholdPrefix"}, - }, - }, - } - dmTH.SetFilter(context.TODO(), fltrTh3, true) - for _, th := range tPrfls { - if err = dmTH.SetThresholdProfile(context.Background(),th, true); err != nil { + } + ev := &ThresholdsArgsProcessEvent{ + ThresholdIDs: []string{"TH_1", "TH_2", "TH_3", "TH_4"}, + CGREvent: argsGetThresholds[0].CGREvent, + } + if err = dmTH.SetThresholdProfile(context.Background(),thPrf, true); err != nil { t.Errorf("Error: %+v", err) } - } - //Test each threshold profile from cache - for _, th := range tPrfls { - if temptTh, err := dmTH.GetThresholdProfile(context.Background(),th.Tenant, - th.ID, true, false, utils.NonTransactional); err != nil { + if temptTh, err := dmTH.GetThresholdProfile(context.Background(),thPrf.Tenant, + thPrf.ID, true, false, utils.NonTransactional); err != nil { t.Errorf("Error: %+v", err) - } else if !reflect.DeepEqual(th, temptTh) { + } else if !reflect.DeepEqual(thPrf, temptTh) { t.Errorf("Expecting: %+v, received: %+v", th, temptTh) } - } - for _, th := range ths { if err = dmTH.SetThreshold(context.Background(),th); err != nil { t.Errorf("Error: %+v", err) } - } - //Test each threshold profile from cache - for _, th := range ths { if temptTh, err := dmTH.GetThreshold(context.Background(),th.Tenant, th.ID, true, false, utils.NonTransactional); err != nil { t.Errorf("Error: %+v", err) } else if !reflect.DeepEqual(th, temptTh) { t.Errorf("Expecting: %+v, received: %+v", th, temptTh) } - } - thIDs := []string{"TH_1"} - if thMatched, err := thServ.processEvent(context.Background(),argsGetThresholds[0].Tenant, argsGetThresholds[0]); err != utils.ErrPartiallyExecuted { - t.Errorf("Error: %+v", err) - } else if !reflect.DeepEqual(thIDs, thMatched) { - t.Errorf("Expecting: %+v, received: %+v", thIDs, thMatched) - } - - thIDs = []string{"TH_2"} - if thMatched, err := thServ.processEvent(context.Background(),argsGetThresholds[1].Tenant, argsGetThresholds[1]); err != utils.ErrPartiallyExecuted { - t.Errorf("Error: %+v", err) - } else if !reflect.DeepEqual(thIDs, thMatched) { - t.Errorf("Expecting: %+v, received: %+v", thIDs, thMatched) - } - - thIDs = []string{"TH_3"} - if thMatched, err := thServ.processEvent(context.Background(),argsGetThresholds[2].Tenant, argsGetThresholds[2]); err != utils.ErrPartiallyExecuted { - t.Errorf("Error: %+v", err) - } else if !reflect.DeepEqual(thIDs, thMatched) { - t.Errorf("Expecting: %+v, received: %+v", thIDs, thMatched) - } -} - -func TestThresholdsVerifyIfExecuted(t *testing.T) { - var dmTH *DataManager - var thServ *ThresholdService - var tPrfls = []*ThresholdProfile{ - { - Tenant: "cgrates.org", - ID: "TH_1", - FilterIDs: []string{"FLTR_TH_1"}, - MaxHits: 12, - Blocker: false, - Weight: 20.0, - ActionProfileIDs: []string{"ACT_1", "ACT_2"}, - Async: false, - }, - { - Tenant: "cgrates.org", - ID: "TH_2", - FilterIDs: []string{"FLTR_TH_2"}, - MaxHits: 12, - MinSleep: 5 * time.Minute, - Blocker: false, - Weight: 20.0, - ActionProfileIDs: []string{"ACT_1", "ACT_2"}, - Async: false, - }, - { - Tenant: "cgrates.org", - ID: "TH_3", - FilterIDs: []string{"FLTR_TH_3"}, - MaxHits: 12, - MinSleep: 5 * time.Minute, - Blocker: false, - Weight: 20.0, - ActionProfileIDs: []string{"ACT_1", "ACT_2"}, - Async: false, - }, - } - ths := Thresholds{ - &Threshold{ - Tenant: "cgrates.org", - ID: "TH_1", - Hits: 0, - }, - &Threshold{ - Tenant: "cgrates.org", - ID: "TH_2", - Hits: 0, - }, - &Threshold{ - Tenant: "cgrates.org", - ID: "TH_3", - Hits: 0, - }, - } - argsGetThresholds := []*utils.CGREvent{ - { - Tenant: "cgrates.org", - ID: "Ev1", - Event: map[string]interface{}{ - "Threshold": "TH_1", - "Weight": "10.0", - }, - }, - { - Tenant: "cgrates.org", - ID: "Ev1", - Event: map[string]interface{}{ - "Threshold": "TH_2", - "Weight": "20.0", - }, - }, - { - Tenant: "cgrates.org", - ID: "Ev1", - Event: map[string]interface{}{ - "Threshold": "ThresholdPrefix123", - }, - }, - } - - cfg := config.NewDefaultCGRConfig() - data := NewInternalDB(nil, nil, cfg.DataDbCfg().Items) - dmTH = NewDataManager(data, config.CgrConfig().CacheCfg(), nil) - cfg.ThresholdSCfg().StoreInterval = 0 - cfg.ThresholdSCfg().StringIndexedFields = nil - cfg.ThresholdSCfg().PrefixIndexedFields = nil - thServ = NewThresholdService(dmTH, cfg, &FilterS{dm: dmTH, cfg: cfg}) - if err != nil { - t.Errorf("Error: %+v", err) - } - fltrTh1 := &Filter{ - Tenant: config.CgrConfig().GeneralCfg().DefaultTenant, - ID: "FLTR_TH_1", - Rules: []*FilterRule{ - { - Type: utils.MetaString, - Element: "~*req.Threshold", - Values: []string{"TH_1"}, - }, - { - Type: utils.MetaGreaterOrEqual, - Element: utils.DynamicDataPrefix + utils.MetaReq + utils.NestingSep + utils.Weight, - Values: []string{"9.0"}, - }, - }, - } - dmTH.SetFilter(context.TODO(), fltrTh1, true) - fltrTh2 := &Filter{ - Tenant: config.CgrConfig().GeneralCfg().DefaultTenant, - ID: "FLTR_TH_2", - Rules: []*FilterRule{ - { - Type: utils.MetaString, - Element: "~*req.Threshold", - Values: []string{"TH_2"}, - }, - { - Type: utils.MetaGreaterOrEqual, - Element: utils.DynamicDataPrefix + utils.MetaReq + utils.NestingSep + utils.Weight, - Values: []string{"15.0"}, - }, - }, - } - dmTH.SetFilter(context.TODO(), fltrTh2, true) - fltrTh3 := &Filter{ - Tenant: config.CgrConfig().GeneralCfg().DefaultTenant, - ID: "FLTR_TH_3", - Rules: []*FilterRule{ - { - Type: utils.MetaPrefix, - Element: "~*req.Threshold", - Values: []string{"ThresholdPrefix"}, - }, - }, - } - dmTH.SetFilter(context.TODO(), fltrTh3, true) - for _, th := range tPrfls { - if err = dmTH.SetThresholdProfile(context.Background(),th, true); err != nil { + thIDs := []string{"TH_1", "TH_4"} + thIDsRev := []string{"TH_4", "TH_1"} + if thMatched, err := thServ.processEvent(ev.Tenant, ev); err != utils.ErrPartiallyExecuted { t.Errorf("Error: %+v", err) + } else if !reflect.DeepEqual(thIDs, thMatched) && !reflect.DeepEqual(thIDsRev, thMatched) { + t.Errorf("Expecting: %+v, received: %+v", thIDs, thMatched) + } + thMatched, err := thServ.matchingThresholdsForEvent(ev.Tenant, ev) + if err != nil { + t.Fatalf("Error: %+v", err) + } + thMatched.unlock() + for _, thM := range thMatched { + if !reflect.DeepEqual(thPrf.Tenant, thM.Tenant) { + t.Errorf("Expecting: %+v, received: %+v", thPrf.Tenant, thM.Tenant) + } else if reflect.DeepEqual(thIDs[0], thM.ID) && thM.Hits != 1 { + t.Errorf("Expecting: 1 for %+v, received: %+v", thM.ID, thM.Hits) + } else if reflect.DeepEqual(thIDs[1], thM.ID) && thM.Hits != 1 { + t.Errorf("Expecting: 1 for %+v, received: %+v", thM.ID, thM.Hits) + } } } - //Test each threshold profile from cache - for _, th := range tPrfls { - if temptTh, err := dmTH.GetThresholdProfile(context.Background(),th.Tenant, - th.ID, true, false, utils.NonTransactional); err != nil { - t.Errorf("Error: %+v", err) - } else if !reflect.DeepEqual(th, temptTh) { - t.Errorf("Expecting: %+v, received: %+v", th, temptTh) - } - } - for _, th := range ths { - if err = dmTH.SetThreshold(context.Background(),th); err != nil { - t.Errorf("Error: %+v", err) - } - } - thIDs := []string{"TH_1"} - if thMatched, err := thServ.processEvent(context.Background(),argsGetThresholds[0].Tenant, argsGetThresholds[0]); err != utils.ErrPartiallyExecuted { - t.Errorf("Error: %+v", err) - } else if !reflect.DeepEqual(thIDs, thMatched) { - t.Errorf("Expecting: %+v, received: %+v", thIDs, thMatched) - } - - thIDs = []string{"TH_2"} - if thMatched, err := thServ.processEvent(context.Background(),argsGetThresholds[1].Tenant, argsGetThresholds[1]); err != utils.ErrPartiallyExecuted { - t.Errorf("Error: %+v", err) - } else if !reflect.DeepEqual(thIDs, thMatched) { - t.Errorf("Expecting: %+v, received: %+v", thIDs, thMatched) - } - - thIDs = []string{"TH_3"} - if thMatched, err := thServ.processEvent(context.Background(),argsGetThresholds[2].Tenant, argsGetThresholds[2]); err != utils.ErrPartiallyExecuted { - t.Errorf("Error: %+v", err) - } else if !reflect.DeepEqual(thIDs, thMatched) { - t.Errorf("Expecting: %+v, received: %+v", thIDs, thMatched) - } - thMatched, err := thServ.matchingThresholdsForEvent(argsGetThresholds[0].Tenant, argsGetThresholds[0]) - if err != nil { - t.Errorf("Error: %+v", err) - } - thMatched.unlock() - if !reflect.DeepEqual(ths[0].Tenant, thMatched[0].Tenant) { - t.Errorf("Expecting: %+v, received: %+v", ths[0].Tenant, thMatched[0].Tenant) - } else if !reflect.DeepEqual(ths[0].ID, thMatched[0].ID) { - t.Errorf("Expecting: %+v, received: %+v", ths[0].ID, thMatched[0].ID) - } else if thMatched[0].Hits != 1 { - t.Errorf("Expecting: 1, received: %+v", thMatched[0].Hits) - } - - thMatched, err = thServ.matchingThresholdsForEvent(argsGetThresholds[1].Tenant, argsGetThresholds[1]) - if err != nil { - t.Errorf("Error: %+v", err) - } - thMatched.unlock() - if !reflect.DeepEqual(ths[1].Tenant, thMatched[0].Tenant) { - t.Errorf("Expecting: %+v, received: %+v", ths[1].Tenant, thMatched[0].Tenant) - } else if !reflect.DeepEqual(ths[1].ID, thMatched[0].ID) { - t.Errorf("Expecting: %+v, received: %+v", ths[1].ID, thMatched[0].ID) - } else if thMatched[0].Hits != 1 { - t.Errorf("Expecting: 1, received: %+v", thMatched[0].Hits) - } - - thMatched, err = thServ.matchingThresholdsForEvent(argsGetThresholds[2].Tenant, argsGetThresholds[2]) - if err != nil { - t.Errorf("Error: %+v", err) - } - thMatched.unlock() - if !reflect.DeepEqual(ths[2].Tenant, thMatched[0].Tenant) { - t.Errorf("Expecting: %+v, received: %+v", ths[2].Tenant, thMatched[0].Tenant) - } else if !reflect.DeepEqual(ths[2].ID, thMatched[0].ID) { - t.Errorf("Expecting: %+v, received: %+v", ths[2].ID, thMatched[0].ID) - } else if thMatched[0].Hits != 1 { - t.Errorf("Expecting: 1, received: %+v", thMatched[0].Hits) - } -} -func TestThresholdsProcessEvent2(t *testing.T) { - var dmTH *DataManager - var thServ *ThresholdService - tPrfls := []*ThresholdProfile{ - { - Tenant: "cgrates.org", - ID: "TH_1", - FilterIDs: []string{"FLTR_TH_1"}, - MaxHits: 12, - Blocker: false, - Weight: 20.0, - ActionProfileIDs: []string{"ACT_1", "ACT_2"}, - Async: false, - }, - { - Tenant: "cgrates.org", - ID: "TH_2", - FilterIDs: []string{"FLTR_TH_2"}, - MaxHits: 12, - MinSleep: 5 * time.Minute, - Blocker: false, - Weight: 20.0, - ActionProfileIDs: []string{"ACT_1", "ACT_2"}, - Async: false, - }, - { - Tenant: "cgrates.org", - ID: "TH_3", - FilterIDs: []string{"FLTR_TH_3"}, - MaxHits: 12, - MinSleep: 5 * time.Minute, - Blocker: false, - Weight: 20.0, - ActionProfileIDs: []string{"ACT_1", "ACT_2"}, - Async: false, - }, - } - ths := Thresholds{ - &Threshold{ - Tenant: "cgrates.org", - ID: "TH_1", - Hits: 0, - }, - &Threshold{ - Tenant: "cgrates.org", - ID: "TH_2", - Hits: 0, - }, - &Threshold{ - Tenant: "cgrates.org", - ID: "TH_3", - Hits: 0, - }, - } - argsGetThresholds := []*utils.CGREvent{ - { - Tenant: "cgrates.org", - ID: "Ev1", - Event: map[string]interface{}{ - "Threshold": "TH_1", - "Weight": "10.0", - }, - }, - { - Tenant: "cgrates.org", - ID: "Ev1", - Event: map[string]interface{}{ - "Threshold": "TH_2", - "Weight": "20.0", - }, - }, - { - Tenant: "cgrates.org", - ID: "Ev1", - Event: map[string]interface{}{ - "Threshold": "ThresholdPrefix123", - }, - }, - } - - cfg := config.NewDefaultCGRConfig() - data := NewInternalDB(nil, nil, cfg.DataDbCfg().Items) - dmTH = NewDataManager(data, config.CgrConfig().CacheCfg(), nil) - cfg.ThresholdSCfg().StoreInterval = 0 - cfg.ThresholdSCfg().StringIndexedFields = nil - cfg.ThresholdSCfg().PrefixIndexedFields = nil - thServ = NewThresholdService(dmTH, cfg, &FilterS{dm: dmTH, cfg: cfg}) - if err != nil { - t.Errorf("Error: %+v", err) - } - - fltrTh1 := &Filter{ - Tenant: config.CgrConfig().GeneralCfg().DefaultTenant, - ID: "FLTR_TH_1", - Rules: []*FilterRule{ - { - Type: utils.MetaString, - Element: "~*req.Threshold", - Values: []string{"TH_1"}, - }, - { - Type: utils.MetaGreaterOrEqual, - Element: utils.DynamicDataPrefix + utils.MetaReq + utils.NestingSep + utils.Weight, - Values: []string{"9.0"}, - }, - }, - } - dmTH.SetFilter(context.TODO(), fltrTh1, true) - fltrTh2 := &Filter{ - Tenant: config.CgrConfig().GeneralCfg().DefaultTenant, - ID: "FLTR_TH_2", - Rules: []*FilterRule{ - { - Type: utils.MetaString, - Element: "~*req.Threshold", - Values: []string{"TH_2"}, - }, - { - Type: utils.MetaGreaterOrEqual, - Element: utils.DynamicDataPrefix + utils.MetaReq + utils.NestingSep + utils.Weight, - Values: []string{"15.0"}, - }, - }, - } - dmTH.SetFilter(context.TODO(), fltrTh2, true) - fltrTh3 := &Filter{ - Tenant: config.CgrConfig().GeneralCfg().DefaultTenant, - ID: "FLTR_TH_3", - Rules: []*FilterRule{ - { - Type: utils.MetaPrefix, - Element: "~*req.Threshold", - Values: []string{"ThresholdPrefix"}, - }, - }, - } - dmTH.SetFilter(context.TODO(), fltrTh3, true) - - for _, th := range tPrfls { - if err = dmTH.SetThresholdProfile(context.Background(),th, true); err != nil { - t.Errorf("Error: %+v", err) - } - } - //Test each threshold profile from cache - for _, th := range tPrfls { - if temptTh, err := dmTH.GetThresholdProfile(context.Background(),th.Tenant, - th.ID, true, false, utils.NonTransactional); err != nil { - t.Errorf("Error: %+v", err) - } else if !reflect.DeepEqual(th, temptTh) { - t.Errorf("Expecting: %+v, received: %+v", th, temptTh) - } - } - for _, th := range ths { - if err = dmTH.SetThreshold(context.Background(),th); err != nil { - t.Errorf("Error: %+v", err) - } - } - //Test each threshold profile from cache - for _, th := range ths { - if temptTh, err := dmTH.GetThreshold(context.Background(),th.Tenant, - th.ID, true, false, utils.NonTransactional); err != nil { - t.Errorf("Error: %+v", err) - } else if !reflect.DeepEqual(th, temptTh) { - t.Errorf("Expecting: %+v, received: %+v", th, temptTh) - } - } - - thPrf := &ThresholdProfile{ - Tenant: "cgrates.org", - ID: "TH_4", - FilterIDs: []string{"FLTR_TH_1"}, - MaxHits: 12, - Blocker: false, - Weight: 20.0, - ActionProfileIDs: []string{"ACT_1", "ACT_2"}, - Async: false, - } - th := &Threshold{ - Tenant: "cgrates.org", - ID: "TH_4", - Hits: 0, - } - ev := &ThresholdsArgsProcessEvent{ - ThresholdIDs: []string{"TH_1", "TH_2", "TH_3", "TH_4"}, - CGREvent: argsGetThresholds[0].CGREvent, - } - if err = dmTH.SetThresholdProfile(context.Background(),thPrf, true); err != nil { - t.Errorf("Error: %+v", err) - } - if temptTh, err := dmTH.GetThresholdProfile(context.Background(),thPrf.Tenant, - thPrf.ID, true, false, utils.NonTransactional); err != nil { - t.Errorf("Error: %+v", err) - } else if !reflect.DeepEqual(thPrf, temptTh) { - t.Errorf("Expecting: %+v, received: %+v", th, temptTh) - } - if err = dmTH.SetThreshold(context.Background(),th); err != nil { - t.Errorf("Error: %+v", err) - } - if temptTh, err := dmTH.GetThreshold(context.Background(),th.Tenant, - th.ID, true, false, utils.NonTransactional); err != nil { - t.Errorf("Error: %+v", err) - } else if !reflect.DeepEqual(th, temptTh) { - t.Errorf("Expecting: %+v, received: %+v", th, temptTh) - } - thIDs := []string{"TH_1", "TH_4"} - thIDsRev := []string{"TH_4", "TH_1"} - if thMatched, err := thServ.processEvent(ev.Tenant, ev); err != utils.ErrPartiallyExecuted { - t.Errorf("Error: %+v", err) - } else if !reflect.DeepEqual(thIDs, thMatched) && !reflect.DeepEqual(thIDsRev, thMatched) { - t.Errorf("Expecting: %+v, received: %+v", thIDs, thMatched) - } - thMatched, err := thServ.matchingThresholdsForEvent(ev.Tenant, ev) - if err != nil { - t.Fatalf("Error: %+v", err) - } - thMatched.unlock() - for _, thM := range thMatched { - if !reflect.DeepEqual(thPrf.Tenant, thM.Tenant) { - t.Errorf("Expecting: %+v, received: %+v", thPrf.Tenant, thM.Tenant) - } else if reflect.DeepEqual(thIDs[0], thM.ID) && thM.Hits != 1 { - t.Errorf("Expecting: 1 for %+v, received: %+v", thM.ID, thM.Hits) - } else if reflect.DeepEqual(thIDs[1], thM.ID) && thM.Hits != 1 { - t.Errorf("Expecting: 1 for %+v, received: %+v", thM.ID, thM.Hits) - } - } -} */ func TestThresholdsUpdateThreshold(t *testing.T) { cfg := config.NewDefaultCGRConfig() diff --git a/engine/z_resources_test.go b/engine/z_resources_test.go index 49896f925..e68e1c390 100644 --- a/engine/z_resources_test.go +++ b/engine/z_resources_test.go @@ -1321,7 +1321,7 @@ func TestResourceMatchingResourcesForEvent(t *testing.T) { } } -//UsageTTL 0 in ResourceProfile and give 10s duration +// UsageTTL 0 in ResourceProfile and give 10s duration func TestResourceUsageTTLCase1(t *testing.T) { resprf := []*ResourceProfile{ { @@ -1527,7 +1527,7 @@ func TestResourceUsageTTLCase1(t *testing.T) { } } -//UsageTTL 5s in ResourceProfile and give nil duration +// UsageTTL 5s in ResourceProfile and give nil duration func TestResourceUsageTTLCase2(t *testing.T) { resprf := []*ResourceProfile{ { @@ -1730,7 +1730,7 @@ func TestResourceUsageTTLCase2(t *testing.T) { } } -//UsageTTL 5s in ResourceProfile and give 0 duration +// UsageTTL 5s in ResourceProfile and give 0 duration func TestResourceUsageTTLCase3(t *testing.T) { resprf := []*ResourceProfile{ { @@ -1934,7 +1934,7 @@ func TestResourceUsageTTLCase3(t *testing.T) { } } -//UsageTTL 5s in ResourceProfile and give 10s duration +// UsageTTL 5s in ResourceProfile and give 10s duration func TestResourceUsageTTLCase4(t *testing.T) { resprf := []*ResourceProfile{ { diff --git a/ers/filejson_it_test.go b/ers/filejson_it_test.go index a3862cd49..d390edc2a 100644 --- a/ers/filejson_it_test.go +++ b/ers/filejson_it_test.go @@ -31,24 +31,27 @@ import ( /* var ( + jsonCfgPath string jsonCfgDIR string jsonCfg *config.CGRConfig jsonRPC *rpc.Client fileContent = ` -{ - "Tenant": "cgrates.org", - "Account": "voiceAccount", - "AnswerTime": "2018-08-24T16:00:26Z", - "SetupTime": "2018-08-24T16:00:26Z", - "Destination": "+4986517174963", - "OriginHost": "192.168.1.1", - "OriginID": "testJsonCDR", - "RequestType": "*pseudoprepaid", - "Source": "jsonFile", - "Usage": 120000000000 -}` + + { + "Tenant": "cgrates.org", + "Account": "voiceAccount", + "AnswerTime": "2018-08-24T16:00:26Z", + "SetupTime": "2018-08-24T16:00:26Z", + "Destination": "+4986517174963", + "OriginHost": "192.168.1.1", + "OriginID": "testJsonCDR", + "RequestType": "*pseudoprepaid", + "Source": "jsonFile", + "Usage": 120000000000 + }` + jsonTests = []func(t *testing.T){ testCreateDirs, testJSONInitConfig, @@ -62,154 +65,157 @@ var ( testCleanupFiles, testJSONKillEngine, } + ) -func TestJSONReadFile(t *testing.T) { - switch *dbType { - case utils.MetaInternal: - jsonCfgDIR = "ers_internal" - case utils.MetaMySQL: - jsonCfgDIR = "ers_mysql" - case utils.MetaMongo: - jsonCfgDIR = "ers_mongo" - case utils.MetaPostgres: - jsonCfgDIR = "ers_postgres" - default: - t.Fatal("Unknown Database type") - } + func TestJSONReadFile(t *testing.T) { + switch *dbType { + case utils.MetaInternal: + jsonCfgDIR = "ers_internal" + case utils.MetaMySQL: + jsonCfgDIR = "ers_mysql" + case utils.MetaMongo: + jsonCfgDIR = "ers_mongo" + case utils.MetaPostgres: + jsonCfgDIR = "ers_postgres" + default: + t.Fatal("Unknown Database type") + } - for _, test := range jsonTests { - t.Run(jsonCfgDIR, test) - } -} - -func testJSONInitConfig(t *testing.T) { - var err error - jsonCfgPath = path.Join(*dataDir, "conf", "samples", jsonCfgDIR) - if jsonCfg, err = config.NewCGRConfigFromPath(jsonCfgPath); err != nil { - t.Fatal("Got config error: ", err.Error()) - } -} - - -// Remove data in both rating and accounting db -func testJSONResetDataDb(t *testing.T) { - if err := engine.InitDataDB(jsonCfg); err != nil { - t.Fatal(err) - } -} - -func testJSONStartEngine(t *testing.T) { - if _, err := engine.StopStartEngine(jsonCfgPath, *waitRater); err != nil { - t.Fatal(err) - } -} - -// Connect rpc client to rater -func testJSONRpcConn(t *testing.T) { - var err error - jsonRPC, err = newRPCClient(jsonCfg.ListenCfg()) // We connect over JSON so we can also troubleshoot if needed - if err != nil { - t.Fatal("Could not connect to rater: ", err.Error()) - } -} - -func testJSONAddData(t *testing.T) { - var reply string - //add a charger - chargerProfile := &v1.ChargerWithAPIOpts{ - ChargerProfile: &engine.ChargerProfile{ - Tenant: "cgrates.org", - ID: "Default", - RunID: utils.MetaDefault, - AttributeIDs: []string{"*none"}, - Weight: 20, - }, - APIOpts: map[string]interface{}{ - utils.CacheOpt: utils.MetaReload, - }, - } - if err := jsonRPC.Call(utils.AdminSv1SetChargerProfile, chargerProfile, &reply); err != nil { - t.Error(err) - } else if reply != utils.OK { - t.Error("Unexpected reply returned", reply) - } - - attrSetAcnt := apis.AttrSetAccount{ - Tenant: "cgrates.org", - Account: "voiceAccount", - } - if err := jsonRPC.Call(utils.APIerSv2SetAccount, &attrSetAcnt, &reply); err != nil { - t.Fatal(err) - } - attrs := &utils.AttrSetBalance{ - Tenant: "cgrates.org", - Account: "voiceAccount", - BalanceType: utils.MetaVoice, - Value: 600000000000, - Balance: map[string]interface{}{ - utils.ID: utils.MetaDefault, - "RatingSubject": "*zero1m", - utils.Weight: 10.0, - }, - } - if err := jsonRPC.Call(utils.APIerSv2SetBalance, attrs, &reply); err != nil { - t.Fatal(err) - } - - var acnt *engine.Account - if err := jsonRPC.Call(utils.APIerSv2GetAccount, - &utils.AttrGetAccount{Tenant: "cgrates.org", Account: "voiceAccount"}, &acnt); err != nil { - t.Error(err) - } else if len(acnt.BalanceMap) != 1 || acnt.BalanceMap[utils.MetaVoice][0].Value != 600000000000 { - t.Errorf("Unexpected balance received: %+v", acnt.BalanceMap[utils.MetaVoice][0]) - } -} - -// The default scenario, out of ers defined in .cfg file -func testJSONHandleFile(t *testing.T) { - fileName := "file1.json" - tmpFilePath := path.Join("/tmp", fileName) - if err := os.WriteFile(tmpFilePath, []byte(fileContent), 0644); err != nil { - t.Fatal(err.Error()) - } - if err := os.Rename(tmpFilePath, path.Join("/tmp/ErsJSON/in", fileName)); err != nil { - t.Fatal("Error moving file to processing directory: ", err) - } - time.Sleep(100 * time.Millisecond) -} - -func testJSONVerify(t *testing.T) { - var cdrs []*engine.CDR - args := &utils.RPCCDRsFilterWithAPIOpts{ - RPCCDRsFilter: &utils.RPCCDRsFilter{ - OriginIDs: []string{"testJsonCDR"}, - }, - } - if err := jsonRPC.Call(utils.CDRsV1GetCDRs, args, &cdrs); err != nil { - t.Error("Unexpected error: ", err.Error()) - } else if len(cdrs) != 1 { - t.Error("Unexpected number of CDRs returned: ", len(cdrs)) - } else { - if cdrs[0].Usage != 2*time.Minute { - t.Errorf("Unexpected usage for CDR: %d", cdrs[0].Usage) + for _, test := range jsonTests { + t.Run(jsonCfgDIR, test) } } - var acnt *engine.Account - if err := jsonRPC.Call(utils.APIerSv2GetAccount, - &utils.AttrGetAccount{Tenant: "cgrates.org", Account: "voiceAccount"}, &acnt); err != nil { - t.Error(err) - } else if len(acnt.BalanceMap) != 1 || acnt.BalanceMap[utils.MetaVoice][0].Value != 480000000000 { - t.Errorf("Unexpected balance received: %+v", acnt.BalanceMap[utils.MetaVoice][0]) + func testJSONInitConfig(t *testing.T) { + var err error + jsonCfgPath = path.Join(*dataDir, "conf", "samples", jsonCfgDIR) + if jsonCfg, err = config.NewCGRConfigFromPath(jsonCfgPath); err != nil { + t.Fatal("Got config error: ", err.Error()) + } } -} -func testJSONKillEngine(t *testing.T) { - if err := engine.KillEngine(*waitRater); err != nil { - t.Error(err) +// Remove data in both rating and accounting db + + func testJSONResetDataDb(t *testing.T) { + if err := engine.InitDataDB(jsonCfg); err != nil { + t.Fatal(err) + } + } + + func testJSONStartEngine(t *testing.T) { + if _, err := engine.StopStartEngine(jsonCfgPath, *waitRater); err != nil { + t.Fatal(err) + } + } + +// Connect rpc client to rater + + func testJSONRpcConn(t *testing.T) { + var err error + jsonRPC, err = newRPCClient(jsonCfg.ListenCfg()) // We connect over JSON so we can also troubleshoot if needed + if err != nil { + t.Fatal("Could not connect to rater: ", err.Error()) + } + } + + func testJSONAddData(t *testing.T) { + var reply string + //add a charger + chargerProfile := &v1.ChargerWithAPIOpts{ + ChargerProfile: &engine.ChargerProfile{ + Tenant: "cgrates.org", + ID: "Default", + RunID: utils.MetaDefault, + AttributeIDs: []string{"*none"}, + Weight: 20, + }, + APIOpts: map[string]interface{}{ + utils.CacheOpt: utils.MetaReload, + }, + } + if err := jsonRPC.Call(utils.AdminSv1SetChargerProfile, chargerProfile, &reply); err != nil { + t.Error(err) + } else if reply != utils.OK { + t.Error("Unexpected reply returned", reply) + } + + attrSetAcnt := apis.AttrSetAccount{ + Tenant: "cgrates.org", + Account: "voiceAccount", + } + if err := jsonRPC.Call(utils.APIerSv2SetAccount, &attrSetAcnt, &reply); err != nil { + t.Fatal(err) + } + attrs := &utils.AttrSetBalance{ + Tenant: "cgrates.org", + Account: "voiceAccount", + BalanceType: utils.MetaVoice, + Value: 600000000000, + Balance: map[string]interface{}{ + utils.ID: utils.MetaDefault, + "RatingSubject": "*zero1m", + utils.Weight: 10.0, + }, + } + if err := jsonRPC.Call(utils.APIerSv2SetBalance, attrs, &reply); err != nil { + t.Fatal(err) + } + + var acnt *engine.Account + if err := jsonRPC.Call(utils.APIerSv2GetAccount, + &utils.AttrGetAccount{Tenant: "cgrates.org", Account: "voiceAccount"}, &acnt); err != nil { + t.Error(err) + } else if len(acnt.BalanceMap) != 1 || acnt.BalanceMap[utils.MetaVoice][0].Value != 600000000000 { + t.Errorf("Unexpected balance received: %+v", acnt.BalanceMap[utils.MetaVoice][0]) + } + } + +// The default scenario, out of ers defined in .cfg file + + func testJSONHandleFile(t *testing.T) { + fileName := "file1.json" + tmpFilePath := path.Join("/tmp", fileName) + if err := os.WriteFile(tmpFilePath, []byte(fileContent), 0644); err != nil { + t.Fatal(err.Error()) + } + if err := os.Rename(tmpFilePath, path.Join("/tmp/ErsJSON/in", fileName)); err != nil { + t.Fatal("Error moving file to processing directory: ", err) + } + time.Sleep(100 * time.Millisecond) + } + + func testJSONVerify(t *testing.T) { + var cdrs []*engine.CDR + args := &utils.RPCCDRsFilterWithAPIOpts{ + RPCCDRsFilter: &utils.RPCCDRsFilter{ + OriginIDs: []string{"testJsonCDR"}, + }, + } + if err := jsonRPC.Call(utils.CDRsV1GetCDRs, args, &cdrs); err != nil { + t.Error("Unexpected error: ", err.Error()) + } else if len(cdrs) != 1 { + t.Error("Unexpected number of CDRs returned: ", len(cdrs)) + } else { + if cdrs[0].Usage != 2*time.Minute { + t.Errorf("Unexpected usage for CDR: %d", cdrs[0].Usage) + } + } + + var acnt *engine.Account + if err := jsonRPC.Call(utils.APIerSv2GetAccount, + &utils.AttrGetAccount{Tenant: "cgrates.org", Account: "voiceAccount"}, &acnt); err != nil { + t.Error(err) + } else if len(acnt.BalanceMap) != 1 || acnt.BalanceMap[utils.MetaVoice][0].Value != 480000000000 { + t.Errorf("Unexpected balance received: %+v", acnt.BalanceMap[utils.MetaVoice][0]) + } + } + + func testJSONKillEngine(t *testing.T) { + if err := engine.KillEngine(*waitRater); err != nil { + t.Error(err) + } } -} */ func TestFileJSONServeErrTimeDuration0(t *testing.T) { cfg := config.NewDefaultCGRConfig() diff --git a/general_tests/accountactions_it_test.go b/general_tests/accountactions_it_test.go index 76b43663d..59749e6c1 100644 --- a/general_tests/accountactions_it_test.go +++ b/general_tests/accountactions_it_test.go @@ -58,7 +58,7 @@ var ( } ) -//Test start here +// Test start here func TestAccActionsIT(t *testing.T) { switch *dbType { case utils.MetaInternal: diff --git a/general_tests/accounts_it_test.go b/general_tests/accounts_it_test.go index f0aad1093..c0f6e2a95 100644 --- a/general_tests/accounts_it_test.go +++ b/general_tests/accounts_it_test.go @@ -272,7 +272,7 @@ func testV1AccMonthly(t *testing.T) { } -//Add test to check if AccountS send event to ThresholdS +// Add test to check if AccountS send event to ThresholdS func testV1AccSendToThreshold(t *testing.T) { var reply string diff --git a/general_tests/cdrs_it_test.go b/general_tests/cdrs_it_test.go index 212209c86..46305b6cd 100644 --- a/general_tests/cdrs_it_test.go +++ b/general_tests/cdrs_it_test.go @@ -200,7 +200,7 @@ func testCDRsProcessCDR(t *testing.T) { } } -//Disable Attributes process +// Disable Attributes process func testCDRsProcessCDR2(t *testing.T) { args := &utils.CGREvent{ Tenant: "cgrates.org", @@ -253,7 +253,7 @@ func testCDRsProcessCDR2(t *testing.T) { } } -//Disable Attributes and Charger process +// Disable Attributes and Charger process func testCDRsProcessCDR3(t *testing.T) { args := &utils.CGREvent{ Tenant: "cgrates.org", diff --git a/general_tests/cgrloader_it_test.go b/general_tests/cgrloader_it_test.go index 6eeafdb84..3b7d52ea1 100644 --- a/general_tests/cgrloader_it_test.go +++ b/general_tests/cgrloader_it_test.go @@ -52,7 +52,7 @@ var ( } ) -//Test start here +// Test start here func TestCGRLoader(t *testing.T) { if !*loaderGoogleSheet { t.SkipNow() diff --git a/general_tests/doubleremove_it_test.go b/general_tests/doubleremove_it_test.go index b6e24cd02..cf44c5b61 100644 --- a/general_tests/doubleremove_it_test.go +++ b/general_tests/doubleremove_it_test.go @@ -62,7 +62,7 @@ var ( } ) -//Test starts here +// Test starts here func TestDoubleRemoveIT(t *testing.T) { switch *dbType { case utils.MetaInternal: diff --git a/general_tests/filter_update_it_test.go b/general_tests/filter_update_it_test.go index 6b13d3d42..8d4bd506c 100644 --- a/general_tests/filter_update_it_test.go +++ b/general_tests/filter_update_it_test.go @@ -95,7 +95,7 @@ func TestFilterUpdateIT(t *testing.T) { } } -//Init Config +// Init Config func testFilterUpdateInitCfg(t *testing.T) { var err error fltrUpdateCfgPath1 = path.Join(*dataDir, "conf", "samples", "cache_replicate", fltrUpdateCfgDIR1) diff --git a/general_tests/filtered_replication_it_test.go b/general_tests/filtered_replication_it_test.go index bb179af89..940340773 100644 --- a/general_tests/filtered_replication_it_test.go +++ b/general_tests/filtered_replication_it_test.go @@ -73,7 +73,7 @@ var ( } ) -//Test start here +// Test start here func TestFilteredReplication(t *testing.T) { switch *dbType { case utils.MetaMySQL: diff --git a/general_tests/gocs_it_test.go b/general_tests/gocs_it_test.go index 1ee46b395..f347830ea 100644 --- a/general_tests/gocs_it_test.go +++ b/general_tests/gocs_it_test.go @@ -68,7 +68,7 @@ func TestGOCSIT(t *testing.T) { } } -//Init Config +// Init Config func testGOCSInitCfg(t *testing.T) { auCfgPath = path.Join(*dataDir, "conf", "samples", "gocs", "au_site") if auCfg, err = config.NewCGRConfigFromPath(context.Background(), auCfgPath); err != nil { diff --git a/general_tests/resourcesv1_it_test.go b/general_tests/resourcesv1_it_test.go index 18a49944c..000dc1ff3 100644 --- a/general_tests/resourcesv1_it_test.go +++ b/general_tests/resourcesv1_it_test.go @@ -50,7 +50,7 @@ var ( } ) -//Test start here +// Test start here func TestRsV1IT(t *testing.T) { switch *dbType { case utils.MetaInternal: diff --git a/general_tests/session_graceful_shutdown_it_test.go b/general_tests/session_graceful_shutdown_it_test.go index 4f47dea0e..0f67a1378 100644 --- a/general_tests/session_graceful_shutdown_it_test.go +++ b/general_tests/session_graceful_shutdown_it_test.go @@ -83,7 +83,7 @@ func TestSessionSRplcGracefulShutdown(t *testing.T) { } } -//Init Config +// Init Config func testSessionSRplcInitCfg(t *testing.T) { smgRplcCfgPath1 = path.Join(*dataDir, "conf", "samples", "sessions_replication", smgRplcCfgDIR1) if smgRplCfg1, err = config.NewCGRConfigFromPath(context.Background(), smgRplcCfgPath1); err != nil { diff --git a/loaders/libloader.go b/loaders/libloader.go index 251d42c3b..4ca8524f6 100644 --- a/loaders/libloader.go +++ b/loaders/libloader.go @@ -122,7 +122,7 @@ func (ar *record) FieldAsInterface(fldPath []string) (val interface{}, err error return } -//SetFields will populate fields of record out of templates +// SetFields will populate fields of record out of templates func (ar *record) SetFields(ctx *context.Context, tmpls []*config.FCTemplate, filterS *engine.FilterS, rndDec int, dftTmz, rsrSep string) (err error) { ar.tmp = &utils.DataNode{Type: utils.NMMapType, Map: make(map[string]*utils.DataNode)} for _, fld := range tmpls { diff --git a/loaders/loader_it_test.go b/loaders/loader_it_test.go index b3f2ed38f..8dedc9fae 100644 --- a/loaders/loader_it_test.go +++ b/loaders/loader_it_test.go @@ -114,7 +114,7 @@ func newRPCClient(cfg *config.ListenCfg) (c *birpc.Client, err error) { } } -//Test start here +// Test start here func TestLoaderIT(t *testing.T) { switch *dbType { case utils.MetaInternal: diff --git a/migrator/load_ids.go b/migrator/load_ids.go index 28c29656b..830565d18 100644 --- a/migrator/load_ids.go +++ b/migrator/load_ids.go @@ -23,7 +23,6 @@ import ( "github.com/cgrates/cgrates/utils" ) -// func (m *Migrator) migrateLoadIDs() (err error) { var vrs engine.Versions if vrs, err = m.getVersions(utils.LoadIDsVrs); err != nil { diff --git a/migrator/storage_map_datadb.go b/migrator/storage_map_datadb.go index d5ce2fbbd..732b61e1f 100644 --- a/migrator/storage_map_datadb.go +++ b/migrator/storage_map_datadb.go @@ -41,8 +41,8 @@ func (iDBMig *internalMigrator) DataManager() *engine.DataManager { return iDBMig.dm } -//Stats methods -//get +// Stats methods +// get func (iDBMig *internalMigrator) getV1Stats() (v1st *v1Stat, err error) { return nil, utils.ErrNotImplemented } @@ -51,7 +51,7 @@ func (iDBMig *internalMigrator) getV3Stats() (v1st *engine.StatQueueProfile, err return nil, utils.ErrNotImplemented } -//set +// set func (iDBMig *internalMigrator) setV1Stats(x *v1Stat) (err error) { return utils.ErrNotImplemented } @@ -60,24 +60,24 @@ func (iDBMig *internalMigrator) getV2Stats() (v2 *engine.StatQueue, err error) { return nil, utils.ErrNotImplemented } -//set +// set func (iDBMig *internalMigrator) setV2Stats(v2 *engine.StatQueue) (err error) { return utils.ErrNotImplemented } -//AttributeProfile methods -//get +// AttributeProfile methods +// get func (iDBMig *internalMigrator) getV1AttributeProfile() (v1attrPrf *v1AttributeProfile, err error) { return nil, utils.ErrNotImplemented } -//set +// set func (iDBMig *internalMigrator) setV1AttributeProfile(x *v1AttributeProfile) (err error) { return utils.ErrNotImplemented } -//ThresholdProfile methods -//get +// ThresholdProfile methods +// get func (iDBMig *internalMigrator) getV2ThresholdProfile() (v2T *v2Threshold, err error) { return nil, utils.ErrNotImplemented } @@ -86,50 +86,50 @@ func (iDBMig *internalMigrator) getV3ThresholdProfile() (v2T *engine.ThresholdPr return nil, utils.ErrNotImplemented } -//set +// set func (iDBMig *internalMigrator) setV2ThresholdProfile(x *v2Threshold) (err error) { return utils.ErrNotImplemented } -//rem +// rem func (iDBMig *internalMigrator) remV2ThresholdProfile(tenant, id string) (err error) { return utils.ErrNotImplemented } -//AttributeProfile methods -//get +// AttributeProfile methods +// get func (iDBMig *internalMigrator) getV2AttributeProfile() (v2attrPrf *v2AttributeProfile, err error) { return nil, utils.ErrNotImplemented } -//set +// set func (iDBMig *internalMigrator) setV2AttributeProfile(x *v2AttributeProfile) (err error) { return utils.ErrNotImplemented } -//rem +// rem func (iDBMig *internalMigrator) remV2AttributeProfile(tenant, id string) (err error) { return utils.ErrNotImplemented } -//AttributeProfile methods -//get +// AttributeProfile methods +// get func (iDBMig *internalMigrator) getV3AttributeProfile() (v3attrPrf *v3AttributeProfile, err error) { return nil, utils.ErrNotImplemented } -//set +// set func (iDBMig *internalMigrator) setV3AttributeProfile(x *v3AttributeProfile) (err error) { return utils.ErrNotImplemented } -//rem +// rem func (iDBMig *internalMigrator) remV3AttributeProfile(tenant, id string) (err error) { return utils.ErrNotImplemented } -//AttributeProfile methods -//get +// AttributeProfile methods +// get func (iDBMig *internalMigrator) getV4AttributeProfile() (v4attrPrf *v4AttributeProfile, err error) { return nil, utils.ErrNotImplemented } @@ -137,18 +137,18 @@ func (iDBMig *internalMigrator) getV5AttributeProfile() (v4attrPrf *v6AttributeP return nil, utils.ErrNotImplemented } -//set +// set func (iDBMig *internalMigrator) setV4AttributeProfile(x *v4AttributeProfile) (err error) { return utils.ErrNotImplemented } -//rem +// rem func (iDBMig *internalMigrator) remV4AttributeProfile(tenant, id string) (err error) { return utils.ErrNotImplemented } // Filter Methods -//get +// get func (iDBMig *internalMigrator) getV1Filter() (v1Fltr *v1Filter, err error) { return nil, utils.ErrNotImplemented } @@ -157,28 +157,28 @@ func (iDBMig *internalMigrator) getV4Filter() (v1Fltr *engine.Filter, err error) return nil, utils.ErrNotImplemented } -//set +// set func (iDBMig *internalMigrator) setV1Filter(x *v1Filter) (err error) { return utils.ErrNotImplemented } -//rem +// rem func (iDBMig *internalMigrator) remV1Filter(tenant, id string) (err error) { return utils.ErrNotImplemented } // Supplier Methods -//get +// get func (iDBMig *internalMigrator) getSupplier() (spl *SupplierProfile, err error) { return nil, utils.ErrNotImplemented } -//set +// set func (iDBMig *internalMigrator) setSupplier(spl *SupplierProfile) (err error) { return utils.ErrNotImplemented } -//rem +// rem func (iDBMig *internalMigrator) remSupplier(tenant, id string) (err error) { return utils.ErrNotImplemented } diff --git a/migrator/storage_mongo_datadb.go b/migrator/storage_mongo_datadb.go index 2bd9eddba..b65df4b12 100644 --- a/migrator/storage_mongo_datadb.go +++ b/migrator/storage_mongo_datadb.go @@ -58,8 +58,8 @@ func (v1ms *mongoMigrator) DataManager() *engine.DataManager { return v1ms.dm } -//Stats methods -//get +// Stats methods +// get func (v1ms *mongoMigrator) getV1Stats() (v1st *v1Stat, err error) { if v1ms.cursor == nil { v1ms.cursor, err = v1ms.mgoDB.DB().Collection(utils.CDRsStatsPrefix).Find(v1ms.mgoDB.GetContext(), bson.D{}) @@ -98,7 +98,7 @@ func (v1ms *mongoMigrator) getV3Stats() (v1st *engine.StatQueueProfile, err erro return v1st, nil } -//set +// set func (v1ms *mongoMigrator) setV1Stats(x *v1Stat) (err error) { _, err = v1ms.mgoDB.DB().Collection(utils.CDRsStatsPrefix).InsertOne(v1ms.mgoDB.GetContext(), x) return @@ -130,8 +130,8 @@ func (v1ms *mongoMigrator) setV2Stats(v2 *engine.StatQueue) (err error) { return } -//AttributeProfile methods -//get +// AttributeProfile methods +// get func (v1ms *mongoMigrator) getV1AttributeProfile() (v1attrPrf *v1AttributeProfile, err error) { if v1ms.cursor == nil { v1ms.cursor, err = v1ms.mgoDB.DB().Collection(v1AttributeProfilesCol).Find(v1ms.mgoDB.GetContext(), bson.D{}) @@ -151,14 +151,14 @@ func (v1ms *mongoMigrator) getV1AttributeProfile() (v1attrPrf *v1AttributeProfil return v1attrPrf, nil } -//set +// set func (v1ms *mongoMigrator) setV1AttributeProfile(x *v1AttributeProfile) (err error) { _, err = v1ms.mgoDB.DB().Collection(v1AttributeProfilesCol).InsertOne(v1ms.mgoDB.GetContext(), x) return } -//ThresholdProfile methods -//get +// ThresholdProfile methods +// get func (v1ms *mongoMigrator) getV2ThresholdProfile() (v2T *v2Threshold, err error) { if v1ms.cursor == nil { v1ms.cursor, err = v1ms.mgoDB.DB().Collection(v2ThresholdProfileCol).Find(v1ms.mgoDB.GetContext(), bson.D{}) @@ -197,20 +197,20 @@ func (v1ms *mongoMigrator) getV3ThresholdProfile() (v2T *engine.ThresholdProfile return v2T, nil } -//set +// set func (v1ms *mongoMigrator) setV2ThresholdProfile(x *v2Threshold) (err error) { _, err = v1ms.mgoDB.DB().Collection(v2ThresholdProfileCol).InsertOne(v1ms.mgoDB.GetContext(), x) return } -//rem +// rem func (v1ms *mongoMigrator) remV2ThresholdProfile(tenant, id string) (err error) { _, err = v1ms.mgoDB.DB().Collection(v2ThresholdProfileCol).DeleteOne(v1ms.mgoDB.GetContext(), bson.M{"tenant": tenant, "id": id}) return } -//AttributeProfile methods -//get +// AttributeProfile methods +// get func (v1ms *mongoMigrator) getV2AttributeProfile() (v2attrPrf *v2AttributeProfile, err error) { if v1ms.cursor == nil { v1ms.cursor, err = v1ms.mgoDB.DB().Collection(v1AttributeProfilesCol).Find(v1ms.mgoDB.GetContext(), bson.D{}) @@ -230,20 +230,20 @@ func (v1ms *mongoMigrator) getV2AttributeProfile() (v2attrPrf *v2AttributeProfil return v2attrPrf, nil } -//set +// set func (v1ms *mongoMigrator) setV2AttributeProfile(x *v2AttributeProfile) (err error) { _, err = v1ms.mgoDB.DB().Collection(v1AttributeProfilesCol).InsertOne(v1ms.mgoDB.GetContext(), x) return } -//rem +// rem func (v1ms *mongoMigrator) remV2AttributeProfile(tenant, id string) (err error) { _, err = v1ms.mgoDB.DB().Collection(v1AttributeProfilesCol).DeleteOne(v1ms.mgoDB.GetContext(), bson.M{"tenant": tenant, "id": id}) return } -//AttributeProfile methods -//get +// AttributeProfile methods +// get func (v1ms *mongoMigrator) getV3AttributeProfile() (v3attrPrf *v3AttributeProfile, err error) { if v1ms.cursor == nil { v1ms.cursor, err = v1ms.mgoDB.DB().Collection(v1AttributeProfilesCol).Find(v1ms.mgoDB.GetContext(), bson.D{}) @@ -263,20 +263,20 @@ func (v1ms *mongoMigrator) getV3AttributeProfile() (v3attrPrf *v3AttributeProfil return v3attrPrf, nil } -//set +// set func (v1ms *mongoMigrator) setV3AttributeProfile(x *v3AttributeProfile) (err error) { _, err = v1ms.mgoDB.DB().Collection(v1AttributeProfilesCol).InsertOne(v1ms.mgoDB.GetContext(), x) return } -//rem +// rem func (v1ms *mongoMigrator) remV3AttributeProfile(tenant, id string) (err error) { _, err = v1ms.mgoDB.DB().Collection(v1AttributeProfilesCol).DeleteOne(v1ms.mgoDB.GetContext(), bson.M{"tenant": tenant, "id": id}) return } -//AttributeProfile methods -//get +// AttributeProfile methods +// get func (v1ms *mongoMigrator) getV4AttributeProfile() (v4attrPrf *v4AttributeProfile, err error) { if v1ms.cursor == nil { v1ms.cursor, err = v1ms.mgoDB.DB().Collection(v1AttributeProfilesCol).Find(v1ms.mgoDB.GetContext(), bson.D{}) @@ -315,20 +315,20 @@ func (v1ms *mongoMigrator) getV5AttributeProfile() (v5attrPrf *v6AttributeProfil return v5attrPrf, nil } -//set +// set func (v1ms *mongoMigrator) setV4AttributeProfile(x *v4AttributeProfile) (err error) { _, err = v1ms.mgoDB.DB().Collection(v1AttributeProfilesCol).InsertOne(v1ms.mgoDB.GetContext(), x) return } -//rem +// rem func (v1ms *mongoMigrator) remV4AttributeProfile(tenant, id string) (err error) { _, err = v1ms.mgoDB.DB().Collection(v1AttributeProfilesCol).DeleteOne(v1ms.mgoDB.GetContext(), bson.M{"tenant": tenant, "id": id}) return } // Filter Methods -//get +// get func (v1ms *mongoMigrator) getV1Filter() (v1Fltr *v1Filter, err error) { if v1ms.cursor == nil { v1ms.cursor, err = v1ms.mgoDB.DB().Collection(engine.ColFlt).Find(v1ms.mgoDB.GetContext(), bson.D{}) @@ -367,20 +367,20 @@ func (v1ms *mongoMigrator) getV4Filter() (v4Fltr *engine.Filter, err error) { return } -//set +// set func (v1ms *mongoMigrator) setV1Filter(x *v1Filter) (err error) { _, err = v1ms.mgoDB.DB().Collection(engine.ColFlt).InsertOne(v1ms.mgoDB.GetContext(), x) return } -//rem +// rem func (v1ms *mongoMigrator) remV1Filter(tenant, id string) (err error) { _, err = v1ms.mgoDB.DB().Collection(engine.ColFlt).DeleteOne(v1ms.mgoDB.GetContext(), bson.M{"tenant": tenant, "id": id}) return } // Supplier Methods -//get +// get func (v1ms *mongoMigrator) getSupplier() (spl *SupplierProfile, err error) { if v1ms.cursor == nil { v1ms.cursor, err = v1ms.mgoDB.DB().Collection(ColSpp).Find(v1ms.mgoDB.GetContext(), bson.D{}) @@ -400,13 +400,13 @@ func (v1ms *mongoMigrator) getSupplier() (spl *SupplierProfile, err error) { return } -//set +// set func (v1ms *mongoMigrator) setSupplier(spl *SupplierProfile) (err error) { _, err = v1ms.mgoDB.DB().Collection(ColSpp).InsertOne(v1ms.mgoDB.GetContext(), spl) return } -//rem +// rem func (v1ms *mongoMigrator) remSupplier(tenant, id string) (err error) { _, err = v1ms.mgoDB.DB().Collection(ColSpp).DeleteOne(v1ms.mgoDB.GetContext(), bson.M{"tenant": tenant, "id": id}) return diff --git a/migrator/storage_redis.go b/migrator/storage_redis.go index 897570be4..cc2c60483 100644 --- a/migrator/storage_redis.go +++ b/migrator/storage_redis.go @@ -50,8 +50,8 @@ func (v1rs *redisMigrator) DataManager() *engine.DataManager { return v1rs.dm } -//Stats methods -//get +// Stats methods +// get func (v1rs *redisMigrator) getV1Stats() (v1st *v1Stat, err error) { if v1rs.qryIdx == nil { v1rs.dataKeys, err = v1rs.rds.GetKeysForPrefix(context.TODO(), utils.CDRsStatsPrefix) @@ -104,7 +104,7 @@ func (v1rs *redisMigrator) getV3Stats() (v1st *engine.StatQueueProfile, err erro return v1st, nil } -//set +// set func (v1rs *redisMigrator) setV1Stats(x *v1Stat) (err error) { key := utils.CDRsStatsPrefix + x.Id bit, err := v1rs.rds.Marshaler().Marshal(x) @@ -117,7 +117,7 @@ func (v1rs *redisMigrator) setV1Stats(x *v1Stat) (err error) { return } -//get +// get func (v1rs *redisMigrator) getV2Stats() (v2 *engine.StatQueue, err error) { if v1rs.qryIdx == nil { v1rs.dataKeys, err = v1rs.rds.GetKeysForPrefix(context.TODO(), utils.StatQueuePrefix) @@ -144,7 +144,7 @@ func (v1rs *redisMigrator) getV2Stats() (v2 *engine.StatQueue, err error) { return v2, nil } -//set +// set func (v1rs *redisMigrator) setV2Stats(v2 *engine.StatQueue) (err error) { key := utils.StatQueuePrefix + v2.ID bit, err := v1rs.rds.Marshaler().Marshal(v2) @@ -157,8 +157,8 @@ func (v1rs *redisMigrator) setV2Stats(v2 *engine.StatQueue) (err error) { return } -//AttributeProfile methods -//get +// AttributeProfile methods +// get func (v1rs *redisMigrator) getV1AttributeProfile() (v1attrPrf *v1AttributeProfile, err error) { var v1attr *v1AttributeProfile if v1rs.qryIdx == nil { @@ -186,7 +186,7 @@ func (v1rs *redisMigrator) getV1AttributeProfile() (v1attrPrf *v1AttributeProfil return v1attr, nil } -//set +// set func (v1rs *redisMigrator) setV1AttributeProfile(x *v1AttributeProfile) (err error) { key := utils.AttributeProfilePrefix + utils.ConcatenatedKey(x.Tenant, x.ID) bit, err := v1rs.rds.Marshaler().Marshal(x) @@ -199,8 +199,8 @@ func (v1rs *redisMigrator) setV1AttributeProfile(x *v1AttributeProfile) (err err return } -//ThresholdProfile methods -//get +// ThresholdProfile methods +// get func (v1rs *redisMigrator) getV2ThresholdProfile() (v2T *v2Threshold, err error) { var v2Th *v2Threshold if v1rs.qryIdx == nil { @@ -254,7 +254,7 @@ func (v1rs *redisMigrator) getV3ThresholdProfile() (v2T *engine.ThresholdProfile return v2T, nil } -//set +// set func (v1rs *redisMigrator) setV2ThresholdProfile(x *v2Threshold) (err error) { key := utils.ThresholdProfilePrefix + utils.ConcatenatedKey(x.Tenant, x.ID) bit, err := v1rs.rds.Marshaler().Marshal(x) @@ -267,14 +267,14 @@ func (v1rs *redisMigrator) setV2ThresholdProfile(x *v2Threshold) (err error) { return } -//rem +// rem func (v1rs *redisMigrator) remV2ThresholdProfile(tenant, id string) (err error) { key := utils.ThresholdProfilePrefix + utils.ConcatenatedKey(tenant, id) return v1rs.rds.Cmd(nil, "DEL", key) } -//AttributeProfile methods -//get +// AttributeProfile methods +// get func (v1rs *redisMigrator) getV2AttributeProfile() (v2attrPrf *v2AttributeProfile, err error) { var v2attr *v2AttributeProfile if v1rs.qryIdx == nil { @@ -302,7 +302,7 @@ func (v1rs *redisMigrator) getV2AttributeProfile() (v2attrPrf *v2AttributeProfil return v2attr, nil } -//set +// set func (v1rs *redisMigrator) setV2AttributeProfile(x *v2AttributeProfile) (err error) { key := utils.AttributeProfilePrefix + utils.ConcatenatedKey(x.Tenant, x.ID) bit, err := v1rs.rds.Marshaler().Marshal(x) @@ -315,14 +315,14 @@ func (v1rs *redisMigrator) setV2AttributeProfile(x *v2AttributeProfile) (err err return } -//rem +// rem func (v1rs *redisMigrator) remV2AttributeProfile(tenant, id string) (err error) { key := utils.AttributeProfilePrefix + utils.ConcatenatedKey(tenant, id) return v1rs.rds.Cmd(nil, "DEL", key) } -//AttributeProfile methods -//get +// AttributeProfile methods +// get func (v1rs *redisMigrator) getV3AttributeProfile() (v3attrPrf *v3AttributeProfile, err error) { var v3attr *v3AttributeProfile if v1rs.qryIdx == nil { @@ -350,7 +350,7 @@ func (v1rs *redisMigrator) getV3AttributeProfile() (v3attrPrf *v3AttributeProfil return v3attr, nil } -//set +// set func (v1rs *redisMigrator) setV3AttributeProfile(x *v3AttributeProfile) (err error) { key := utils.AttributeProfilePrefix + utils.ConcatenatedKey(x.Tenant, x.ID) bit, err := v1rs.rds.Marshaler().Marshal(x) @@ -363,14 +363,14 @@ func (v1rs *redisMigrator) setV3AttributeProfile(x *v3AttributeProfile) (err err return } -//rem +// rem func (v1rs *redisMigrator) remV3AttributeProfile(tenant, id string) (err error) { key := utils.AttributeProfilePrefix + utils.ConcatenatedKey(tenant, id) return v1rs.rds.Cmd(nil, "DEL", key) } -//AttributeProfile methods -//get +// AttributeProfile methods +// get func (v1rs *redisMigrator) getV4AttributeProfile() (v3attrPrf *v4AttributeProfile, err error) { var v4attr *v4AttributeProfile if v1rs.qryIdx == nil { @@ -424,7 +424,7 @@ func (v1rs *redisMigrator) getV5AttributeProfile() (v5attr *v6AttributeProfile, return } -//set +// set func (v1rs *redisMigrator) setV4AttributeProfile(x *v4AttributeProfile) (err error) { key := utils.AttributeProfilePrefix + utils.ConcatenatedKey(x.Tenant, x.ID) bit, err := v1rs.rds.Marshaler().Marshal(x) @@ -437,14 +437,14 @@ func (v1rs *redisMigrator) setV4AttributeProfile(x *v4AttributeProfile) (err err return } -//rem +// rem func (v1rs *redisMigrator) remV4AttributeProfile(tenant, id string) (err error) { key := utils.AttributeProfilePrefix + utils.ConcatenatedKey(tenant, id) return v1rs.rds.Cmd(nil, "DEL", key) } // Filter Methods -//get +// get func (v1rs *redisMigrator) getV1Filter() (v1Fltr *v1Filter, err error) { if v1rs.qryIdx == nil { v1rs.dataKeys, err = v1rs.rds.GetKeysForPrefix(context.TODO(), utils.FilterPrefix) @@ -497,7 +497,7 @@ func (v1rs *redisMigrator) getV4Filter() (v4Fltr *engine.Filter, err error) { return } -//set +// set func (v1rs *redisMigrator) setV1Filter(x *v1Filter) (err error) { key := utils.FilterPrefix + utils.ConcatenatedKey(x.Tenant, x.ID) bit, err := v1rs.rds.Marshaler().Marshal(x) @@ -507,7 +507,7 @@ func (v1rs *redisMigrator) setV1Filter(x *v1Filter) (err error) { return v1rs.rds.Cmd(nil, "SET", key, string(bit)) } -//rem +// rem func (v1rs *redisMigrator) remV1Filter(tenant, id string) (err error) { key := utils.FilterPrefix + utils.ConcatenatedKey(tenant, id) return v1rs.rds.Cmd(nil, "DEL", key) @@ -540,7 +540,7 @@ func (v1rs *redisMigrator) getSupplier() (spl *SupplierProfile, err error) { return } -//set +// set func (v1rs *redisMigrator) setSupplier(spl *SupplierProfile) (err error) { key := SupplierProfilePrefix + utils.ConcatenatedKey(spl.Tenant, spl.ID) bit, err := v1rs.rds.Marshaler().Marshal(spl) @@ -553,7 +553,7 @@ func (v1rs *redisMigrator) setSupplier(spl *SupplierProfile) (err error) { return } -//rem +// rem func (v1rs *redisMigrator) remSupplier(tenant, id string) (err error) { key := SupplierProfilePrefix + utils.ConcatenatedKey(tenant, id) return v1rs.rds.Cmd(nil, "DEL", key) diff --git a/rates/librates.go b/rates/librates.go index c4d2b6bfd..8f5a866fd 100644 --- a/rates/librates.go +++ b/rates/librates.go @@ -54,7 +54,7 @@ type ratesWithWinner struct { wnr *rateWithTimes } -//add will add the rate to the rates +// add will add the rate to the rates func (rs *ratesWithWinner) add(rWt *rateWithTimes) { rs.rts[rWt.id()] = rWt if rs.wnr == nil || rs.wnr.weight < rWt.weight { diff --git a/services/accounts_test.go b/services/accounts_test.go index 0b3e60af3..846ca3784 100644 --- a/services/accounts_test.go +++ b/services/accounts_test.go @@ -32,7 +32,7 @@ import ( "github.com/cgrates/cgrates/utils" ) -//TestAccountSCoverage for cover testing +// TestAccountSCoverage for cover testing func TestAccountSCoverage(t *testing.T) { cfg := config.NewDefaultCGRConfig() filterSChan := make(chan *engine.FilterS, 1) diff --git a/services/actions_test.go b/services/actions_test.go index 2b467d933..0a216bf04 100644 --- a/services/actions_test.go +++ b/services/actions_test.go @@ -31,7 +31,7 @@ import ( "github.com/cgrates/cgrates/utils" ) -//TestActionSCoverage for cover testing +// TestActionSCoverage for cover testing func TestActionSCoverage(t *testing.T) { cfg := config.NewDefaultCGRConfig() filterSChan := make(chan *engine.FilterS, 1) diff --git a/services/analyzers_test.go b/services/analyzers_test.go index 1be83b955..263f46d58 100644 --- a/services/analyzers_test.go +++ b/services/analyzers_test.go @@ -31,7 +31,7 @@ import ( "github.com/cgrates/cgrates/utils" ) -//TestAnalyzerCoverage for cover testing +// TestAnalyzerCoverage for cover testing func TestAnalyzerCoverage(t *testing.T) { cfg := config.NewDefaultCGRConfig() filterSChan := make(chan *engine.FilterS, 1) diff --git a/services/asteriskagent_test.go b/services/asteriskagent_test.go index 367b4dcea..dc9b7f074 100644 --- a/services/asteriskagent_test.go +++ b/services/asteriskagent_test.go @@ -28,7 +28,7 @@ import ( "github.com/cgrates/cgrates/utils" ) -//TestAsteriskAgentCoverage for cover testing +// TestAsteriskAgentCoverage for cover testing func TestAsteriskAgentCoverage(t *testing.T) { cfg := config.NewDefaultCGRConfig() cfg.SessionSCfg().Enabled = true diff --git a/services/attributes_test.go b/services/attributes_test.go index da685b6ea..7094595b3 100644 --- a/services/attributes_test.go +++ b/services/attributes_test.go @@ -30,7 +30,7 @@ import ( "github.com/cgrates/cgrates/utils" ) -//TestAttributeSCoverage for cover testing +// TestAttributeSCoverage for cover testing func TestAttributeSCoverage(t *testing.T) { cfg := config.NewDefaultCGRConfig() filterSChan := make(chan *engine.FilterS, 1) diff --git a/services/cdrs_test.go b/services/cdrs_test.go index c136c4274..8e08faea3 100644 --- a/services/cdrs_test.go +++ b/services/cdrs_test.go @@ -28,7 +28,7 @@ import ( "github.com/cgrates/cgrates/utils" ) -//TestCdrsCoverage for cover testing +// TestCdrsCoverage for cover testing func TestCdrsCoverage(t *testing.T) { cfg := config.NewDefaultCGRConfig() filterSChan := make(chan *engine.FilterS, 1) diff --git a/services/chargers_test.go b/services/chargers_test.go index bc6b5dc94..ee19b920b 100644 --- a/services/chargers_test.go +++ b/services/chargers_test.go @@ -30,7 +30,7 @@ import ( "github.com/cgrates/cgrates/utils" ) -//TestChargerSCoverage for cover testing +// TestChargerSCoverage for cover testing func TestChargerSCoverage(t *testing.T) { cfg := config.NewDefaultCGRConfig() cfg.AttributeSCfg().Enabled = true diff --git a/services/cores_test.go b/services/cores_test.go index 68234fc92..f93479269 100644 --- a/services/cores_test.go +++ b/services/cores_test.go @@ -29,7 +29,7 @@ import ( "github.com/cgrates/cgrates/utils" ) -//TestCoreSCoverage for cover testing +// TestCoreSCoverage for cover testing func TestCoreSCoverage(t *testing.T) { cfg := config.NewDefaultCGRConfig() caps := engine.NewCaps(1, "test_caps") diff --git a/services/datadb_test.go b/services/datadb_test.go index c0a2a01b9..1271d9322 100644 --- a/services/datadb_test.go +++ b/services/datadb_test.go @@ -28,7 +28,7 @@ import ( "github.com/cgrates/cgrates/utils" ) -//TestDataDBCoverage for cover testing +// TestDataDBCoverage for cover testing func TestDataDBCoverage(t *testing.T) { cfg := config.NewDefaultCGRConfig() //chS := engine.NewCacheS(cfg, nil, nil) diff --git a/services/dispatchers_test.go b/services/dispatchers_test.go index 91616ac28..407dedb13 100644 --- a/services/dispatchers_test.go +++ b/services/dispatchers_test.go @@ -31,7 +31,7 @@ import ( "github.com/cgrates/cgrates/utils" ) -//TestDispatcherSCoverage for cover testing +// TestDispatcherSCoverage for cover testing func TestDispatcherSCoverage(t *testing.T) { cfg := config.NewDefaultCGRConfig() cfg.AttributeSCfg().Enabled = true diff --git a/services/dnsagent_test.go b/services/dnsagent_test.go index 6c9cfaad3..f07eefcc6 100644 --- a/services/dnsagent_test.go +++ b/services/dnsagent_test.go @@ -27,7 +27,7 @@ import ( "github.com/cgrates/cgrates/utils" ) -//TestDNSAgentCoverage for cover testing +// TestDNSAgentCoverage for cover testing func TestDNSAgentCoverage(t *testing.T) { cfg := config.NewDefaultCGRConfig() cfg.SessionSCfg().Enabled = true diff --git a/services/ees_test.go b/services/ees_test.go index bafde99e6..07a3ef461 100644 --- a/services/ees_test.go +++ b/services/ees_test.go @@ -30,7 +30,7 @@ import ( "github.com/cgrates/cgrates/utils" ) -//TestEventExporterSCoverage for cover testing +// TestEventExporterSCoverage for cover testing func TestEventExporterSCoverage(t *testing.T) { cfg := config.NewDefaultCGRConfig() diff --git a/services/ers_test.go b/services/ers_test.go index 14098d5b2..5544d3ae8 100644 --- a/services/ers_test.go +++ b/services/ers_test.go @@ -29,7 +29,7 @@ import ( "github.com/cgrates/cgrates/utils" ) -//TestEventReaderSCoverage for cover testing +// TestEventReaderSCoverage for cover testing func TestEventReaderSCoverage(t *testing.T) { cfg := config.NewDefaultCGRConfig() cfg.SessionSCfg().Enabled = true diff --git a/services/freeswitchagent_test.go b/services/freeswitchagent_test.go index 25660d0b6..6b0af3cb8 100644 --- a/services/freeswitchagent_test.go +++ b/services/freeswitchagent_test.go @@ -28,7 +28,7 @@ import ( "github.com/cgrates/cgrates/utils" ) -//TestFreeSwitchAgentCoverage for cover testing +// TestFreeSwitchAgentCoverage for cover testing func TestFreeSwitchAgentCoverage(t *testing.T) { cfg := config.NewDefaultCGRConfig() cfg.SessionSCfg().Enabled = true diff --git a/services/httpagent_test.go b/services/httpagent_test.go index d8b60525a..4f7abca6c 100644 --- a/services/httpagent_test.go +++ b/services/httpagent_test.go @@ -28,7 +28,7 @@ import ( "github.com/cgrates/cgrates/utils" ) -//TestHTTPAgent for cover testing +// TestHTTPAgent for cover testing func TestHTTPAgentCoverage(t *testing.T) { cfg := config.NewDefaultCGRConfig() server := cores.NewServer(nil) diff --git a/services/loaders_test.go b/services/loaders_test.go index 5f3c52a36..2079a97a2 100644 --- a/services/loaders_test.go +++ b/services/loaders_test.go @@ -30,7 +30,7 @@ import ( "github.com/cgrates/cgrates/utils" ) -//TestLoaderSCoverage for cover testing +// TestLoaderSCoverage for cover testing func TestLoaderSCoverage(t *testing.T) { cfg := config.NewDefaultCGRConfig() filterSChan := make(chan *engine.FilterS, 1) diff --git a/services/radiusagent_test.go b/services/radiusagent_test.go index dda8e2700..39583cfe3 100644 --- a/services/radiusagent_test.go +++ b/services/radiusagent_test.go @@ -28,7 +28,7 @@ import ( "github.com/cgrates/cgrates/utils" ) -//TestLoaderSCoverage for cover testing +// TestLoaderSCoverage for cover testing func TestRadiusAgentCoverage(t *testing.T) { cfg := config.NewDefaultCGRConfig() cfg.SessionSCfg().Enabled = true diff --git a/services/rates_test.go b/services/rates_test.go index 94e00bbeb..f6576c84d 100644 --- a/services/rates_test.go +++ b/services/rates_test.go @@ -32,7 +32,7 @@ import ( "github.com/cgrates/cgrates/utils" ) -//TestRateSCoverage for cover testing +// TestRateSCoverage for cover testing func TestRateSCoverage(t *testing.T) { cfg := config.NewDefaultCGRConfig() filterSChan := make(chan *engine.FilterS, 1) diff --git a/services/registrarc_test.go b/services/registrarc_test.go index 4a9d618ad..ae02f21e8 100644 --- a/services/registrarc_test.go +++ b/services/registrarc_test.go @@ -30,7 +30,7 @@ import ( "github.com/cgrates/cgrates/utils" ) -//TestDispatcherCoverage for cover testing +// TestDispatcherCoverage for cover testing func TestDispatcherHCoverage(t *testing.T) { cfg := config.NewDefaultCGRConfig() filterSChan := make(chan *engine.FilterS, 1) diff --git a/services/resources_test.go b/services/resources_test.go index 2000cb5c7..90013b0b4 100644 --- a/services/resources_test.go +++ b/services/resources_test.go @@ -30,7 +30,7 @@ import ( "github.com/cgrates/cgrates/utils" ) -//TestResourceSCoverage for cover testing +// TestResourceSCoverage for cover testing func TestResourceSCoverage(t *testing.T) { cfg := config.NewDefaultCGRConfig() cfg.ThresholdSCfg().Enabled = true diff --git a/services/routes_test.go b/services/routes_test.go index 7f00c2dd5..6ce873af2 100644 --- a/services/routes_test.go +++ b/services/routes_test.go @@ -30,7 +30,7 @@ import ( "github.com/cgrates/cgrates/utils" ) -//TestSupplierSCoverage for cover testing +// TestSupplierSCoverage for cover testing func TestSupplierSCoverage(t *testing.T) { cfg := config.NewDefaultCGRConfig() cfg.StatSCfg().Enabled = true diff --git a/services/sessions_test.go b/services/sessions_test.go index e705f8cc0..bc7c6688d 100644 --- a/services/sessions_test.go +++ b/services/sessions_test.go @@ -40,7 +40,7 @@ func (sT *testMockClients) Call(ctx *context.Context, method string, arg, rply i return sT.calls(ctx, arg, rply) } -//TestSessionSCoverage for cover testing +// TestSessionSCoverage for cover testing func TestSessionSCoverage(t *testing.T) { cfg := config.NewDefaultCGRConfig() cfg.ChargerSCfg().Enabled = true diff --git a/services/sipagent_test.go b/services/sipagent_test.go index 149e7fcbe..6849b6edf 100644 --- a/services/sipagent_test.go +++ b/services/sipagent_test.go @@ -28,7 +28,7 @@ import ( "github.com/cgrates/cgrates/utils" ) -//TestSIPAgentCoverage for cover testing +// TestSIPAgentCoverage for cover testing func TestSIPAgentCoverage(t *testing.T) { cfg := config.NewDefaultCGRConfig() cfg.SessionSCfg().Enabled = true diff --git a/services/stats_test.go b/services/stats_test.go index 7cd0a35bd..65c4c5e05 100644 --- a/services/stats_test.go +++ b/services/stats_test.go @@ -30,7 +30,7 @@ import ( "github.com/cgrates/cgrates/utils" ) -//TestStatSCoverage for cover testing +// TestStatSCoverage for cover testing func TestStatSCoverage(t *testing.T) { // utils.Logger.SetLogLevel(7) cfg := config.NewDefaultCGRConfig() diff --git a/services/thresholds_test.go b/services/thresholds_test.go index b81e58101..608c069eb 100644 --- a/services/thresholds_test.go +++ b/services/thresholds_test.go @@ -30,7 +30,7 @@ import ( "github.com/cgrates/cgrates/utils" ) -//TestThresholdSCoverage for cover testing +// TestThresholdSCoverage for cover testing func TestThresholdSCoverage(t *testing.T) { cfg := config.NewDefaultCGRConfig() filterSChan := make(chan *engine.FilterS, 1) diff --git a/sessions/session_test.go b/sessions/session_test.go index df6d41b24..e9499fa50 100644 --- a/sessions/session_test.go +++ b/sessions/session_test.go @@ -317,165 +317,165 @@ func TestSessionAsExternalSessions(t *testing.T) { } /* -func TestSessionAsExternalSessions2(t *testing.T) { - startEv := map[string]interface{}{ - utils.EventName: "TEST_EVENT", - utils.ToR: utils.MetaVoice, - utils.OriginID: "123451", - utils.AccountField: "1001", - utils.Subject: "1001", - utils.Destination: "1004", - utils.Category: "call", - utils.Tenant: "cgrates.org", - utils.RequestType: utils.MetaPrepaid, - utils.SetupTime: time.Date(2016, time.January, 5, 18, 30, 59, 0, time.UTC), - utils.AnswerTime: time.Date(2016, time.January, 5, 18, 31, 05, 0, time.UTC), - utils.Usage: 2 * time.Second, - utils.Cost: 12.12, - } - ev := map[string]interface{}{ - utils.EventName: "TEST_EVENT2", - utils.ToR: utils.MetaVoice, - utils.OriginID: "123451", - utils.AccountField: "1001", - utils.Subject: "1001", - utils.Destination: "1004", - utils.Category: "call", - utils.RunID: utils.MetaDefault, - utils.Tenant: "cgrates.org", - utils.RequestType: utils.MetaPrepaid, - utils.SetupTime: time.Date(2016, time.January, 5, 18, 30, 59, 0, time.UTC), - utils.AnswerTime: time.Date(2016, time.January, 5, 18, 31, 05, 0, time.UTC), - utils.Usage: 2 * time.Second, - utils.Cost: 12.13, - } - s := &Session{ - OptsStart: map[string]interface{}{ - utils.MetaOriginID: "RandomoriginID", - }, - Tenant: "cgrates.org", - EventStart: engine.NewMapEvent(startEv), - DebitInterval: time.Second, - SRuns: []*SRun{{ - Event: engine.NewMapEvent(ev), - TotalUsage: 2 * time.Second, - }}, - } - exp := []*ExternalSession{{ - //CGRID: "RandomCGRID", - RunID: utils.MetaDefault, - ToR: utils.MetaVoice, - OriginID: "123451", - // OriginHost: s.EventStart.GetStringIgnoreErrors(utils.OriginHost), - Source: utils.SessionS + "_" + "TEST_EVENT", - RequestType: utils.MetaPrepaid, - Tenant: "cgrates.org", - Category: "call", - Account: "1001", - Subject: "1001", - Destination: "1004", - SetupTime: time.Date(2016, time.January, 5, 18, 30, 59, 0, time.UTC), - AnswerTime: time.Date(2016, time.January, 5, 18, 31, 05, 0, time.UTC), - Usage: 2 * time.Second, - ExtraFields: map[string]string{ - utils.EventName: "TEST_EVENT2", - }, - NodeID: "ALL", - DebitInterval: time.Second, - LoopIndex: 10, - DurationIndex: 3 * time.Second, - MaxRate: 11, - MaxRateUnit: 30 * time.Second, - MaxCostSoFar: 20, - }} - //check for some fields if populated correct - rply := s.AsExternalSessions("", "ALL") - if !reflect.DeepEqual(exp, rply) { - t.Errorf("Expecting: %s, received: %s", utils.ToJSON(exp), utils.ToJSON(rply)) - } + func TestSessionAsExternalSessions2(t *testing.T) { + startEv := map[string]interface{}{ + utils.EventName: "TEST_EVENT", + utils.ToR: utils.MetaVoice, + utils.OriginID: "123451", + utils.AccountField: "1001", + utils.Subject: "1001", + utils.Destination: "1004", + utils.Category: "call", + utils.Tenant: "cgrates.org", + utils.RequestType: utils.MetaPrepaid, + utils.SetupTime: time.Date(2016, time.January, 5, 18, 30, 59, 0, time.UTC), + utils.AnswerTime: time.Date(2016, time.January, 5, 18, 31, 05, 0, time.UTC), + utils.Usage: 2 * time.Second, + utils.Cost: 12.12, + } + ev := map[string]interface{}{ + utils.EventName: "TEST_EVENT2", + utils.ToR: utils.MetaVoice, + utils.OriginID: "123451", + utils.AccountField: "1001", + utils.Subject: "1001", + utils.Destination: "1004", + utils.Category: "call", + utils.RunID: utils.MetaDefault, + utils.Tenant: "cgrates.org", + utils.RequestType: utils.MetaPrepaid, + utils.SetupTime: time.Date(2016, time.January, 5, 18, 30, 59, 0, time.UTC), + utils.AnswerTime: time.Date(2016, time.January, 5, 18, 31, 05, 0, time.UTC), + utils.Usage: 2 * time.Second, + utils.Cost: 12.13, + } + s := &Session{ + OptsStart: map[string]interface{}{ + utils.MetaOriginID: "RandomoriginID", + }, + Tenant: "cgrates.org", + EventStart: engine.NewMapEvent(startEv), + DebitInterval: time.Second, + SRuns: []*SRun{{ + Event: engine.NewMapEvent(ev), + TotalUsage: 2 * time.Second, + }}, + } + exp := []*ExternalSession{{ + //CGRID: "RandomCGRID", + RunID: utils.MetaDefault, + ToR: utils.MetaVoice, + OriginID: "123451", + // OriginHost: s.EventStart.GetStringIgnoreErrors(utils.OriginHost), + Source: utils.SessionS + "_" + "TEST_EVENT", + RequestType: utils.MetaPrepaid, + Tenant: "cgrates.org", + Category: "call", + Account: "1001", + Subject: "1001", + Destination: "1004", + SetupTime: time.Date(2016, time.January, 5, 18, 30, 59, 0, time.UTC), + AnswerTime: time.Date(2016, time.January, 5, 18, 31, 05, 0, time.UTC), + Usage: 2 * time.Second, + ExtraFields: map[string]string{ + utils.EventName: "TEST_EVENT2", + }, + NodeID: "ALL", + DebitInterval: time.Second, + LoopIndex: 10, + DurationIndex: 3 * time.Second, + MaxRate: 11, + MaxRateUnit: 30 * time.Second, + MaxCostSoFar: 20, + }} + //check for some fields if populated correct + rply := s.AsExternalSessions("", "ALL") + if !reflect.DeepEqual(exp, rply) { + t.Errorf("Expecting: %s, received: %s", utils.ToJSON(exp), utils.ToJSON(rply)) + } } -func TestSessionAsExternalSessions3(t *testing.T) { - startEv := map[string]interface{}{ - utils.EventName: "TEST_EVENT", - utils.ToR: utils.MetaVoice, - utils.OriginID: "123451", - utils.AccountField: "1001", - utils.Subject: "1001", - utils.Destination: "1004", - utils.Category: "call", - utils.Tenant: "cgrates.org", - utils.RequestType: utils.MetaPrepaid, - utils.SetupTime: time.Date(2016, time.January, 5, 18, 30, 59, 0, time.UTC), - utils.AnswerTime: time.Date(2016, time.January, 5, 18, 31, 05, 0, time.UTC), - utils.Usage: 2 * time.Second, - utils.Cost: 12.12, - } - ev := map[string]interface{}{ - utils.EventName: "TEST_EVENT2", - utils.ToR: utils.MetaVoice, - utils.OriginID: "123451", - utils.AccountField: "1001", - utils.Subject: "1001", - utils.Destination: "1004", - utils.Category: "call", - utils.RunID: utils.MetaDefault, - utils.Tenant: "cgrates.org", - utils.RequestType: utils.MetaPrepaid, - utils.SetupTime: time.Date(2016, time.January, 5, 18, 30, 59, 0, time.UTC), - utils.AnswerTime: time.Date(2016, time.January, 5, 18, 31, 05, 0, time.UTC), - utils.Usage: 2 * time.Second, - utils.Cost: 12.13, - } - tTime := time.Date(2020, time.April, 18, 23, 0, 0, 0, time.UTC) + func TestSessionAsExternalSessions3(t *testing.T) { + startEv := map[string]interface{}{ + utils.EventName: "TEST_EVENT", + utils.ToR: utils.MetaVoice, + utils.OriginID: "123451", + utils.AccountField: "1001", + utils.Subject: "1001", + utils.Destination: "1004", + utils.Category: "call", + utils.Tenant: "cgrates.org", + utils.RequestType: utils.MetaPrepaid, + utils.SetupTime: time.Date(2016, time.January, 5, 18, 30, 59, 0, time.UTC), + utils.AnswerTime: time.Date(2016, time.January, 5, 18, 31, 05, 0, time.UTC), + utils.Usage: 2 * time.Second, + utils.Cost: 12.12, + } + ev := map[string]interface{}{ + utils.EventName: "TEST_EVENT2", + utils.ToR: utils.MetaVoice, + utils.OriginID: "123451", + utils.AccountField: "1001", + utils.Subject: "1001", + utils.Destination: "1004", + utils.Category: "call", + utils.RunID: utils.MetaDefault, + utils.Tenant: "cgrates.org", + utils.RequestType: utils.MetaPrepaid, + utils.SetupTime: time.Date(2016, time.January, 5, 18, 30, 59, 0, time.UTC), + utils.AnswerTime: time.Date(2016, time.January, 5, 18, 31, 05, 0, time.UTC), + utils.Usage: 2 * time.Second, + utils.Cost: 12.13, + } + tTime := time.Date(2020, time.April, 18, 23, 0, 0, 0, time.UTC) - s := &Session{ - OptsStart: map[string]interface{}{ - utils.MetaOriginID: "RandomCGRID", - }, - Tenant: "cgrates.org", - EventStart: engine.NewMapEvent(startEv), - DebitInterval: time.Second, - SRuns: []*SRun{{ - Event: engine.NewMapEvent(ev), - TotalUsage: 2 * time.Second, - NextAutoDebit: &tTime, - }}, - } - exp := &ExternalSession{ - CGRID: "RandomCGRID", - RunID: utils.MetaDefault, - ToR: utils.MetaVoice, - OriginID: "123451", - // OriginHost: s.EventStart.GetStringIgnoreErrors(utils.OriginHost), - Source: utils.SessionS + "_" + "TEST_EVENT", - RequestType: utils.MetaPrepaid, - Tenant: "cgrates.org", - Category: "call", - Account: "1001", - Subject: "1001", - Destination: "1004", - SetupTime: time.Date(2016, time.January, 5, 18, 30, 59, 0, time.UTC), - AnswerTime: time.Date(2016, time.January, 5, 18, 31, 05, 0, time.UTC), - Usage: 2 * time.Second, - ExtraFields: map[string]string{ - utils.EventName: "TEST_EVENT2", - }, - NodeID: "ALL", - DebitInterval: time.Second, - LoopIndex: 10, - DurationIndex: 3 * time.Second, - MaxRate: 11, - MaxRateUnit: 30 * time.Second, - MaxCostSoFar: 20, - NextAutoDebit: tTime, - } - //check for some fields if populated correct - rply := s.AsExternalSession(s.SRuns[0], "", "ALL") - if !reflect.DeepEqual(exp, rply) { - t.Errorf("Expecting: %s, received: %s", utils.ToJSON(exp), utils.ToJSON(rply)) - } + s := &Session{ + OptsStart: map[string]interface{}{ + utils.MetaOriginID: "RandomCGRID", + }, + Tenant: "cgrates.org", + EventStart: engine.NewMapEvent(startEv), + DebitInterval: time.Second, + SRuns: []*SRun{{ + Event: engine.NewMapEvent(ev), + TotalUsage: 2 * time.Second, + NextAutoDebit: &tTime, + }}, + } + exp := &ExternalSession{ + CGRID: "RandomCGRID", + RunID: utils.MetaDefault, + ToR: utils.MetaVoice, + OriginID: "123451", + // OriginHost: s.EventStart.GetStringIgnoreErrors(utils.OriginHost), + Source: utils.SessionS + "_" + "TEST_EVENT", + RequestType: utils.MetaPrepaid, + Tenant: "cgrates.org", + Category: "call", + Account: "1001", + Subject: "1001", + Destination: "1004", + SetupTime: time.Date(2016, time.January, 5, 18, 30, 59, 0, time.UTC), + AnswerTime: time.Date(2016, time.January, 5, 18, 31, 05, 0, time.UTC), + Usage: 2 * time.Second, + ExtraFields: map[string]string{ + utils.EventName: "TEST_EVENT2", + }, + NodeID: "ALL", + DebitInterval: time.Second, + LoopIndex: 10, + DurationIndex: 3 * time.Second, + MaxRate: 11, + MaxRateUnit: 30 * time.Second, + MaxCostSoFar: 20, + NextAutoDebit: tTime, + } + //check for some fields if populated correct + rply := s.AsExternalSession(s.SRuns[0], "", "ALL") + if !reflect.DeepEqual(exp, rply) { + t.Errorf("Expecting: %s, received: %s", utils.ToJSON(exp), utils.ToJSON(rply)) + } } */ diff --git a/utils/account.go b/utils/account.go index e473a5d58..77067383a 100644 --- a/utils/account.go +++ b/utils/account.go @@ -365,7 +365,7 @@ func (acc *Account) Clone() (cln *Account) { return } -//Clone returns a clone of the ActivationInterval +// Clone returns a clone of the ActivationInterval func (aI *ActivationInterval) Clone() *ActivationInterval { if aI == nil { return nil @@ -376,7 +376,7 @@ func (aI *ActivationInterval) Clone() *ActivationInterval { } } -//Clone return a clone of the Balance +// Clone return a clone of the Balance func (blnc *Balance) Clone() (cln *Balance) { cln = &Balance{ ID: blnc.ID, diff --git a/utils/apitpdata.go b/utils/apitpdata.go index e67ab669b..6753b9b66 100644 --- a/utils/apitpdata.go +++ b/utils/apitpdata.go @@ -227,7 +227,7 @@ type AttrDisconnectSession struct { Reason string } -//MetricWithFilters is used in TPStatProfile +// MetricWithFilters is used in TPStatProfile type MetricWithFilters struct { FilterIDs []string MetricID string diff --git a/utils/coreutils.go b/utils/coreutils.go index 71be8aef4..b2133a95a 100644 --- a/utils/coreutils.go +++ b/utils/coreutils.go @@ -164,6 +164,7 @@ func UUIDSha1Prefix() string { // Round return rounded version of x with prec precision. // // Special cases are: +// // Round(±0) = ±0 // Round(±Inf) = ±Inf // Round(NaN) = NaN @@ -199,7 +200,7 @@ func Round(x float64, prec int, method string) float64 { return rounder / pow } -//RoundStatDuration is used in engine package for stat metrics that has duration (e.g acd metric, tcd metric, etc...) +// RoundStatDuration is used in engine package for stat metrics that has duration (e.g acd metric, tcd metric, etc...) func RoundStatDuration(x time.Duration, prec int) time.Duration { return x.Round(time.Duration(math.Pow10(9 - prec))) } @@ -374,7 +375,7 @@ func InfieldSplit(val string) []string { return strings.Split(val, InfieldSep) } -//Splited Unzip in small functions to have better coverage +// Splited Unzip in small functions to have better coverage func Unzip(src, dest string) error { r, err := zip.OpenReader(src) if err != nil { @@ -513,10 +514,11 @@ func ToUnescapedJSON(value interface{}) (bts []byte, err error) { // Used as generic function logic for various fields // Attributes -// source - the base source -// width - the field width -// strip - if present it will specify the strip strategy, when missing strip will not be allowed -// padding - if present it will specify the padding strategy to use, left, right, zeroleft, zeroright +// +// source - the base source +// width - the field width +// strip - if present it will specify the strip strategy, when missing strip will not be allowed +// padding - if present it will specify the padding strategy to use, left, right, zeroleft, zeroright func FmtFieldWidth(fieldID, source string, width int, strip, padding string, mandatory bool) (string, error) { if mandatory && len(source) == 0 { return "", fmt.Errorf("Empty source value for fieldID: <%s>", fieldID) @@ -897,19 +899,19 @@ func VerifyHash(hash string, dataKeys ...string) bool { return err == nil } -//newBoolGen initialize an efficient boolean generator +// newBoolGen initialize an efficient boolean generator func newBoolGen() *boolGen { return &boolGen{src: math_rand.NewSource(time.Now().UnixNano())} } -//boolGen is an efficient boolean generator +// boolGen is an efficient boolean generator type boolGen struct { src math_rand.Source cache int64 remaining int } -//RandomBool generate a random boolean +// RandomBool generate a random boolean func (b *boolGen) RandomBool() bool { if b.remaining == 0 { b.cache, b.remaining = b.src.Int63(), 63 diff --git a/utils/pathitemlist_test.go b/utils/pathitemlist_test.go index c9a1c5eef..cfcec86ef 100644 --- a/utils/pathitemlist_test.go +++ b/utils/pathitemlist_test.go @@ -573,11 +573,12 @@ func BenchmarkGetPathIndexSlice(b *testing.B) { } /* -func BenchmarkGetPathIndexSliceSplit(b *testing.B) { - for i := 0; i < b.N; i++ { - GetPathIndexSlice(benchPath) + func BenchmarkGetPathIndexSliceSplit(b *testing.B) { + for i := 0; i < b.N; i++ { + GetPathIndexSlice(benchPath) + } } -}*/ +*/ func BenchmarkGetPathIndexSliceStringsIndex(b *testing.B) { for i := 0; i < b.N; i++ { GetPathIndexSliceStringsIndex(benchPath)