Skip to content

Commit

Permalink
refactor(rate): update code
Browse files Browse the repository at this point in the history
  • Loading branch information
novln committed Aug 18, 2017
1 parent caa19da commit 1f17b99
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 20 deletions.
28 changes: 12 additions & 16 deletions rate.go
Original file line number Diff line number Diff line change
@@ -1,10 +1,11 @@
package limiter

import (
"fmt"
"strconv"
"strings"
"time"

"github.com/pkg/errors"
)

// Rate is the rate.
Expand All @@ -20,7 +21,7 @@ func NewRateFromFormatted(formatted string) (Rate, error) {

values := strings.Split(formatted, "-")
if len(values) != 2 {
return rate, fmt.Errorf("Incorrect format '%s'", formatted)
return rate, errors.Errorf("incorrect format '%s'", formatted)
}

periods := map[string]time.Duration{
Expand All @@ -32,26 +33,21 @@ func NewRateFromFormatted(formatted string) (Rate, error) {
limit, period := values[0], strings.ToUpper(values[1])

duration, ok := periods[period]

if !ok {
return rate, fmt.Errorf("Incorrect period '%s'", period)
return rate, errors.Errorf("incorrect period '%s'", period)
}

var (
p time.Duration
l int
)

p = 1 * duration

l, err := strconv.Atoi(limit)
p := 1 * duration
l, err := strconv.ParseInt(limit, 10, 64)
if err != nil {
return rate, fmt.Errorf("Incorrect limit '%s'", limit)
return rate, errors.Errorf("incorrect limit '%s'", limit)
}

return Rate{
rate = Rate{
Formatted: formatted,
Period: p,
Limit: int64(l),
}, nil
Limit: l,
}

return rate, nil
}
10 changes: 6 additions & 4 deletions rate_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,11 +5,13 @@ import (
"testing"
"time"

"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)

// TestRate tests Rate methods.
func TestRate(t *testing.T) {
is := require.New(t)

expected := map[string]Rate{
"10-S": {
Formatted: "10-S",
Expand All @@ -30,8 +32,8 @@ func TestRate(t *testing.T) {

for k, v := range expected {
r, err := NewRateFromFormatted(k)
assert.Nil(t, err)
assert.True(t, reflect.DeepEqual(v, r))
is.NoError(err)
is.True(reflect.DeepEqual(v, r))
}

wrongs := []string{
Expand All @@ -44,7 +46,7 @@ func TestRate(t *testing.T) {

for _, w := range wrongs {
_, err := NewRateFromFormatted(w)
assert.NotNil(t, err)
is.Error(err)
}

}

0 comments on commit 1f17b99

Please sign in to comment.