109 lines
2.1 KiB
Go
109 lines
2.1 KiB
Go
|
package user
|
||
|
|
||
|
import (
|
||
|
"context"
|
||
|
"log"
|
||
|
"testing"
|
||
|
|
||
|
"git.dotya.ml/mirre-mt/pcmt/ent"
|
||
|
"git.dotya.ml/mirre-mt/pcmt/slogging"
|
||
|
_ "github.com/xiaoqidun/entps"
|
||
|
)
|
||
|
|
||
|
func TestUserExists(t *testing.T) {
|
||
|
t.Parallel()
|
||
|
|
||
|
db := supplyDBClient()
|
||
|
if db == nil {
|
||
|
t.Error("could not connect to db")
|
||
|
}
|
||
|
defer db.Close()
|
||
|
|
||
|
username := "dude"
|
||
|
email := "dude@b.cc"
|
||
|
ctx := getCtx()
|
||
|
|
||
|
usernameFound, err := UsernameExists(ctx, db, username)
|
||
|
if err != nil {
|
||
|
t.Errorf("error checking for username {%s} existence: %q",
|
||
|
username,
|
||
|
err,
|
||
|
)
|
||
|
}
|
||
|
|
||
|
if usernameFound {
|
||
|
t.Errorf("unexpected: user{%s} should not have been found",
|
||
|
username,
|
||
|
)
|
||
|
}
|
||
|
|
||
|
if _, err := EmailExists(ctx, db, email); err != nil {
|
||
|
t.Errorf("unexpected: user email '%s' should not have been found",
|
||
|
email,
|
||
|
)
|
||
|
}
|
||
|
|
||
|
usr, err := CreateUser(ctx, db, email, username, "so strong")
|
||
|
if err != nil {
|
||
|
t.Fatalf("failed to create user, error: %q", err)
|
||
|
} else if usr == nil {
|
||
|
t.Fatal("got nil usr back")
|
||
|
}
|
||
|
|
||
|
if usr.Username != username {
|
||
|
t.Errorf("got back wrong username, want: %s, got: %s", username, usr.Username)
|
||
|
}
|
||
|
|
||
|
usernameFound, err = UsernameExists(ctx, db, username)
|
||
|
if err != nil {
|
||
|
t.Errorf("error checking for username {%s} existence: %q",
|
||
|
username,
|
||
|
err,
|
||
|
)
|
||
|
}
|
||
|
|
||
|
if !usernameFound {
|
||
|
t.Errorf("unexpected: user{%s} should not have been found",
|
||
|
username,
|
||
|
)
|
||
|
}
|
||
|
|
||
|
exists, err := Exists(ctx, db, username, email)
|
||
|
if err != nil {
|
||
|
t.Errorf("error checking whether user exists: %q", err)
|
||
|
}
|
||
|
|
||
|
if !exists {
|
||
|
t.Errorf("unexpected: user{%s} does not exists and they should", username)
|
||
|
}
|
||
|
}
|
||
|
|
||
|
func supplyDBClient() *ent.Client {
|
||
|
connstr := "file:ent_tests?mode=memory&cache=shared&_fk=1"
|
||
|
|
||
|
db, err := ent.Open("sqlite3", connstr)
|
||
|
if err != nil {
|
||
|
log.Printf("failed to open a connection to sqlite %q\n", err)
|
||
|
return nil
|
||
|
}
|
||
|
|
||
|
if err = db.Schema.Create(context.Background()); err != nil {
|
||
|
log.Printf("failed creating schema resources: %v", err)
|
||
|
return nil
|
||
|
}
|
||
|
|
||
|
return db
|
||
|
}
|
||
|
|
||
|
func getCtx() context.Context {
|
||
|
l := slogging.Init(false)
|
||
|
|
||
|
ctx := context.WithValue(
|
||
|
context.Background(),
|
||
|
CtxKey{},
|
||
|
l,
|
||
|
)
|
||
|
|
||
|
return ctx
|
||
|
}
|