dndex/server/auth/scope_test.go

147 lines
2.7 KiB
Go

package auth
import (
"context"
"local/dndex/storage"
"local/dndex/storage/entity"
"net/http"
"net/http/httptest"
"testing"
"github.com/google/uuid"
)
func TestScopeFromCtx(t *testing.T) {
var scope Scope
if ok := scope.fromCtx(context.TODO()); ok {
t.Fatal(ok)
}
ctxScope := Scope{
Namespace: uuid.New().String(),
EntityName: uuid.New().String(),
EntityID: uuid.New().String(),
}
ctx := context.WithValue(context.TODO(), ScopeKey, ctxScope)
if ok := scope.fromCtx(ctx); !ok {
t.Fatal(ok)
} else if ctxScope != scope {
t.Fatal(scope)
}
}
func TestScopeFromToken(t *testing.T) {
var scope Scope
r := httptest.NewRequest(http.MethodGet, "/", nil)
if ok := scope.fromToken(r); ok {
t.Fatal(ok)
}
token := Token{
Namespace: uuid.New().String(),
}
obf, _ := token.Obfuscate()
r.AddCookie(&http.Cookie{
Name: AuthKey,
Value: obf,
})
if ok := scope.fromToken(r); !ok {
t.Fatal(ok)
}
}
func TestScopeFromPath(t *testing.T) {
cases := map[string]struct {
ok bool
id string
}{
"/": {},
"/hello": {},
"/hello/": {},
"/hello/entity": {},
"/entity": {},
"/entity/": {},
"/entity/id": {
ok: true,
id: "id",
},
"/entity/id/": {
ok: true,
id: "id",
},
"/entity/id/excess": {
ok: true,
id: "id",
},
"/entity/id#excess": {
ok: true,
id: "id",
},
"/entity/id?excess": {
ok: true,
id: "id",
},
}
for name, d := range cases {
c := d
path := name
t.Run(name, func(t *testing.T) {
r := httptest.NewRequest(http.MethodGet, path, nil)
var scope Scope
ok := scope.fromPath(r.URL.Path)
if ok != c.ok {
t.Fatal(c.ok, ok)
}
if scope.EntityID != c.id {
t.Fatalf("want %q, got %q", c.id, scope.EntityID)
}
})
}
}
// func (s *Scope) fromGraph(ctx context.Context, g storage.RateLimitedGraph) bool {
func TestScopeFromGraph(t *testing.T) {
namespace := uuid.New().String()
id := uuid.New().String()
name := uuid.New().String()
gEmpty := storage.NewRateLimitedGraph()
gOne := storage.NewRateLimitedGraph()
if err := gOne.Insert(context.TODO(), namespace, entity.One{ID: id, Name: name}); err != nil {
t.Fatal(err)
}
scope := Scope{
Namespace: namespace,
}
if ok := scope.fromGraph(context.TODO(), gEmpty); ok {
t.Fatal(ok)
} else if scope.EntityName != "" {
t.Fatal(scope)
}
if ok := scope.fromGraph(context.TODO(), gOne); ok {
t.Fatal(ok)
} else if scope.EntityName != "" {
t.Fatal(scope)
}
scope.EntityID = id
if ok := scope.fromGraph(context.TODO(), gEmpty); ok {
t.Fatal(ok)
} else if scope.EntityName != "" {
t.Fatal(scope)
}
if ok := scope.fromGraph(context.TODO(), gOne); !ok {
t.Fatal(ok)
} else if scope.EntityName != name {
t.Fatal(scope)
}
}