Files
namespace/context_test.go
zeekayandHanzo Dev f9fcf0e65d Carry the namespace on the context
A namespace names the entity a piece of work acts for, so it has to reach the
store that opens a database or builds a key. Threading it through every call
between the handler and the store means one missed parameter reads another
entity's data.

Every service needs this, so the carrier belongs here. A service-local copy is
how two services end up disagreeing about what an unset namespace means: the
zero value is not carried, an unset context reports ok=false rather than
standing for everything, and spanning entities is the explicit system kind.

Co-authored-by: Hanzo Dev <[email protected]>
2026-08-01 10:42:56 -07:00

57 lines
1.6 KiB
Go

// Copyright (C) 2026, Hanzo AI. All rights reserved.
// See the file LICENSE for licensing terms.
package namespace
import (
"context"
"testing"
)
func TestContextRoundTrip(t *testing.T) {
ns := MustOrg("acme")
got, ok := FromContext(NewContext(context.Background(), ns))
if !ok {
t.Fatal("namespace did not survive the context")
}
if got.String() != ns.String() {
t.Fatalf("got %q, want %q", got, ns)
}
}
// Nothing set means nothing set. Reporting ok here would let a caller treat an
// unset namespace as permission to read every entity.
func TestFromContextReportsUnset(t *testing.T) {
if _, ok := FromContext(context.Background()); ok {
t.Fatal("an unscoped context must report ok=false")
}
}
// Storing the zero namespace would turn "never set" into "set to nothing".
func TestZeroNamespaceIsNotCarried(t *testing.T) {
ctx := NewContext(context.Background(), Namespace{})
if _, ok := FromContext(ctx); ok {
t.Fatal("the zero namespace must not be carried")
}
}
func TestReScopingReplaces(t *testing.T) {
ctx := NewContext(NewContext(context.Background(), MustOrg("a")), MustOrg("b"))
got, _ := FromContext(ctx)
if got.ID() != "b" {
t.Fatalf("got %q, want the inner scope to win", got.ID())
}
}
func TestIsSystem(t *testing.T) {
if !IsSystem(NewContext(context.Background(), System())) {
t.Fatal("system namespace must report IsSystem")
}
if IsSystem(NewContext(context.Background(), MustOrg("acme"))) {
t.Fatal("an org namespace must not report IsSystem")
}
if IsSystem(context.Background()) {
t.Fatal("an unscoped context must not report IsSystem")
}
}