Refactor and add more tests
diff --git a/api.go b/api.go
index 50d340f..f72ec1b 100644
--- a/api.go
+++ b/api.go
@@ -3,15 +3,18 @@
import (
"encoding/json"
"github.com/30x/apid-core"
+ "github.com/30x/apidQuota/constants"
+ "github.com/30x/apidQuota/globalVariables"
"github.com/30x/apidQuota/quotaBucket"
+ "github.com/30x/apidQuota/util"
"io/ioutil"
"net/http"
"strconv"
)
func InitAPI(services apid.Services) {
- Log.Debug("initialized API's exposed by apidQuota plugin")
- quotaBasePath := Config.GetString(ConfigQuotaBasePath)
+ globalVariables.Log.Debug("initialized API's exposed by apidQuota plugin")
+ quotaBasePath := globalVariables.Config.GetString(constants.ConfigQuotaBasePath)
services.API().HandleFunc(quotaBasePath, getAllQuotaValues).Methods("GET") //yet to implement.
services.API().HandleFunc(quotaBasePath+"/{quotaItentifier}", incrementAndCheckQuotaLimit).Methods("POST")
@@ -30,27 +33,27 @@
bodyBytes, err := ioutil.ReadAll(req.Body)
defer req.Body.Close()
if err != nil {
- WriteErrorResponse(http.StatusBadRequest, UnableToParseBody, "unable to read request body: "+err.Error(), res, req)
+ util.WriteErrorResponse(http.StatusBadRequest, constants.UnableToParseBody, "unable to read request body: "+err.Error(), res, req)
return
}
quotaBucketMap := make(map[string]interface{}, 0)
if err := json.Unmarshal(bodyBytes, "aBucketMap); err != nil {
- WriteErrorResponse(http.StatusBadRequest, UnMarshalJSONError, "unable to convert request body to an object: "+err.Error(), res, req)
+ util.WriteErrorResponse(http.StatusBadRequest, constants.UnMarshalJSONError, "unable to convert request body to an object: "+err.Error(), res, req)
return
}
- Log.Println("quotaBucketMap from request: ", quotaBucketMap)
+ globalVariables.Log.Println("quotaBucketMap from request: ", quotaBucketMap)
// parse the request body into the Event struct
qBucket := new(quotaBucket.QuotaBucket)
if err = qBucket.FromAPIRequest(quotaBucketMap); err != nil {
- WriteErrorResponse(http.StatusBadRequest, ErrorConvertReqBodyToEntity, err.Error(), res, req)
+ util.WriteErrorResponse(http.StatusBadRequest, constants.ErrorConvertReqBodyToEntity, err.Error(), res, req)
return
}
quotaCount, err := qBucket.GetQuotaCount()
if err != nil {
- WriteErrorResponse(http.StatusBadRequest, UnMarshalJSONError, "error retrieving count for the give identifier "+err.Error(), res, req)
+ util.WriteErrorResponse(http.StatusBadRequest, constants.UnMarshalJSONError, "error retrieving count for the give identifier "+err.Error(), res, req)
return
}
diff --git a/api_test.go b/api_test.go
index 8a83c8f..9d6452c 100644
--- a/api_test.go
+++ b/api_test.go
@@ -2,8 +2,16 @@
import (
. "github.com/onsi/ginkgo"
+ //"net/http"
)
-var _ = Describe("Api", func() {
+func init() {
+ //testAPIDQuotaURL = ""
+}
+var _ = Describe("Api", func() {
+ It("test Synchronous quota", func() {
+
+ //req, err := http.NewRequest("POST", )
+ })
})
diff --git a/constants.go b/constants.go
deleted file mode 100644
index 588b808..0000000
--- a/constants.go
+++ /dev/null
@@ -1,9 +0,0 @@
-package apidQuota
-
-const (
- UnableToParseBody = "unable_to_parse_body"
- UnMarshalJSONError = "unmarshal_json_error"
- ErrorConvertReqBodyToEntity = "error_convert_reqBody_to_entity"
- ConfigQuotaBasePath = "quota_base_path"
- quotaBasePathDefault = "/quota"
-)
diff --git a/constants/constants.go b/constants/constants.go
new file mode 100644
index 0000000..9ced04b
--- /dev/null
+++ b/constants/constants.go
@@ -0,0 +1,14 @@
+package constants
+
+const (
+ UnableToParseBody = "unable_to_parse_body"
+ UnMarshalJSONError = "unmarshal_json_error"
+ ErrorConvertReqBodyToEntity = "error_convert_reqBody_to_entity"
+ ConfigQuotaBasePath = "quota_base_path"
+ QuotaBasePathDefault = "/quota"
+
+ ConfigCounterServiceBasePath = "counterService_base_path"
+ URLCounterServiceNotSet = "url_counter_service_not_set"
+ URLCounterServiceInvalid = "url_counter_service_invalid"
+ MarshalJSONError = "marshal_JSON_error"
+)
diff --git a/globalVariables/globalVariables.go b/globalVariables/globalVariables.go
new file mode 100644
index 0000000..50a4df0
--- /dev/null
+++ b/globalVariables/globalVariables.go
@@ -0,0 +1,9 @@
+package globalVariables
+
+import "github.com/30x/apid-core"
+
+var (
+ Log apid.LogService
+ Config apid.ConfigService
+ CounterServiceURL string
+)
diff --git a/init.go b/init.go
index 93e1c1b..66e0a40 100644
--- a/init.go
+++ b/init.go
@@ -2,20 +2,31 @@
import (
"github.com/30x/apid-core"
-)
-
-var (
- Log apid.LogService
- Config apid.ConfigService
+ "github.com/30x/apidQuota/constants"
+ "github.com/30x/apidQuota/globalVariables"
)
func init() {
apid.RegisterPlugin(initPlugin)
+ initCounterService()
+}
+
+// set config for counter service.
+func initCounterService() {
+ //counterBasePath := globalVariables.Config.Get(constants.ConfigCounterServiceBasePath)
+ //fmt.Println("counterBasePath: ", counterBasePath , "//")
+ /*if counterBasePath != nil {
+ if reflect.TypeOf(counterBasePath).Kind() != reflect.String{
+ globalVariables.Log.Fatal("value of: " + constants.ConfigCounterServiceBasePath + " in the config should be string")
+ }
+ globalVariables.CounterServiceURL = counterBasePath.(string)
+ }*/
+ globalVariables.CounterServiceURL = "http://54.86.114.219:8989/increment"
}
func initPlugin(services apid.Services) (apid.PluginData, error) {
- Log = services.Log().ForModule("apidQuota")
- Log.Debug("start init")
+ globalVariables.Log = services.Log().ForModule("apidQuota")
+ globalVariables.Log.Debug("start init")
setConfig(services)
InitAPI(services)
@@ -25,8 +36,8 @@
func setConfig(services apid.Services) {
// set configuration
- Config = services.Config()
+ globalVariables.Config = services.Config()
// set plugin config defaults
- Config.SetDefault(ConfigQuotaBasePath, quotaBasePathDefault)
+ globalVariables.Config.SetDefault(constants.ConfigQuotaBasePath, constants.QuotaBasePathDefault)
}
diff --git a/quotaBucket/apiUtil.go b/quotaBucket/apiUtil.go
index 155a24d..c29e427 100644
--- a/quotaBucket/apiUtil.go
+++ b/quotaBucket/apiUtil.go
@@ -90,56 +90,6 @@
startTime = int64(startTimeFloat)
//fmt.Println("startTime: ", startTime)
- quotaPeriod := QuotaPeriod{}
- value, ok = quotaBucketMap["period"]
- //if period is not sent in the request, it is calculated based in the startTime, quotaType and interval.
- if ok {
- var inStartInt, startInt, endInt int64
-
- isPeriodMap := reflect.TypeOf(value)
- if isPeriodMap.Kind() != reflect.Map {
- return errors.New(`invalid type : 'period' should be a Map`)
- }
- periodMap := value.(map[string]interface{})
-
- inStartTimeValue, ok := periodMap["inputStartTime"]
- if !ok {
- //set period.inputStart time from qBucket.startTime
- inStartInt = startTime
- } else {
- if inStartType := reflect.TypeOf(inStartTimeValue); inStartType.Kind() != reflect.Float64 {
- return errors.New(`invalid type : 'inputStartTime' in 'period' should be UNIX timestamp`)
- }
- inStartFloat := inStartTimeValue.(float64)
- inStartInt = int64(inStartFloat)
- if startTime != inStartInt {
- return errors.New(`invalid value : 'inputStartTime' in 'period' should be same as 'startTime'' in request`)
- }
- }
-
- startTimeValue, ok := periodMap["startTime"]
- if !ok {
- return errors.New(`missing field : 'startTime' in 'period' cannot be empty`)
- }
- if periodStartType := reflect.TypeOf(startTimeValue); periodStartType.Kind() != reflect.Float64 {
- return errors.New(`invalid type : 'startTime' in 'period' should be UNIX timestamp`)
- }
- periodStartFloat := startTimeValue.(float64)
- startInt = int64(periodStartFloat)
-
- periodEndValue, ok := periodMap["endTime"]
- if !ok {
- return errors.New(`missing field : 'endTime' in 'period' cannot be empty`)
- }
- if periodEndType := reflect.TypeOf(periodEndValue); periodEndType.Kind() != reflect.Float64 {
- return errors.New(`invalid type : 'endTime' in 'period' should be UNIX timestamp`)
- }
- periodEndFloat := periodEndValue.(float64)
- endInt = int64(periodEndFloat)
-
- quotaPeriod = NewQuotaPeriod(inStartInt, startInt, endInt)
- }
-
value, ok = quotaBucketMap["maxCount"]
if !ok {
return errors.New(`missing field: 'maxCount' is required`)
@@ -162,7 +112,12 @@
bucketType = value.(string)
//fmt.Println("bucketType: ", bucketType)
- newQBucket := NewQuotaBucket(edgeOrgID, id, interval, timeUnit, quotaType, preciseAtSecondsLevel, quotaPeriod, startTime, maxCount, bucketType)
+ newQBucket, err := NewQuotaBucket(edgeOrgID, id, interval, timeUnit, quotaType, preciseAtSecondsLevel, startTime, maxCount, bucketType)
+ if err != nil {
+ return errors.New("error creating newquotaBucket: " + err.Error())
+
+ }
+
qBucket.quotaBucketData = newQBucket.quotaBucketData
if err := qBucket.Validate(); err != nil {
diff --git a/quotaBucket/quotaBucket.go b/quotaBucket/quotaBucket.go
index 99bc6ba..119482b 100644
--- a/quotaBucket/quotaBucket.go
+++ b/quotaBucket/quotaBucket.go
@@ -3,6 +3,8 @@
import (
"errors"
"fmt"
+ "github.com/30x/apidQuota/services"
+ "strings"
"time"
)
@@ -22,9 +24,10 @@
//todo: Add other accepted bucketTypes
//errors
- InvalidQuotaTimeUnitType = "invalidQuotaTimeUnitType"
- InvalidQuotaBucketType = "invalidQuotaBucketType"
- InvalidQuotaPeriod = "invalidQuotaPeriod"
+ InvalidQuotaTimeUnitType = "invalidQuotaTimeUnitType"
+ InvalidQuotaDescriptorType = "invalidQuotaTimeUnitType"
+ InvalidQuotaBucketType = "invalidQuotaBucketType"
+ InvalidQuotaPeriod = "invalidQuotaPeriod"
)
var (
@@ -85,7 +88,7 @@
ID string
Interval int
TimeUnit string //TimeUnit {SECOND, MINUTE, HOUR, DAY, WEEK, MONTH}
- QuotaType string //Type {CALENDAR, FLEXI, ROLLING_WINDOW}
+ QuotaDescriptorType string //Type {CALENDAR, FLEXI, ROLLING_WINDOW}
PreciseAtSecondsLevel bool
Period QuotaPeriod
StartTime time.Time
@@ -98,18 +101,18 @@
}
func NewQuotaBucket(edgeOrgID string, id string, interval int,
- timeUnit string, quotaType string, preciseAtSecondsLevel bool, period QuotaPeriod,
- startTime int64, maxCount int, bucketType string) *QuotaBucket {
+ timeUnit string, quotaType string, preciseAtSecondsLevel bool,
+ startTime int64, maxCount int, bucketType string) (*QuotaBucket, error) {
fromUNIXTime := time.Unix(startTime, 0)
+
quotaBucketDataStruct := "aBucketData{
EdgeOrgID: edgeOrgID,
ID: id,
Interval: interval,
TimeUnit: timeUnit,
- QuotaType: quotaType,
+ QuotaDescriptorType: quotaType,
PreciseAtSecondsLevel: preciseAtSecondsLevel,
- Period: period,
StartTime: fromUNIXTime,
MaxCount: maxCount,
BucketType: bucketType,
@@ -119,13 +122,28 @@
quotaBucketData: *quotaBucketDataStruct,
}
- return quotaBucket
+ err := quotaBucket.setCurrentPeriod()
+ if err != nil {
+ return nil, err
+ }
+ return quotaBucket, nil
}
func (q *QuotaBucket) Validate() error {
+
+ //check valid quotaTimeUnit
+ if ok := IsValidTimeUnit(strings.ToLower(q.GetTimeUnit())); !ok {
+ return errors.New(InvalidQuotaTimeUnitType)
+ }
+
+ //check valid quotaBucketType
+ if ok := IsValidQuotaBucketType(strings.ToLower(q.GetBucketType())); !ok {
+ return errors.New(InvalidQuotaBucketType)
+ }
+
//check if the period is valid
- period,err := q.GetQuotaBucketPeriod()
+ period, err := q.GetQuotaBucketPeriod()
if err != nil {
return err
}
@@ -133,16 +151,6 @@
return errors.New("invalid Period: " + err.Error())
}
- //check valid quotaTimeUnit
- if ok := IsValidTimeUnit(q.GetTimeUnit()); !ok {
- return errors.New(InvalidQuotaTimeUnitType)
- }
-
- //check valid quotaBucketType
- if ok := IsValidQuotaBucketType(q.GetBucketType()); !ok {
- return errors.New(InvalidQuotaBucketType)
- }
-
return nil
}
@@ -167,16 +175,16 @@
}
func (q *QuotaBucket) GetQuotaType() string {
- return q.quotaBucketData.QuotaType
+ return q.quotaBucketData.QuotaDescriptorType
}
func (q *QuotaBucket) GetPreciseAtSecondsLevel() bool {
return q.quotaBucketData.PreciseAtSecondsLevel
}
-//Calls setCurrentPeriod if QuotaType is rollingWindow or period.endTime is before now.
+//Calls setCurrentPeriod if QuotaDescriptorType is rollingWindow or period.endTime is before now.
func (q *QuotaBucket) GetPeriod() (*QuotaPeriod, error) {
- if q.quotaBucketData.QuotaType == QuotaTypeRollingWindow {
+ if q.quotaBucketData.QuotaDescriptorType == QuotaTypeRollingWindow {
qRWType := RollingWindowQuotaDescriptorType{}
err := qRWType.SetCurrentPeriod(q)
if err != nil {
@@ -184,12 +192,12 @@
}
}
- period,err := q.GetQuotaBucketPeriod()
+ period, err := q.GetQuotaBucketPeriod()
if err != nil {
- return nil,err
+ return nil, err
}
//setCurrentPeriod if endTime > time.now()
- if period.endTime.Before(time.Now()) || period.endTime.Equal(time.Now()){
+ if period.endTime.Before(time.Now().UTC()) || period.endTime.Equal(time.Now().UTC()) {
if err := q.setCurrentPeriod(); err != nil {
return nil, err
}
@@ -199,19 +207,17 @@
}
//setCurrentPeriod only for rolling window else just return the value of QuotaPeriod
-func (q *QuotaBucket) GetQuotaBucketPeriod() (*QuotaPeriod,error) {
- if q.quotaBucketData.QuotaType == QuotaTypeRollingWindow {
+func (q *QuotaBucket) GetQuotaBucketPeriod() (*QuotaPeriod, error) {
+ if q.quotaBucketData.QuotaDescriptorType == QuotaTypeRollingWindow {
qRWType := RollingWindowQuotaDescriptorType{}
err := qRWType.SetCurrentPeriod(q)
if err != nil {
return nil, err
}
}
- return &q.quotaBucketData.Period,nil
+ return &q.quotaBucketData.Period, nil
}
-
-
func (q *QuotaBucket) GetMaxCount() int {
return q.quotaBucketData.MaxCount
}
@@ -230,7 +236,7 @@
func (q *QuotaBucket) setCurrentPeriod() error {
- qDescriptorType, err := GetQuotaTypeHandler(q.GetQuotaType())
+ qDescriptorType, err := GetQuotaDescriptorTypeHandler(q.GetQuotaType())
if err != nil {
return err
}
@@ -241,15 +247,15 @@
func (period *QuotaPeriod) IsCurrentPeriod(qBucket *QuotaBucket) bool {
if qBucket != nil && qBucket.GetBucketType() != "" {
if qBucket.GetQuotaType() == QuotaTypeRollingWindow {
- return (period.inputStartTime.Equal(time.Now()) || period.inputStartTime.Before(time.Now()) )
+ return (period.inputStartTime.Equal(time.Now().UTC()) || period.inputStartTime.Before(time.Now().UTC()))
}
- return (period.inputStartTime.Equal(time.Now()) || period.inputStartTime.Before(time.Now())) &&
+ return (period.inputStartTime.Equal(time.Now().UTC()) || period.inputStartTime.Before(time.Now().UTC())) &&
period.startTime.String() != "" &&
period.endTime.String() != "" &&
period.startTime.Before(period.endTime) &&
- (period.startTime.Equal(time.Now()) || period.startTime.Before(time.Now()))&&
- (period.endTime.Equal(time.Now()) || period.endTime.After(time.Now()))
+ (period.startTime.Equal(time.Now().UTC()) || period.startTime.Before(time.Now().UTC())) &&
+ (period.endTime.Equal(time.Now().UTC()) || period.endTime.After(time.Now().UTC()))
}
return false
}
@@ -265,9 +271,12 @@
}
fmt.Println("period set: ", period)
- //todo API call to counter service using Period start end and keyspace.
+ resp, err := services.IncrementAndGetCount(q.GetEdgeOrgID(), q.GetID(), 0)
+ if err != nil {
+ return 0, err
+ }
- return 10, nil
+ return resp, nil
}
func (q *QuotaBucket) IncrementQuota() (int, error) {
diff --git a/quotaBucket/quotaBucketType_test.go b/quotaBucket/quotaBucketType_test.go
index 70ee53d..d6ac8c0 100644
--- a/quotaBucket/quotaBucketType_test.go
+++ b/quotaBucket/quotaBucketType_test.go
@@ -5,5 +5,7 @@
)
var _ = Describe("QuotaBucketType", func() {
-
+ It("test QuotaBucketType", func() {
+ //fmt.Println("inside QuotaBucketType")
+ })
})
diff --git a/quotaBucket/quotaBucket_suite_test.go b/quotaBucket/quotaBucket_suite_test.go
index b05019b..43fa8cb 100644
--- a/quotaBucket/quotaBucket_suite_test.go
+++ b/quotaBucket/quotaBucket_suite_test.go
@@ -3,7 +3,6 @@
import (
. "github.com/onsi/ginkgo"
. "github.com/onsi/gomega"
- "fmt"
"testing"
)
@@ -12,11 +11,11 @@
RunSpecs(t, "QuotaBucket Suite")
}
-var _ = BeforeSuite(func() {
- fmt.Println("before suite")
-
-})
-
-var _ = AfterSuite(func() {
- fmt.Println("after suite")
-})
+//var _ = BeforeSuite(func() {
+// fmt.Println("before suite")
+//
+//})
+//
+//var _ = AfterSuite(func() {
+// fmt.Println("after suite")
+//})
diff --git a/quotaBucket/quotaBucket_test.go b/quotaBucket/quotaBucket_test.go
index df50e82..4d1e166 100644
--- a/quotaBucket/quotaBucket_test.go
+++ b/quotaBucket/quotaBucket_test.go
@@ -11,49 +11,59 @@
var _ = Describe("Test QuotaPeriod", func() {
It("Valid NewQuotaPeriod", func() {
//startTime before endTime
- period := NewQuotaPeriod(1492324596, 1490047028, 1492725428)
+ period := NewQuotaPeriod(time.Now().UTC().AddDate(0, -1, 0).Unix(),
+ time.Now().UTC().AddDate(0, 0, -1).Unix(),
+ time.Now().UTC().AddDate(0, 1, 0).Unix())
isValid, err := period.Validate()
- if !isValid || err != nil {
- Fail("expected isValid: true and error: nil for NewQuotaPeriod")
+ if !isValid {
+ Fail("expected isValid true but got false")
+ }
+ if err != nil {
+ Fail("expected error <nil> but got " + err.Error())
}
})
It("Invalid NewQuotaPeriod", func() {
//startTime after endTime
- period := NewQuotaPeriod(1492324596, 1492725428, 1490047028)
+ period := NewQuotaPeriod(time.Now().UTC().AddDate(0, -1, 0).Unix(),
+ time.Now().UTC().AddDate(0, 1, 0).Unix(),
+ time.Now().UTC().AddDate(0, 0, -1).Unix())
isValid, err := period.Validate()
- if err == nil || isValid {
- Fail("Expected isValid: false and error: <notNil> for invalid NewQuotaPeriod. startTime should be before endTime")
+ if isValid {
+ Fail("Expected isValid false but got true")
+ }
+
+ if err == nil {
+ Fail(" Expected error but got <nil>")
}
})
-
})
var _ = Describe("Test AcceptedQuotaTimeUnitTypes", func() {
It("testTimeUnit", func() {
if !IsValidTimeUnit("second") {
- Fail("second is a valid TimeUnit")
+ Fail("Expected true: second is a valid TimeUnit")
}
if !IsValidTimeUnit("minute") {
- Fail("minute is a valid TimeUnit")
+ Fail("Expected true: minute is a valid TimeUnit")
}
if !IsValidTimeUnit("hour") {
- Fail("hour is a valid TimeUnit")
+ Fail("Expected true: hour is a valid TimeUnit")
}
if !IsValidTimeUnit("day") {
- Fail("day is a valid TimeUnit")
+ Fail("Expected true: day is a valid TimeUnit")
}
if !IsValidTimeUnit("week") {
- Fail("week is a valid TimeUnit")
+ Fail("Expected true: week is a valid TimeUnit")
}
if !IsValidTimeUnit("month") {
- Fail("month is a valid TimeUnit")
+ Fail("Expected true: month is a valid TimeUnit")
}
//invalid type
if IsValidTimeUnit("invalidType") {
- Fail("invalidType is a invalid TimeUnit")
+ Fail("Expected false: invalidType is not a valid TimeUnit")
}
})
})
@@ -61,18 +71,18 @@
var _ = Describe("Test AcceptedQuotaBucketTypes", func() {
It("testTimeUnit", func() {
if !IsValidQuotaBucketType("synchronous") {
- Fail("synchronous is a valid quotaBucket")
+ Fail("Expected true: synchronous is a valid quotaBucket")
}
if !IsValidQuotaBucketType("asynchronous") {
- Fail("asynchronous is a valid quotaBucket")
+ Fail("Expected true: asynchronous is a valid quotaBucket")
}
if !IsValidQuotaBucketType("nonDistributed") {
- Fail("nonDistributed is a valid quotaBucket")
+ Fail("Expected true: nonDistributed is a valid quotaBucket")
}
//invalid type
if IsValidQuotaBucketType("invalidType") {
- Fail("invalidType is a invalid quotaBucket")
+ Fail("Expected false: invalidType is a invalid quotaBucket")
}
})
})
@@ -87,15 +97,13 @@
interval := 1
maxCount := 10
preciseAtSecondsLevel := true
- period := NewQuotaPeriod(time.Now().AddDate(0,-1,0).Unix(),
- time.Now().AddDate(0,0,-1).Unix(),
- time.Now().AddDate(0,1,0).Unix())
- startTime := int64(1492324596)
+ startTime := time.Now().UTC().AddDate(0, -1, 0).Unix()
- quotaBucket := NewQuotaBucket(edgeOrgID, id, interval, timeUnit, quotaType, preciseAtSecondsLevel, period, startTime, maxCount, bucketType)
- err := quotaBucket.Validate()
+ quotaBucket, err := NewQuotaBucket(edgeOrgID, id, interval, timeUnit, quotaType, preciseAtSecondsLevel, startTime, maxCount, bucketType)
Expect(err).NotTo(HaveOccurred())
+ err = quotaBucket.Validate()
+ Expect(err).NotTo(HaveOccurred())
//also check if all the fields are set as expected
sTime := time.Unix(startTime, 0)
@@ -110,10 +118,13 @@
Expect(preciseAtSecondsLevel).To(Equal(quotaBucket.GetPreciseAtSecondsLevel()))
getPeriod, err := quotaBucket.GetPeriod()
Expect(err).NotTo(HaveOccurred())
- Expect(period).To(Equal(*getPeriod))
+ Expect(getPeriod.GetPeriodInputStartTime().String()).ShouldNot(BeEmpty())
+ Expect(getPeriod.GetPeriodStartTime().String()).ShouldNot(BeEmpty())
+ Expect(getPeriod.GetPeriodEndTime().String()).ShouldNot(BeEmpty())
})
+ //end before start
It("Test invalid quotaPeriod", func() {
edgeOrgID := "sampleOrg"
id := "sampleID"
@@ -123,11 +134,13 @@
interval := 1
maxCount := 10
preciseAtSecondsLevel := true
- period := NewQuotaPeriod(1492324596, 1492725428, 1490047028)
- startTime := int64(1492324596)
+ startTime := time.Now().UTC().AddDate(0, -1, 0).Unix()
- quotaBucket := NewQuotaBucket(edgeOrgID, id, interval, timeUnit, quotaType, preciseAtSecondsLevel, period, startTime, maxCount, bucketType)
- err := quotaBucket.Validate()
+ quotaBucket, err := NewQuotaBucket(edgeOrgID, id, interval, timeUnit, quotaType, preciseAtSecondsLevel, startTime, maxCount, bucketType)
+ Expect(err).NotTo(HaveOccurred())
+
+ quotaBucket.SetPeriod(time.Now().UTC().UTC().AddDate(0, 1, 0), time.Now().AddDate(0, 0, -1))
+ err = quotaBucket.Validate()
if err == nil {
Fail("error expected but got <nil>")
}
@@ -146,18 +159,15 @@
interval := 1
maxCount := 10
preciseAtSecondsLevel := true
- period := NewQuotaPeriod(time.Now().AddDate(0,-1,0).Unix(),
- time.Now().AddDate(0,0,-1).Unix(),
- time.Now().AddDate(0,1,0).Unix())
- startTime := int64(1492324596)
+ startTime := time.Now().UTC().AddDate(0, -1, 0).Unix()
+ quotaBucket, err := NewQuotaBucket(edgeOrgID, id, interval, timeUnit, quotaType, preciseAtSecondsLevel, startTime, maxCount, bucketType)
+ Expect(err).To(HaveOccurred())
- quotaBucket := NewQuotaBucket(edgeOrgID, id, interval, timeUnit, quotaType, preciseAtSecondsLevel, period, startTime, maxCount, bucketType)
- err := quotaBucket.Validate()
- if err == nil {
- Fail("error expected but got <nil>")
+ if !strings.Contains(err.Error(), InvalidQuotaTimeUnitType) {
+ Fail("expected: " + InvalidQuotaTimeUnitType + "but got: " + err.Error())
}
- if err.Error() != InvalidQuotaTimeUnitType {
- Fail("expected: " + InvalidQuotaBucketType + "but got: " + err.Error())
+ if quotaBucket != nil {
+ Fail("quotaBucket returned should be nil.")
}
})
@@ -171,28 +181,23 @@
interval := 1
maxCount := 10
preciseAtSecondsLevel := true
- period := NewQuotaPeriod(time.Now().AddDate(0,-1,0).Unix(),
- time.Now().AddDate(0,0,-1).Unix(),
- time.Now().AddDate(0,1,0).Unix())
- startTime := time.Now().AddDate(0,-1,0).Unix()
+ startTime := time.Now().UTC().AddDate(0, -1, 0).Unix()
- quotaBucket := NewQuotaBucket(edgeOrgID, id, interval, timeUnit, quotaType, preciseAtSecondsLevel, period, startTime, maxCount, bucketType)
- err := quotaBucket.Validate()
+ quotaBucket, err := NewQuotaBucket(edgeOrgID, id, interval, timeUnit, quotaType, preciseAtSecondsLevel, startTime, maxCount, bucketType)
+ Expect(err).NotTo(HaveOccurred())
+
+ err = quotaBucket.Validate()
if err == nil {
Fail("error expected but got <nil>")
}
- if err.Error() != InvalidQuotaBucketType {
- Fail("expected: " + InvalidQuotaBucketType + "but got: " + err.Error())
+ if !strings.Contains(err.Error(), InvalidQuotaBucketType) {
+ Fail("expected: " + InvalidQuotaBucketType + " in the error message but got: " + err.Error())
}
-
})
})
-
-
-
-var _ = Describe("IsCurrentPeriod", func(){
+var _ = Describe("IsCurrentPeriod", func() {
It("Test RollingType Window Valid TestCase", func() {
edgeOrgID := "sampleOrg"
@@ -204,30 +209,34 @@
maxCount := 10
preciseAtSecondsLevel := true
//InputStart time is before now
- period := NewQuotaPeriod(time.Now().AddDate(0, -1,0).Unix(),
- time.Now().AddDate(0,0, -1).Unix(),
- time.Now().AddDate(0,1,0).Unix())
- startTime := time.Now().AddDate(0,-1,0).Unix()
+ startTime := time.Now().UTC().AddDate(0, -1, 0).Unix()
- quotaBucket := NewQuotaBucket(edgeOrgID, id, interval, timeUnit, quotaType, preciseAtSecondsLevel, period, startTime, maxCount, bucketType)
- err := quotaBucket.Validate()
+ quotaBucket, err := NewQuotaBucket(edgeOrgID, id, interval, timeUnit, quotaType, preciseAtSecondsLevel, startTime, maxCount, bucketType)
Expect(err).NotTo(HaveOccurred())
- if ok := period.IsCurrentPeriod(quotaBucket); !ok{
+ err = quotaBucket.Validate()
+ Expect(err).NotTo(HaveOccurred())
+
+ period, err := quotaBucket.GetPeriod()
+ if err != nil {
+ Fail("no error expected")
+ }
+ if ok := period.IsCurrentPeriod(quotaBucket); !ok {
Fail("Exprected true, returned: false")
}
//InputStart time is now
- period = NewQuotaPeriod(time.Now().Unix(),
- time.Now().AddDate(0,0,-1).Unix(),
- time.Now().AddDate(0,1,0).Unix())
- startTime = time.Now().Unix()
- quotaBucket = NewQuotaBucket(edgeOrgID, id, interval, timeUnit, quotaType, preciseAtSecondsLevel, period, startTime, maxCount, bucketType)
+ startTime = time.Now().UTC().Unix()
+ quotaBucket, err = NewQuotaBucket(edgeOrgID, id, interval, timeUnit, quotaType, preciseAtSecondsLevel, startTime, maxCount, bucketType)
+ Expect(err).NotTo(HaveOccurred())
err = quotaBucket.Validate()
Expect(err).NotTo(HaveOccurred())
-
+ period, err = quotaBucket.GetPeriod()
+ if err != nil {
+ Fail("no error expected")
+ }
period.IsCurrentPeriod(quotaBucket)
- if ok := period.IsCurrentPeriod(quotaBucket); !ok{
+ if ok := period.IsCurrentPeriod(quotaBucket); !ok {
Fail("Exprected true, returned: false")
}
})
@@ -243,30 +252,33 @@
maxCount := 10
preciseAtSecondsLevel := true
//InputStart time is after now.
- period := NewQuotaPeriod(time.Now().AddDate(0,1,0).Unix(),
- time.Now().AddDate(0,1,0).Unix(), time.Now().AddDate(0,0,1).Unix())
- startTime := time.Now().AddDate(0,1,0).Unix()
+ startTime := time.Now().UTC().AddDate(0, 1, 0).Unix()
- quotaBucket := NewQuotaBucket(edgeOrgID, id, interval, timeUnit, quotaType, preciseAtSecondsLevel, period, startTime, maxCount, bucketType)
- err := quotaBucket.Validate()
+ quotaBucket, err := NewQuotaBucket(edgeOrgID, id, interval, timeUnit, quotaType, preciseAtSecondsLevel, startTime, maxCount, bucketType)
Expect(err).NotTo(HaveOccurred())
+ err = quotaBucket.Validate()
+ Expect(err).NotTo(HaveOccurred())
- if ok := period.IsCurrentPeriod(quotaBucket); ok{
+ quotaBucket.SetPeriod(time.Now().UTC().AddDate(0, -1, 0), time.Now().UTC().AddDate(0, 0, 1))
+ period, err := quotaBucket.GetPeriod()
+ Expect(err).NotTo(HaveOccurred())
+ if ok := period.IsCurrentPeriod(quotaBucket); ok {
Fail("Exprected true, returned: false")
}
//endTime before startTime in period
- startTime = time.Now().AddDate(0,-1,0).Unix()
- quotaBucket = NewQuotaBucket(edgeOrgID, id, interval, timeUnit, quotaType, preciseAtSecondsLevel, period, startTime, maxCount, bucketType)
- quotaBucket.SetPeriod(time.Now(), time.Now().AddDate(0,1,0))
- if ok := period.IsCurrentPeriod(quotaBucket); ok{
+ startTime = time.Now().UTC().AddDate(0, -1, 0).Unix()
+ quotaBucket, err = NewQuotaBucket(edgeOrgID, id, interval, timeUnit, quotaType, preciseAtSecondsLevel, startTime, maxCount, bucketType)
+ Expect(err).NotTo(HaveOccurred())
+
+ quotaBucket.SetPeriod(time.Now().UTC(), time.Now().UTC().AddDate(0, -1, 0))
+ if ok := period.IsCurrentPeriod(quotaBucket); ok {
Fail("Exprected false, returned: true")
}
})
-
- It("Test NonRollingType Window Valid TestCases", func() {
+ It("Test calendarType Window Valid TestCases", func() {
edgeOrgID := "sampleOrg"
id := "sampleID"
@@ -277,61 +289,74 @@
maxCount := 10
preciseAtSecondsLevel := true
-
//InputStart time is before now
- period := NewQuotaPeriod(time.Now().AddDate(0, -1,0).Unix(),
- time.Now().AddDate(0,0, -1).Unix(),
- time.Now().AddDate(0,1,0).Unix())
- startTime := time.Now().AddDate(0,-1,0).Unix()
+ startTime := time.Now().UTC().UTC().AddDate(-1, -1, 0).Unix()
- quotaBucket := NewQuotaBucket(edgeOrgID, id, interval, timeUnit, quotaType, preciseAtSecondsLevel, period, startTime, maxCount, bucketType)
- err := quotaBucket.Validate()
+ quotaBucket, err := NewQuotaBucket(edgeOrgID, id, interval, timeUnit, quotaType, preciseAtSecondsLevel, startTime, maxCount, bucketType)
Expect(err).NotTo(HaveOccurred())
- if ok := period.IsCurrentPeriod(quotaBucket); !ok{
- Fail("Exprected true, returned: false")
- }
-
-
- //InputStart time is now
- period = NewQuotaPeriod(time.Now().Unix(),
- time.Now().AddDate(0,0,-1).Unix(),
- time.Now().AddDate(0,1,0).Unix())
- startTime = time.Now().Unix()
- quotaBucket = NewQuotaBucket(edgeOrgID, id, interval, timeUnit, quotaType, preciseAtSecondsLevel, period, startTime, maxCount, bucketType)
err = quotaBucket.Validate()
Expect(err).NotTo(HaveOccurred())
+ period, err := quotaBucket.GetPeriod()
+ if err != nil {
+ Fail("no error expected but returned " + err.Error())
+ }
+ if ok := period.IsCurrentPeriod(quotaBucket); !ok {
+ Fail("Exprected true, returned: false")
+ }
+
+ //InputStart time is now
+ startTime = time.Now().UTC().Unix()
+ quotaBucket, err = NewQuotaBucket(edgeOrgID, id, interval, timeUnit, quotaType, preciseAtSecondsLevel, startTime, maxCount, bucketType)
+ Expect(err).NotTo(HaveOccurred())
+
+ err = quotaBucket.Validate()
+ Expect(err).NotTo(HaveOccurred())
+
+ period, err = quotaBucket.GetPeriod()
+ if err != nil {
+ Fail("no error expected but returned " + err.Error())
+ }
period.IsCurrentPeriod(quotaBucket)
- if ok := period.IsCurrentPeriod(quotaBucket); !ok{
+ if ok := period.IsCurrentPeriod(quotaBucket); !ok {
Fail("Exprected true, returned: false")
}
//start Time in period is before now
- startTime = time.Now().Unix()
- period = NewQuotaPeriod(time.Now().AddDate(0,-1,0).Unix(),
- time.Now().AddDate(0,0,-1).Unix(),
- time.Now().AddDate(0,1,0).Unix())
- quotaBucket = NewQuotaBucket(edgeOrgID, id, interval, timeUnit, quotaType, preciseAtSecondsLevel, period, startTime, maxCount, bucketType)
+ startTime = time.Now().UTC().Unix()
+ quotaBucket, err = NewQuotaBucket(edgeOrgID, id, interval, timeUnit, quotaType, preciseAtSecondsLevel, startTime, maxCount, bucketType)
+ Expect(err).NotTo(HaveOccurred())
+
err = quotaBucket.Validate()
Expect(err).NotTo(HaveOccurred())
+ quotaBucket.SetPeriod(time.Now().UTC().AddDate(0, 0, -1),
+ time.Now().UTC().AddDate(0, 1, 0))
+ period, err = quotaBucket.GetPeriod()
+ if err != nil {
+ Fail("no error expected but returned " + err.Error())
+ }
period.IsCurrentPeriod(quotaBucket)
- if ok := period.IsCurrentPeriod(quotaBucket); !ok{
+ if ok := period.IsCurrentPeriod(quotaBucket); !ok {
Fail("Exprected true, returned: false")
}
//start Time in period is now
- startTime = time.Now().Unix()
- period = NewQuotaPeriod(time.Now().AddDate(0,-1,0).Unix(),
- time.Now().Unix(),
- time.Now().AddDate(0,1,0).Unix())
- quotaBucket = NewQuotaBucket(edgeOrgID, id, interval, timeUnit, quotaType, preciseAtSecondsLevel, period, startTime, maxCount, bucketType)
- err = quotaBucket.Validate()
+ startTime = time.Now().UTC().Unix()
+ quotaBucket, err = NewQuotaBucket(edgeOrgID, id, interval, timeUnit, quotaType, preciseAtSecondsLevel, startTime, maxCount, bucketType)
Expect(err).NotTo(HaveOccurred())
+ err = quotaBucket.Validate()
+ Expect(err).NotTo(HaveOccurred())
+ quotaBucket.SetPeriod(time.Now().UTC(),
+ time.Now().UTC().AddDate(0, 1, 0))
+ period, err = quotaBucket.GetPeriod()
+ if err != nil {
+ Fail("no error expected but returned " + err.Error())
+ }
period.IsCurrentPeriod(quotaBucket)
- if ok := period.IsCurrentPeriod(quotaBucket); !ok{
+ if ok := period.IsCurrentPeriod(quotaBucket); !ok {
Fail("Exprected true, returned: false")
}
@@ -353,30 +378,40 @@
//}
//end Time in period is after now
- startTime = time.Now().Unix()
- period = NewQuotaPeriod(time.Now().AddDate(0,-1,0).Unix(),
- time.Now().AddDate(0,0,-1).Unix(),
- time.Now().AddDate(0,1,0).Unix())
- quotaBucket = NewQuotaBucket(edgeOrgID, id, interval, timeUnit, quotaType, preciseAtSecondsLevel, period, startTime, maxCount, bucketType)
+ startTime = time.Now().UTC().Unix()
+ quotaBucket, err = NewQuotaBucket(edgeOrgID, id, interval, timeUnit, quotaType, preciseAtSecondsLevel, startTime, maxCount, bucketType)
+ Expect(err).NotTo(HaveOccurred())
+
err = quotaBucket.Validate()
Expect(err).NotTo(HaveOccurred())
+ quotaBucket.SetPeriod(time.Now().UTC().AddDate(0, 0, -1),
+ time.Now().UTC().AddDate(0, 1, 0))
+ period, err = quotaBucket.GetPeriod()
+ if err != nil {
+ Fail("no error expected but returned " + err.Error())
+ }
+
period.IsCurrentPeriod(quotaBucket)
- if ok := period.IsCurrentPeriod(quotaBucket); !ok{
+ if ok := period.IsCurrentPeriod(quotaBucket); !ok {
Fail("Exprected true, returned: false")
}
//start time in period is before end time
- startTime = time.Now().Unix()
- period = NewQuotaPeriod(time.Now().AddDate(0,-1,0).Unix(),
- time.Now().AddDate(0,-1,0).Unix(),
- time.Now().AddDate(0,1,0).Unix())
- quotaBucket = NewQuotaBucket(edgeOrgID, id, interval, timeUnit, quotaType, preciseAtSecondsLevel, period, startTime, maxCount, bucketType)
- err = quotaBucket.Validate()
+ startTime = time.Now().UTC().Unix()
+ quotaBucket, err = NewQuotaBucket(edgeOrgID, id, interval, timeUnit, quotaType, preciseAtSecondsLevel, startTime, maxCount, bucketType)
Expect(err).NotTo(HaveOccurred())
+ err = quotaBucket.Validate()
+ Expect(err).NotTo(HaveOccurred())
+ quotaBucket.SetPeriod(time.Now().UTC().AddDate(0, 0, -1),
+ time.Now().UTC().AddDate(0, 1, 0))
+ period, err = quotaBucket.GetPeriod()
+ if err != nil {
+ Fail("no error expected but returned " + err.Error())
+ }
period.IsCurrentPeriod(quotaBucket)
- if ok := period.IsCurrentPeriod(quotaBucket); !ok{
+ if ok := period.IsCurrentPeriod(quotaBucket); !ok {
Fail("Exprected true, returned: false")
}
@@ -394,49 +429,51 @@
preciseAtSecondsLevel := true
//InputStart time is after now.
- period := NewQuotaPeriod(time.Now().AddDate(0,1,0).Unix(),
- time.Now().AddDate(0,1,0).Unix(), time.Now().AddDate(1,0,1).Unix())
- startTime := time.Now().AddDate(0,1,0).Unix()
+ period := NewQuotaPeriod(time.Now().UTC().AddDate(0, 1, 0).Unix(),
+ time.Now().UTC().AddDate(0, 1, 0).Unix(), time.Now().AddDate(1, 0, 1).Unix())
+ startTime := time.Now().UTC().AddDate(0, 1, 0).Unix()
- quotaBucket := NewQuotaBucket(edgeOrgID, id, interval, timeUnit, quotaType, preciseAtSecondsLevel, period, startTime, maxCount, bucketType)
- err := quotaBucket.Validate()
+ quotaBucket, err := NewQuotaBucket(edgeOrgID, id, interval, timeUnit, quotaType, preciseAtSecondsLevel, startTime, maxCount, bucketType)
Expect(err).NotTo(HaveOccurred())
- if ok := period.IsCurrentPeriod(quotaBucket); ok{
- Fail("Exprected true, returned: false")
- }
-
-
- //endTime is before start time
- startTime = time.Now().AddDate(0,-1,0).Unix()
- quotaBucket = NewQuotaBucket(edgeOrgID, id, interval, timeUnit, quotaType, preciseAtSecondsLevel, period, startTime, maxCount, bucketType)
err = quotaBucket.Validate()
Expect(err).NotTo(HaveOccurred())
- quotaBucket.SetPeriod(time.Now(), time.Now().AddDate(0,-1,0))
+ if ok := period.IsCurrentPeriod(quotaBucket); ok {
+ Fail("Exprected true, returned: false")
+ }
- if ok := period.IsCurrentPeriod(quotaBucket); ok{
+ //endTime is before start time
+ startTime = time.Now().UTC().AddDate(0, -1, 0).Unix()
+ quotaBucket, err = NewQuotaBucket(edgeOrgID, id, interval, timeUnit, quotaType, preciseAtSecondsLevel, startTime, maxCount, bucketType)
+ Expect(err).NotTo(HaveOccurred())
+
+ err = quotaBucket.Validate()
+ Expect(err).NotTo(HaveOccurred())
+
+ quotaBucket.SetPeriod(time.Now().UTC(), time.Now().UTC().AddDate(0, -1, 0))
+
+ if ok := period.IsCurrentPeriod(quotaBucket); ok {
Fail("Exprected true, returned: false")
}
//start time in period after now
- quotaBucket.SetPeriod(time.Now().AddDate(0,1,0), time.Now().AddDate(1,1,0))
+ quotaBucket.SetPeriod(time.Now().AddDate(0, 1, 0), time.Now().AddDate(1, 1, 0))
- if ok := period.IsCurrentPeriod(quotaBucket); ok{
+ if ok := period.IsCurrentPeriod(quotaBucket); ok {
Fail("Exprected true, returned: false")
}
//end time in period is before now
- quotaBucket.SetPeriod(time.Now().AddDate(-1,-1,0), time.Now().AddDate(0,-1,0))
+ quotaBucket.SetPeriod(time.Now().UTC().AddDate(-1, -1, 0), time.Now().UTC().AddDate(0, -1, 0))
- if ok := period.IsCurrentPeriod(quotaBucket); ok{
+ if ok := period.IsCurrentPeriod(quotaBucket); ok {
Fail("Exprected true, returned: false")
}
})
})
-
var _ = Describe("Test GetPeriod and setCurrentPeriod", func() {
It("Valid GetPeriod", func() {
edgeOrgID := "sampleOrg"
@@ -448,60 +485,58 @@
maxCount := 10
preciseAtSecondsLevel := true
//InputStart time is before now
- period := NewQuotaPeriod(time.Now().AddDate(0, -1,0).Unix(),
- time.Now().AddDate(0,0, -1).Unix(),
- time.Now().AddDate(0,1,0).Unix())
- startTime := time.Now().AddDate(0,-1,0).Unix()
- quotaBucket := NewQuotaBucket(edgeOrgID, id, interval, timeUnit, quotaType, preciseAtSecondsLevel, period, startTime, maxCount, bucketType)
- err := quotaBucket.Validate()
+ startTime := time.Now().UTC().AddDate(0, -1, 0).Unix()
+ quotaBucket, err := NewQuotaBucket(edgeOrgID, id, interval, timeUnit, quotaType, preciseAtSecondsLevel, startTime, maxCount, bucketType)
+ Expect(err).NotTo(HaveOccurred())
+
+ quotaBucket.SetPeriod(time.Now().UTC().AddDate(0, 0, -1), time.Now().UTC().AddDate(0, 1, 0))
+ err = quotaBucket.Validate()
Expect(err).NotTo(HaveOccurred())
qPeriod, err := quotaBucket.GetPeriod()
Expect(err).NotTo(HaveOccurred())
// check if the rolling window was set properly
Expect(qPeriod.GetPeriodInputStartTime()).Should(Equal(quotaBucket.GetStartTime()))
- if !qPeriod.GetPeriodEndTime().After(qPeriod.GetPeriodStartTime()){
+ if !qPeriod.GetPeriodEndTime().After(qPeriod.GetPeriodStartTime()) {
Fail("Rolling Window was not set as expected")
}
intervalDuration := qPeriod.GetPeriodEndTime().Sub(qPeriod.GetPeriodStartTime())
expectedDuration, err := GetIntervalDurtation(quotaBucket)
Expect(intervalDuration).Should(Equal(expectedDuration))
-
//for non rolling Type window do not setCurrentPeriod as endTime is > time.now.
quotaType = "calendar"
- pstartTime := time.Now().AddDate(0,-1,0)
- pendTime := time.Now().AddDate(0,1,0)
- quotaBucket = NewQuotaBucket(edgeOrgID, id, interval, timeUnit, quotaType, preciseAtSecondsLevel, period, startTime, maxCount, bucketType)
+ pstartTime := time.Now().UTC().AddDate(0, -1, 0)
+ pendTime := time.Now().UTC().AddDate(0, 1, 0)
+ quotaBucket, err = NewQuotaBucket(edgeOrgID, id, interval, timeUnit, quotaType, preciseAtSecondsLevel, startTime, maxCount, bucketType)
+ Expect(err).NotTo(HaveOccurred())
+
quotaBucket.SetPeriod(pstartTime, pendTime)
qPeriod, err = quotaBucket.GetPeriod()
Expect(err).NotTo(HaveOccurred())
// check if the calendar window was set properly
Expect(qPeriod.GetPeriodInputStartTime()).Should(Equal(quotaBucket.GetStartTime()))
- if !qPeriod.GetPeriodEndTime().After(qPeriod.GetPeriodStartTime()){
+ if !qPeriod.GetPeriodEndTime().After(qPeriod.GetPeriodStartTime()) {
Fail("Rolling Window was not set as expected")
}
//for non rolling Type window setCurrentPeriod as endTime is < time.now.
quotaType = "calendar"
- pstartTime = time.Now().AddDate(0,-1,0)
- pendTime = time.Now().AddDate(0,-1,0)
- quotaBucket = NewQuotaBucket(edgeOrgID, id, interval, timeUnit, quotaType, preciseAtSecondsLevel, period, startTime, maxCount, bucketType)
+ pstartTime = time.Now().UTC().AddDate(0, -1, 0)
+ pendTime = time.Now().UTC().AddDate(0, -1, 0)
+ quotaBucket, err = NewQuotaBucket(edgeOrgID, id, interval, timeUnit, quotaType, preciseAtSecondsLevel, startTime, maxCount, bucketType)
+ Expect(err).NotTo(HaveOccurred())
+
quotaBucket.SetPeriod(pstartTime, pendTime)
qPeriod, err = quotaBucket.GetPeriod()
Expect(err).NotTo(HaveOccurred())
// check if the calendar window was set properly
Expect(qPeriod.GetPeriodInputStartTime()).Should(Equal(quotaBucket.GetStartTime()))
- if !qPeriod.GetPeriodEndTime().After(qPeriod.GetPeriodStartTime()){
- Fail("Rolling Window was not set as expected")
+ if !qPeriod.GetPeriodEndTime().After(qPeriod.GetPeriodStartTime()) {
+ Fail("period for Non Rolling Window Type was not set as expected")
}
intervalDuration = qPeriod.GetPeriodEndTime().Sub(qPeriod.GetPeriodStartTime())
expectedDuration, err = GetIntervalDurtation(quotaBucket)
Expect(intervalDuration).Should(Equal(expectedDuration))
-
-
-
})
-
})
-
diff --git a/quotaBucket/quotaDescriptorType.go b/quotaBucket/quotaDescriptorType.go
index c94333c..87e8f0c 100644
--- a/quotaBucket/quotaDescriptorType.go
+++ b/quotaBucket/quotaDescriptorType.go
@@ -2,7 +2,6 @@
import (
"errors"
- "fmt"
"strings"
"time"
)
@@ -17,7 +16,7 @@
SetCurrentPeriod(bucket *QuotaBucket) error
}
-func GetQuotaTypeHandler(qType string) (QuotaDescriptorType, error) {
+func GetQuotaDescriptorTypeHandler(qType string) (QuotaDescriptorType, error) {
var qDescriptor QuotaDescriptorType
quotaType := strings.ToLower(strings.TrimSpace(qType))
switch quotaType {
@@ -28,7 +27,7 @@
qDescriptor = &RollingWindowQuotaDescriptorType{}
return qDescriptor, nil
default:
- return nil, errors.New("Quota type " + qType + " in the request is not supported")
+ return nil, errors.New(InvalidQuotaDescriptorType + " Quota type " + qType + " in the request is not supported")
}
}
@@ -37,11 +36,11 @@
func (c CalendarQuotaDescriptorType) SetCurrentPeriod(qbucket *QuotaBucket) error {
startTime := qbucket.GetStartTime()
- currentPeriod,err := qbucket.GetQuotaBucketPeriod()
-if err != nil {
- return err
-}
- if startTime.Before(time.Now()) || startTime.Equal(time.Now()) {
+ currentPeriod, err := qbucket.GetQuotaBucketPeriod()
+ if err != nil {
+ return err
+ }
+ if startTime.Before(time.Now().UTC()) || startTime.Equal(time.Now().UTC()) {
if currentPeriod != nil {
if currentPeriod.IsCurrentPeriod(qbucket) {
return nil
@@ -60,7 +59,7 @@
}
var currentStart, currentEnd time.Time
- now := time.Now()
+ now := time.Now().UTC()
timeUnit := strings.ToLower(strings.TrimSpace(qbucket.TimeUnit))
switch timeUnit {
case TimeUnitSECOND:
@@ -95,19 +94,22 @@
currentStart = time.Date(now.Year(), now.Month(), 0, 0, 0, 0, 0, time.UTC)
currentEnd = currentStart.AddDate(0, qbucket.Interval, 0)
break
+ default:
+ return errors.New(InvalidQuotaTimeUnitType + " : ignoring unrecognized timeUnit : " + timeUnit)
+
}
qbucket.SetPeriod(currentStart, currentEnd)
- fmt.Println("inside calendar set period: ", qbucket.quotaBucketData.Period)
return nil
}
type RollingWindowQuotaDescriptorType struct{}
func (c RollingWindowQuotaDescriptorType) SetCurrentPeriod(qbucket *QuotaBucket) error {
+
//yet to implement
var currentStart, currentEnd time.Time
- currentEnd = time.Now()
+ currentEnd = time.Now().UTC()
interval, err := GetIntervalDurtation(qbucket)
if err != nil {
return errors.New("error in SetCurrentPeriod: " + err.Error())
@@ -118,6 +120,7 @@
return nil
}
func GetIntervalDurtation(qb *QuotaBucket) (time.Duration, error) {
+
timeUnit := strings.ToLower(strings.TrimSpace(qb.TimeUnit))
switch timeUnit {
case TimeUnitSECOND:
@@ -131,9 +134,9 @@
case TimeUnitWEEK:
return time.Duration(int64(qb.Interval*24*7) * time.Hour.Nanoseconds()), nil
case TimeUnitMONTH:
- now := time.Now()
+ now := time.Now().UTC()
var currentStart, currentEnd time.Time
- quotaType := strings.ToLower(strings.TrimSpace(qb.QuotaType))
+ quotaType := strings.ToLower(strings.TrimSpace(qb.QuotaDescriptorType))
switch quotaType {
case QuotaTypeCalendar:
currentStart = time.Date(now.Year(), now.Month(), 0, 0, 0, 0, 0, time.UTC)
@@ -144,11 +147,11 @@
currentStart = currentEnd.AddDate(0, -qb.Interval, 0)
return currentEnd.Sub(currentStart), nil
default:
- return time.Duration(0), errors.New("Ignoring unrecognized quotaType : " + quotaType)
+ return time.Duration(0), errors.New(InvalidQuotaDescriptorType + " : ignoring unrecognized quotaType : " + quotaType)
}
default:
- return time.Duration(0), errors.New("Ignoring unrecognized timeUnit : " + timeUnit)
+ return time.Duration(0), errors.New(InvalidQuotaTimeUnitType + " : ignoring unrecognized timeUnit : " + timeUnit)
}
diff --git a/quotaBucket/quotaDescriptorType_test.go b/quotaBucket/quotaDescriptorType_test.go
index 22a4a08..0bd44cf 100644
--- a/quotaBucket/quotaDescriptorType_test.go
+++ b/quotaBucket/quotaDescriptorType_test.go
@@ -1,9 +1,411 @@
package quotaBucket_test
import (
+ . "github.com/30x/apidQuota/quotaBucket"
. "github.com/onsi/ginkgo"
+ . "github.com/onsi/gomega"
+ "time"
+ "strings"
+ "reflect"
)
-var _ = Describe("QuotaDescriptorType", func() {
+var _ = Describe("Check Descriptor Type ", func() {
+ It("test Calendar Type descriptor", func() {
+ descriptorType, err := GetQuotaDescriptorTypeHandler("calendar")
+ Expect(err).NotTo(HaveOccurred())
+ if reflect.TypeOf(descriptorType)!= reflect.TypeOf(&CalendarQuotaDescriptorType{}){
+ Fail("Excepted CalendarQuotaDescriptorType, but got: " + reflect.TypeOf(descriptorType).String())
+ }
+ })
+
+ FIt("test RollingWindow Type descriptor", func() {
+ descriptorType, err := GetQuotaDescriptorTypeHandler("rollingwindow")
+ Expect(err).NotTo(HaveOccurred())
+ if reflect.TypeOf(descriptorType)!= reflect.TypeOf(&RollingWindowQuotaDescriptorType{}){
+ Fail("Excepted RollingWindowQuotaDescriptorType, but got: " + reflect.TypeOf(descriptorType).String())
+ }
+ })
+
+ FIt("test invalid Type descriptor", func() {
+ _, err := GetQuotaDescriptorTypeHandler("invalidDescriptorType")
+ Expect(err).To(HaveOccurred())
+ if !strings.Contains(err.Error(), InvalidQuotaDescriptorType) {
+ Fail("Excepted error to contain: " + InvalidQuotaDescriptorType + " but got: " + err.Error())
+ }
+ })
})
+
+var _ = Describe("QuotaDescriptorType", func() {
+ It("Valid testcases for CalendarType", func() {
+
+ // test set period for timeUnit=second
+ edgeOrgID := "sampleOrg"
+ id := "sampleID"
+ timeUnit := "second"
+ quotaType := "calendar"
+ bucketType := "synchronous"
+ interval := 1
+ maxCount := 10
+ preciseAtSecondsLevel := true
+ startTime := time.Now().UTC().UTC().AddDate(0, -1, 0).Unix()
+
+ quotaBucket, err := NewQuotaBucket(edgeOrgID, id, interval, timeUnit, quotaType, preciseAtSecondsLevel, startTime, maxCount, bucketType)
+ Expect(err).NotTo(HaveOccurred())
+
+ err = quotaBucket.Validate()
+ Expect(err).NotTo(HaveOccurred())
+
+ period, err := quotaBucket.GetPeriod()
+ Expect(err).NotTo(HaveOccurred())
+ // check if the calendar window was set properly
+ Expect(period.GetPeriodInputStartTime()).Should(Equal(quotaBucket.GetStartTime()))
+ if !period.GetPeriodEndTime().After(period.GetPeriodStartTime()) {
+ Fail("period for Calendar Type was not set as expected")
+ }
+ Expect(period.GetPeriodStartTime().String()).ShouldNot(BeEmpty())
+ Expect(period.GetPeriodEndTime().String()).ShouldNot(BeEmpty())
+ intervalDuration := period.GetPeriodEndTime().Sub(period.GetPeriodStartTime())
+ Expect(intervalDuration).Should(Equal(time.Second))
+
+
+ // test set period for timeUnit=minute
+ timeUnit = "minute"
+
+ quotaBucket, err = NewQuotaBucket(edgeOrgID, id, interval, timeUnit, quotaType, preciseAtSecondsLevel, startTime, maxCount, bucketType)
+ Expect(err).NotTo(HaveOccurred())
+
+ err = quotaBucket.Validate()
+ Expect(err).NotTo(HaveOccurred())
+
+ period, err = quotaBucket.GetPeriod()
+ Expect(err).NotTo(HaveOccurred())
+ // check if the calendar window was set properly
+ Expect(period.GetPeriodInputStartTime()).Should(Equal(quotaBucket.GetStartTime()))
+ if !period.GetPeriodEndTime().After(period.GetPeriodStartTime()) {
+ Fail("period for Calendar Type was not set as expected")
+ }
+ Expect(period.GetPeriodStartTime().String()).ShouldNot(BeEmpty())
+ Expect(period.GetPeriodEndTime().String()).ShouldNot(BeEmpty())
+ intervalDuration = period.GetPeriodEndTime().Sub(period.GetPeriodStartTime())
+ Expect(intervalDuration).Should(Equal(time.Minute))
+
+ // test set period for timeUnit=hour
+ timeUnit = "hour"
+
+ quotaBucket, err = NewQuotaBucket(edgeOrgID, id, interval, timeUnit, quotaType, preciseAtSecondsLevel, startTime, maxCount, bucketType)
+ Expect(err).NotTo(HaveOccurred())
+
+ err = quotaBucket.Validate()
+ Expect(err).NotTo(HaveOccurred())
+
+ period, err = quotaBucket.GetPeriod()
+ Expect(err).NotTo(HaveOccurred())
+ // check if the calendar window was set properly
+ Expect(period.GetPeriodInputStartTime()).Should(Equal(quotaBucket.GetStartTime()))
+ if !period.GetPeriodEndTime().After(period.GetPeriodStartTime()) {
+ Fail("period for Calendar Type was not set as expected")
+ }
+ Expect(period.GetPeriodStartTime().String()).ShouldNot(BeEmpty())
+ Expect(period.GetPeriodEndTime().String()).ShouldNot(BeEmpty())
+ intervalDuration = period.GetPeriodEndTime().Sub(period.GetPeriodStartTime())
+ Expect(intervalDuration).Should(Equal(time.Hour))
+
+
+ // test set period for timeUnit=day
+ timeUnit = "day"
+
+ quotaBucket, err = NewQuotaBucket(edgeOrgID, id, interval, timeUnit, quotaType, preciseAtSecondsLevel, startTime, maxCount, bucketType)
+ Expect(err).NotTo(HaveOccurred())
+
+ err = quotaBucket.Validate()
+ Expect(err).NotTo(HaveOccurred())
+
+ period, err = quotaBucket.GetPeriod()
+ Expect(err).NotTo(HaveOccurred())
+ // check if the calendar window was set properly
+ Expect(period.GetPeriodInputStartTime()).Should(Equal(quotaBucket.GetStartTime()))
+ if !period.GetPeriodEndTime().After(period.GetPeriodStartTime()) {
+ Fail("period for Calendar Type was not set as expected")
+ }
+ Expect(period.GetPeriodStartTime().String()).ShouldNot(BeEmpty())
+ Expect(period.GetPeriodEndTime().String()).ShouldNot(BeEmpty())
+ intervalDuration = period.GetPeriodEndTime().Sub(period.GetPeriodStartTime())
+ Expect(intervalDuration).Should(Equal(24 * time.Hour))
+
+ // test set period for timeUnit=week
+ timeUnit = "week"
+
+ quotaBucket, err = NewQuotaBucket(edgeOrgID, id, interval, timeUnit, quotaType, preciseAtSecondsLevel, startTime, maxCount, bucketType)
+ Expect(err).NotTo(HaveOccurred())
+
+ err = quotaBucket.Validate()
+ Expect(err).NotTo(HaveOccurred())
+
+ period, err = quotaBucket.GetPeriod()
+ Expect(err).NotTo(HaveOccurred())
+ // check if the calendar window was set properly
+ Expect(period.GetPeriodInputStartTime()).Should(Equal(quotaBucket.GetStartTime()))
+ if !period.GetPeriodEndTime().After(period.GetPeriodStartTime()) {
+ Fail("period for Calendar Type was not set as expected")
+ }
+ Expect(period.GetPeriodStartTime().String()).ShouldNot(BeEmpty())
+ Expect(period.GetPeriodEndTime().String()).ShouldNot(BeEmpty())
+ intervalDuration = period.GetPeriodEndTime().Sub(period.GetPeriodStartTime())
+ Expect(intervalDuration).Should(Equal(7 * 24 * time.Hour))
+
+
+ // test set period for timeUnit=month
+ timeUnit = "month"
+
+ quotaBucket, err = NewQuotaBucket(edgeOrgID, id, interval, timeUnit, quotaType, preciseAtSecondsLevel, startTime, maxCount, bucketType)
+ Expect(err).NotTo(HaveOccurred())
+
+ err = quotaBucket.Validate()
+ Expect(err).NotTo(HaveOccurred())
+
+ period, err = quotaBucket.GetPeriod()
+ Expect(err).NotTo(HaveOccurred())
+ // check if the calendar window was set properly
+ Expect(period.GetPeriodInputStartTime()).Should(Equal(quotaBucket.GetStartTime()))
+ if !period.GetPeriodEndTime().After(period.GetPeriodStartTime()) {
+ Fail("period for Calendar Type was not set as expected")
+ }
+ Expect(period.GetPeriodStartTime().String()).ShouldNot(BeEmpty())
+ Expect(period.GetPeriodEndTime().String()).ShouldNot(BeEmpty())
+ intervalDuration = period.GetPeriodEndTime().Sub(period.GetPeriodStartTime())
+ addMonthToStartDate := period.GetPeriodStartTime().AddDate(0,interval*1,0)
+ actualDuration := addMonthToStartDate.Sub(period.GetPeriodStartTime())
+ Expect(intervalDuration).Should(Equal(actualDuration))
+
+ })
+
+ It("inValid testcases for CalendarType", func() {
+
+ // test set period for timeUnit=second
+ edgeOrgID := "sampleOrg"
+ id := "sampleID"
+ timeUnit := "second"
+ quotaType := "calendar"
+ bucketType := "synchronous"
+ interval := 1
+ maxCount := 10
+ preciseAtSecondsLevel := true
+ startTime := time.Now().UTC().UTC().AddDate(0, -1, 0).Unix()
+
+ quotaBucket, err := NewQuotaBucket(edgeOrgID, id, interval, timeUnit, quotaType, preciseAtSecondsLevel, startTime, maxCount, bucketType)
+ Expect(err).NotTo(HaveOccurred())
+
+ err = quotaBucket.Validate()
+ Expect(err).NotTo(HaveOccurred())
+
+ period, err := quotaBucket.GetPeriod()
+ Expect(err).NotTo(HaveOccurred())
+ // check if the calendar window was set properly
+ Expect(period.GetPeriodInputStartTime()).Should(Equal(quotaBucket.GetStartTime()))
+ if !period.GetPeriodEndTime().After(period.GetPeriodStartTime()) {
+ Fail("period for Calendar Type was not set as expected")
+ }
+ Expect(period.GetPeriodStartTime().String()).ShouldNot(BeEmpty())
+ Expect(period.GetPeriodEndTime().String()).ShouldNot(BeEmpty())
+ intervalDuration := period.GetPeriodEndTime().Sub(period.GetPeriodStartTime())
+ Expect(intervalDuration).Should(Equal(time.Second))
+
+
+ // test set period for timeUnit=month
+ timeUnit = "invalidTimeUnit"
+
+ quotaBucket, err = NewQuotaBucket(edgeOrgID, id, interval, timeUnit, quotaType, preciseAtSecondsLevel, startTime, maxCount, bucketType)
+ Expect(err).To(HaveOccurred())
+ if ok := strings.Contains(err.Error(),InvalidQuotaTimeUnitType); !ok {
+ Fail("expected error to contain " + InvalidQuotaTimeUnitType + " but got different error message: " + err.Error())
+ }
+
+ })
+
+ It("Valid testcases for RollingWindow Type", func() {
+
+ // test set period for timeUnit=second
+ edgeOrgID := "sampleOrg"
+ id := "sampleID"
+ timeUnit := "second"
+ quotaType := "rollingWindow"
+ bucketType := "synchronous"
+ interval := 1
+ maxCount := 10
+ preciseAtSecondsLevel := true
+ startTime := time.Now().UTC().UTC().AddDate(0, -1, 0).Unix()
+
+ quotaBucket, err := NewQuotaBucket(edgeOrgID, id, interval, timeUnit, quotaType, preciseAtSecondsLevel, startTime, maxCount, bucketType)
+ Expect(err).NotTo(HaveOccurred())
+
+ err = quotaBucket.Validate()
+ Expect(err).NotTo(HaveOccurred())
+
+ period, err := quotaBucket.GetPeriod()
+ Expect(err).NotTo(HaveOccurred())
+ // check if the calendar window was set properly
+ Expect(period.GetPeriodInputStartTime()).Should(Equal(quotaBucket.GetStartTime()))
+ if !period.GetPeriodEndTime().After(period.GetPeriodStartTime()) {
+ Fail("period for Rolling Window Type was not set as expected")
+ }
+ Expect(period.GetPeriodStartTime().String()).ShouldNot(BeEmpty())
+ Expect(period.GetPeriodEndTime().String()).ShouldNot(BeEmpty())
+ intervalDuration := period.GetPeriodEndTime().Sub(period.GetPeriodStartTime())
+ Expect(intervalDuration).Should(Equal(time.Second))
+
+
+ // test set period for timeUnit=minute
+ timeUnit = "minute"
+
+ quotaBucket, err = NewQuotaBucket(edgeOrgID, id, interval, timeUnit, quotaType, preciseAtSecondsLevel, startTime, maxCount, bucketType)
+ Expect(err).NotTo(HaveOccurred())
+
+ err = quotaBucket.Validate()
+ Expect(err).NotTo(HaveOccurred())
+
+ period, err = quotaBucket.GetPeriod()
+ Expect(err).NotTo(HaveOccurred())
+ // check if the calendar window was set properly
+ Expect(period.GetPeriodInputStartTime()).Should(Equal(quotaBucket.GetStartTime()))
+ if !period.GetPeriodEndTime().After(period.GetPeriodStartTime()) {
+ Fail("period for Rolling Window Type was not set as expected")
+ }
+ Expect(period.GetPeriodStartTime().String()).ShouldNot(BeEmpty())
+ Expect(period.GetPeriodEndTime().String()).ShouldNot(BeEmpty())
+ intervalDuration = period.GetPeriodEndTime().Sub(period.GetPeriodStartTime())
+ Expect(intervalDuration).Should(Equal(time.Minute))
+
+ // test set period for timeUnit=hour
+ timeUnit = "hour"
+
+ quotaBucket, err = NewQuotaBucket(edgeOrgID, id, interval, timeUnit, quotaType, preciseAtSecondsLevel, startTime, maxCount, bucketType)
+ Expect(err).NotTo(HaveOccurred())
+
+ err = quotaBucket.Validate()
+ Expect(err).NotTo(HaveOccurred())
+
+ period, err = quotaBucket.GetPeriod()
+ Expect(err).NotTo(HaveOccurred())
+ // check if the calendar window was set properly
+ Expect(period.GetPeriodInputStartTime()).Should(Equal(quotaBucket.GetStartTime()))
+ if !period.GetPeriodEndTime().After(period.GetPeriodStartTime()) {
+ Fail("period for Rolling Window Type was not set as expected")
+ }
+ Expect(period.GetPeriodStartTime().String()).ShouldNot(BeEmpty())
+ Expect(period.GetPeriodEndTime().String()).ShouldNot(BeEmpty())
+ intervalDuration = period.GetPeriodEndTime().Sub(period.GetPeriodStartTime())
+ Expect(intervalDuration).Should(Equal(time.Hour))
+
+
+ // test set period for timeUnit=day
+ timeUnit = "day"
+
+ quotaBucket, err = NewQuotaBucket(edgeOrgID, id, interval, timeUnit, quotaType, preciseAtSecondsLevel, startTime, maxCount, bucketType)
+ Expect(err).NotTo(HaveOccurred())
+
+ err = quotaBucket.Validate()
+ Expect(err).NotTo(HaveOccurred())
+
+ period, err = quotaBucket.GetPeriod()
+ Expect(err).NotTo(HaveOccurred())
+ // check if the calendar window was set properly
+ Expect(period.GetPeriodInputStartTime()).Should(Equal(quotaBucket.GetStartTime()))
+ if !period.GetPeriodEndTime().After(period.GetPeriodStartTime()) {
+ Fail("period for Rolling Window Type was not set as expected")
+ }
+ Expect(period.GetPeriodStartTime().String()).ShouldNot(BeEmpty())
+ Expect(period.GetPeriodEndTime().String()).ShouldNot(BeEmpty())
+ intervalDuration = period.GetPeriodEndTime().Sub(period.GetPeriodStartTime())
+ Expect(intervalDuration).Should(Equal(24 * time.Hour))
+
+ // test set period for timeUnit=week
+ timeUnit = "week"
+
+ quotaBucket, err = NewQuotaBucket(edgeOrgID, id, interval, timeUnit, quotaType, preciseAtSecondsLevel, startTime, maxCount, bucketType)
+ Expect(err).NotTo(HaveOccurred())
+
+ err = quotaBucket.Validate()
+ Expect(err).NotTo(HaveOccurred())
+
+ period, err = quotaBucket.GetPeriod()
+ Expect(err).NotTo(HaveOccurred())
+ // check if the calendar window was set properly
+ Expect(period.GetPeriodInputStartTime()).Should(Equal(quotaBucket.GetStartTime()))
+ if !period.GetPeriodEndTime().After(period.GetPeriodStartTime()) {
+ Fail("period for Rolling Window Type was not set as expected")
+ }
+ Expect(period.GetPeriodStartTime().String()).ShouldNot(BeEmpty())
+ Expect(period.GetPeriodEndTime().String()).ShouldNot(BeEmpty())
+ intervalDuration = period.GetPeriodEndTime().Sub(period.GetPeriodStartTime())
+ Expect(intervalDuration).Should(Equal(7 * 24 * time.Hour))
+
+
+ // test set period for timeUnit=month
+ timeUnit = "month"
+
+ quotaBucket, err = NewQuotaBucket(edgeOrgID, id, interval, timeUnit, quotaType, preciseAtSecondsLevel, startTime, maxCount, bucketType)
+ Expect(err).NotTo(HaveOccurred())
+
+ err = quotaBucket.Validate()
+ Expect(err).NotTo(HaveOccurred())
+
+ period, err = quotaBucket.GetPeriod()
+ Expect(err).NotTo(HaveOccurred())
+ // check if the calendar window was set properly
+ Expect(period.GetPeriodInputStartTime()).Should(Equal(quotaBucket.GetStartTime()))
+ if !period.GetPeriodEndTime().After(period.GetPeriodStartTime()) {
+ Fail("period for Rolling Window Type was not set as expected")
+ }
+ Expect(period.GetPeriodStartTime().String()).ShouldNot(BeEmpty())
+ Expect(period.GetPeriodEndTime().String()).ShouldNot(BeEmpty())
+ intervalDuration = period.GetPeriodEndTime().Sub(period.GetPeriodStartTime())
+ addMonthToStartDate := period.GetPeriodStartTime().AddDate(0,interval*1,0)
+ actualDuration := addMonthToStartDate.Sub(period.GetPeriodStartTime())
+ Expect(intervalDuration).Should(Equal(actualDuration))
+
+ })
+
+ It("inValid testcases for RollingWindow Type", func() {
+
+ // test set period for timeUnit=second
+ edgeOrgID := "sampleOrg"
+ id := "sampleID"
+ timeUnit := "second"
+ quotaType := "rollingwindow"
+ bucketType := "synchronous"
+ interval := 1
+ maxCount := 10
+ preciseAtSecondsLevel := true
+ startTime := time.Now().UTC().UTC().AddDate(0, -1, 0).Unix()
+
+ quotaBucket, err := NewQuotaBucket(edgeOrgID, id, interval, timeUnit, quotaType, preciseAtSecondsLevel, startTime, maxCount, bucketType)
+ Expect(err).NotTo(HaveOccurred())
+
+ err = quotaBucket.Validate()
+ Expect(err).NotTo(HaveOccurred())
+
+ period, err := quotaBucket.GetPeriod()
+ Expect(err).NotTo(HaveOccurred())
+ // check if the calendar window was set properly
+ Expect(period.GetPeriodInputStartTime()).Should(Equal(quotaBucket.GetStartTime()))
+ if !period.GetPeriodEndTime().After(period.GetPeriodStartTime()) {
+ Fail("period for Rolling Window Type was not set as expected")
+ }
+ Expect(period.GetPeriodStartTime().String()).ShouldNot(BeEmpty())
+ Expect(period.GetPeriodEndTime().String()).ShouldNot(BeEmpty())
+ intervalDuration := period.GetPeriodEndTime().Sub(period.GetPeriodStartTime())
+ Expect(intervalDuration).Should(Equal(time.Second))
+
+
+ // test set period for timeUnit=month
+ timeUnit = "invalidTimeUnit"
+
+ quotaBucket, err = NewQuotaBucket(edgeOrgID, id, interval, timeUnit, quotaType, preciseAtSecondsLevel, startTime, maxCount, bucketType)
+ Expect(err).To(HaveOccurred())
+ if ok := strings.Contains(err.Error(),InvalidQuotaTimeUnitType); !ok {
+ Fail("expected error to contain " + InvalidQuotaTimeUnitType + " but got different error message: " + err.Error())
+ }
+
+ })
+})
\ No newline at end of file
diff --git a/services/counterServiceHelper.go b/services/counterServiceHelper.go
new file mode 100644
index 0000000..8568d8d
--- /dev/null
+++ b/services/counterServiceHelper.go
@@ -0,0 +1,101 @@
+package services
+
+import (
+ "bytes"
+ "encoding/json"
+ "errors"
+ "github.com/30x/apidQuota/constants"
+ "github.com/30x/apidQuota/globalVariables"
+ "io/ioutil"
+ "net/http"
+ "net/url"
+ "time"
+)
+
+const (
+ edgeOrgID = "orgId"
+ key = "key"
+ delta = "delta"
+)
+
+var client *http.Client = &http.Client{
+ //setting the timeout to 60 sec for requests to counterService
+ Timeout: time.Duration(60 * time.Second),
+}
+
+func IncrementAndGetCount(orgID string, quotaKey string, count int) (int, error) {
+ headers := http.Header{}
+ headers.Set("Accept", "application/json")
+ headers.Set("Content-Type", "application/json")
+
+ method := "POST"
+
+ if globalVariables.CounterServiceURL == "" {
+ return 0, errors.New(constants.URLCounterServiceNotSet)
+ }
+
+ serviceURL, err := url.Parse(globalVariables.CounterServiceURL)
+ if err != nil {
+ return 0, errors.New(constants.URLCounterServiceInvalid)
+ }
+
+ //'{ "orgId": "test_org", "delta": 1, "key": "fixed-test-key" } '
+ reqBody := make(map[string]interface{})
+ reqBody[edgeOrgID] = orgID
+ reqBody[key] = quotaKey
+ reqBody[delta] = count
+
+ reqBodyBytes, err := json.Marshal(reqBody)
+ if err != nil {
+ return 0, errors.New(constants.MarshalJSONError)
+ }
+
+ contentLength := len(reqBodyBytes)
+ request := &http.Request{
+ Header: headers,
+ Method: method,
+ URL: serviceURL,
+ Body: ioutil.NopCloser(bytes.NewReader(reqBodyBytes)),
+ ContentLength: int64(contentLength),
+ }
+
+ resp, err := client.Do(request)
+
+ if err != nil {
+ return 0, errors.New("error calling CounterService: " + err.Error())
+ }
+
+ globalVariables.Log.Debug("response: ", resp)
+ if resp.StatusCode != http.StatusOK {
+ if resp.StatusCode == http.StatusNotFound {
+ return 0, errors.New(err.Error())
+ }
+ respBodyBytes, err := ioutil.ReadAll(resp.Body)
+ if err != nil {
+
+ }
+ return 0, errors.New("response from counter service: " + resp.Status + " and response body is: " + string(respBodyBytes))
+
+ }
+
+ respBodyBytes, err := ioutil.ReadAll(resp.Body)
+ respBody := make(map[string]interface{})
+ err = json.Unmarshal(respBodyBytes, &respBody)
+ if err != nil {
+ return 0, errors.New("unable to parse response from counter service, error: " + err.Error())
+ }
+
+ respCount, ok := respBody["count"]
+ if !ok {
+ return 0, errors.New(`invalid response from counter service. field 'count' not sent in the response`)
+ }
+
+ globalVariables.Log.Debug("responseCount: ", respCount)
+ respCountInt, ok := respCount.(int)
+ if !ok {
+ return 0, errors.New(`invalid response from counter service. field 'count' sent in the response is not int`)
+ }
+
+ return respCountInt, nil
+
+}
diff --git a/util.go b/util/util.go
similarity index 96%
rename from util.go
rename to util/util.go
index 696d5bc..5e8d6b6 100644
--- a/util.go
+++ b/util/util.go
@@ -1,4 +1,4 @@
-package apidQuota
+package util
import (
"encoding/json"