From 667c180f30c2498f97d4c680109c19cc750f910c Mon Sep 17 00:00:00 2001 From: Edwardro22 Date: Wed, 16 Nov 2016 23:55:03 +0100 Subject: [PATCH] Renamed integration tests --- apier/v1/apier_it_test.go | 1705 ++++++++++++++++++++++++++++++++ apier/v1/cdrstatsv1_it_test.go | 195 ++++ cdrc/flatstore_it_test.go | 154 +++ cdrc/fwv_it_test.go | 146 +++ config/multifiles_it_test.go | 95 ++ engine/actions_it_test.go | 170 ++++ engine/cdr_it_test.go | 50 + engine/loader_it_test.go | 424 ++++++++ utils/httpclient_it_test.go | 73 ++ 9 files changed, 3012 insertions(+) create mode 100644 apier/v1/apier_it_test.go create mode 100644 apier/v1/cdrstatsv1_it_test.go create mode 100644 cdrc/flatstore_it_test.go create mode 100644 cdrc/fwv_it_test.go create mode 100644 config/multifiles_it_test.go create mode 100644 engine/actions_it_test.go create mode 100644 engine/cdr_it_test.go create mode 100644 engine/loader_it_test.go create mode 100644 utils/httpclient_it_test.go diff --git a/apier/v1/apier_it_test.go b/apier/v1/apier_it_test.go new file mode 100644 index 000000000..d6f481152 --- /dev/null +++ b/apier/v1/apier_it_test.go @@ -0,0 +1,1705 @@ +// +build integration + +/* +Real-time Online/Offline Charging System (OCS) for Telecom & ISP environments +Copyright (C) ITsysCOM GmbH + +This program is free software: you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU General Public License for more details. + +You should have received a copy of the GNU General Public License +along with this program. If not, see +*/ +package v1 + +import ( + "encoding/json" + "flag" + "fmt" + "net/http" + "net/rpc" + "net/rpc/jsonrpc" + "net/url" + "os" + "os/exec" + "path" + "reflect" + "strings" + "testing" + "time" + + "github.com/cgrates/cgrates/config" + "github.com/cgrates/cgrates/engine" + "github.com/cgrates/cgrates/utils" +) + +// ToDo: Replace rpc.Client with internal rpc server and Apier using internal map as both data and stor so we can run the tests non-local + +/* +README: + + Enable local tests by passing '-local' to the go test command + It is expected that the data folder of CGRateS exists at path /usr/share/cgrates/data or passed via command arguments. + Prior running the tests, create database and users by running: + mysql -pyourrootpwd < /usr/share/cgrates/data/storage/mysql/create_db_with_users.sql + What these tests do: + * Flush tables in storDb to start clean. + * Start engine with default configuration and give it some time to listen (here caching can slow down, hence the command argument parameter). + * Connect rpc client depending on encoding defined in configuration. + * Execute remote Apis and test their replies(follow testtp scenario so we can test load in dataDb also). +*/ + +var cfgPath string +var cfg *config.CGRConfig +var rater *rpc.Client + +var testIT = flag.Bool("integration", false, "Perform the tests only on local test environment, not by default.") +var dataDir = flag.String("data_dir", "/usr/share/cgrates", "CGR data dir path here") +var storDbType = flag.String("stordb_type", "mysql", "The type of the storDb database ") +var waitRater = flag.Int("wait_rater", 500, "Number of miliseconds to wait for rater to start and cache") + +func TestApierLoadConfig(t *testing.T) { + + var err error + cfgPath = path.Join(*dataDir, "conf", "samples", "apier") + if cfg, err = config.NewCGRConfigFromFolder(cfgPath); err != nil { + t.Error(err) + } +} + +func TestApierCreateDirs(t *testing.T) { + + for _, pathDir := range []string{cfg.CdreProfiles[utils.META_DEFAULT].ExportDirectory, "/var/log/cgrates/cdrc/in", "/var/log/cgrates/cdrc/out", cfg.HistoryDir} { + + if err := os.RemoveAll(pathDir); err != nil { + t.Fatal("Error removing folder: ", pathDir, err) + } + if err := os.MkdirAll(pathDir, 0755); err != nil { + t.Fatal("Error creating folder: ", pathDir, err) + } + } +} + +func TestApierInitDataDb(t *testing.T) { + + if err := engine.InitDataDb(cfg); err != nil { + t.Fatal(err) + } +} + +// Empty tables before using them +func TestApierInitStorDb(t *testing.T) { + + if err := engine.InitStorDb(cfg); err != nil { + t.Fatal(err) + } +} + +// Finds cgr-engine executable and starts it with default configuration +func TestApierStartEngine(t *testing.T) { + + enginePath, err := exec.LookPath("cgr-engine") + if err != nil { + t.Fatal("Cannot find cgr-engine executable") + } + exec.Command("pkill", "cgr-engine").Run() // Just to make sure another one is not running, bit brutal maybe we can fine tune it + time.Sleep(time.Duration(*waitRater) * time.Millisecond) + engine := exec.Command(enginePath, "-config_dir", cfgPath) + //engine.Stderr = os.Stderr + if err := engine.Start(); err != nil { + t.Fatal("Cannot start cgr-engine: ", err.Error()) + } + time.Sleep(time.Duration(*waitRater) * time.Millisecond) // Give time to rater to fire up +} + +// Connect rpc client to rater +func TestApierRpcConn(t *testing.T) { + + var err error + rater, err = jsonrpc.Dial("tcp", cfg.RPCJSONListen) // We connect over JSON so we can also troubleshoot if needed + if err != nil { + t.Fatal("Could not connect to rater: ", err.Error()) + } +} + +// Test here TPTiming APIs +func TestApierTPTiming(t *testing.T) { + + // ALWAYS,*any,*any,*any,*any,00:00:00 + tmAlways := &utils.ApierTPTiming{TPid: utils.TEST_SQL, + TimingId: "ALWAYS", + Years: "*any", + Months: "*any", + MonthDays: "*any", + WeekDays: "*any", + Time: "00:00:00", + } + tmAlways2 := new(utils.ApierTPTiming) + *tmAlways2 = *tmAlways + tmAlways2.TimingId = "ALWAYS2" + tmAsap := &utils.ApierTPTiming{TPid: utils.TEST_SQL, + TimingId: "ASAP", + Years: "*any", + Months: "*any", + MonthDays: "*any", + WeekDays: "*any", + Time: "*asap", + } + reply := "" + for _, tm := range []*utils.ApierTPTiming{tmAlways, tmAsap, tmAlways2} { + if err := rater.Call("ApierV1.SetTPTiming", tm, &reply); err != nil { + t.Error("Got error on ApierV1.SetTPTiming: ", err.Error()) + } else if reply != "OK" { + t.Error("Unexpected reply received when calling ApierV1.SetTPTiming: ", reply) + } + } + // Check second set + if err := rater.Call("ApierV1.SetTPTiming", tmAlways, &reply); err != nil { + t.Error("Got error on second ApierV1.SetTPTiming: ", err.Error()) + } else if reply != "OK" { + t.Error("Calling ApierV1.SetTPTiming got reply: ", reply) + } + // Check missing params + if err := rater.Call("ApierV1.SetTPTiming", new(utils.ApierTPTiming), &reply); err == nil { + t.Error("Calling ApierV1.SetTPTiming, expected error, received: ", reply) + } else if err.Error() != "MANDATORY_IE_MISSING:[TPid TimingId Years Months MonthDays WeekDays Time]" { + t.Error("Calling ApierV1.SetTPTiming got unexpected error: ", err.Error()) + } + // Test get + var rplyTmAlways2 *utils.ApierTPTiming + if err := rater.Call("ApierV1.GetTPTiming", AttrGetTPTiming{tmAlways2.TPid, tmAlways2.TimingId}, &rplyTmAlways2); err != nil { + t.Error("Calling ApierV1.GetTPTiming, got error: ", err.Error()) + } else if !reflect.DeepEqual(tmAlways2, rplyTmAlways2) { + t.Errorf("Calling ApierV1.GetTPTiming expected: %v, received: %v", tmAlways, rplyTmAlways2) + } + // Test remove + if err := rater.Call("ApierV1.RemTPTiming", AttrGetTPTiming{tmAlways2.TPid, tmAlways2.TimingId}, &reply); err != nil { + t.Error("Calling ApierV1.RemTPTiming, got error: ", err.Error()) + } else if reply != "OK" { + t.Error("Calling ApierV1.RemTPTiming received: ", reply) + } + // Test getIds + var rplyTmIds []string + expectedTmIds := []string{"ALWAYS", "ASAP"} + if err := rater.Call("ApierV1.GetTPTimingIds", AttrGetTPTimingIds{tmAlways.TPid, utils.Paginator{}}, &rplyTmIds); err != nil { + t.Error("Calling ApierV1.GetTPTimingIds, got error: ", err.Error()) + } else if !reflect.DeepEqual(expectedTmIds, rplyTmIds) { + t.Errorf("Calling ApierV1.GetTPTimingIds expected: %v, received: %v", expectedTmIds, rplyTmIds) + } +} + +// Test here TPTiming APIs +func TestApierTPDestination(t *testing.T) { + + reply := "" + dstDe := &utils.TPDestination{TPid: utils.TEST_SQL, DestinationId: "GERMANY", Prefixes: []string{"+49"}} + dstDeMobile := &utils.TPDestination{TPid: utils.TEST_SQL, DestinationId: "GERMANY_MOBILE", Prefixes: []string{"+4915", "+4916", "+4917"}} + dstFs := &utils.TPDestination{TPid: utils.TEST_SQL, DestinationId: "FS_USERS", Prefixes: []string{"10"}} + dstDe2 := new(utils.TPDestination) + *dstDe2 = *dstDe // Data which we use for remove, still keeping the sample data to check proper loading + dstDe2.DestinationId = "GERMANY2" + for _, dst := range []*utils.TPDestination{dstDe, dstDeMobile, dstFs, dstDe2} { + if err := rater.Call("ApierV1.SetTPDestination", dst, &reply); err != nil { + t.Error("Got error on ApierV1.SetTPDestination: ", err.Error()) + } else if reply != "OK" { + t.Error("Unexpected reply received when calling ApierV1.SetTPDestination: ", reply) + } + } + // Check second set + if err := rater.Call("ApierV1.SetTPDestination", dstDe2, &reply); err != nil { + t.Error("Got error on second ApierV1.SetTPDestination: ", err.Error()) + } else if reply != "OK" { + t.Error("Calling ApierV1.SetTPDestination got reply: ", reply) + } + // Check missing params + if err := rater.Call("ApierV1.SetTPDestination", new(utils.TPDestination), &reply); err == nil { + t.Error("Calling ApierV1.SetTPDestination, expected error, received: ", reply) + } else if err.Error() != "MANDATORY_IE_MISSING:[TPid DestinationId Prefixes]" { + t.Error("Calling ApierV1.SetTPDestination got unexpected error: ", err.Error()) + } + // Test get + var rplyDstDe2 *utils.TPDestination + if err := rater.Call("ApierV1.GetTPDestination", AttrGetTPDestination{dstDe2.TPid, dstDe2.DestinationId}, &rplyDstDe2); err != nil { + t.Error("Calling ApierV1.GetTPDestination, got error: ", err.Error()) + } else if !reflect.DeepEqual(dstDe2, rplyDstDe2) { + t.Errorf("Calling ApierV1.GetTPDestination expected: %v, received: %v", dstDe2, rplyDstDe2) + } + // Test remove + if err := rater.Call("ApierV1.RemTPDestination", AttrGetTPDestination{dstDe2.TPid, dstDe2.DestinationId}, &reply); err != nil { + t.Error("Calling ApierV1.RemTPTiming, got error: ", err.Error()) + } else if reply != "OK" { + t.Error("Calling ApierV1.RemTPTiming received: ", reply) + } + // Test getIds + var rplyDstIds []string + expectedDstIds := []string{"FS_USERS", "GERMANY", "GERMANY_MOBILE"} + if err := rater.Call("ApierV1.GetTPDestinationIds", AttrGetTPDestinationIds{TPid: dstDe.TPid}, &rplyDstIds); err != nil { + t.Error("Calling ApierV1.GetTPDestinationIds, got error: ", err.Error()) + } else if !reflect.DeepEqual(expectedDstIds, rplyDstIds) { + t.Errorf("Calling ApierV1.GetTPDestinationIds expected: %v, received: %v", expectedDstIds, rplyDstIds) + } +} + +// Test here TPRate APIs +func TestApierTPRate(t *testing.T) { + + reply := "" + rt := &utils.TPRate{TPid: utils.TEST_SQL, RateId: "RT_FS_USERS", RateSlots: []*utils.RateSlot{ + &utils.RateSlot{ConnectFee: 0, Rate: 0, RateUnit: "60s", RateIncrement: "60s", GroupIntervalStart: "0s"}, + }} + rt2 := new(utils.TPRate) + *rt2 = *rt + rt2.RateId = "RT_FS_USERS2" + for _, r := range []*utils.TPRate{rt, rt2} { + if err := rater.Call("ApierV1.SetTPRate", r, &reply); err != nil { + t.Error("Got error on ApierV1.SetTPRate: ", err.Error()) + } else if reply != "OK" { + t.Error("Unexpected reply received when calling ApierV1.SetTPRate: ", reply) + } + } + // Check second set + if err := rater.Call("ApierV1.SetTPRate", rt2, &reply); err != nil { + t.Error("Got error on second ApierV1.SetTPRate: ", err.Error()) + } else if reply != "OK" { + t.Error("Calling ApierV1.SetTPRate got reply: ", reply) + } + // Check missing params + if err := rater.Call("ApierV1.SetTPRate", new(utils.TPRate), &reply); err == nil { + t.Error("Calling ApierV1.SetTPDestination, expected error, received: ", reply) + } else if err.Error() != "MANDATORY_IE_MISSING:[TPid RateId RateSlots]" { + t.Error("Calling ApierV1.SetTPRate got unexpected error: ", err.Error()) + } + // Test get + var rplyRt2 *utils.TPRate + if err := rater.Call("ApierV1.GetTPRate", AttrGetTPRate{rt2.TPid, rt2.RateId}, &rplyRt2); err != nil { + t.Error("Calling ApierV1.GetTPRate, got error: ", err.Error()) + } else if !reflect.DeepEqual(rt2, rplyRt2) { + t.Errorf("Calling ApierV1.GetTPRate expected: %+v, received: %+v", rt2, rplyRt2) + } + // Test remove + if err := rater.Call("ApierV1.RemTPRate", AttrGetTPRate{rt2.TPid, rt2.RateId}, &reply); err != nil { + t.Error("Calling ApierV1.RemTPRate, got error: ", err.Error()) + } else if reply != "OK" { + t.Error("Calling ApierV1.RemTPRate received: ", reply) + } + // Test getIds + var rplyRtIds []string + expectedRtIds := []string{"RT_FS_USERS"} + if err := rater.Call("ApierV1.GetTPRateIds", AttrGetTPRateIds{rt.TPid, utils.Paginator{}}, &rplyRtIds); err != nil { + t.Error("Calling ApierV1.GetTPRateIds, got error: ", err.Error()) + } else if !reflect.DeepEqual(expectedRtIds, rplyRtIds) { + t.Errorf("Calling ApierV1.GetTPDestinationIDs expected: %v, received: %v", expectedRtIds, rplyRtIds) + } +} + +// Test here TPDestinationRate APIs +func TestApierTPDestinationRate(t *testing.T) { + + reply := "" + dr := &utils.TPDestinationRate{TPid: utils.TEST_SQL, DestinationRateId: "DR_FREESWITCH_USERS", DestinationRates: []*utils.DestinationRate{ + &utils.DestinationRate{DestinationId: "FS_USERS", RateId: "RT_FS_USERS", RoundingMethod: "*up", RoundingDecimals: 2}, + }} + drDe := &utils.TPDestinationRate{TPid: utils.TEST_SQL, DestinationRateId: "DR_FREESWITCH_USERS", DestinationRates: []*utils.DestinationRate{ + &utils.DestinationRate{DestinationId: "GERMANY_MOBILE", RateId: "RT_FS_USERS", RoundingMethod: "*up", RoundingDecimals: 2}, + }} + dr2 := new(utils.TPDestinationRate) + *dr2 = *dr + dr2.DestinationRateId = utils.TEST_SQL + for _, d := range []*utils.TPDestinationRate{dr, dr2, drDe} { + if err := rater.Call("ApierV1.SetTPDestinationRate", d, &reply); err != nil { + t.Error("Got error on ApierV1.SetTPDestinationRate: ", err.Error()) + } else if reply != "OK" { + t.Error("Unexpected reply received when calling ApierV1.SetTPDestinationRate: ", reply) + } + } + // Check second set + if err := rater.Call("ApierV1.SetTPDestinationRate", dr2, &reply); err != nil { + t.Error("Got error on second ApierV1.SetTPDestinationRate: ", err.Error()) + } else if reply != "OK" { + t.Error("Calling ApierV1.SetTPDestinationRate got reply: ", reply) + } + // Check missing params + if err := rater.Call("ApierV1.SetTPDestinationRate", new(utils.TPDestinationRate), &reply); err == nil { + t.Error("Calling ApierV1.SetTPDestination, expected error, received: ", reply) + } else if err.Error() != "MANDATORY_IE_MISSING:[TPid DestinationRateId DestinationRates]" { + t.Error("Calling ApierV1.SetTPDestinationRate got unexpected error: ", err.Error()) + } + // Test get + var rplyDr2 *utils.TPDestinationRate + if err := rater.Call("ApierV1.GetTPDestinationRate", AttrGetTPDestinationRate{dr2.TPid, dr2.DestinationRateId, utils.Paginator{}}, &rplyDr2); err != nil { + t.Error("Calling ApierV1.GetTPDestinationRate, got error: ", err.Error()) + } else if !reflect.DeepEqual(dr2, rplyDr2) { + t.Errorf("Calling ApierV1.GetTPDestinationRate expected: %v, received: %v", dr2, rplyDr2) + } + // Test remove + if err := rater.Call("ApierV1.RemTPDestinationRate", AttrGetTPDestinationRate{dr2.TPid, dr2.DestinationRateId, utils.Paginator{}}, &reply); err != nil { + t.Error("Calling ApierV1.RemTPRate, got error: ", err.Error()) + } else if reply != "OK" { + t.Error("Calling ApierV1.RemTPRate received: ", reply) + } + // Test getIds + var rplyDrIds []string + expectedDrIds := []string{"DR_FREESWITCH_USERS"} + if err := rater.Call("ApierV1.GetTPDestinationRateIds", AttrTPDestinationRateIds{dr.TPid, utils.Paginator{}}, &rplyDrIds); err != nil { + t.Error("Calling ApierV1.GetTPDestinationRateIds, got error: ", err.Error()) + } else if !reflect.DeepEqual(expectedDrIds, rplyDrIds) { + t.Errorf("Calling ApierV1.GetTPDestinationRateIds expected: %v, received: %v", expectedDrIds, rplyDrIds) + } +} + +// Test here TPRatingPlan APIs +func TestApierTPRatingPlan(t *testing.T) { + + reply := "" + rp := &utils.TPRatingPlan{TPid: utils.TEST_SQL, RatingPlanId: "RETAIL1", RatingPlanBindings: []*utils.TPRatingPlanBinding{ + &utils.TPRatingPlanBinding{DestinationRatesId: "DR_FREESWITCH_USERS", TimingId: "ALWAYS", Weight: 10}, + }} + rpTst := new(utils.TPRatingPlan) + *rpTst = *rp + rpTst.RatingPlanId = utils.TEST_SQL + for _, rpl := range []*utils.TPRatingPlan{rp, rpTst} { + if err := rater.Call("ApierV1.SetTPRatingPlan", rpl, &reply); err != nil { + t.Error("Got error on ApierV1.SetTPRatingPlan: ", err.Error()) + } else if reply != "OK" { + t.Error("Unexpected reply received when calling ApierV1.SetTPRatingPlan: ", reply) + } + } + // Check second set + if err := rater.Call("ApierV1.SetTPRatingPlan", rpTst, &reply); err != nil { + t.Error("Got error on second ApierV1.SetTPRatingPlan: ", err.Error()) + } else if reply != "OK" { + t.Error("Calling ApierV1.SetTPRatingPlan got reply: ", reply) + } + // Check missing params + if err := rater.Call("ApierV1.SetTPRatingPlan", new(utils.TPRatingPlan), &reply); err == nil { + t.Error("Calling ApierV1.SetTPRatingPlan, expected error, received: ", reply) + } else if err.Error() != "MANDATORY_IE_MISSING:[TPid RatingPlanId RatingPlanBindings]" { + t.Error("Calling ApierV1.SetTPRatingPlan got unexpected error: ", err.Error()) + } + // Test get + var rplyRpTst *utils.TPRatingPlan + if err := rater.Call("ApierV1.GetTPRatingPlan", AttrGetTPRatingPlan{TPid: rpTst.TPid, RatingPlanId: rpTst.RatingPlanId}, &rplyRpTst); err != nil { + t.Error("Calling ApierV1.GetTPRatingPlan, got error: ", err.Error()) + } else if !reflect.DeepEqual(rpTst, rplyRpTst) { + t.Errorf("Calling ApierV1.GetTPRatingPlan expected: %v, received: %v", rpTst, rplyRpTst) + } + // Test remove + if err := rater.Call("ApierV1.RemTPRatingPlan", AttrGetTPRatingPlan{TPid: rpTst.TPid, RatingPlanId: rpTst.RatingPlanId}, &reply); err != nil { + t.Error("Calling ApierV1.RemTPRatingPlan, got error: ", err.Error()) + } else if reply != "OK" { + t.Error("Calling ApierV1.RemTPRatingPlan received: ", reply) + } + // Test getIds + var rplyRpIds []string + expectedRpIds := []string{"RETAIL1"} + if err := rater.Call("ApierV1.GetTPRatingPlanIds", AttrGetTPRatingPlanIds{rp.TPid, utils.Paginator{}}, &rplyRpIds); err != nil { + t.Error("Calling ApierV1.GetTPRatingPlanIds, got error: ", err.Error()) + } else if !reflect.DeepEqual(expectedRpIds, rplyRpIds) { + t.Errorf("Calling ApierV1.GetTPRatingPlanIds expected: %v, received: %v", expectedRpIds, rplyRpIds) + } +} + +// Test here TPRatingPlan APIs +func TestApierTPRatingProfile(t *testing.T) { + + reply := "" + rpf := &utils.TPRatingProfile{TPid: utils.TEST_SQL, LoadId: utils.TEST_SQL, Tenant: "cgrates.org", Category: "call", Direction: "*out", Subject: "*any", + RatingPlanActivations: []*utils.TPRatingActivation{ + &utils.TPRatingActivation{ActivationTime: "2012-01-01T00:00:00Z", RatingPlanId: "RETAIL1", FallbackSubjects: ""}, + }} + rpfTst := new(utils.TPRatingProfile) + *rpfTst = *rpf + rpfTst.Subject = utils.TEST_SQL + for _, rp := range []*utils.TPRatingProfile{rpf, rpfTst} { + if err := rater.Call("ApierV1.SetTPRatingProfile", rp, &reply); err != nil { + t.Error("Got error on ApierV1.SetTPRatingProfile: ", err.Error()) + } else if reply != "OK" { + t.Error("Unexpected reply received when calling ApierV1.SetTPRatingProfile: ", reply) + } + } + // Check second set + if err := rater.Call("ApierV1.SetTPRatingProfile", rpfTst, &reply); err != nil { + t.Error("Got error on second ApierV1.SetTPRatingProfile: ", err.Error()) + } else if reply != "OK" { + t.Error("Calling ApierV1.SetTPRatingProfile got reply: ", reply) + } + // Check missing params + if err := rater.Call("ApierV1.SetTPRatingProfile", new(utils.TPRatingProfile), &reply); err == nil { + t.Error("Calling ApierV1.SetTPRatingProfile, expected error, received: ", reply) + } else if err.Error() != "MANDATORY_IE_MISSING:[TPid LoadId Tenant Category Direction Subject RatingPlanActivations]" { + t.Error("Calling ApierV1.SetTPRatingProfile got unexpected error: ", err.Error()) + } + // Test get + var rplyRpf *utils.TPRatingProfile + if err := rater.Call("ApierV1.GetTPRatingProfile", AttrGetTPRatingProfile{TPid: rpfTst.TPid, RatingProfileId: rpfTst.GetRatingProfilesId()}, &rplyRpf); err != nil { + t.Error("Calling ApierV1.GetTPRatingProfiles, got error: ", err.Error()) + } else if !reflect.DeepEqual(rpfTst, rplyRpf) { + t.Errorf("Calling ApierV1.GetTPRatingProfiles expected: %v, received: %v", rpfTst, rplyRpf) + } + // Test remove + if err := rater.Call("ApierV1.RemTPRatingProfile", AttrGetTPRatingProfile{TPid: rpfTst.TPid, RatingProfileId: rpfTst.GetRatingProfilesId()}, &reply); err != nil { + t.Error("Calling ApierV1.RemTPRatingProfile, got error: ", err.Error()) + } else if reply != "OK" { + t.Error("Calling ApierV1.RemTPRatingProfile received: ", reply) + } + // Test getLoadIds + var rplyRpIds []string + expectedRpIds := []string{utils.TEST_SQL} + if err := rater.Call("ApierV1.GetTPRatingProfileLoadIds", utils.AttrTPRatingProfileIds{TPid: rpf.TPid}, &rplyRpIds); err != nil { + t.Error("Calling ApierV1.GetTPRatingProfileLoadIds, got error: ", err.Error()) + } else if !reflect.DeepEqual(expectedRpIds, rplyRpIds) { + t.Errorf("Calling ApierV1.GetTPRatingProfileLoadIds expected: %v, received: %v", expectedRpIds, rplyRpIds) + } +} + +func TestApierTPActions(t *testing.T) { + + reply := "" + act := &utils.TPActions{TPid: utils.TEST_SQL, ActionsId: "PREPAID_10", Actions: []*utils.TPAction{ + &utils.TPAction{Identifier: "*topup_reset", BalanceType: "*monetary", Directions: "*out", Units: "10", ExpiryTime: "*unlimited", + DestinationIds: "*any", BalanceWeight: "10", Weight: 10}, + }} + actWarn := &utils.TPActions{TPid: utils.TEST_SQL, ActionsId: "WARN_VIA_HTTP", Actions: []*utils.TPAction{ + &utils.TPAction{Identifier: "*call_url", ExtraParameters: "http://localhost:8000", Weight: 10}, + }} + actLog := &utils.TPActions{TPid: utils.TEST_SQL, ActionsId: "LOG_BALANCE", Actions: []*utils.TPAction{ + &utils.TPAction{Identifier: "*log", Weight: 10}, + }} + actTst := new(utils.TPActions) + *actTst = *act + actTst.ActionsId = utils.TEST_SQL + for _, ac := range []*utils.TPActions{act, actWarn, actTst, actLog} { + if err := rater.Call("ApierV1.SetTPActions", ac, &reply); err != nil { + t.Error("Got error on ApierV1.SetTPActions: ", err.Error()) + } else if reply != "OK" { + t.Error("Unexpected reply received when calling ApierV1.SetTPActions: ", reply) + } + } + // Check second set + if err := rater.Call("ApierV1.SetTPActions", actTst, &reply); err != nil { + t.Error("Got error on second ApierV1.SetTPActions: ", err.Error()) + } else if reply != "OK" { + t.Error("Calling ApierV1.SetTPActions got reply: ", reply) + } + // Check missing params + if err := rater.Call("ApierV1.SetTPActions", new(utils.TPActions), &reply); err == nil { + t.Error("Calling ApierV1.SetTPActions, expected error, received: ", reply) + } else if err.Error() != "MANDATORY_IE_MISSING:[TPid ActionsId Actions]" { + t.Error("Calling ApierV1.SetTPActions got unexpected error: ", err.Error()) + } + // Test get + var rplyActs *utils.TPActions + if err := rater.Call("ApierV1.GetTPActions", AttrGetTPActions{TPid: actTst.TPid, ActionsId: actTst.ActionsId}, &rplyActs); err != nil { + t.Error("Calling ApierV1.GetTPActions, got error: ", err.Error()) + } else if !reflect.DeepEqual(actTst, rplyActs) { + t.Errorf("Calling ApierV1.GetTPActions expected: %v, received: %v", actTst, rplyActs) + } + // Test remove + if err := rater.Call("ApierV1.RemTPActions", AttrGetTPActions{TPid: actTst.TPid, ActionsId: actTst.ActionsId}, &reply); err != nil { + t.Error("Calling ApierV1.RemTPActions, got error: ", err.Error()) + } else if reply != "OK" { + t.Error("Calling ApierV1.RemTPActions received: ", reply) + } + // Test getIds + var rplyIds []string + expectedIds := []string{"LOG_BALANCE", "PREPAID_10", "WARN_VIA_HTTP"} + if err := rater.Call("ApierV1.GetTPActionIds", AttrGetTPActionIds{TPid: actTst.TPid}, &rplyIds); err != nil { + t.Error("Calling ApierV1.GetTPActionIds, got error: ", err.Error()) + } else if !reflect.DeepEqual(expectedIds, rplyIds) { + t.Errorf("Calling ApierV1.GetTPActionIds expected: %v, received: %v", expectedIds, rplyIds) + } +} + +func TestApierTPActionPlan(t *testing.T) { + + reply := "" + at := &utils.TPActionPlan{TPid: utils.TEST_SQL, ActionPlanId: "PREPAID_10", ActionPlan: []*utils.TPActionTiming{ + &utils.TPActionTiming{ActionsId: "PREPAID_10", TimingId: "ASAP", Weight: 10}, + }} + atTst := new(utils.TPActionPlan) + *atTst = *at + atTst.ActionPlanId = utils.TEST_SQL + for _, act := range []*utils.TPActionPlan{at, atTst} { + if err := rater.Call("ApierV1.SetTPActionPlan", act, &reply); err != nil { + t.Error("Got error on ApierV1.SetTPActionPlan: ", err.Error()) + } else if reply != "OK" { + t.Error("Unexpected reply received when calling ApierV1.SetTPActionPlan: ", reply) + } + } + // Check second set + if err := rater.Call("ApierV1.SetTPActionPlan", atTst, &reply); err != nil { + t.Error("Got error on second ApierV1.SetTPActionPlan: ", err.Error()) + } else if reply != "OK" { + t.Error("Calling ApierV1.SetTPActionPlan got reply: ", reply) + } + // Check missing params + if err := rater.Call("ApierV1.SetTPActionPlan", new(utils.TPActionPlan), &reply); err == nil { + t.Error("Calling ApierV1.SetTPActionPlan, expected error, received: ", reply) + } else if err.Error() != "MANDATORY_IE_MISSING:[TPid ActionPlanId ActionPlan]" { + t.Error("Calling ApierV1.SetTPActionPlan got unexpected error: ", err.Error()) + } + // Test get + var rplyActs *utils.TPActionPlan + if err := rater.Call("ApierV1.GetTPActionPlan", AttrGetTPActionPlan{TPid: atTst.TPid, Id: atTst.ActionPlanId}, &rplyActs); err != nil { + t.Error("Calling ApierV1.GetTPActionPlan, got error: ", err.Error()) + } else if !reflect.DeepEqual(atTst, rplyActs) { + t.Errorf("Calling ApierV1.GetTPActionPlan expected: %v, received: %v", atTst, rplyActs) + } + // Test remove + if err := rater.Call("ApierV1.RemTPActionPlan", AttrGetTPActionPlan{TPid: atTst.TPid, Id: atTst.ActionPlanId}, &reply); err != nil { + t.Error("Calling ApierV1.RemTPActionPlan, got error: ", err.Error()) + } else if reply != "OK" { + t.Error("Calling ApierV1.RemTPActionPlan received: ", reply) + } + // Test getIds + var rplyIds []string + expectedIds := []string{"PREPAID_10"} + if err := rater.Call("ApierV1.GetTPActionPlanIds", AttrGetTPActionPlanIds{TPid: atTst.TPid}, &rplyIds); err != nil { + t.Error("Calling ApierV1.GetTPActionPlanIds, got error: ", err.Error()) + } else if !reflect.DeepEqual(expectedIds, rplyIds) { + t.Errorf("Calling ApierV1.GetTPActionPlanIds expected: %v, received: %v", expectedIds, rplyIds) + } +} + +func TestApierTPActionTriggers(t *testing.T) { + + reply := "" + at := &utils.TPActionTriggers{TPid: utils.TEST_SQL, ActionTriggersId: "STANDARD_TRIGGERS", ActionTriggers: []*utils.TPActionTrigger{ + &utils.TPActionTrigger{Id: "STANDARD_TRIGGERS", UniqueID: "MYFIRSTTRIGGER", BalanceType: "*monetary", BalanceDirections: "*out", ThresholdType: "*min_balance", ThresholdValue: 2, ActionsId: "LOG_BALANCE", Weight: 10}, + }} + atTst := new(utils.TPActionTriggers) + *atTst = *at + atTst.ActionTriggersId = utils.TEST_SQL + for _, act := range []*utils.TPActionTriggers{at, atTst} { + if err := rater.Call("ApierV1.SetTPActionTriggers", act, &reply); err != nil { + t.Error("Got error on ApierV1.SetTPActionTriggers: ", err.Error()) + } else if reply != "OK" { + t.Error("Unexpected reply received when calling ApierV1.SetTPActionTriggers: ", reply) + } + } + // Check second set + if err := rater.Call("ApierV1.SetTPActionTriggers", atTst, &reply); err != nil { + t.Error("Got error on second ApierV1.SetTPActionTriggers: ", err.Error()) + } else if reply != "OK" { + t.Error("Calling ApierV1.SetTPActionTriggers got reply: ", reply) + } + // Check missing params + if err := rater.Call("ApierV1.SetTPActionTriggers", new(utils.TPActionTriggers), &reply); err == nil { + t.Error("Calling ApierV1.SetTPActionTriggers, expected error, received: ", reply) + } else if err.Error() != "MANDATORY_IE_MISSING:[TPid ActionTriggersId]" { + t.Error("Calling ApierV1.SetTPActionTriggers got unexpected error: ", err.Error()) + } + atTst.ActionTriggers[0].Id = utils.TEST_SQL + // Test get + var rplyActs *utils.TPActionTriggers + if err := rater.Call("ApierV1.GetTPActionTriggers", AttrGetTPActionTriggers{TPid: atTst.TPid, ActionTriggersId: atTst.ActionTriggersId}, &rplyActs); err != nil { + t.Errorf("Calling ApierV1.GetTPActionTriggers %s, got error: %s", atTst.ActionTriggersId, err.Error()) + } else if !reflect.DeepEqual(atTst, rplyActs) { + t.Errorf("Calling ApierV1.GetTPActionTriggers expected: %+v, received: %+v", atTst.ActionTriggers[0], rplyActs.ActionTriggers[0]) + } + // Test remove + if err := rater.Call("ApierV1.RemTPActionTriggers", AttrGetTPActionTriggers{TPid: atTst.TPid, ActionTriggersId: atTst.ActionTriggersId}, &reply); err != nil { + t.Error("Calling ApierV1.RemTPActionTriggers, got error: ", err.Error()) + } else if reply != "OK" { + t.Error("Calling ApierV1.RemTPActionTriggers received: ", reply) + } + // Test getIds + var rplyIds []string + expectedIds := []string{"STANDARD_TRIGGERS"} + if err := rater.Call("ApierV1.GetTPActionTriggerIds", AttrGetTPActionTriggerIds{TPid: atTst.TPid}, &rplyIds); err != nil { + t.Error("Calling ApierV1.GetTPActionTriggerIds, got error: ", err.Error()) + } else if !reflect.DeepEqual(expectedIds, rplyIds) { + t.Errorf("Calling ApierV1.GetTPActionTriggerIds expected: %v, received: %v", expectedIds, rplyIds) + } +} + +// Test here TPAccountActions APIs +func TestApierTPAccountActions(t *testing.T) { + + reply := "" + aa1 := &utils.TPAccountActions{TPid: utils.TEST_SQL, LoadId: utils.TEST_SQL, Tenant: "cgrates.org", + Account: "1001", ActionPlanId: "PREPAID_10", ActionTriggersId: "STANDARD_TRIGGERS"} + aa2 := &utils.TPAccountActions{TPid: utils.TEST_SQL, LoadId: utils.TEST_SQL, Tenant: "cgrates.org", + Account: "1002", ActionPlanId: "PREPAID_10", ActionTriggersId: "STANDARD_TRIGGERS"} + aa3 := &utils.TPAccountActions{TPid: utils.TEST_SQL, LoadId: utils.TEST_SQL, Tenant: "cgrates.org", + Account: "1003", ActionPlanId: "PREPAID_10", ActionTriggersId: "STANDARD_TRIGGERS"} + aa4 := &utils.TPAccountActions{TPid: utils.TEST_SQL, LoadId: utils.TEST_SQL, Tenant: "cgrates.org", + Account: "1004", ActionPlanId: "PREPAID_10", ActionTriggersId: "STANDARD_TRIGGERS"} + aa5 := &utils.TPAccountActions{TPid: utils.TEST_SQL, LoadId: utils.TEST_SQL, Tenant: "cgrates.org", + Account: "1005", ActionPlanId: "PREPAID_10", ActionTriggersId: "STANDARD_TRIGGERS"} + aaTst := new(utils.TPAccountActions) + *aaTst = *aa1 + aaTst.Account = utils.TEST_SQL + for _, aact := range []*utils.TPAccountActions{aa1, aa2, aa3, aa4, aa5, aaTst} { + if err := rater.Call("ApierV1.SetTPAccountActions", aact, &reply); err != nil { + t.Error("Got error on ApierV1.SetTPAccountActions: ", err.Error()) + } else if reply != "OK" { + t.Error("Unexpected reply received when calling ApierV1.SetTPAccountActions: ", reply) + } + } + // Check second set + if err := rater.Call("ApierV1.SetTPAccountActions", aaTst, &reply); err != nil { + t.Error("Got error on second ApierV1.SetTPAccountActions: ", err.Error()) + } else if reply != "OK" { + t.Error("Calling ApierV1.SetTPAccountActions got reply: ", reply) + } + // Check missing params + if err := rater.Call("ApierV1.SetTPAccountActions", new(utils.TPAccountActions), &reply); err == nil { + t.Error("Calling ApierV1.SetTPAccountActions, expected error, received: ", reply) + } else if err.Error() != "MANDATORY_IE_MISSING:[TPid LoadId Tenant Account ActionPlanId ActionTriggersId]" { + t.Error("Calling ApierV1.SetTPAccountActions got unexpected error: ", err.Error()) + } + // Test get + var rplyaa *utils.TPAccountActions + if err := rater.Call("ApierV1.GetTPAccountActions", AttrGetTPAccountActions{TPid: aaTst.TPid, AccountActionsId: aaTst.GetAccountActionsId()}, &rplyaa); err != nil { + t.Error("Calling ApierV1.GetTPAccountActions, got error: ", err.Error()) + } else if !reflect.DeepEqual(aaTst, rplyaa) { + t.Errorf("Calling ApierV1.GetTPAccountActions expected: %v, received: %v", aaTst, rplyaa) + } + // Test remove + if err := rater.Call("ApierV1.RemTPAccountActions", AttrGetTPAccountActions{TPid: aaTst.TPid, AccountActionsId: aaTst.GetAccountActionsId()}, &reply); err != nil { + t.Error("Calling ApierV1.RemTPAccountActions, got error: ", err.Error()) + } else if reply != "OK" { + t.Error("Calling ApierV1.RemTPAccountActions received: ", reply) + } + // Test getLoadIds + var rplyRpIds []string + expectedRpIds := []string{utils.TEST_SQL} + if err := rater.Call("ApierV1.GetTPAccountActionLoadIds", AttrGetTPAccountActionIds{TPid: aaTst.TPid}, &rplyRpIds); err != nil { + t.Error("Calling ApierV1.GetTPAccountActionLoadIds, got error: ", err.Error()) + } else if !reflect.DeepEqual(expectedRpIds, rplyRpIds) { + t.Errorf("Calling ApierV1.GetTPAccountActionLoadIds expected: %v, received: %v", expectedRpIds, rplyRpIds) + } +} + +// Test here LoadRatingPlan +func TestApierLoadRatingPlan(t *testing.T) { + + reply := "" + if err := rater.Call("ApierV1.LoadRatingPlan", AttrLoadRatingPlan{TPid: utils.TEST_SQL, RatingPlanId: "RETAIL1"}, &reply); err != nil { + t.Error("Got error on ApierV1.LoadRatingPlan: ", err.Error()) + } else if reply != "OK" { + t.Error("Calling ApierV1.LoadRatingPlan got reply: ", reply) + } +} + +// Test here SetRatingProfile +func TestApierSetRatingProfile(t *testing.T) { + + reply := "" + rpa := &utils.TPRatingActivation{ActivationTime: "2012-01-01T00:00:00Z", RatingPlanId: "RETAIL1", FallbackSubjects: "dan2"} + rpf := &AttrSetRatingProfile{Tenant: "cgrates.org", Category: "call", Direction: "*out", Subject: "dan", RatingPlanActivations: []*utils.TPRatingActivation{rpa}} + if err := rater.Call("ApierV1.SetRatingProfile", rpf, &reply); err != nil { + t.Error("Got error on ApierV1.SetRatingProfile: ", err.Error()) + } else if reply != "OK" { + t.Error("Calling ApierV1.SetRatingProfile got reply: ", reply) + } + // Calling the second time should not raise EXISTS + if err := rater.Call("ApierV1.SetRatingProfile", rpf, &reply); err != nil { + t.Error("Unexpected result on duplication: ", err.Error()) + } + // Make sure rates were loaded for account dan + // Test here ResponderGetCost + tStart, _ := utils.ParseDate("2013-08-07T17:30:00Z") + tEnd, _ := utils.ParseDate("2013-08-07T17:31:30Z") + cd := engine.CallDescriptor{ + Direction: "*out", + Category: "call", + Tenant: "cgrates.org", + Subject: "dan", + Account: "dan", + Destination: "+4917621621391", + DurationIndex: 90, + TimeStart: tStart, + TimeEnd: tEnd, + } + var cc engine.CallCost + // Simple test that command is executed without errors + if err := rater.Call("Responder.GetCost", cd, &cc); err != nil { + t.Error("Got error on Responder.GetCost: ", err.Error()) + } else if cc.Cost != 0 { + t.Errorf("Calling Responder.GetCost got callcost: %v", cc.Cost) + } +} + +// Test here LoadRatingProfile +func TestApierLoadRatingProfile(t *testing.T) { + + reply := "" + rpf := &utils.TPRatingProfile{TPid: utils.TEST_SQL, LoadId: utils.TEST_SQL, Tenant: "cgrates.org", Category: "call", Direction: "*out", Subject: "*any"} + if err := rater.Call("ApierV1.LoadRatingProfile", rpf, &reply); err != nil { + t.Error("Got error on ApierV1.LoadRatingProfile: ", err.Error()) + } else if reply != "OK" { + t.Error("Calling ApierV1.LoadRatingProfile got reply: ", reply) + } +} + +// Test here LoadAccountActions +func TestApierLoadAccountActions(t *testing.T) { + + reply := "" + aa1 := &utils.TPAccountActions{TPid: utils.TEST_SQL, LoadId: utils.TEST_SQL, Tenant: "cgrates.org", Account: "1001"} + if err := rater.Call("ApierV1.LoadAccountActions", aa1, &reply); err != nil { + t.Error("Got error on ApierV1.LoadAccountActions: ", err.Error()) + } else if reply != "OK" { + t.Error("Calling ApierV1.LoadAccountActions got reply: ", reply) + } +} + +// Test here ReloadScheduler +func TestApierReloadScheduler(t *testing.T) { + + reply := "" + // Simple test that command is executed without errors + if err := rater.Call("ApierV1.ReloadScheduler", reply, &reply); err != nil { + t.Error("Got error on ApierV1.ReloadScheduler: ", err.Error()) + } else if reply != "OK" { + t.Error("Calling ApierV1.ReloadScheduler got reply: ", reply) + } +} + +// Test here ReloadCache +func TestApierReloadCache(t *testing.T) { + + reply := "" + arc := new(utils.AttrReloadCache) + // Simple test that command is executed without errors + if err := rater.Call("ApierV1.ReloadCache", arc, &reply); err != nil { + t.Error("Got error on ApierV1.ReloadCache: ", err.Error()) + } else if reply != "OK" { + t.Error("Calling ApierV1.ReloadCache got reply: ", reply) + } +} + +func TestApierGetCacheStats(t *testing.T) { + + var rcvStats *utils.CacheStats + var args utils.AttrCacheStats + err := rater.Call("ApierV1.GetCacheStats", args, &rcvStats) + expectedStats := &utils.CacheStats{Destinations: 0, RatingPlans: 1, RatingProfiles: 0, Actions: 0, ActionPlans: 0} + if err != nil { + t.Error("Got error on ApierV1.GetCacheStats: ", err.Error()) + } else if !reflect.DeepEqual(expectedStats, rcvStats) { + t.Errorf("Calling ApierV1.GetCacheStats expected: %+v, received: %+v", expectedStats, rcvStats) + } +} + +// Test here GetDestination +func TestApierGetDestination(t *testing.T) { + + reply := new(engine.Destination) + dstId := "GERMANY_MOBILE" + expectedReply := &engine.Destination{Id: dstId, Prefixes: []string{"+4915", "+4916", "+4917"}} + if err := rater.Call("ApierV1.GetDestination", dstId, reply); err != nil { + t.Error("Got error on ApierV1.GetDestination: ", err.Error()) + } else if !reflect.DeepEqual(expectedReply, reply) { + t.Errorf("Calling ApierV1.GetDestination expected: %v, received: %v", expectedReply, reply) + } +} + +// Test here GetRatingPlan +func TestApierGetRatingPlan(t *testing.T) { + + reply := new(engine.RatingPlan) + rplnId := "RETAIL1" + if err := rater.Call("ApierV1.GetRatingPlan", rplnId, reply); err != nil { + t.Error("Got error on ApierV1.GetRatingPlan: ", err.Error()) + } + // Check parts of info received since a full one is not possible due to unique map keys inside reply + if reply.Id != rplnId { + t.Error("Unexpected id received", reply.Id) + } + if len(reply.Timings) != 1 || len(reply.Ratings) != 1 { + t.Error("Unexpected number of items received") + } + riRate := &engine.RIRate{ConnectFee: 0, RoundingMethod: "*up", RoundingDecimals: 2, Rates: []*engine.Rate{ + &engine.Rate{GroupIntervalStart: 0, Value: 0, RateIncrement: time.Duration(60) * time.Second, RateUnit: time.Duration(60) * time.Second}, + }} + for _, rating := range reply.Ratings { + riRateJson, _ := json.Marshal(rating) + if !reflect.DeepEqual(rating, riRate) { + t.Errorf("Unexpected riRate received: %s", riRateJson) + // {"Id":"RT_FS_USERS","ConnectFee":0,"Rates":[{"GroupIntervalStart":0,"Value":0,"RateIncrement":60000000000,"RateUnit":60000000000}],"RoundingMethod":"*up","RoundingDecimals":0} + } + } +} + +// Test here AddBalance +func TestApierAddBalance(t *testing.T) { + + reply := "" + attrs := &AttrAddBalance{Tenant: "cgrates.org", Account: "1001", BalanceType: "*monetary", Value: 1.5} + if err := rater.Call("ApierV1.AddBalance", attrs, &reply); err != nil { + t.Error("Got error on ApierV1.AddBalance: ", err.Error()) + } else if reply != "OK" { + t.Errorf("Calling ApierV1.AddBalance received: %s", reply) + } + attrs = &AttrAddBalance{Tenant: "cgrates.org", Account: "dan", BalanceType: "*monetary", Value: 1.5} + if err := rater.Call("ApierV1.AddBalance", attrs, &reply); err != nil { + t.Error("Got error on ApierV1.AddBalance: ", err.Error()) + } else if reply != "OK" { + t.Errorf("Calling ApierV1.AddBalance received: %s", reply) + } + attrs = &AttrAddBalance{Tenant: "cgrates.org", Account: "dan2", BalanceType: "*monetary", Value: 1.5} + if err := rater.Call("ApierV1.AddBalance", attrs, &reply); err != nil { + t.Error("Got error on ApierV1.AddBalance: ", err.Error()) + } else if reply != "OK" { + t.Errorf("Calling ApierV1.AddBalance received: %s", reply) + } + attrs = &AttrAddBalance{Tenant: "cgrates.org", Account: "dan3", BalanceType: "*monetary", Value: 1.5} + if err := rater.Call("ApierV1.AddBalance", attrs, &reply); err != nil { + t.Error("Got error on ApierV1.AddBalance: ", err.Error()) + } else if reply != "OK" { + t.Errorf("Calling ApierV1.AddBalance received: %s", reply) + } + attrs = &AttrAddBalance{Tenant: "cgrates.org", Account: "dan3", BalanceType: "*monetary", Value: 2.1} + if err := rater.Call("ApierV1.AddBalance", attrs, &reply); err != nil { + t.Error("Got error on ApierV1.AddBalance: ", err.Error()) + } else if reply != "OK" { + t.Errorf("Calling ApierV1.AddBalance received: %s", reply) + } + attrs = &AttrAddBalance{Tenant: "cgrates.org", Account: "dan6", BalanceType: "*monetary", Value: 2.1} + if err := rater.Call("ApierV1.AddBalance", attrs, &reply); err != nil { + t.Error("Got error on ApierV1.AddBalance: ", err.Error()) + } else if reply != "OK" { + t.Errorf("Calling ApierV1.AddBalance received: %s", reply) + } + attrs = &AttrAddBalance{Tenant: "cgrates.org", Account: "dan6", BalanceType: "*monetary", Value: 1, Overwrite: true} + if err := rater.Call("ApierV1.AddBalance", attrs, &reply); err != nil { + t.Error("Got error on ApierV1.AddBalance: ", err.Error()) + } else if reply != "OK" { + t.Errorf("Calling ApierV1.AddBalance received: %s", reply) + } + +} + +// Test here ExecuteAction +func TestApierExecuteAction(t *testing.T) { + + reply := "" + // Add balance to a previously known account + attrs := utils.AttrExecuteAction{Tenant: "cgrates.org", Account: "dan2", ActionsId: "PREPAID_10"} + if err := rater.Call("ApierV1.ExecuteAction", attrs, &reply); err != nil { + t.Error("Got error on ApierV1.ExecuteAction: ", err.Error()) + } else if reply != "OK" { + t.Errorf("Calling ApierV1.ExecuteAction received: %s", reply) + } + reply2 := "" + // Add balance to an account which does n exist + attrs = utils.AttrExecuteAction{Tenant: "cgrates.org", Account: "dan2", ActionsId: "DUMMY_ACTION"} + if err := rater.Call("ApierV1.ExecuteAction", attrs, &reply2); err == nil || reply2 == "OK" { + t.Error("Expecting error on ApierV1.ExecuteAction.", err, reply2) + } +} + +func TestApierSetActions(t *testing.T) { + + act1 := &V1TPAction{Identifier: engine.TOPUP_RESET, BalanceType: utils.MONETARY, Directions: utils.OUT, Units: 75.0, ExpiryTime: engine.UNLIMITED, Weight: 20.0} + attrs1 := &V1AttrSetActions{ActionsId: "ACTS_1", Actions: []*V1TPAction{act1}} + reply1 := "" + if err := rater.Call("ApierV1.SetActions", attrs1, &reply1); err != nil { + t.Error("Got error on ApierV1.SetActions: ", err.Error()) + } else if reply1 != "OK" { + t.Errorf("Calling ApierV1.SetActions received: %s", reply1) + } + // Calling the second time should raise EXISTS + if err := rater.Call("ApierV1.SetActions", attrs1, &reply1); err == nil || err.Error() != "EXISTS" { + t.Error("Unexpected result on duplication: ", err.Error()) + } +} + +func TestApierGetActions(t *testing.T) { + + expectActs := []*utils.TPAction{ + &utils.TPAction{Identifier: engine.TOPUP_RESET, BalanceType: utils.MONETARY, Directions: utils.OUT, Units: "75", BalanceWeight: "0", BalanceBlocker: "false", BalanceDisabled: "false", ExpiryTime: engine.UNLIMITED, Weight: 20.0}} + + var reply []*utils.TPAction + if err := rater.Call("ApierV1.GetActions", "ACTS_1", &reply); err != nil { + t.Error("Got error on ApierV1.GetActions: ", err.Error()) + } else if !reflect.DeepEqual(expectActs, reply) { + t.Errorf("Expected: %v, received: %v", utils.ToJSON(expectActs), utils.ToJSON(reply)) + } +} + +func TestApierSetActionPlan(t *testing.T) { + + atm1 := &AttrActionPlan{ActionsId: "ACTS_1", MonthDays: "1", Time: "00:00:00", Weight: 20.0} + atms1 := &AttrSetActionPlan{Id: "ATMS_1", ActionPlan: []*AttrActionPlan{atm1}} + reply1 := "" + if err := rater.Call("ApierV1.SetActionPlan", atms1, &reply1); err != nil { + t.Error("Got error on ApierV1.SetActionPlan: ", err.Error()) + } else if reply1 != "OK" { + t.Errorf("Calling ApierV1.SetActionPlan received: %s", reply1) + } + // Calling the second time should raise EXISTS + if err := rater.Call("ApierV1.SetActionPlan", atms1, &reply1); err == nil || err.Error() != "EXISTS" { + t.Error("Unexpected result on duplication: ", err.Error()) + } +} + +// Test here AddTriggeredAction +func TestApierAddTriggeredAction(t *testing.T) { + + var reply string + attrs := &AttrAddBalance{Tenant: "cgrates.org", Account: "dan32", BalanceType: "*monetary", Value: 1.5} + if err := rater.Call("ApierV1.AddBalance", attrs, &reply); err != nil { + t.Error("Got error on ApierV1.AddBalance: ", err.Error()) + } else if reply != "OK" { + t.Errorf("Calling ApierV1.AddBalance received: %s", reply) + } + // Add balance to a previously known account + attrsAddTrigger := &AttrAddActionTrigger{Tenant: "cgrates.org", Account: "dan32", BalanceDirection: "*out", BalanceType: "*monetary", + ThresholdType: "*min_balance", ThresholdValue: 2, BalanceDestinationIds: "*any", Weight: 10, ActionsId: "WARN_VIA_HTTP"} + if err := rater.Call("ApierV1.AddTriggeredAction", attrsAddTrigger, &reply); err != nil { + t.Error("Got error on ApierV1.AddTriggeredAction: ", err.Error()) + } else if reply != "OK" { + t.Errorf("Calling ApierV1.AddTriggeredAction received: %s", reply) + } + reply2 := "" + attrs2 := new(AttrAddActionTrigger) + *attrs2 = *attrsAddTrigger + attrs2.Account = "dan10" // Does not exist so it should error when adding triggers on it + // Add trigger to an account which does n exist + if err := rater.Call("ApierV1.AddTriggeredAction", attrs2, &reply2); err == nil { + t.Error("Expecting error on ApierV1.AddTriggeredAction.", err, reply2) + } +} + +// Test here GetAccountActionTriggers +func TestApierGetAccountActionTriggers(t *testing.T) { + + var reply engine.ActionTriggers + req := AttrAcntAction{Tenant: "cgrates.org", Account: "dan32"} + if err := rater.Call("ApierV1.GetAccountActionTriggers", req, &reply); err != nil { + t.Error("Got error on ApierV1.GetAccountActionTimings: ", err.Error()) + } else if len(reply) != 1 || reply[0].ActionsID != "WARN_VIA_HTTP" { + t.Errorf("Unexpected action triggers received %v", reply) + } +} + +func TestApierAddTriggeredAction2(t *testing.T) { + + reply := "" + // Add balance to a previously known account + attrs := &AttrAddAccountActionTriggers{ActionTriggerIDs: &[]string{"STANDARD_TRIGGERS"}, Tenant: "cgrates.org", Account: "dan2"} + if err := rater.Call("ApierV1.AddAccountActionTriggers", attrs, &reply); err != nil { + t.Error("Got error on ApierV1.AddAccountActionTriggers: ", err.Error()) + } else if reply != "OK" { + t.Errorf("Calling ApierV1.AddAccountActionTriggers received: %s", reply) + } + reply2 := "" + attrs2 := new(AttrAddAccountActionTriggers) + *attrs2 = *attrs + attrs2.Account = "dan10" // Does not exist so it should error when adding triggers on it + // Add trigger to an account which does n exist + if err := rater.Call("ApierV1.AddAccountActionTriggers", attrs2, &reply2); err == nil || reply2 == "OK" { + t.Error("Expecting error on ApierV1.AddAccountActionTriggers.", err, reply2) + } +} + +// Test here GetAccountActionTriggers +func TestApierGetAccountActionTriggers2(t *testing.T) { + + var reply engine.ActionTriggers + req := AttrAcntAction{Tenant: "cgrates.org", Account: "dan2"} + if err := rater.Call("ApierV1.GetAccountActionTriggers", req, &reply); err != nil { + t.Error("Got error on ApierV1.GetAccountActionTimings: ", err.Error()) + } else if len(reply) != 1 || reply[0].ActionsID != "LOG_BALANCE" { + t.Errorf("Unexpected action triggers received %v", reply) + } +} + +// Test here SetAccountActionTriggers +func TestApierSetAccountActionTriggers(t *testing.T) { + + // Test first get so we can steal the id which we need to remove + var reply engine.ActionTriggers + req := AttrAcntAction{Tenant: "cgrates.org", Account: "dan2"} + if err := rater.Call("ApierV1.GetAccountActionTriggers", req, &reply); err != nil { + t.Error("Got error on ApierV1.GetAccountActionTimings: ", err.Error()) + } else if len(reply) != 1 || reply[0].ActionsID != "LOG_BALANCE" { + for _, atr := range reply { + t.Logf("ATR: %+v", atr) + } + t.Errorf("Unexpected action triggers received %v", reply) + } + var setReply string + setReq := AttrSetAccountActionTriggers{Tenant: "cgrates.org", Account: "dan2", UniqueID: reply[0].UniqueID, ActivationDate: utils.StringPointer("2016-02-05T18:00:00Z")} + if err := rater.Call("ApierV1.ResetAccountActionTriggers", setReq, &setReply); err != nil { + t.Error("Got error on ApierV1.ResetActionTiming: ", err.Error()) + } else if setReply != OK { + t.Error("Unexpected answer received", setReply) + } + if err := rater.Call("ApierV1.SetAccountActionTriggers", setReq, &setReply); err != nil { + t.Error("Got error on ApierV1.RemoveActionTiming: ", err.Error()) + } else if setReply != OK { + t.Error("Unexpected answer received", setReply) + } + if err := rater.Call("ApierV1.GetAccountActionTriggers", req, &reply); err != nil { + t.Error("Got error on ApierV1.GetAccountActionTriggers: ", err.Error()) + } else if len(reply) != 1 || reply[0].ActivationDate != time.Date(2016, 2, 5, 18, 0, 0, 0, time.UTC) { + t.Errorf("Unexpected action triggers received %+v", reply[0]) + } +} + +// Test here RemAccountActionTriggers +func TestApierRemAccountActionTriggers(t *testing.T) { + + // Test first get so we can steal the id which we need to remove + var reply engine.ActionTriggers + req := AttrAcntAction{Tenant: "cgrates.org", Account: "dan2"} + if err := rater.Call("ApierV1.GetAccountActionTriggers", req, &reply); err != nil { + t.Error("Got error on ApierV1.GetAccountActionTimings: ", err.Error()) + } else if len(reply) != 1 || reply[0].ActionsID != "LOG_BALANCE" { + for _, atr := range reply { + t.Logf("ATR: %+v", atr) + } + t.Errorf("Unexpected action triggers received %v", reply) + } + var rmReply string + rmReq := AttrRemoveAccountActionTriggers{Tenant: "cgrates.org", Account: "dan2", UniqueID: reply[0].UniqueID} + if err := rater.Call("ApierV1.ResetAccountActionTriggers", rmReq, &rmReply); err != nil { + t.Error("Got error on ApierV1.ResetActionTiming: ", err.Error()) + } else if rmReply != OK { + t.Error("Unexpected answer received", rmReply) + } + if err := rater.Call("ApierV1.RemoveAccountActionTriggers", rmReq, &rmReply); err != nil { + t.Error("Got error on ApierV1.RemoveActionTiming: ", err.Error()) + } else if rmReply != OK { + t.Error("Unexpected answer received", rmReply) + } + if err := rater.Call("ApierV1.GetAccountActionTriggers", req, &reply); err != nil { + t.Error("Got error on ApierV1.GetAccountActionTriggers: ", err.Error()) + } else if len(reply) != 0 { + t.Errorf("Unexpected action triggers received %+v", reply[0]) + } +} + +// Test here SetAccount +func TestApierSetAccount(t *testing.T) { + + reply := "" + attrs := &utils.AttrSetAccount{Tenant: "cgrates.org", Account: "dan7", ActionPlanId: "ATMS_1", ReloadScheduler: true} + if err := rater.Call("ApierV1.SetAccount", attrs, &reply); err != nil { + t.Error("Got error on ApierV1.SetAccount: ", err.Error()) + } else if reply != "OK" { + t.Errorf("Calling ApierV1.SetAccount received: %s", reply) + } + reply2 := "" + attrs2 := new(utils.AttrSetAccount) + *attrs2 = *attrs + attrs2.ActionPlanId = "DUMMY_DATA" // Does not exist so it should error when adding triggers on it + // Add account with actions timing which does not exist + if err := rater.Call("ApierV1.SetAccount", attrs2, &reply2); err == nil || reply2 == "OK" { // OK is not welcomed + t.Error("Expecting error on ApierV1.SetAccount.", err, reply2) + } +} + +// Test here GetAccountActionTimings +func TestApierGetAccountActionPlan(t *testing.T) { + + var reply []*AccountActionTiming + req := AttrAcntAction{Tenant: "cgrates.org", Account: "dan7"} + if err := rater.Call("ApierV1.GetAccountActionPlan", req, &reply); err != nil { + t.Error("Got error on ApierV1.GetAccountActionPlan: ", err.Error()) + } else if len(reply) != 1 { + t.Error("Unexpected action plan received: ", utils.ToJSON(reply)) + } else { + if reply[0].ActionPlanId != "ATMS_1" { + t.Errorf("Unexpected ActionoveAccountPlanId received") + } + } +} + +// Test here RemoveActionTiming +func TestApierRemUniqueIDActionTiming(t *testing.T) { + + var rmReply string + rmReq := AttrRemActionTiming{ActionPlanId: "ATMS_1", Tenant: "cgrates.org", Account: "dan4"} + if err := rater.Call("ApierV1.RemActionTiming", rmReq, &rmReply); err != nil { + t.Error("Got error on ApierV1.RemActionTiming: ", err.Error()) + } else if rmReply != OK { + t.Error("Unexpected answer received", rmReply) + } + var reply []*AccountActionTiming + req := AttrAcntAction{Tenant: "cgrates.org", Account: "dan4"} + if err := rater.Call("ApierV1.GetAccountActionPlan", req, &reply); err != nil { + t.Error("Got error on ApierV1.GetAccountActionPlan: ", err.Error()) + } else if len(reply) != 0 { + t.Error("Action timings was not removed") + } +} + +// Test here GetAccount +func TestApierGetAccount(t *testing.T) { + + var reply *engine.Account + attrs := &utils.AttrGetAccount{Tenant: "cgrates.org", Account: "1001"} + if err := rater.Call("ApierV2.GetAccount", attrs, &reply); err != nil { + t.Error("Got error on ApierV1.GetAccount: ", err.Error()) + } else if reply.BalanceMap[utils.MONETARY].GetTotalValue() != 11.5 { // We expect 11.5 since we have added in the previous test 1.5 + t.Errorf("Calling ApierV1.GetBalance expected: 11.5, received: %f", reply.BalanceMap[utils.MONETARY].GetTotalValue()) + } + attrs = &utils.AttrGetAccount{Tenant: "cgrates.org", Account: "dan"} + if err := rater.Call("ApierV2.GetAccount", attrs, &reply); err != nil { + t.Error("Got error on ApierV1.GetAccount: ", err.Error()) + } else if reply.BalanceMap[utils.MONETARY].GetTotalValue() != 1.5 { + t.Errorf("Calling ApierV1.GetAccount expected: 1.5, received: %f", reply.BalanceMap[utils.MONETARY].GetTotalValue()) + } + // The one we have topped up though executeAction + attrs = &utils.AttrGetAccount{Tenant: "cgrates.org", Account: "dan2"} + if err := rater.Call("ApierV2.GetAccount", attrs, &reply); err != nil { + t.Error("Got error on ApierV1.GetAccount: ", err.Error()) + } else if reply.BalanceMap[utils.MONETARY].GetTotalValue() != 11.5 { + t.Errorf("Calling ApierV1.GetAccount expected: 10, received: %f", reply.BalanceMap[utils.MONETARY].GetTotalValue()) + } + attrs = &utils.AttrGetAccount{Tenant: "cgrates.org", Account: "dan3"} + if err := rater.Call("ApierV2.GetAccount", attrs, &reply); err != nil { + t.Error("Got error on ApierV1.GetAccount: ", err.Error()) + } else if reply.BalanceMap[utils.MONETARY].GetTotalValue() != 3.6 { + t.Errorf("Calling ApierV1.GetAccount expected: 3.6, received: %f", reply.BalanceMap[utils.MONETARY].GetTotalValue()) + } + attrs = &utils.AttrGetAccount{Tenant: "cgrates.org", Account: "dan6"} + if err := rater.Call("ApierV2.GetAccount", attrs, &reply); err != nil { + t.Error("Got error on ApierV1.GetAccount: ", err.Error()) + } else if reply.BalanceMap[utils.MONETARY].GetTotalValue() != 1 { + t.Errorf("Calling ApierV1.GetAccount expected: 1, received: %f", reply.BalanceMap[utils.MONETARY].GetTotalValue()) + } +} + +// Start with initial balance, top-up to test max_balance +func TestApierTriggersExecute(t *testing.T) { + + reply := "" + attrs := &utils.AttrSetAccount{Tenant: "cgrates.org", Account: "dan8", ReloadScheduler: true} + if err := rater.Call("ApierV1.SetAccount", attrs, &reply); err != nil { + t.Error("Got error on ApierV1.SetAccount: ", err.Error()) + } else if reply != "OK" { + t.Errorf("Calling ApierV1.SetAccount received: %s", reply) + } + attrAddBlnc := &AttrAddBalance{Tenant: "cgrates.org", Account: "1008", BalanceType: "*monetary", Value: 2} + if err := rater.Call("ApierV1.AddBalance", attrAddBlnc, &reply); err != nil { + t.Error("Got error on ApierV1.AddBalance: ", err.Error()) + } else if reply != "OK" { + t.Errorf("Calling ApierV1.AddBalance received: %s", reply) + } +} + +// Start fresh before loading from folder +func TestApierResetDataBeforeLoadFromFolder(t *testing.T) { + + TestApierInitDataDb(t) + reply := "" + arc := new(utils.AttrReloadCache) + // Simple test that command is executed without errors + if err := rater.Call("ApierV1.ReloadCache", arc, &reply); err != nil { + t.Error("Got error on ApierV1.ReloadCache: ", err.Error()) + } else if reply != "OK" { + t.Error("Calling ApierV1.ReloadCache got reply: ", reply) + } + var rcvStats *utils.CacheStats + var args utils.AttrCacheStats + err := rater.Call("ApierV1.GetCacheStats", args, &rcvStats) + expectedStats := new(utils.CacheStats) + if err != nil { + t.Error("Got error on ApierV1.GetCacheStats: ", err.Error()) + } else if !reflect.DeepEqual(rcvStats, expectedStats) { + t.Errorf("Calling ApierV1.GetCacheStats received: %v, expected: %v", rcvStats, expectedStats) + } +} + +// Test here LoadTariffPlanFromFolder +func TestApierLoadTariffPlanFromFolder(t *testing.T) { + + reply := "" + attrs := &utils.AttrLoadTpFromFolder{FolderPath: ""} + if err := rater.Call("ApierV1.LoadTariffPlanFromFolder", attrs, &reply); err == nil || !strings.HasPrefix(err.Error(), utils.ErrMandatoryIeMissing.Error()) { + t.Error(err) + } + attrs = &utils.AttrLoadTpFromFolder{FolderPath: "/INVALID/"} + if err := rater.Call("ApierV1.LoadTariffPlanFromFolder", attrs, &reply); err == nil || err.Error() != utils.ErrInvalidPath.Error() { + t.Error(err) + } + // Simple test that command is executed without errors + attrs = &utils.AttrLoadTpFromFolder{FolderPath: path.Join(*dataDir, "tariffplans", "testtp")} + if err := rater.Call("ApierV1.LoadTariffPlanFromFolder", attrs, &reply); err != nil { + t.Error("Got error on ApierV1.LoadTariffPlanFromFolder: ", err.Error()) + } else if reply != "OK" { + t.Error("Calling ApierV1.LoadTariffPlanFromFolder got reply: ", reply) + } + time.Sleep(time.Duration(1 * time.Second)) +} + +func TestApierResetDataAfterLoadFromFolder(t *testing.T) { + + reply := "" + arc := new(utils.AttrReloadCache) + // Simple test that command is executed without errors + if err := rater.Call("ApierV1.ReloadCache", arc, &reply); err != nil { + t.Error("Got error on ApierV1.ReloadCache: ", err.Error()) + } else if reply != "OK" { + t.Error("Calling ApierV1.ReloadCache got reply: ", reply) + } + var rcvStats *utils.CacheStats + var args utils.AttrCacheStats + if err := rater.Call("ApierV1.GetCacheStats", args, &rcvStats); err != nil { + t.Error("Got error on ApierV1.GetCacheStats: ", err.Error()) + } else { + if rcvStats.Destinations != 0 || + rcvStats.RatingPlans != 5 || + rcvStats.RatingProfiles != 0 || + rcvStats.Actions != 0 || + rcvStats.DerivedChargers != 0 { + t.Errorf("Calling ApierV1.GetCacheStats received: %+v", rcvStats) + } + } +} + +// Make sure balance was topped-up +// Bug reported by DigiDaz over IRC +func TestApierGetAccountAfterLoad(t *testing.T) { + + var reply *engine.Account + attrs := &utils.AttrGetAccount{Tenant: "cgrates.org", Account: "1001"} + if err := rater.Call("ApierV2.GetAccount", attrs, &reply); err != nil { + t.Error("Got error on ApierV1.GetAccount: ", err.Error()) + } else if reply.BalanceMap[utils.MONETARY].GetTotalValue() != 11 { + t.Errorf("Calling ApierV1.GetBalance expected: 11, received: %f", reply.BalanceMap[utils.MONETARY].GetTotalValue()) + } +} + +// Test here ResponderGetCost +func TestApierResponderGetCost(t *testing.T) { + + tStart, _ := utils.ParseDate("2013-08-07T17:30:00Z") + tEnd, _ := utils.ParseDate("2013-08-07T17:31:30Z") + cd := engine.CallDescriptor{ + Direction: "*out", + Category: "call", + Tenant: "cgrates.org", + Subject: "1001", + Account: "1001", + Destination: "+4917621621391", + DurationIndex: 90, + TimeStart: tStart, + TimeEnd: tEnd, + } + var cc engine.CallCost + // Simple test that command is executed without errors + if err := rater.Call("Responder.GetCost", cd, &cc); err != nil { + t.Error("Got error on Responder.GetCost: ", err.Error()) + } else if cc.Cost != 90.0 { + t.Errorf("Calling Responder.GetCost got callcost: %v", cc) + } +} + +// Test here ResponderGetCost +func TestApierGetCallCostLog(t *testing.T) { + + var cc engine.CallCost + var attrs utils.AttrGetCallCost + // Simple test that command is executed without errors + if err := rater.Call("ApierV1.GetCallCostLog", attrs, &cc); err == nil { + t.Error("Failed to detect missing fields in ApierV1.GetCallCostLog") + } + attrs.CgrId = "dummyid" + attrs.RunId = "default" + if err := rater.Call("ApierV1.GetCallCostLog", attrs, &cc); err == nil || err.Error() != utils.ErrNotFound.Error() { + t.Error("ApierV1.GetCallCostLog: should return NOT_FOUND, got:", err) + } +} + +func TestApierMaxDebitInexistentAcnt(t *testing.T) { + + cc := &engine.CallCost{} + cd := engine.CallDescriptor{ + Direction: "*out", + Tenant: "cgrates.org", + Category: "call", + Subject: "INVALID", + Account: "INVALID", + Destination: "1002", + TimeStart: time.Date(2014, 3, 27, 10, 42, 26, 0, time.UTC), + TimeEnd: time.Date(2014, 3, 27, 10, 42, 26, 0, time.UTC).Add(time.Duration(10) * time.Second), + } + if err := rater.Call("Responder.MaxDebit", cd, cc); err == nil { + t.Error(err.Error()) + } + if err := rater.Call("Responder.Debit", cd, cc); err == nil { + t.Error(err.Error()) + } + +} + +func TestApierCdrServer(t *testing.T) { + + httpClient := new(http.Client) + cdrForm1 := url.Values{utils.ACCID: []string{"dsafdsaf"}, utils.CDRHOST: []string{"192.168.1.1"}, utils.REQTYPE: []string{utils.META_RATED}, utils.DIRECTION: []string{"*out"}, + utils.TENANT: []string{"cgrates.org"}, utils.CATEGORY: []string{"call"}, utils.ACCOUNT: []string{"1001"}, utils.SUBJECT: []string{"1001"}, utils.DESTINATION: []string{"1002"}, + utils.SETUP_TIME: []string{"2013-11-07T08:42:22Z"}, + utils.ANSWER_TIME: []string{"2013-11-07T08:42:26Z"}, utils.USAGE: []string{"10"}, "field_extr1": []string{"val_extr1"}, "fieldextr2": []string{"valextr2"}} + cdrForm2 := url.Values{utils.ACCID: []string{"adsafdsaf"}, utils.CDRHOST: []string{"192.168.1.1"}, utils.REQTYPE: []string{utils.META_RATED}, utils.DIRECTION: []string{"*out"}, + utils.TENANT: []string{"cgrates.org"}, utils.CATEGORY: []string{"call"}, utils.ACCOUNT: []string{"1001"}, utils.SUBJECT: []string{"1001"}, utils.DESTINATION: []string{"1002"}, + utils.SETUP_TIME: []string{"2013-11-07T08:42:23Z"}, + utils.ANSWER_TIME: []string{"2013-11-07T08:42:26Z"}, utils.USAGE: []string{"10"}, "field_extr1": []string{"val_extr1"}, "fieldextr2": []string{"valextr2"}} + for _, cdrForm := range []url.Values{cdrForm1, cdrForm2} { + cdrForm.Set(utils.CDRSOURCE, utils.TEST_SQL) + if _, err := httpClient.PostForm(fmt.Sprintf("http://%s/cdr_http", "127.0.0.1:2080"), cdrForm); err != nil { + t.Error(err.Error()) + } + } + time.Sleep(time.Duration(*waitRater) * time.Millisecond) +} + +/* +func TestApierExportCdrsToFile(t *testing.T) { + + var reply *utils.ExportedFileCdrs + req := utils.AttrExpFileCdrs{} + //if err := rater.Call("ApierV1.ExportCdrsToFile", req, &reply); err == nil || !strings.HasPrefix(err.Error(), utils.ERR_MANDATORY_IE_MISSING) { + // t.Error("Failed to detect missing parameter") + //} + dryRun := utils.CDRE_DRYRUN + req.CdrFormat = &dryRun + tm1, _ := utils.ParseTimeDetectLayout("2013-11-07T08:42:22Z") + tm2, _ := utils.ParseTimeDetectLayout("2013-11-07T08:42:23Z") + expectReply := &utils.ExportedFileCdrs{ExportedFilePath: utils.CDRE_DRYRUN, TotalRecords: 2, ExportedCGRIDs: []string{utils.Sha1("dsafdsaf", tm1.String()), + utils.Sha1("adsafdsaf", tm2.String())}} + if err := rater.Call("ApierV1.ExportCdrsToFile", req, &reply); err != nil { + t.Error(err.Error()) + } else if !reflect.DeepEqual(reply, expectReply) { + t.Errorf("Unexpected reply: %v", reply) + } + Need to implement temporary file writing in order to test removal from db, not possible on DRYRUN + req.RemoveFromDb = true + if err := rater.Call("ApierV1.ExportCdrsToFile", req, &reply); err != nil { + t.Error(err.Error()) + } else if !reflect.DeepEqual(reply, expectReply) { + t.Errorf("Unexpected reply: %v", reply) + } + expectReply.NumberOfRecords = 0 // We should have deleted previously + if err := rater.Call("ApierV1.ExportCdrsToFile", req, &reply); err != nil { + t.Error(err.Error()) + } else if !reflect.DeepEqual(reply, expectReply) { + t.Errorf("Unexpected reply: %v", reply) + } + +} +*/ + +func TestApierLocalGetCdrs(t *testing.T) { + + var reply []*engine.ExternalCDR + req := utils.AttrGetCdrs{MediationRunIds: []string{utils.MetaRaw}} + if err := rater.Call("ApierV1.GetCdrs", req, &reply); err != nil { + t.Error("Unexpected error: ", err.Error()) + } else if len(reply) != 2 { + t.Error("Unexpected number of CDRs returned: ", len(reply)) + } +} + +func TestApierLocalProcessCdr(t *testing.T) { + + var reply string + cdr := engine.CDR{CGRID: utils.Sha1("dsafdsaf", time.Date(2013, 11, 7, 8, 42, 26, 0, time.UTC).String()), OrderID: 123, ToR: utils.VOICE, OriginID: "dsafdsaf", + OriginHost: "192.168.1.1", Source: "test", RequestType: utils.META_RATED, Direction: "*out", Tenant: "cgrates.org", Category: "call", Account: "1001", Subject: "1001", + Destination: "1002", + SetupTime: time.Date(2013, 11, 7, 8, 42, 26, 0, time.UTC), AnswerTime: time.Date(2013, 11, 7, 8, 42, 26, 0, time.UTC), RunID: utils.DEFAULT_RUNID, + Usage: time.Duration(10) * time.Second, ExtraFields: map[string]string{"field_extr1": "val_extr1", "fieldextr2": "valextr2"}, Cost: 1.01, + } + if err := rater.Call("CdrsV1.ProcessCDR", cdr, &reply); err != nil { + t.Error("Unexpected error: ", err.Error()) + } else if reply != utils.OK { + t.Error("Unexpected reply received: ", reply) + } + var cdrs []*engine.ExternalCDR + req := utils.AttrGetCdrs{MediationRunIds: []string{utils.MetaRaw}} + if err := rater.Call("ApierV1.GetCdrs", req, &cdrs); err != nil { + t.Error("Unexpected error: ", err.Error()) + } else if len(cdrs) != 3 { + t.Error("Unexpected number of CDRs returned: ", len(cdrs)) + } +} + +func TestApierLocalSetDC(t *testing.T) { + + dcs1 := []*utils.DerivedCharger{ + &utils.DerivedCharger{RunID: "extra1", RequestTypeField: "^prepaid", DirectionField: "*default", TenantField: "*default", CategoryField: "*default", + AccountField: "rif", SubjectField: "rif", DestinationField: "*default", SetupTimeField: "*default", AnswerTimeField: "*default", UsageField: "*default"}, + &utils.DerivedCharger{RunID: "extra2", RequestTypeField: "*default", DirectionField: "*default", TenantField: "*default", CategoryField: "*default", + AccountField: "ivo", SubjectField: "ivo", DestinationField: "*default", SetupTimeField: "*default", AnswerTimeField: "*default", UsageField: "*default"}, + } + attrs := AttrSetDerivedChargers{Direction: "*out", Tenant: "cgrates.org", Category: "call", Account: "dan", Subject: "dan", DerivedChargers: dcs1, Overwrite: true} + var reply string + if err := rater.Call("ApierV1.SetDerivedChargers", attrs, &reply); err != nil { + t.Error("Unexpected error", err.Error()) + } else if reply != utils.OK { + t.Error("Unexpected reply returned", reply) + } +} + +func TestApierLocalGetDC(t *testing.T) { + + attrs := utils.AttrDerivedChargers{Tenant: "cgrates.org", Category: "call", Direction: "*out", Account: "dan", Subject: "dan"} + eDcs := utils.DerivedChargers{DestinationIDs: utils.NewStringMap(), + Chargers: []*utils.DerivedCharger{ + &utils.DerivedCharger{RunID: "extra1", RequestTypeField: "^prepaid", DirectionField: "*default", TenantField: "*default", CategoryField: "*default", + AccountField: "rif", SubjectField: "rif", DestinationField: "*default", SetupTimeField: "*default", AnswerTimeField: "*default", UsageField: "*default"}, + &utils.DerivedCharger{RunID: "extra2", RequestTypeField: "*default", DirectionField: "*default", TenantField: "*default", CategoryField: "*default", + AccountField: "ivo", SubjectField: "ivo", DestinationField: "*default", SetupTimeField: "*default", AnswerTimeField: "*default", UsageField: "*default"}, + }} + var dcs utils.DerivedChargers + if err := rater.Call("ApierV1.GetDerivedChargers", attrs, &dcs); err != nil { + t.Error("Unexpected error", err.Error()) + } else if !reflect.DeepEqual(dcs, eDcs) { + t.Errorf("Expecting: %v, received: %v", eDcs, dcs) + } +} + +func TestApierLocalRemDC(t *testing.T) { + + attrs := utils.AttrDerivedChargers{Tenant: "cgrates.org", Category: "call", Direction: "*out", Account: "dan", Subject: "dan"} + var reply string + if err := rater.Call("ApierV1.RemDerivedChargers", attrs, &reply); err != nil { + t.Error("Unexpected error", err.Error()) + } else if reply != utils.OK { + t.Error("Unexpected reply returned", reply) + } +} + +func TestApierLocalSetDestination(t *testing.T) { + + attrs := utils.AttrSetDestination{Id: "TEST_SET_DESTINATION", Prefixes: []string{"+4986517174963", "+4986517174960"}} + var reply string + if err := rater.Call("ApierV1.SetDestination", attrs, &reply); err != nil { + t.Error("Unexpected error", err.Error()) + } else if reply != utils.OK { + t.Error("Unexpected reply returned", reply) + } + if err := rater.Call("ApierV1.SetDestination", attrs, &reply); err == nil || err.Error() != "EXISTS" { // Second time without overwrite should generate error + t.Error("Unexpected error", err.Error()) + } + attrs = utils.AttrSetDestination{Id: "TEST_SET_DESTINATION", Prefixes: []string{"+4986517174963", "+4986517174964"}, Overwrite: true} + if err := rater.Call("ApierV1.SetDestination", attrs, &reply); err != nil { + t.Error("Unexpected error", err.Error()) + } else if reply != utils.OK { + t.Error("Unexpected reply returned", reply) + } + eDestination := engine.Destination{Id: attrs.Id, Prefixes: attrs.Prefixes} + var rcvDestination engine.Destination + if err := rater.Call("ApierV1.GetDestination", attrs.Id, &rcvDestination); err != nil { + t.Error("Unexpected error", err.Error()) + } else if !reflect.DeepEqual(eDestination, rcvDestination) { + t.Error("Expecting: %+v, received: %+v", eDestination, rcvDestination) + } +} + +func TestApierLocalGetAliases(t *testing.T) { + + var alias engine.Alias + //al.Direction, al.Tenant, al.Category, al.Account, al.Subject, al.Group + if err := rater.Call("AliasesV1.GetAlias", engine.Alias{Context: utils.ALIAS_CONTEXT_RATING, Direction: "*out", Tenant: "cgrates.org", Category: "call", Account: "2001", Subject: "2001"}, &alias); err == nil { + t.Error("Unexpected nil error received") + } else if err.Error() != utils.ErrNotFound.Error() { + t.Error("Unexpected error", err.Error()) + } + if err := rater.Call("AliasesV1.GetAlias", engine.Alias{Context: utils.ALIAS_CONTEXT_RATING, Direction: "*out", Tenant: "cgrates.org", Category: "call", Account: "2001", Subject: "2001"}, &alias); err == nil { + t.Error("Unexpected nil error received") + } else if err.Error() != utils.ErrNotFound.Error() { + t.Error("Unexpected error", err.Error()) + } +} + +func TestApierLocalAddRatingSubjectAliases(t *testing.T) { + + addRtSubjAliases := &AttrAddRatingSubjectAliases{Tenant: "cgrates.org", Category: "call", Subject: "1001", Aliases: []string{"2001", "2002", "2003"}} + var rply string + if err := rater.Call("ApierV1.AddRatingSubjectAliases", addRtSubjAliases, &rply); err != nil { + t.Error("Unexpected error", err.Error()) + } else if rply != utils.OK { + t.Error("Unexpected reply: ", rply) + } + var alias engine.Alias + for _, als := range addRtSubjAliases.Aliases { + if err := rater.Call("AliasesV1.GetAlias", engine.Alias{Context: utils.ALIAS_CONTEXT_RATING, Direction: "*out", Tenant: addRtSubjAliases.Tenant, Category: addRtSubjAliases.Category, + Account: als, Subject: als}, &alias); err != nil { + t.Error("Unexpected error", err.Error()) + } + } +} + +func TestApierLocalRemRatingSubjectAliases(t *testing.T) { + + tenantRatingSubj := engine.TenantRatingSubject{Tenant: "cgrates.org", Subject: "1001"} + var rply string + if err := rater.Call("ApierV1.RemRatingSubjectAliases", tenantRatingSubj, &rply); err != nil { + t.Error("Unexpected error", err.Error()) + } else if rply != utils.OK { + t.Error("Unexpected reply: ", rply) + } + var alias engine.Alias + //al.Direction, al.Tenant, al.Category, al.Account, al.Subject, al.Group + if err := rater.Call("AliasesV1.GetAlias", engine.Alias{Context: utils.ALIAS_CONTEXT_RATING, Direction: "*out", Tenant: "cgrates.org", Category: "call", Account: "2001", Subject: "2001"}, &alias); err == nil || err.Error() != utils.ErrNotFound.Error() { + t.Errorf("Unexpected error %v, alias: %+v", err, alias) + } +} + +func TestApierLocalAddAccountAliases(t *testing.T) { + + addAcntAliases := &AttrAddAccountAliases{Tenant: "cgrates.org", Category: "call", Account: "1001", Aliases: []string{"2001", "2002", "2003"}} + var rply string + if err := rater.Call("ApierV1.AddAccountAliases", addAcntAliases, &rply); err != nil { + t.Error("Unexpected error", err.Error()) + } else if rply != utils.OK { + t.Error("Unexpected reply: ", rply) + } + var alias engine.Alias + for _, als := range addAcntAliases.Aliases { + if err := rater.Call("AliasesV1.GetAlias", engine.Alias{Context: utils.ALIAS_CONTEXT_RATING, Direction: "*out", Tenant: addAcntAliases.Tenant, Category: addAcntAliases.Category, + Account: als, Subject: als}, &alias); err != nil { + t.Error("Unexpected error", err.Error()) + } + } +} + +func TestApierLocalRemAccountAliases(t *testing.T) { + + tenantAcnt := engine.TenantAccount{Tenant: "cgrates.org", Account: "1001"} + var rply string + if err := rater.Call("ApierV1.RemAccountAliases", tenantAcnt, &rply); err != nil { + t.Error("Unexpected error", err.Error()) + } else if rply != utils.OK { + t.Error("Unexpected reply: ", rply) + } + var alias engine.Alias + //al.Direction, al.Tenant, al.Category, al.Account, al.Subject, al.Group + if err := rater.Call("AliasesV1.GetAlias", engine.Alias{Context: utils.ALIAS_CONTEXT_RATING, Direction: "*out", Tenant: "cgrates.org", Category: "call", Account: "2001", Subject: "2001"}, &alias); err == nil || err.Error() != utils.ErrNotFound.Error() { + t.Errorf("Unexpected error %v, alias: %+v", err, alias) + } +} + +func TestApierLocalGetScheduledActions(t *testing.T) { + + var rply []*ScheduledActions + if err := rater.Call("ApierV1.GetScheduledActions", AttrsGetScheduledActions{}, &rply); err != nil { + t.Error("Unexpected error: ", err) + } +} + +func TestApierLocalGetDataCost(t *testing.T) { + + attrs := AttrGetDataCost{Direction: "*out", Category: "data", Tenant: "cgrates.org", Account: "1001", Subject: "1001", StartTime: time.Now(), Usage: 640113} + var rply *engine.DataCost + if err := rater.Call("ApierV1.GetDataCost", attrs, &rply); err != nil { + t.Error("Unexpected nil error received: ", err.Error()) + } else if rply.Cost != 128.0240 { + t.Errorf("Unexpected cost received: %f", rply.Cost) + } +} + +// Test LoadTPFromStorDb +func TestApierInitDataDb2(t *testing.T) { + + if err := engine.InitDataDb(cfg); err != nil { + t.Fatal(err) + } +} + +func TestApierInitStorDb2(t *testing.T) { + + if err := engine.InitStorDb(cfg); err != nil { + t.Fatal(err) + } +} + +func TestApierReloadCache2(t *testing.T) { + + reply := "" + arc := new(utils.AttrReloadCache) + // Simple test that command is executed without errors + if err := rater.Call("ApierV1.ReloadCache", arc, &reply); err != nil { + t.Error("Got error on ApierV1.ReloadCache: ", err.Error()) + } else if reply != utils.OK { + t.Error("Calling ApierV1.ReloadCache got reply: ", reply) + } +} + +func TestApierReloadScheduler2(t *testing.T) { + + reply := "" + // Simple test that command is executed without errors + if err := rater.Call("ApierV1.ReloadScheduler", reply, &reply); err != nil { + t.Error("Got error on ApierV1.ReloadScheduler: ", err.Error()) + } else if reply != utils.OK { + t.Error("Calling ApierV1.ReloadScheduler got reply: ", reply) + } +} + +func TestApierImportTPFromFolderPath(t *testing.T) { + + var reply string + if err := rater.Call("ApierV1.ImportTariffPlanFromFolder", utils.AttrImportTPFromFolder{TPid: "TEST_TPID2", FolderPath: "/usr/share/cgrates/tariffplans/tutorial"}, &reply); err != nil { + t.Error("Got error on ApierV1.ImportTarrifPlanFromFolder: ", err.Error()) + } else if reply != utils.OK { + t.Error("Calling ApierV1.ImportTarrifPlanFromFolder got reply: ", reply) + } +} + +func TestApierLoadTariffPlanFromStorDbDryRun(t *testing.T) { + + var reply string + if err := rater.Call("ApierV1.LoadTariffPlanFromStorDb", AttrLoadTpFromStorDb{TPid: "TEST_TPID2", DryRun: true}, &reply); err != nil { + t.Error("Got error on ApierV1.LoadTariffPlanFromStorDb: ", err.Error()) + } else if reply != utils.OK { + t.Error("Calling ApierV1.LoadTariffPlanFromStorDb got reply: ", reply) + } +} + +func TestApierGetCacheStats2(t *testing.T) { + + var rcvStats *utils.CacheStats + var args utils.AttrCacheStats + err := rater.Call("ApierV1.GetCacheStats", args, &rcvStats) + expectedStats := new(utils.CacheStats) + if err != nil { + t.Error("Got error on ApierV1.GetCacheStats: ", err.Error()) + } else if !reflect.DeepEqual(expectedStats, rcvStats) { + t.Errorf("Calling ApierV1.GetCacheStats expected: %v, received: %v", expectedStats, rcvStats) + } +} + +func TestApierLoadTariffPlanFromStorDb(t *testing.T) { + + var reply string + if err := rater.Call("ApierV1.LoadTariffPlanFromStorDb", AttrLoadTpFromStorDb{TPid: "TEST_TPID2"}, &reply); err != nil { + t.Error("Got error on ApierV1.LoadTariffPlanFromStorDb: ", err.Error()) + } else if reply != utils.OK { + t.Error("Calling ApierV1.LoadTariffPlanFromStorDb got reply: ", reply) + } +} + +/* +func TestApierGetCacheStats3(t *testing.T) { + + var rcvStats *utils.CacheStats + expectedStats := &utils.CacheStats{Destinations: 4, RatingPlans: 3, RatingProfiles: 8, Actions: 7, SharedGroups: 1, RatingAliases: 1, AccountAliases: 1, DerivedChargers: 1} + var args utils.AttrCacheStats + if err := rater.Call("ApierV1.GetCacheStats", args, &rcvStats); err != nil { + t.Error("Got error on ApierV1.GetCacheStats: ", err.Error()) + } else if !reflect.DeepEqual(expectedStats, rcvStats) { + t.Errorf("Calling ApierV1.GetCacheStats expected: %v, received: %v", expectedStats, rcvStats) + } +}*/ + +// Simply kill the engine after we are done with tests within this file +func TestApierStopEngine(t *testing.T) { + + exec.Command("pkill", "cgr-engine").Run() +} diff --git a/apier/v1/cdrstatsv1_it_test.go b/apier/v1/cdrstatsv1_it_test.go new file mode 100644 index 000000000..091ec1c4d --- /dev/null +++ b/apier/v1/cdrstatsv1_it_test.go @@ -0,0 +1,195 @@ +// +build integration + +/* +Real-time Online/Offline Charging System (OCS) for Telecom & ISP environments +Copyright (C) ITsysCOM GmbH + +This program is free software: you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU General Public License for more details. + +You should have received a copy of the GNU General Public License +along with this program. If not, see +*/ +package v1 + +import ( + "net/rpc" + "net/rpc/jsonrpc" + "path" + "reflect" + "testing" + "time" + + "github.com/cgrates/cgrates/config" + "github.com/cgrates/cgrates/engine" + "github.com/cgrates/cgrates/utils" +) + +var cdrstCfgPath string +var cdrstCfg *config.CGRConfig +var cdrstRpc *rpc.Client + +func TestCDRStatsitLoadConfig(t *testing.T) { + var err error + cdrstCfgPath = path.Join(*dataDir, "conf", "samples", "cdrstats") + if cdrstCfg, err = config.NewCGRConfigFromFolder(cfgPath); err != nil { + t.Error(err) + } +} + +func TestCDRStatsitInitDataDb(t *testing.T) { + + if err := engine.InitDataDb(cdrstCfg); err != nil { + t.Fatal(err) + } +} + +func TestCDRStatsitStartEngine(t *testing.T) { + if _, err := engine.StopStartEngine(cdrstCfgPath, 1000); err != nil { + t.Fatal(err) + } +} + +// Connect rpc client to rater +func TestCDRStatsitRpcConn(t *testing.T) { + var err error + cdrstRpc, err = jsonrpc.Dial("tcp", cdrstCfg.RPCJSONListen) // We connect over JSON so we can also troubleshoot if needed + if err != nil { + t.Fatal("Could not connect to rater: ", err.Error()) + } +} + +func TestCDRStatsitLoadTariffPlanFromFolder(t *testing.T) { + reply := "" + // Simple test that command is executed without errors + attrs := &utils.AttrLoadTpFromFolder{FolderPath: path.Join(*dataDir, "tariffplans", "cdrstats")} + if err := cdrstRpc.Call("ApierV1.LoadTariffPlanFromFolder", attrs, &reply); err != nil { + t.Error("Got error on ApierV1.LoadTariffPlanFromFolder: ", err.Error()) + } else if reply != "OK" { + t.Error("Calling ApierV1.LoadTariffPlanFromFolder got reply: ", reply) + } + time.Sleep(time.Duration(*waitRater) * time.Millisecond) // Give time for scheduler to execute topups +} + +func TestCDRStatsitGetQueueIds2(t *testing.T) { + + var queueIds []string + eQueueIds := []string{"CDRST3", "CDRST4"} + if err := cdrstRpc.Call("CDRStatsV1.GetQueueIds", "", &queueIds); err != nil { + t.Error("Calling CDRStatsV1.GetQueueIds, got error: ", err.Error()) + } else if len(eQueueIds) != len(queueIds) { + t.Errorf("Expecting: %v, received: %v", eQueueIds, queueIds) + } + var rcvMetrics map[string]float64 + expectedMetrics := map[string]float64{"ASR": -1, "ACD": -1} + if err := cdrstRpc.Call("CDRStatsV1.GetMetrics", AttrGetMetrics{StatsQueueId: "CDRST4"}, &rcvMetrics); err != nil { + t.Error("Calling CDRStatsV1.GetMetrics, got error: ", err.Error()) + } else if !reflect.DeepEqual(expectedMetrics, rcvMetrics) { + t.Errorf("Expecting: %v, received: %v", expectedMetrics, rcvMetrics) + } +} + +func TestCDRStatsitPostCdrs(t *testing.T) { + + storedCdrs := []*engine.CDR{ + &engine.CDR{CGRID: utils.Sha1("dsafdsafa", time.Date(2013, 11, 7, 8, 42, 26, 0, time.UTC).String()), OrderID: 123, ToR: utils.VOICE, OriginID: "dsafdsafa", + OriginHost: "192.168.1.1", Source: "test", + RequestType: utils.META_RATED, Direction: "*out", Tenant: "cgrates.org", + Category: "call", Account: "1001", Subject: "1001", Destination: "+4986517174963", SetupTime: time.Now(), + AnswerTime: time.Now(), RunID: utils.DEFAULT_RUNID, Usage: time.Duration(10) * time.Second, + ExtraFields: map[string]string{"field_extr1": "val_extr1", "fieldextr2": "valextr2"}, Cost: 1.01, + }, + &engine.CDR{CGRID: utils.Sha1("dsafdsafb", time.Date(2013, 11, 7, 8, 42, 26, 0, time.UTC).String()), OrderID: 123, ToR: utils.VOICE, OriginID: "dsafdsafb", + OriginHost: "192.168.1.1", Source: "test", + RequestType: utils.META_RATED, Direction: "*out", Tenant: "cgrates.org", + Category: "call", Account: "1001", Subject: "1001", Destination: "+4986517174963", SetupTime: time.Now(), + AnswerTime: time.Now(), RunID: utils.DEFAULT_RUNID, + Usage: time.Duration(5) * time.Second, ExtraFields: map[string]string{"field_extr1": "val_extr1", "fieldextr2": "valextr2"}, Cost: 1.01, + }, + &engine.CDR{CGRID: utils.Sha1("dsafdsafc", time.Date(2013, 11, 7, 8, 42, 26, 0, time.UTC).String()), OrderID: 123, ToR: utils.VOICE, OriginID: "dsafdsafc", + OriginHost: "192.168.1.1", Source: "test", + RequestType: utils.META_RATED, Direction: "*out", Tenant: "cgrates.org", + Category: "call", Account: "1001", Subject: "1001", Destination: "+4986517174963", SetupTime: time.Now(), AnswerTime: time.Now(), + RunID: utils.DEFAULT_RUNID, + Usage: time.Duration(30) * time.Second, ExtraFields: map[string]string{"field_extr1": "val_extr1", "fieldextr2": "valextr2"}, Cost: 1.01, + }, + &engine.CDR{CGRID: utils.Sha1("dsafdsafd", time.Date(2013, 11, 7, 8, 42, 26, 0, time.UTC).String()), OrderID: 123, ToR: utils.VOICE, OriginID: "dsafdsafd", + OriginHost: "192.168.1.1", Source: "test", + RequestType: utils.META_RATED, Direction: "*out", Tenant: "cgrates.org", + Category: "call", Account: "1001", Subject: "1001", Destination: "+4986517174963", SetupTime: time.Now(), AnswerTime: time.Time{}, + RunID: utils.DEFAULT_RUNID, + Usage: time.Duration(0) * time.Second, ExtraFields: map[string]string{"field_extr1": "val_extr1", "fieldextr2": "valextr2"}, Cost: 1.01, + }, + } + for _, cdr := range storedCdrs { + var reply string + if err := cdrstRpc.Call("CdrsV1.ProcessCdr", cdr, &reply); err != nil { + t.Error(err) + } + } + time.Sleep(time.Duration(*waitRater) * time.Millisecond) +} + +func TestCDRStatsitGetMetrics1(t *testing.T) { + + var rcvMetrics2 map[string]float64 + expectedMetrics2 := map[string]float64{"ASR": 75, "ACD": 15} + if err := cdrstRpc.Call("CDRStatsV1.GetMetrics", AttrGetMetrics{StatsQueueId: "CDRST4"}, &rcvMetrics2); err != nil { + t.Error("Calling CDRStatsV1.GetMetrics, got error: ", err.Error()) + } else if !reflect.DeepEqual(expectedMetrics2, rcvMetrics2) { + t.Errorf("Expecting: %v, received: %v", expectedMetrics2, rcvMetrics2) + } +} + +// Test stats persistence +func TestCDRStatsitStatsPersistence(t *testing.T) { + + time.Sleep(time.Duration(2) * time.Second) // Allow stats to be updated in dataDb + if _, err := engine.StopStartEngine(cdrstCfgPath, *waitRater); err != nil { + t.Fatal(err) + } + var err error + cdrstRpc, err = jsonrpc.Dial("tcp", cdrstCfg.RPCJSONListen) // We connect over JSON so we can also troubleshoot if needed + if err != nil { + t.Fatal("Could not connect to rater: ", err.Error()) + } + var rcvMetrics map[string]float64 + expectedMetrics := map[string]float64{"ASR": 75, "ACD": 15} + if err := cdrstRpc.Call("CDRStatsV1.GetMetrics", AttrGetMetrics{StatsQueueId: "CDRST4"}, &rcvMetrics); err != nil { + t.Error("Calling CDRStatsV1.GetMetrics, got error: ", err.Error()) + } else if !reflect.DeepEqual(expectedMetrics, rcvMetrics) { + t.Errorf("Expecting: %v, received: %v", expectedMetrics, rcvMetrics) + } +} + +func TestCDRStatsitResetMetrics(t *testing.T) { + + var reply string + if err := cdrstRpc.Call("CDRStatsV1.ResetQueues", utils.AttrCDRStatsReloadQueues{StatsQueueIds: []string{"CDRST4"}}, &reply); err != nil { + t.Error("Calling CDRStatsV1.ResetQueues, got error: ", err.Error()) + } else if reply != utils.OK { + t.Error("Unexpected reply received: ", reply) + } + time.Sleep(time.Duration(*waitRater) * time.Millisecond) + var rcvMetrics2 map[string]float64 + expectedMetrics2 := map[string]float64{"ASR": -1, "ACD": -1} + if err := cdrstRpc.Call("CDRStatsV1.GetMetrics", AttrGetMetrics{StatsQueueId: "CDRST4"}, &rcvMetrics2); err != nil { + t.Error("Calling CDRStatsV1.GetMetrics, got error: ", err.Error()) + } else if !reflect.DeepEqual(expectedMetrics2, rcvMetrics2) { + t.Errorf("Expecting: %v, received: %v", expectedMetrics2, rcvMetrics2) + } +} + +func TestCDRStatsitKillEngine(t *testing.T) { + + if err := engine.KillEngine(*waitRater); err != nil { + t.Error(err) + } +} diff --git a/cdrc/flatstore_it_test.go b/cdrc/flatstore_it_test.go new file mode 100644 index 000000000..0d84a40d6 --- /dev/null +++ b/cdrc/flatstore_it_test.go @@ -0,0 +1,154 @@ +// +build integration + +/* +Real-time Online/Offline Charging System (OCS) for Telecom & ISP environments +Copyright (C) ITsysCOM GmbH + +This program is free software: you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU General Public License for more details. + +You should have received a copy of the GNU General Public License +along with this program. If not, see +*/ +package cdrc + +import ( + "io/ioutil" + "net/rpc" + "net/rpc/jsonrpc" + "os" + "path" + "testing" + "time" + + "github.com/cgrates/cgrates/config" + "github.com/cgrates/cgrates/engine" +) + +var flatstoreCfgPath string +var flatstoreCfg *config.CGRConfig +var flatstoreRpc *rpc.Client +var flatstoreCdrcCfg *config.CdrcConfig + +var fullSuccessfull = `INVITE|2daec40c|548625ac|dd0c4c617a9919d29a6175cdff223a9e@0:0:0:0:0:0:0:0|200|OK|1436454408|*prepaid|1001|1002||3401:2069362475 +BYE|2daec40c|548625ac|dd0c4c617a9919d29a6175cdff223a9e@0:0:0:0:0:0:0:0|200|OK|1436454410|||||3401:2069362475 +INVITE|f9d3d5c3|c863a6e3|214d8f52b566e33a9349b184e72a4cca@0:0:0:0:0:0:0:0|200|OK|1436454647|*postpaid|1002|1001||1877:893549741 +BYE|f9d3d5c3|c863a6e3|214d8f52b566e33a9349b184e72a4cca@0:0:0:0:0:0:0:0|200|OK|1436454651|||||1877:893549741 +INVITE|36e39a5|42d996f9|3a63321dd3b325eec688dc2aefb6ac2d@0:0:0:0:0:0:0:0|200|OK|1436454657|*prepaid|1001|1002||2407:1884881533 +BYE|36e39a5|42d996f9|3a63321dd3b325eec688dc2aefb6ac2d@0:0:0:0:0:0:0:0|200|OK|1436454661|||||2407:1884881533 +INVITE|3111f3c9|49ca4c42|a58ebaae40d08d6757d8424fb09c4c54@0:0:0:0:0:0:0:0|200|OK|1436454690|*prepaid|1001|1002||3099:1909036290 +BYE|3111f3c9|49ca4c42|a58ebaae40d08d6757d8424fb09c4c54@0:0:0:0:0:0:0:0|200|OK|1436454692|||||3099:1909036290 +` + +var fullMissed = `INVITE|ef6c6256|da501581|0bfdd176d1b93e7df3de5c6f4873ee04@0:0:0:0:0:0:0:0|487|Request Terminated|1436454643|*prepaid|1001|1002||1224:339382783 +INVITE|7905e511||81880da80a94bda81b425b09009e055c@0:0:0:0:0:0:0:0|404|Not Found|1436454668|*prepaid|1001|1002||1980:1216490844 +INVITE|324cb497|d4af7023|8deaadf2ae9a17809a391f05af31afb0@0:0:0:0:0:0:0:0|486|Busy here|1436454687|*postpaid|1002|1001||474:130115066` + +var part1 = `BYE|f9d3d5c3|c863a6e3|214d8f52b566e33a9349b184e72a4ccb@0:0:0:0:0:0:0:0|200|OK|1436454651|||||1877:893549742 +` + +var part2 = `INVITE|f9d3d5c3|c863a6e3|214d8f52b566e33a9349b184e72a4ccb@0:0:0:0:0:0:0:0|200|OK|1436454647|*postpaid|1002|1003||1877:893549742 +INVITE|2daec40c|548625ac|dd0c4c617a9919d29a6175cdff223a9e@0:0:0:0:0:0:0:0|200|OK|1436454408|*prepaid|1001|1002||3401:2069362475` + +func TestFlatstoreitInitCfg(t *testing.T) { + + var err error + flatstoreCfgPath = path.Join(*dataDir, "conf", "samples", "cdrcflatstore") + if flatstoreCfg, err = config.NewCGRConfigFromFolder(flatstoreCfgPath); err != nil { + t.Fatal("Got config error: ", err.Error()) + } +} + +// InitDb so we can rely on count +func TestFlatstoreitInitCdrDb(t *testing.T) { + + if err := engine.InitStorDb(flatstoreCfg); err != nil { + t.Fatal(err) + } +} + +// Creates cdr files and moves them into processing folder +func TestFlatstoreitCreateCdrFiles(t *testing.T) { + + if flatstoreCfg == nil { + t.Fatal("Empty default cdrc configuration") + } + for _, cdrcCfg := range flatstoreCfg.CdrcProfiles["/tmp/cgr_flatstore/cdrc/in"] { + if cdrcCfg.ID == "FLATSTORE" { + flatstoreCdrcCfg = cdrcCfg + } + } + if err := os.RemoveAll(flatstoreCdrcCfg.CdrInDir); err != nil { + t.Fatal("Error removing folder: ", flatstoreCdrcCfg.CdrInDir, err) + } + if err := os.MkdirAll(flatstoreCdrcCfg.CdrInDir, 0755); err != nil { + t.Fatal("Error creating folder: ", flatstoreCdrcCfg.CdrInDir, err) + } + if err := os.RemoveAll(flatstoreCdrcCfg.CdrOutDir); err != nil { + t.Fatal("Error removing folder: ", flatstoreCdrcCfg.CdrOutDir, err) + } + if err := os.MkdirAll(flatstoreCdrcCfg.CdrOutDir, 0755); err != nil { + t.Fatal("Error creating folder: ", flatstoreCdrcCfg.CdrOutDir, err) + } +} + +func TestFlatstoreitStartEngine(t *testing.T) { + + if _, err := engine.StopStartEngine(flatstoreCfgPath, *waitRater); err != nil { + t.Fatal(err) + } +} + +// Connect rpc client to rater +func TestFlatstoreitRpcConn(t *testing.T) { + + var err error + flatstoreRpc, err = jsonrpc.Dial("tcp", flatstoreCfg.RPCJSONListen) // We connect over JSON so we can also troubleshoot if needed + if err != nil { + t.Fatal("Could not connect to rater: ", err.Error()) + } +} + +func TestFlatstoreitProcessFiles(t *testing.T) { + + if err := ioutil.WriteFile(path.Join("/tmp", "acc_1.log"), []byte(fullSuccessfull), 0644); err != nil { + t.Fatal(err.Error) + } + if err := ioutil.WriteFile(path.Join("/tmp", "missed_calls_1.log"), []byte(fullMissed), 0644); err != nil { + t.Fatal(err.Error) + } + if err := ioutil.WriteFile(path.Join("/tmp", "acc_2.log"), []byte(part1), 0644); err != nil { + t.Fatal(err.Error) + } + if err := ioutil.WriteFile(path.Join("/tmp", "acc_3.log"), []byte(part2), 0644); err != nil { + t.Fatal(err.Error) + } + //Rename(oldpath, newpath string) + for _, fileName := range []string{"acc_1.log", "missed_calls_1.log", "acc_2.log", "acc_3.log"} { + if err := os.Rename(path.Join("/tmp", fileName), path.Join(flatstoreCdrcCfg.CdrInDir, fileName)); err != nil { + t.Fatal(err) + } + } + time.Sleep(time.Duration(2) * time.Second) // Give time for processing to happen and the .unparired file to be written + filesInDir, _ := ioutil.ReadDir(flatstoreCdrcCfg.CdrInDir) + if len(filesInDir) != 0 { + t.Errorf("Files in cdrcInDir: %+v", filesInDir) + } + filesOutDir, _ := ioutil.ReadDir(flatstoreCdrcCfg.CdrOutDir) + if len(filesOutDir) != 5 { + t.Errorf("In CdrcOutDir, expecting 5 files, got: %d", len(filesOutDir)) + } + ePartContent := "INVITE|2daec40c|548625ac|dd0c4c617a9919d29a6175cdff223a9e@0:0:0:0:0:0:0:0|200|OK|1436454408|*prepaid|1001|1002||3401:2069362475\n" + if partContent, err := ioutil.ReadFile(path.Join(flatstoreCdrcCfg.CdrOutDir, "acc_3.log.unpaired")); err != nil { + t.Error(err) + } else if ePartContent != string(partContent) { + t.Errorf("Expecting: %s, received: %s", ePartContent, string(partContent)) + } +} diff --git a/cdrc/fwv_it_test.go b/cdrc/fwv_it_test.go new file mode 100644 index 000000000..ec9d4083e --- /dev/null +++ b/cdrc/fwv_it_test.go @@ -0,0 +1,146 @@ +// +build integration + +/* +Real-time Online/Offline Charging System (OCS) for Telecom & ISP environments +Copyright (C) ITsysCOM GmbH + +This program is free software: you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU General Public License for more details. + +You should have received a copy of the GNU General Public License +along with this program. If not, see +*/ +package cdrc + +import ( + "io/ioutil" + "net/rpc" + "net/rpc/jsonrpc" + "os" + "path" + "testing" + "time" + + "github.com/cgrates/cgrates/config" + "github.com/cgrates/cgrates/engine" +) + +var fwvCfgPath string +var fwvCfg *config.CGRConfig +var fwvRpc *rpc.Client +var fwvCdrcCfg *config.CdrcConfig + +var FW_CDR_FILE1 = `HDR0001DDB ABC Some Connect A.B. DDB-Some-10022-20120711-309.CDR 00030920120711100255 +CDR0000010 0 20120708181506000123451234 0040123123120 004 000018009980010001ISDN ABC 10Buiten uw regio EHV 00000009190000000009 +CDR0000020 0 20120708190945000123451234 0040123123120 004 000016009980010001ISDN ABC 10Buiten uw regio EHV 00000009190000000009 +CDR0000030 0 20120708191009000123451234 0040123123120 004 000020009980010001ISDN ABC 10Buiten uw regio EHV 00000009190000000009 +CDR0000040 0 20120708231043000123451234 0040123123120 004 000011009980010001ISDN ABC 10Buiten uw regio EHV 00000009190000000009 +CDR0000050 0 20120709122216000123451235 004212 004 000217009980010001ISDN ABC 10Buiten uw regio HMR 00000000190000000000 +CDR0000060 0 20120709130542000123451236 0012323453 004 000019009980010001ISDN ABC 35Sterdiensten AP 00000000190000000000 +CDR0000070 0 20120709140032000123451237 0040012323453100 001 000050009980030001ISDN ABD 20Internationaal NLB 00000000190000000000 +CDR0000080 0 20120709140142000123451237 0040012323453100 001 000050009980030001ISDN ABD 20Internationaal NLB 00000000190000000000 +CDR0000090 0 20120709150305000123451237 0040012323453100 001 000050009980030001ISDN ABD 20Internationaal NLB 00000000190000000000 +CDR0000100 0 20120709150414000123451237 0040012323453100 001 000057009980030001ISDN ABD 20Internationaal NLB 00000000190000000000 +CDR0000110 0 20120709150531000123451237 0040012323453100 001 000059009980030001ISDN ABD 20Internationaal NLB 00000000190000000000 +CDR0000120 0 20120709150635000123451237 0040012323453100 001 000050009980030001ISDN ABD 20Internationaal NLB 00000000190000000000 +CDR0000130 0 20120709151756000123451237 0040012323453100 001 000050009980030001ISDN ABD 20Internationaal NLB 00000000190000000000 +CDR0000140 0 20120709154549000123451237 0040012323453100 001 000052009980030001ISDN ABD 20Internationaal NLB 00000000190000000000 +CDR0000150 0 20120709154701000123451237 0040012323453100 001 000121009980030001ISDN ABD 20Internationaal NLB 00000000190000000000 +CDR0000160 0 20120709154842000123451237 0040012323453100 001 000055009980030001ISDN ABD 20Internationaal NLB 00000000190000000000 +CDR0000170 0 20120709154956000123451237 0040012323453100 001 000115009980030001ISDN ABD 20Internationaal NLB 00000000190000000000 +CDR0000180 0 20120709155131000123451237 0040012323453100 001 000059009980030001ISDN ABD 20Internationaal NLB 00000000190000000000 +CDR0000190 0 20120709155236000123451237 0040012323453100 001 000050009980030001ISDN ABD 20Internationaal NLB 00000000190000000000 +CDR0000200 0 20120709160309000123451237 0040012323453100 001 000100009980030001ISDN ABD 20Internationaal NLB 00000000190000000000 +CDR0000210 0 20120709160415000123451237 0040012323453100 001 000050009980030001ISDN ABD 20Internationaal NLB 00000000190000000000 +CDR0000220 0 20120709161739000123451237 0040012323453100 001 000058009980030001ISDN ABD 20Internationaal NLB 00000000190000000000 +CDR0000230 0 20120709170356000123123459 0040123234531 004 000012002760010001ISDN 276 10Buiten uw regio TB 00000009190000000009 +CDR0000240 0 20120709181036000123123450 0012323453 004 000042009980010001ISDN ABC 05Binnen uw regio AP 00000010190000000010 +CDR0000250 0 20120709191245000123123458 0040123232350 004 000012002760000001PSTN 276 10Buiten uw regio TB 00000009190000000009 +CDR0000260 0 20120709202324000123123459 0040123234531 004 000011002760010001ISDN 276 10Buiten uw regio TB 00000009190000000009 +CDR0000270 0 20120709211756000123451237 0040012323453100 001 000051009980030001ISDN ABD 20Internationaal NLB 00000000190000000000 +CDR0000280 0 20120709211852000123451237 0040012323453100 001 000050009980030001ISDN ABD 20Internationaal NLB 00000000190000000000 +CDR0000290 0 20120709212904000123123458 0040123232350 004 000012002760000001PSTN 276 10Buiten uw regio TB 00000009190000000009 +CDR0000300 0 20120709073707000123123459 0040123234531 004 000012002760010001ISDN 276 10Buiten uw regio TB 00000009190000000009 +CDR0000310 0 20120709085451000123451237 0040012323453100 001 000744009980030001ISDN ABD 20Internationaal NLB 00000000190000000000 +CDR0000320 0 20120709091756000123451237 0040012323453100 001 000050009980030001ISDN ABD 20Internationaal NLB 00000000190000000000 +CDR0000330 0 20120710070434000123123458 0040123232350 004 000012002760000001PSTN 276 10Buiten uw regio TB 00000009190000000009 +TRL0001DDB ABC Some Connect A.B. DDB-Some-10022-20120711-309.CDR 0003090000003300000030550000000001000000000100Y +` + +func TestFwvitInitCfg(t *testing.T) { + + var err error + fwvCfgPath = path.Join(*dataDir, "conf", "samples", "cdrcfwv") + if fwvCfg, err = config.NewCGRConfigFromFolder(fwvCfgPath); err != nil { + t.Fatal("Got config error: ", err.Error()) + } +} + +// Creates cdr files and moves them into processing folder +func TestFwvitCreateCdrFiles(t *testing.T) { + + if fwvCfg == nil { + t.Fatal("Empty default cdrc configuration") + } + for _, cdrcCfg := range fwvCfg.CdrcProfiles["/tmp/cgr_fwv/cdrc/in"] { + if cdrcCfg.ID == "FWV1" { + fwvCdrcCfg = cdrcCfg + } + } + if err := os.RemoveAll(fwvCdrcCfg.CdrInDir); err != nil { + t.Fatal("Error removing folder: ", fwvCdrcCfg.CdrInDir, err) + } + if err := os.MkdirAll(fwvCdrcCfg.CdrInDir, 0755); err != nil { + t.Fatal("Error creating folder: ", fwvCdrcCfg.CdrInDir, err) + } + if err := os.RemoveAll(fwvCdrcCfg.CdrOutDir); err != nil { + t.Fatal("Error removing folder: ", fwvCdrcCfg.CdrOutDir, err) + } + if err := os.MkdirAll(fwvCdrcCfg.CdrOutDir, 0755); err != nil { + t.Fatal("Error creating folder: ", fwvCdrcCfg.CdrOutDir, err) + } +} + +func TestFwvitStartEngine(t *testing.T) { + + if _, err := engine.StopStartEngine(fwvCfgPath, *waitRater); err != nil { + t.Fatal(err) + } +} + +// Connect rpc client to rater +func TestFwvitRpcConn(t *testing.T) { + + var err error + fwvRpc, err = jsonrpc.Dial("tcp", fwvCfg.RPCJSONListen) // We connect over JSON so we can also troubleshoot if needed + if err != nil { + t.Fatal("Could not connect to rater: ", err.Error()) + } +} + +func TestFwvitProcessFiles(t *testing.T) { + + fileName := "test1.fwv" + if err := ioutil.WriteFile(path.Join("/tmp", fileName), []byte(FW_CDR_FILE1), 0644); err != nil { + t.Fatal(err.Error) + } + if err := os.Rename(path.Join("/tmp", fileName), path.Join(fwvCdrcCfg.CdrInDir, fileName)); err != nil { + t.Fatal(err) + } + time.Sleep(time.Duration(1) * time.Second) + filesInDir, _ := ioutil.ReadDir(fwvCdrcCfg.CdrInDir) + if len(filesInDir) != 0 { + t.Errorf("Files in cdrcInDir: %d", len(filesInDir)) + } + filesOutDir, _ := ioutil.ReadDir(fwvCdrcCfg.CdrOutDir) + if len(filesOutDir) != 1 { + t.Errorf("In CdrcOutDir, expecting 1 files, got: %d", len(filesOutDir)) + } +} diff --git a/config/multifiles_it_test.go b/config/multifiles_it_test.go new file mode 100644 index 000000000..3bc133939 --- /dev/null +++ b/config/multifiles_it_test.go @@ -0,0 +1,95 @@ +// +build integration + +/* +Real-time Online/Offline Charging System (OCS) for Telecom & ISP environments +Copyright (C) ITsysCOM GmbH + +This program is free software: you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU General Public License for more details. + +You should have received a copy of the GNU General Public License +along with this program. If not, see +*/ +package config + +import ( + "flag" + "github.com/cgrates/cgrates/utils" + "testing" +) + +var testIT = flag.Bool("integration", false, "Perform the tests only on local test environment, not by default.") +var mfCgrCfg *CGRConfig + +func TestMfInitConfig(t *testing.T) { + + var err error + if mfCgrCfg, err = NewCGRConfigFromFolder("/usr/share/cgrates/conf/samples/multifiles"); err != nil { + t.Fatal("Got config error: ", err.Error()) + } +} + +func TestMfGeneralItems(t *testing.T) { + + if mfCgrCfg.DefaultReqType != utils.META_PSEUDOPREPAID { // Twice reconfigured + t.Error("DefaultReqType: ", mfCgrCfg.DefaultReqType) + } + if mfCgrCfg.DefaultCategory != "call" { // Not configred, should be inherited from default + t.Error("DefaultCategory: ", mfCgrCfg.DefaultCategory) + } +} + +func TestMfCdreDefaultInstance(t *testing.T) { + + for _, prflName := range []string{"*default", "export1"} { + if _, hasIt := mfCgrCfg.CdreProfiles[prflName]; !hasIt { + t.Error("Cdre does not contain profile ", prflName) + } + } + prfl := "*default" + if mfCgrCfg.CdreProfiles[prfl].CdrFormat != "csv" { + t.Error("Default instance has cdrFormat: ", mfCgrCfg.CdreProfiles[prfl].CdrFormat) + } + if mfCgrCfg.CdreProfiles[prfl].DataUsageMultiplyFactor != 1024.0 { + t.Error("Default instance has cdrFormat: ", mfCgrCfg.CdreProfiles[prfl].DataUsageMultiplyFactor) + } + if len(mfCgrCfg.CdreProfiles[prfl].HeaderFields) != 0 { + t.Error("Default instance has number of header fields: ", len(mfCgrCfg.CdreProfiles[prfl].HeaderFields)) + } + if len(mfCgrCfg.CdreProfiles[prfl].ContentFields) != 12 { + t.Error("Default instance has number of content fields: ", len(mfCgrCfg.CdreProfiles[prfl].ContentFields)) + } + if mfCgrCfg.CdreProfiles[prfl].ContentFields[2].Tag != "Direction" { + t.Error("Unexpected headerField value: ", mfCgrCfg.CdreProfiles[prfl].ContentFields[2].Tag) + } +} + +func TestMfCdreExport1Instance(t *testing.T) { + + prfl := "export1" + if mfCgrCfg.CdreProfiles[prfl].CdrFormat != "csv" { + t.Error("Export1 instance has cdrFormat: ", mfCgrCfg.CdreProfiles[prfl].CdrFormat) + } + if mfCgrCfg.CdreProfiles[prfl].DataUsageMultiplyFactor != 1.0 { + t.Error("Export1 instance has DataUsageMultiplyFormat: ", mfCgrCfg.CdreProfiles[prfl].DataUsageMultiplyFactor) + } + if len(mfCgrCfg.CdreProfiles[prfl].HeaderFields) != 2 { + t.Error("Export1 instance has number of header fields: ", len(mfCgrCfg.CdreProfiles[prfl].HeaderFields)) + } + if mfCgrCfg.CdreProfiles[prfl].HeaderFields[1].Tag != "RunId" { + t.Error("Unexpected headerField value: ", mfCgrCfg.CdreProfiles[prfl].HeaderFields[1].Tag) + } + if len(mfCgrCfg.CdreProfiles[prfl].ContentFields) != 9 { + t.Error("Export1 instance has number of content fields: ", len(mfCgrCfg.CdreProfiles[prfl].ContentFields)) + } + if mfCgrCfg.CdreProfiles[prfl].ContentFields[2].Tag != "Account" { + t.Error("Unexpected headerField value: ", mfCgrCfg.CdreProfiles[prfl].ContentFields[2].Tag) + } +} diff --git a/engine/actions_it_test.go b/engine/actions_it_test.go new file mode 100644 index 000000000..36a63e5a9 --- /dev/null +++ b/engine/actions_it_test.go @@ -0,0 +1,170 @@ +// +build integration + +/* +Real-time Online/Offline Charging System (OCS) for Telecom & ISP environments +Copyright (C) ITsysCOM GmbH + +This program is free software: you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU General Public License for more details. + +You should have received a copy of the GNU General Public License +along with this program. If not, see +*/ +package engine + +import ( + "flag" + "net/rpc" + "net/rpc/jsonrpc" + "path" + "strconv" + "testing" + "time" + + "github.com/cgrates/cgrates/config" + "github.com/cgrates/cgrates/utils" +) + +var actsLclCfg *config.CGRConfig +var actsLclRpc *rpc.Client +var actsLclCfgPath = path.Join(*dataDir, "conf", "samples", "actions") + +var waitRater = flag.Int("wait_rater", 100, "Number of miliseconds to wait for rater to start and cache") + +func TestActionsitInitCfg(t *testing.T) { + + // Init config first + var err error + actsLclCfg, err = config.NewCGRConfigFromFolder(actsLclCfgPath) + if err != nil { + t.Error(err) + } + actsLclCfg.DataFolderPath = *dataDir // Share DataFolderPath through config towards StoreDb for Flush() + config.SetCgrConfig(actsLclCfg) +} + +func TestActionsitInitCdrDb(t *testing.T) { + + if err := InitStorDb(actsLclCfg); err != nil { + t.Fatal(err) + } +} + +// Finds cgr-engine executable and starts it with default configuration +func TestActionsitStartEngine(t *testing.T) { + + if _, err := StartEngine(actsLclCfgPath, *waitRater); err != nil { + t.Fatal(err) + } +} + +// Connect rpc client to rater +func TestActionsitRpcConn(t *testing.T) { + + var err error + time.Sleep(500 * time.Millisecond) + actsLclRpc, err = jsonrpc.Dial("tcp", actsLclCfg.RPCJSONListen) // We connect over JSON so we can also troubleshoot if needed + if err != nil { + t.Fatal(err) + } +} + +func TestActionsitSetCdrlogDebit(t *testing.T) { + + var reply string + attrsSetAccount := &utils.AttrSetAccount{Tenant: "cgrates.org", Account: "dan2904"} + if err := actsLclRpc.Call("ApierV1.SetAccount", attrsSetAccount, &reply); err != nil { + t.Error("Got error on ApierV1.SetAccount: ", err.Error()) + } else if reply != utils.OK { + t.Errorf("Calling ApierV1.SetAccount received: %s", reply) + } + attrsAA := &utils.AttrSetActions{ActionsId: "ACTS_1", Actions: []*utils.TPAction{ + &utils.TPAction{Identifier: DEBIT, BalanceType: utils.MONETARY, Units: "5", ExpiryTime: UNLIMITED, Weight: 20.0}, + &utils.TPAction{Identifier: CDRLOG}, + }} + if err := actsLclRpc.Call("ApierV2.SetActions", attrsAA, &reply); err != nil && err.Error() != utils.ErrExists.Error() { + t.Error("Got error on ApierV2.SetActions: ", err.Error()) + } else if reply != utils.OK { + t.Errorf("Calling ApierV2.SetActions received: %s", reply) + } + attrsEA := &utils.AttrExecuteAction{Tenant: attrsSetAccount.Tenant, Account: attrsSetAccount.Account, ActionsId: attrsAA.ActionsId} + if err := actsLclRpc.Call("ApierV1.ExecuteAction", attrsEA, &reply); err != nil { + t.Error("Got error on ApierV1.ExecuteAction: ", err.Error()) + } else if reply != utils.OK { + t.Errorf("Calling ApierV1.ExecuteAction received: %s", reply) + } + var rcvedCdrs []*ExternalCDR + if err := actsLclRpc.Call("ApierV2.GetCdrs", utils.RPCCDRsFilter{Sources: []string{CDRLOG}, Accounts: []string{attrsSetAccount.Account}}, &rcvedCdrs); err != nil { + t.Error("Unexpected error: ", err.Error()) + } else if len(rcvedCdrs) != 1 { + t.Error("Unexpected number of CDRs returned: ", len(rcvedCdrs)) + } else if rcvedCdrs[0].ToR != utils.MONETARY || + rcvedCdrs[0].OriginHost != "127.0.0.1" || + rcvedCdrs[0].Source != CDRLOG || + rcvedCdrs[0].RequestType != utils.META_PREPAID || + rcvedCdrs[0].Tenant != "cgrates.org" || + rcvedCdrs[0].Account != "dan2904" || + rcvedCdrs[0].Subject != "dan2904" || + rcvedCdrs[0].Usage != "1" || + rcvedCdrs[0].RunID != DEBIT || + strconv.FormatFloat(rcvedCdrs[0].Cost, 'f', -1, 64) != attrsAA.Actions[0].Units { + t.Errorf("Received: %+v", rcvedCdrs[0]) + } +} + +func TestActionsitSetCdrlogTopup(t *testing.T) { + + var reply string + attrsSetAccount := &utils.AttrSetAccount{Tenant: "cgrates.org", Account: "dan2905"} + if err := actsLclRpc.Call("ApierV1.SetAccount", attrsSetAccount, &reply); err != nil { + t.Error("Got error on ApierV1.SetAccount: ", err.Error()) + } else if reply != utils.OK { + t.Errorf("Calling ApierV1.SetAccount received: %s", reply) + } + attrsAA := &utils.AttrSetActions{ActionsId: "ACTS_2", Actions: []*utils.TPAction{ + &utils.TPAction{Identifier: TOPUP, BalanceType: utils.MONETARY, Units: "5", ExpiryTime: UNLIMITED, Weight: 20.0}, + &utils.TPAction{Identifier: CDRLOG}, + }} + if err := actsLclRpc.Call("ApierV2.SetActions", attrsAA, &reply); err != nil && err.Error() != utils.ErrExists.Error() { + t.Error("Got error on ApierV2.SetActions: ", err.Error()) + } else if reply != utils.OK { + t.Errorf("Calling ApierV2.SetActions received: %s", reply) + } + attrsEA := &utils.AttrExecuteAction{Tenant: attrsSetAccount.Tenant, Account: attrsSetAccount.Account, ActionsId: attrsAA.ActionsId} + if err := actsLclRpc.Call("ApierV1.ExecuteAction", attrsEA, &reply); err != nil { + t.Error("Got error on ApierV1.ExecuteAction: ", err.Error()) + } else if reply != utils.OK { + t.Errorf("Calling ApierV1.ExecuteAction received: %s", reply) + } + var rcvedCdrs []*ExternalCDR + if err := actsLclRpc.Call("ApierV2.GetCdrs", utils.RPCCDRsFilter{Sources: []string{CDRLOG}, Accounts: []string{attrsSetAccount.Account}}, &rcvedCdrs); err != nil { + t.Error("Unexpected error: ", err.Error()) + } else if len(rcvedCdrs) != 1 { + t.Error("Unexpected number of CDRs returned: ", len(rcvedCdrs)) + } else if rcvedCdrs[0].ToR != utils.MONETARY || + rcvedCdrs[0].OriginHost != "127.0.0.1" || + rcvedCdrs[0].Source != CDRLOG || + rcvedCdrs[0].RequestType != utils.META_PREPAID || + rcvedCdrs[0].Tenant != "cgrates.org" || + rcvedCdrs[0].Account != "dan2905" || + rcvedCdrs[0].Subject != "dan2905" || + rcvedCdrs[0].Usage != "1" || + rcvedCdrs[0].RunID != TOPUP || + strconv.FormatFloat(-rcvedCdrs[0].Cost, 'f', -1, 64) != attrsAA.Actions[0].Units { + t.Errorf("Received: %+v", rcvedCdrs[0]) + } +} + +func TestActionsitStopCgrEngine(t *testing.T) { + + if err := KillEngine(*waitRater); err != nil { + t.Error(err) + } +} diff --git a/engine/cdr_it_test.go b/engine/cdr_it_test.go new file mode 100644 index 000000000..c4d5f820f --- /dev/null +++ b/engine/cdr_it_test.go @@ -0,0 +1,50 @@ +// +build integration + +/* +Real-time Online/Offline Charging System (OCS) for Telecom & ISP environments +Copyright (C) ITsysCOM GmbH + +This program is free software: you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU General Public License for more details. + +You should have received a copy of the GNU General Public License +along with this program. If not, see +*/ +package engine + +import ( + "encoding/json" + "flag" + "testing" + "time" + + "github.com/cgrates/cgrates/utils" +) + +// Arguments received via test command +var testIT = flag.Bool("integration", false, "Perform the tests only on local test environment, not by default.") +var dataDir = flag.String("data_dir", "/usr/share/cgrates", "CGR data dir path here") + +// Sample HttpJsonPost, more for usage purposes +func TestHttpJsonPost(t *testing.T) { + + cdrOut := &ExternalCDR{CGRID: utils.Sha1("dsafdsaf", time.Date(2013, 11, 7, 8, 42, 20, 0, time.UTC).String()), OrderID: 123, ToR: utils.VOICE, OriginID: "dsafdsaf", + OriginHost: "192.168.1.1", + Source: utils.UNIT_TEST, RequestType: utils.META_RATED, Direction: "*out", Tenant: "cgrates.org", + Category: "call", Account: "account1", Subject: "tgooiscs0014", Destination: "1002", + SetupTime: time.Date(2013, 11, 7, 8, 42, 20, 0, time.UTC).String(), AnswerTime: time.Date(2013, 11, 7, 8, 42, 26, 0, time.UTC).String(), + RunID: utils.DEFAULT_RUNID, + Usage: "0.00000001", ExtraFields: map[string]string{"field_extr1": "val_extr1", "fieldextr2": "valextr2"}, Cost: 1.01, + } + jsn, _ := json.Marshal(cdrOut) + if _, err := utils.HttpJsonPost("http://localhost:8000", false, jsn); err == nil { + t.Error(err) + } +} diff --git a/engine/loader_it_test.go b/engine/loader_it_test.go new file mode 100644 index 000000000..27c1e2523 --- /dev/null +++ b/engine/loader_it_test.go @@ -0,0 +1,424 @@ +// +build integration + +/* +Real-time Online/Offline Charging System (OCS) for Telecom & ISP environments +Copyright (C) ITsysCOM GmbH + +This program is free software: you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU General Public License for more details. + +You should have received a copy of the GNU General Public License +along with this program. If not, see +*/ +package engine + +import ( + "flag" + "path" + "testing" + + "github.com/cgrates/cgrates/config" + "github.com/cgrates/cgrates/utils" +) + +// Globals used +var ratingDbCsv, ratingDbStor, ratingDbApier RatingStorage // Each ratingDb will have it's own sources to collect data +var accountDbCsv, accountDbStor, accountDbApier AccountingStorage // Each ratingDb will have it's own sources to collect data +var storDb LoadStorage +var lCfg *config.CGRConfig + +var tpCsvScenario = flag.String("tp_scenario", "testtp", "Use this scenario folder to import tp csv data from") + +// Create connection to ratingDb +// Will use 3 different datadbs in order to be able to see differences in data loaded +func TestConnDataDbs(t *testing.T) { + + lCfg, _ = config.NewDefaultCGRConfig() + var err error + if ratingDbCsv, err = ConfigureRatingStorage(lCfg.TpDbType, lCfg.TpDbHost, lCfg.TpDbPort, "4", lCfg.TpDbUser, lCfg.TpDbPass, lCfg.DBDataEncoding, nil, 1); err != nil { + t.Fatal("Error on ratingDb connection: ", err.Error()) + } + if ratingDbStor, err = ConfigureRatingStorage(lCfg.TpDbType, lCfg.TpDbHost, lCfg.TpDbPort, "5", lCfg.TpDbUser, lCfg.TpDbPass, lCfg.DBDataEncoding, nil, 1); err != nil { + t.Fatal("Error on ratingDb connection: ", err.Error()) + } + if ratingDbApier, err = ConfigureRatingStorage(lCfg.TpDbType, lCfg.TpDbHost, lCfg.TpDbPort, "6", lCfg.TpDbUser, lCfg.TpDbPass, lCfg.DBDataEncoding, nil, 1); err != nil { + t.Fatal("Error on ratingDb connection: ", err.Error()) + } + if accountDbCsv, err = ConfigureAccountingStorage(lCfg.DataDbType, lCfg.DataDbHost, lCfg.DataDbPort, "7", + lCfg.DataDbUser, lCfg.DataDbPass, lCfg.DBDataEncoding, nil, 1); err != nil { + t.Fatal("Error on ratingDb connection: ", err.Error()) + } + if accountDbStor, err = ConfigureAccountingStorage(lCfg.DataDbType, lCfg.DataDbHost, lCfg.DataDbPort, "8", + lCfg.DataDbUser, lCfg.DataDbPass, lCfg.DBDataEncoding, nil, 1); err != nil { + t.Fatal("Error on ratingDb connection: ", err.Error()) + } + if accountDbApier, err = ConfigureAccountingStorage(lCfg.DataDbType, lCfg.DataDbHost, lCfg.DataDbPort, "9", + lCfg.DataDbUser, lCfg.DataDbPass, lCfg.DBDataEncoding, nil, 1); err != nil { + t.Fatal("Error on ratingDb connection: ", err.Error()) + } + for _, db := range []Storage{ratingDbCsv, ratingDbStor, ratingDbApier, accountDbCsv, accountDbStor, accountDbApier} { + if err = db.Flush(""); err != nil { + t.Fatal("Error when flushing datadb") + } + } + +} + +// Create/reset storage tariff plan tables, used as database connectin establishment also +func TestCreateStorTpTables(t *testing.T) { + + db, err := NewMySQLStorage(lCfg.StorDBHost, lCfg.StorDBPort, lCfg.StorDBName, lCfg.StorDBUser, lCfg.StorDBPass, lCfg.StorDBMaxOpenConns, lCfg.StorDBMaxIdleConns) + if err != nil { + t.Error("Error on opening database connection: ", err) + return + } else { + storDb = db + } + // Creating the table serves also as reset since there is a drop prior to create + if err := db.CreateTablesFromScript(path.Join(*dataDir, "storage", "mysql", utils.CREATE_TARIFFPLAN_TABLES_SQL)); err != nil { + t.Error("Error on db creation: ", err.Error()) + return // No point in going further + } +} + +// Loads data from csv files in tp scenario to ratingDbCsv +func TestLoadFromCSV(t *testing.T) { + + /*var err error + for fn, v := range FileValidators { + if err = ValidateCSVData(path.Join(*dataDir, "tariffplans", *tpCsvScenario, fn), v.Rule); err != nil { + t.Error("Failed validating data: ", err.Error()) + } + }*/ + loader := NewTpReader(ratingDbCsv, accountDbCsv, NewFileCSVStorage(utils.CSV_SEP, + path.Join(*dataDir, "tariffplans", *tpCsvScenario, utils.DESTINATIONS_CSV), + path.Join(*dataDir, "tariffplans", *tpCsvScenario, utils.TIMINGS_CSV), + path.Join(*dataDir, "tariffplans", *tpCsvScenario, utils.RATES_CSV), + path.Join(*dataDir, "tariffplans", *tpCsvScenario, utils.DESTINATION_RATES_CSV), + path.Join(*dataDir, "tariffplans", *tpCsvScenario, utils.RATING_PLANS_CSV), + path.Join(*dataDir, "tariffplans", *tpCsvScenario, utils.RATING_PROFILES_CSV), + path.Join(*dataDir, "tariffplans", *tpCsvScenario, utils.SHARED_GROUPS_CSV), + path.Join(*dataDir, "tariffplans", *tpCsvScenario, utils.LCRS_CSV), + path.Join(*dataDir, "tariffplans", *tpCsvScenario, utils.ACTIONS_CSV), + path.Join(*dataDir, "tariffplans", *tpCsvScenario, utils.ACTION_PLANS_CSV), + path.Join(*dataDir, "tariffplans", *tpCsvScenario, utils.ACTION_TRIGGERS_CSV), + path.Join(*dataDir, "tariffplans", *tpCsvScenario, utils.ACCOUNT_ACTIONS_CSV), + path.Join(*dataDir, "tariffplans", *tpCsvScenario, utils.DERIVED_CHARGERS_CSV), + path.Join(*dataDir, "tariffplans", *tpCsvScenario, utils.CDR_STATS_CSV), + path.Join(*dataDir, "tariffplans", *tpCsvScenario, utils.USERS_CSV), + path.Join(*dataDir, "tariffplans", *tpCsvScenario, utils.ALIASES_CSV), + path.Join(*dataDir, "tariffplans", *tpCsvScenario, utils.ResourceLimitsCsv), + ), "", "") + + if err = loader.LoadDestinations(); err != nil { + t.Error("Failed loading destinations: ", err.Error()) + } + if err = loader.LoadTimings(); err != nil { + t.Error("Failed loading timings: ", err.Error()) + } + if err = loader.LoadRates(); err != nil { + t.Error("Failed loading rates: ", err.Error()) + } + if err = loader.LoadDestinationRates(); err != nil { + t.Error("Failed loading destination rates: ", err.Error()) + } + if err = loader.LoadRatingPlans(); err != nil { + t.Error("Failed loading rating plans: ", err.Error()) + } + if err = loader.LoadRatingProfiles(); err != nil { + t.Error("Failed loading rating profiles: ", err.Error()) + } + if err = loader.LoadActions(); err != nil { + t.Error("Failed loading actions: ", err.Error()) + } + if err = loader.LoadActionPlans(); err != nil { + t.Error("Failed loading action timings: ", err.Error()) + } + if err = loader.LoadActionTriggers(); err != nil { + t.Error("Failed loading action triggers: ", err.Error()) + } + if err = loader.LoadAccountActions(); err != nil { + t.Error("Failed loading account actions: ", err.Error()) + } + if err = loader.LoadDerivedChargers(); err != nil { + t.Error("Failed loading derived chargers: ", err.Error()) + } + if err = loader.LoadLCRs(); err != nil { + t.Error("Failed loading lcr rules: ", err.Error()) + } + if err = loader.LoadUsers(); err != nil { + t.Error("Failed loading users: ", err.Error()) + } + if err = loader.LoadAliases(); err != nil { + t.Error("Failed loading aliases: ", err.Error()) + } + if err = loader.LoadResourceLimits(); err != nil { + t.Error("Failed loading resource limits: ", err.Error()) + } + if err := loader.WriteToDatabase(true, false, false); err != nil { + t.Error("Could not write data into ratingDb: ", err.Error()) + } +} + +// Imports data from csv files in tpScenario to storDb +func TestImportToStorDb(t *testing.T) { + + csvImporter := TPCSVImporter{ + TPid: utils.TEST_SQL, + StorDb: storDb, + DirPath: path.Join(*dataDir, "tariffplans", *tpCsvScenario), + Sep: utils.CSV_SEP, + Verbose: false, + ImportId: utils.TEST_SQL} + if err := csvImporter.Run(); err != nil { + t.Error("Error when importing tpdata to storDb: ", err) + } + if tpids, err := storDb.GetTpIds(); err != nil { + t.Error("Error when querying storDb for imported data: ", err) + } else if len(tpids) != 1 || tpids[0] != utils.TEST_SQL { + t.Errorf("Data in storDb is different than expected %v", tpids) + } +} + +// Loads data from storDb into ratingDb +func TestLoadFromStorDb(t *testing.T) { + + loader := NewTpReader(ratingDbStor, accountDbStor, storDb, utils.TEST_SQL, "") + if err := loader.LoadDestinations(); err != nil { + t.Error("Failed loading destinations: ", err.Error()) + } + if err := loader.LoadTimings(); err != nil { + t.Error("Failed loading timings: ", err.Error()) + } + if err := loader.LoadRates(); err != nil { + t.Error("Failed loading rates: ", err.Error()) + } + if err := loader.LoadDestinationRates(); err != nil { + t.Error("Failed loading destination rates: ", err.Error()) + } + if err := loader.LoadRatingPlans(); err != nil { + t.Error("Failed loading rating plans: ", err.Error()) + } + if err := loader.LoadRatingProfiles(); err != nil { + t.Error("Failed loading rating profiles: ", err.Error()) + } + if err := loader.LoadActions(); err != nil { + t.Error("Failed loading actions: ", err.Error()) + } + if err := loader.LoadActionPlans(); err != nil { + t.Error("Failed loading action timings: ", err.Error()) + } + if err := loader.LoadActionTriggers(); err != nil { + t.Error("Failed loading action triggers: ", err.Error()) + } + if err := loader.LoadAccountActions(); err != nil { + t.Error("Failed loading account actions: ", err.Error()) + } + if err := loader.LoadDerivedChargers(); err != nil { + t.Error("Failed loading derived chargers: ", err.Error()) + } + if err := loader.LoadLCRs(); err != nil { + t.Error("Failed loading lcr rules: ", err.Error()) + } + if err := loader.LoadUsers(); err != nil { + t.Error("Failed loading users: ", err.Error()) + } + if err := loader.LoadAliases(); err != nil { + t.Error("Failed loading aliases: ", err.Error()) + } +} + +func TestLoadIndividualProfiles(t *testing.T) { + + loader := NewTpReader(ratingDbApier, accountDbApier, storDb, utils.TEST_SQL, "") + // Load ratingPlans. This will also set destination keys + if ratingPlans, err := storDb.GetTpRatingPlans(utils.TEST_SQL, "", nil); err != nil { + t.Fatal("Could not retrieve rating plans") + } else { + rpls, err := TpRatingPlans(ratingPlans).GetRatingPlans() + if err != nil { + t.Fatal("Could not convert rating plans") + } + for tag := range rpls { + if loaded, err := loader.LoadRatingPlansFiltered(tag); err != nil { + t.Fatalf("Could not load ratingPlan for tag: %s, error: %s", tag, err.Error()) + } else if !loaded { + t.Fatal("Cound not find ratingPLan with id:", tag) + } + } + } + // Load rating profiles + loadId := utils.CSV_LOAD + "_" + utils.TEST_SQL + if ratingProfiles, err := storDb.GetTpRatingProfiles(&TpRatingProfile{Tpid: utils.TEST_SQL, Loadid: loadId}); err != nil { + t.Fatal("Could not retrieve rating profiles, error: ", err.Error()) + } else if len(ratingProfiles) == 0 { + t.Fatal("Could not retrieve rating profiles") + } else { + rpfs, err := TpRatingProfiles(ratingProfiles).GetRatingProfiles() + if err != nil { + t.Fatal("Could not convert rating profiles") + } + for rpId := range rpfs { + rp, _ := utils.NewTPRatingProfileFromKeyId(utils.TEST_SQL, loadId, rpId) + mrp := APItoModelRatingProfile(rp) + if err := loader.LoadRatingProfilesFiltered(&mrp[0]); err != nil { + t.Fatalf("Could not load ratingProfile with id: %s, error: %s", rpId, err.Error()) + } + } + } + // Load derived chargers + loadId = utils.CSV_LOAD + "_" + utils.TEST_SQL + if derivedChargers, err := storDb.GetTpDerivedChargers(&TpDerivedCharger{Tpid: utils.TEST_SQL, Loadid: loadId}); err != nil { + t.Fatal("Could not retrieve derived chargers, error: ", err.Error()) + } else if len(derivedChargers) == 0 { + t.Fatal("Could not retrieve derived chargers") + } else { + dcs, err := TpDerivedChargers(derivedChargers).GetDerivedChargers() + if err != nil { + t.Fatal("Could not convert derived chargers") + } + for dcId := range dcs { + mdc := &TpDerivedCharger{Tpid: utils.TEST_SQL, Loadid: loadId} + mdc.SetDerivedChargersId(dcId) + if err := loader.LoadDerivedChargersFiltered(mdc, true); err != nil { + t.Fatalf("Could not load derived charger with id: %s, error: %s", dcId, err.Error()) + } + } + } + // Load cdr stats + //loadId = utils.CSV_LOAD + "_" + utils.TEST_SQL + if cdrStats, err := storDb.GetTpCdrStats(utils.TEST_SQL, ""); err != nil { + t.Fatal("Could not retrieve cdr stats, error: ", err.Error()) + } else if len(cdrStats) == 0 { + t.Fatal("Could not retrieve cdr stats") + } else { + cds, err := TpCdrStats(cdrStats).GetCdrStats() + if err != nil { + t.Fatal("Could not convert cdr stats") + } + for id := range cds { + if err := loader.LoadCdrStatsFiltered(id, true); err != nil { + t.Fatalf("Could not load cdr stats with id: %s, error: %s", id, err.Error()) + } + } + } + // Load users + if users, err := storDb.GetTpUsers(&TpUser{Tpid: utils.TEST_SQL}); err != nil { + t.Fatal("Could not retrieve users, error: ", err.Error()) + } else if len(users) == 0 { + t.Fatal("Could not retrieve users") + } else { + for _, usr := range users { + if found, err := loader.LoadUsersFiltered(&usr); found && err != nil { + t.Fatalf("Could not user with id: %s, error: %s", usr.GetId(), err.Error()) + } + } + } + // Load aliases + if aliases, err := storDb.GetTpAliases(&TpAlias{Tpid: utils.TEST_SQL}); err != nil { + t.Fatal("Could not retrieve aliases, error: ", err.Error()) + } else if len(aliases) == 0 { + t.Fatal("Could not retrieve aliases") + } else { + for _, al := range aliases { + if found, err := loader.LoadAliasesFiltered(&al); found && err != nil { + t.Fatalf("Could not load aliase with id: %s, error: %s", al.GetId(), err.Error()) + } + } + } + // Load account actions + if accountActions, err := storDb.GetTpAccountActions(&TpAccountAction{Tpid: utils.TEST_SQL, Loadid: loadId}); err != nil { + t.Fatal("Could not retrieve account action profiles, error: ", err.Error()) + } else if len(accountActions) == 0 { + t.Error("No account actions") + } else { + aas, err := TpAccountActions(accountActions).GetAccountActions() + if err != nil { + t.Fatal("Could not convert account actions") + } + for aaId := range aas { + aa, _ := utils.NewTPAccountActionsFromKeyId(utils.TEST_SQL, loadId, aaId) + maa := APItoModelAccountAction(aa) + + if err := loader.LoadAccountActionsFiltered(maa); err != nil { + t.Fatalf("Could not load account actions with id: %s, error: %s", aaId, err.Error()) + } + } + } +} + +/* +// Compares previously loaded data from csv and stor to be identical, redis specific tests +func TestMatchLoadCsvWithStorRating(t *testing.T) { + + rsCsv, redisDb := ratingDbCsv.(*RedisStorage) + if !redisDb { + return // We only support these tests for redis + } + rsStor := ratingDbStor.(*RedisStorage) + rsApier := ratingDbApier.(*RedisStorage) + keysCsv, err := rsCsv.db.Cmd("KEYS", "*").List() + if err != nil { + t.Fatal("Failed querying redis keys for csv data") + } + for _, key := range keysCsv { + var refVal []byte + for idx, rs := range []*RedisStorage{rsCsv, rsStor, rsApier} { + if key == utils.TASKS_KEY || strings.HasPrefix(key, utils.ACTION_PLAN_PREFIX) { // action plans are not consistent + continue + } + qVal, err := rs.db.Cmd("GET", key).Bytes() + if err != nil { + t.Fatalf("Run: %d, could not retrieve key %s, error: %s", idx, key, err.Error()) + } + if idx == 0 { // Only compare at second iteration, first one is to set reference value + refVal = qVal + continue + } + if len(refVal) != len(qVal) { + t.Errorf("Missmatched data for key: %s\n\t reference val: %s \n\t retrieved val: %s\n on iteration: %d", key, refVal, qVal, idx) + } + } + } +} + +func TestMatchLoadCsvWithStorAccounting(t *testing.T) { + + rsCsv, redisDb := accountDbCsv.(*RedisStorage) + if !redisDb { + return // We only support these tests for redis + } + rsStor := accountDbStor.(*RedisStorage) + rsApier := accountDbApier.(*RedisStorage) + keysCsv, err := rsCsv.db.Cmd("KEYS", "*").List() + if err != nil { + t.Fatal("Failed querying redis keys for csv data") + } + for _, key := range keysCsv { + var refVal []byte + if key == "load_history" { + continue + } + for idx, rs := range []*RedisStorage{rsCsv, rsStor, rsApier} { + qVal, err := rs.db.Cmd("GET", key).Bytes() + if err != nil { + t.Fatalf("Run: %d, could not retrieve key %s, error: %s", idx, key, err.Error()) + } + if idx == 0 { // Only compare at second iteration, first one is to set reference value + refVal = qVal + continue + } + if len(refVal) != len(qVal) { + t.Errorf("Missmatched data for key: %s\n\t, reference val: %s \n\t retrieved value: %s\n on iteration: %d", key, refVal, qVal, idx) + } + } + } +} +*/ diff --git a/utils/httpclient_it_test.go b/utils/httpclient_it_test.go new file mode 100644 index 000000000..c28252e55 --- /dev/null +++ b/utils/httpclient_it_test.go @@ -0,0 +1,73 @@ +// +build integration + +/* +Real-time Online/Offline Charging System (OCS) for Telecom & ISP environments +Copyright (C) ITsysCOM GmbH + +This program is free software: you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU General Public License for more details. + +You should have received a copy of the GNU General Public License +along with this program. If not, see +*/ +package utils + +import ( + "encoding/json" + "flag" + "io/ioutil" + "os" + "reflect" + "testing" + "time" +) +var testIT = flag.Bool("integration", false, "Perform the tests only on local test environment, not by default.") + +type TestContent struct { + Var1 string + Var2 string +} + +func TestHttpJsonPoster(t *testing.T) { + + content := &TestContent{Var1: "Val1", Var2: "Val2"} + jsn, _ := json.Marshal(content) + filePath := "/tmp/cgr_test_http_poster.json" + if _, err := NewHTTPPoster(true, time.Duration(2*time.Second)).Post("http://localhost:8080/invalid", CONTENT_JSON, jsn, 3, filePath); err != nil { + t.Error(err) + } + if readBytes, err := ioutil.ReadFile(filePath); err != nil { + t.Error(err) + } else if !reflect.DeepEqual(jsn, readBytes) { + t.Errorf("Expecting: %q, received: %q", string(jsn), string(readBytes)) + } + if err := os.Remove(filePath); err != nil { + t.Error("Failed removing file: ", filePath) + } +} + +func TestHttpBytesPoster(t *testing.T) { + + content := []byte(`Test + Test2 + `) + filePath := "/tmp/test_http_poster.http" + if _, err := NewHTTPPoster(true, time.Duration(2*time.Second)).Post("http://localhost:8080/invalid", CONTENT_TEXT, content, 3, filePath); err != nil { + t.Error(err) + } + if readBytes, err := ioutil.ReadFile(filePath); err != nil { + t.Error(err) + } else if !reflect.DeepEqual(content, readBytes) { + t.Errorf("Expecting: %q, received: %q", string(content), string(readBytes)) + } + if err := os.Remove(filePath); err != nil { + t.Error("Failed removing file: ", filePath) + } +}