micro/store/cockroach/cockroach_test.go

131 lines
2.4 KiB
Go
Raw Normal View History

2019-12-16 18:09:59 +03:00
package cockroach
2019-11-01 17:13:21 +03:00
import (
"database/sql"
"fmt"
"os"
2019-11-01 17:13:21 +03:00
"testing"
"time"
"github.com/kr/pretty"
"github.com/micro/go-micro/v3/store"
2019-11-01 17:13:21 +03:00
)
func TestSQL(t *testing.T) {
if len(os.Getenv("IN_TRAVIS_CI")) != 0 {
t.Skip()
}
2019-11-01 17:13:21 +03:00
connection := fmt.Sprintf(
"host=%s port=%d user=%s sslmode=disable dbname=%s",
"localhost",
26257,
"root",
2019-11-01 17:13:21 +03:00
"test",
)
db, err := sql.Open("postgres", connection)
if err != nil {
t.Fatal(err)
}
if err := db.Ping(); err != nil {
t.Skip("store/cockroach: can't connect to db")
2019-11-01 17:13:21 +03:00
}
db.Close()
2020-01-06 20:44:32 +03:00
sqlStore := NewStore(
store.Database("testsql"),
2019-11-01 17:13:21 +03:00
store.Nodes(connection),
)
if err := sqlStore.Init(); err != nil {
t.Fatal(err)
}
keys, err := sqlStore.List()
2019-11-01 17:13:21 +03:00
if err != nil {
t.Error(err)
} else {
t.Logf("%# v\n", pretty.Formatter(keys))
2019-11-01 17:13:21 +03:00
}
err = sqlStore.Write(
&store.Record{
Key: "test",
Value: []byte("foo"),
},
)
if err != nil {
t.Error(err)
}
err = sqlStore.Write(
2019-11-01 17:13:21 +03:00
&store.Record{
Key: "bar",
Value: []byte("baz"),
},
)
if err != nil {
t.Error(err)
}
err = sqlStore.Write(
2019-11-01 17:13:21 +03:00
&store.Record{
Key: "qux",
Value: []byte("aasad"),
},
)
if err != nil {
t.Error(err)
}
err = sqlStore.Delete("qux")
if err != nil {
t.Error(err)
}
err = sqlStore.Write(&store.Record{
Key: "test",
Value: []byte("bar"),
Expiry: time.Second * 10,
2019-11-01 17:13:21 +03:00
})
if err != nil {
t.Error(err)
}
records, err := sqlStore.Read("test")
2019-11-01 17:13:21 +03:00
if err != nil {
t.Error(err)
}
t.Logf("%# v\n", pretty.Formatter(records))
if string(records[0].Value) != "bar" {
t.Error("Expected bar, got ", string(records[0].Value))
2019-11-01 17:13:21 +03:00
}
time.Sleep(11 * time.Second)
_, err = sqlStore.Read("test")
switch err {
case nil:
2019-11-01 17:13:21 +03:00
t.Error("Key test should have expired")
default:
t.Error(err)
case store.ErrNotFound:
break
2019-11-01 17:13:21 +03:00
}
sqlStore.Delete("bar")
sqlStore.Write(&store.Record{Key: "aaa", Value: []byte("bbb"), Expiry: 5 * time.Second})
sqlStore.Write(&store.Record{Key: "aaaa", Value: []byte("bbb"), Expiry: 5 * time.Second})
sqlStore.Write(&store.Record{Key: "aaaaa", Value: []byte("bbb"), Expiry: 5 * time.Second})
results, err := sqlStore.Read("a", store.ReadPrefix())
if err != nil {
t.Error(err)
}
if len(results) != 3 {
t.Fatal("Results should have returned 3 records")
}
time.Sleep(6 * time.Second)
results, err = sqlStore.Read("a", store.ReadPrefix())
if err != nil {
t.Error(err)
}
if len(results) != 0 {
t.Fatal("Results should have returned 0 records")
}
2019-11-01 17:13:21 +03:00
}