Skip to content

Commit

Permalink
Add main unit tests
Browse files Browse the repository at this point in the history
  • Loading branch information
codeinuit committed Jul 25, 2023
1 parent beba9ac commit 4699b20
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 19 deletions.
23 changes: 4 additions & 19 deletions cmd/shibesbot/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -79,12 +79,10 @@ func initConfiguration() *Shibesbot {
}
}

func (sb *Shibesbot) setDailyKey() {
sb.log.Info("setting daily counter")
func (sb *Shibesbot) setDailyKey(t time.Time) {
sb.mtx.Lock()
defer sb.mtx.Unlock()

t := time.Now()
key := fmt.Sprintf("usage:%d%d%d", t.Day(), t.Month(), t.Year())

isUnset, err := sb.cache.SetNX(context.Background(), key, 0)
Expand All @@ -94,20 +92,6 @@ func (sb *Shibesbot) setDailyKey() {
}

if isUnset {
count, err := sb.cache.Get(context.Background(), key)

if err != nil {
sb.log.Warn("could not update and retrieve usage count: ", err.Error())
return
}

countInt, ok := count.(int64)
if !ok {
sb.log.Warn("could not set daily counter")
return
}

sb.setDailyCounter(countInt)
sb.dailyKey = key

return
Expand Down Expand Up @@ -139,8 +123,9 @@ func main() {
}()

_, err := c.AddFunc("0 0 * * *", func() {
sb.log.Info("running daily counter update job")
sb.setDailyKey()
sb.log.Info("updating usage count status")
sb.setDailyKey(time.Now())
sb.setDailyCounter(0)
})

if err != nil {
Expand Down
25 changes: 25 additions & 0 deletions cmd/shibesbot/main_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
package main

import (
"testing"
"time"

"github.com/P147x/shibesbot/pkg/cache/localstorage"
"github.com/P147x/shibesbot/pkg/logger/logrus"
"github.com/stretchr/testify/assert"
)

func TestResetDailyCounterKey(t *testing.T) {
bot := &Shibesbot{
cache: localstorage.NewLocalStorageCache(),
log: logrus.NewLogrusLogger(),
}

date := time.Unix(1690212965, 0)
bot.setDailyKey(date)
assert.Equal(t, "usage:2472023", bot.dailyKey)

date = time.Unix(1690236000, 0)
bot.setDailyKey(date)
assert.Equal(t, "usage:2572023", bot.dailyKey)
}

0 comments on commit 4699b20

Please sign in to comment.