multi tenant chats (#79)

This commit is contained in:
Dominic Wong
2021-03-25 21:34:57 +00:00
committed by GitHub
parent 8e38c8b834
commit 88085c7044
9 changed files with 75 additions and 43 deletions

View File

@@ -1,17 +1,18 @@
package handler_test
import (
"context"
"database/sql"
"os"
"testing"
"time"
"github.com/micro/micro/v3/service/auth"
"github.com/micro/services/chats/handler"
pb "github.com/micro/services/chats/proto"
"github.com/stretchr/testify/assert"
"github.com/golang/protobuf/ptypes/timestamp"
"gorm.io/driver/postgres"
"gorm.io/gorm"
)
func testHandler(t *testing.T) *handler.Chats {
@@ -20,22 +21,19 @@ func testHandler(t *testing.T) *handler.Chats {
if len(addr) == 0 {
addr = "postgresql://postgres@localhost:5432/postgres?sslmode=disable"
}
db, err := gorm.Open(postgres.Open(addr), &gorm.Config{})
sqlDB, err := sql.Open("pgx", addr)
if err != nil {
t.Fatalf("Error connecting to database: %v", err)
t.Fatalf("Failed to open connection to DB %s", err)
}
// clean any data from a previous run
if err := db.Exec("DROP TABLE IF EXISTS chats, messages CASCADE").Error; err != nil {
if _, err := sqlDB.Exec("DROP TABLE IF EXISTS micro_chats, micro_messages CASCADE"); err != nil {
t.Fatalf("Error cleaning database: %v", err)
}
// migrate the database
if err := db.AutoMigrate(&handler.Chat{}, &handler.Message{}); err != nil {
t.Fatalf("Error migrating database: %v", err)
}
return &handler.Chats{DB: db, Time: func() time.Time { return time.Unix(1611327673, 0) }}
h := &handler.Chats{Time: func() time.Time { return time.Unix(1611327673, 0) }}
h.DBConn(sqlDB).Migrations(&handler.Chat{}, &handler.Message{})
return h
}
func assertChatsMatch(t *testing.T, exp, act *pb.Chat) {
@@ -64,8 +62,8 @@ func assertChatsMatch(t *testing.T, exp, act *pb.Chat) {
// postgres has a resolution of 100microseconds so just test that it's accurate to the second
func microSecondTime(t *timestamp.Timestamp) time.Time {
tt:=t.AsTime()
return time.Unix(tt.Unix(), int64( tt.Nanosecond() - tt.Nanosecond() % 1000))
tt := t.AsTime()
return time.Unix(tt.Unix(), int64(tt.Nanosecond()-tt.Nanosecond()%1000))
}
func assertMessagesMatch(t *testing.T, exp, act *pb.Message) {
@@ -91,3 +89,9 @@ func assertMessagesMatch(t *testing.T, exp, act *pb.Message) {
}
assert.True(t, microSecondTime(exp.SentAt).Equal(microSecondTime(act.SentAt)))
}
func microAccountCtx() context.Context {
return auth.ContextWithAccount(context.TODO(), &auth.Account{
Issuer: "micro",
})
}