Skip to content

Commit

Permalink
add ttl tests, add doc not found err control for couchbase
Browse files Browse the repository at this point in the history
  • Loading branch information
mstrYoda committed May 29, 2023
1 parent 9c5122b commit 356be1c
Show file tree
Hide file tree
Showing 2 changed files with 47 additions and 2 deletions.
13 changes: 12 additions & 1 deletion couchbase/couchbase.go
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,15 @@ func New(config ...Config) *Storage {
func (s *Storage) Get(key string) ([]byte, error) {
out, err := s.bucket.DefaultCollection().Get(key, nil)
if err != nil {
switch e := err.(type) {
case *gocb.KeyValueError:
if e.InnerError.Error() == gocb.ErrDocumentNotFound.Error() {
return nil, nil
}
default: //*gocb.TimeoutError,...
return nil, err
}

return nil, err
}

Expand All @@ -59,7 +68,9 @@ func (s *Storage) Get(key string) ([]byte, error) {
}

func (s *Storage) Set(key string, val []byte, exp time.Duration) error {
if _, err := s.bucket.DefaultCollection().Upsert(key, val, nil); err != nil {
if _, err := s.bucket.DefaultCollection().Upsert(key, val, &gocb.UpsertOptions{
Expiry: exp,
}); err != nil {
return err
}

Expand Down
36 changes: 35 additions & 1 deletion couchbase/couchbase_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ package couchbase
import (
"strings"
"testing"
"time"

"github.com/gofiber/utils"
)
Expand All @@ -20,6 +21,20 @@ func TestSetCouchbase_ShouldReturnNoError(t *testing.T) {
utils.AssertEqual(t, nil, err)
}

func TestGetCouchbase_ShouldReturnNil_WhenDocumentNotFound(t *testing.T) {
testStorage := New(Config{
Username: "admin",
Password: "123456",
Host: "127.0.0.1:8091",
Bucket: "fiber_storage",
})

val, err := testStorage.Get("not_found_key")

utils.AssertEqual(t, nil, err)
utils.AssertEqual(t, 0, len(val))
}

func TestSetAndGet_GetShouldReturn_SettedValueWithoutError(t *testing.T) {
testStorage := New(Config{
Username: "admin",
Expand All @@ -37,6 +52,25 @@ func TestSetAndGet_GetShouldReturn_SettedValueWithoutError(t *testing.T) {
utils.AssertEqual(t, val, []byte("fiber_test_value"))
}

func TestSetAndGet_GetShouldReturnNil_WhenTTLExpired(t *testing.T) {
testStorage := New(Config{
Username: "admin",
Password: "123456",
Host: "127.0.0.1:8091",
Bucket: "fiber_storage",
})

err := testStorage.Set("test", []byte("fiber_test_value"), 3*time.Second)
utils.AssertEqual(t, nil, err)

time.Sleep(6 * time.Second)

val, err := testStorage.Get("test")

utils.AssertEqual(t, nil, err)
utils.AssertEqual(t, 0, len(val))
}

func TestSetAndDelete_DeleteShouldReturn_NoError(t *testing.T) {
testStorage := New(Config{
Username: "admin",
Expand Down Expand Up @@ -98,4 +132,4 @@ func TestGetConn_ReturnsNotNill(t *testing.T) {
})
conn := testStorage.Conn()
utils.AssertEqual(t, true, conn != nil)
}
}

0 comments on commit 356be1c

Please sign in to comment.