refactor: testing from the beginning. a journey in 150k lines of tests to none
This commit is contained in:
651 files changed
-146443
No files matched your search
@@ -1,86 +0,0 @@
|
||||
package config
|
||||
|
||||
import "testing"
|
||||
|
||||
// TestChatConfigFrontEnds is the single definition of "a chat front-end is
|
||||
// configured". Two surfaces read it -- the daemon's channel status manager and
|
||||
// the configuration projection published for the extracted UI process -- so a
|
||||
// front-end counted by one and missed by the other is a dashboard that
|
||||
// contradicts itself (GitHub #821).
|
||||
func TestChatConfigFrontEnds(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
chat ChatConfig
|
||||
want map[string]bool
|
||||
}{
|
||||
{
|
||||
name: "nothing configured",
|
||||
chat: ChatConfig{},
|
||||
want: map[string]bool{"telegram": false, "email": false, "webhook": false},
|
||||
},
|
||||
{
|
||||
name: "telegram bot token through the secret engine",
|
||||
chat: ChatConfig{Telegram: TelegramConfig{Token: SecretRef{Engine: "builtin", Key: "telegram"}}},
|
||||
want: map[string]bool{"telegram": true, "email": false, "webhook": false},
|
||||
},
|
||||
{
|
||||
name: "inbound mail gateway",
|
||||
chat: ChatConfig{Email: EmailConfig{ListenAddr: "127.0.0.1:2525"}},
|
||||
want: map[string]bool{"telegram": false, "email": true, "webhook": false},
|
||||
},
|
||||
{
|
||||
name: "webhook gateway",
|
||||
chat: ChatConfig{WebhookAddr: "127.0.0.1:9099"},
|
||||
want: map[string]bool{"telegram": false, "email": false, "webhook": true},
|
||||
},
|
||||
{
|
||||
name: "every front-end at once",
|
||||
chat: ChatConfig{
|
||||
Telegram: TelegramConfig{Token: SecretRef{Engine: "env", Key: "TELEGRAM_TOKEN"}},
|
||||
Email: EmailConfig{ListenAddr: "127.0.0.1:2525"},
|
||||
WebhookAddr: "127.0.0.1:9099",
|
||||
},
|
||||
want: map[string]bool{"telegram": true, "email": true, "webhook": true},
|
||||
},
|
||||
{
|
||||
// Whitespace is not a value: " " cannot be listened on.
|
||||
name: "whitespace-only values are not configured",
|
||||
chat: ChatConfig{
|
||||
Email: EmailConfig{ListenAddr: " "},
|
||||
WebhookAddr: "\t",
|
||||
},
|
||||
want: map[string]bool{"telegram": false, "email": false, "webhook": false},
|
||||
},
|
||||
}
|
||||
|
||||
for _, tc := range tests {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
got := map[string]bool{}
|
||||
for _, frontEnd := range tc.chat.FrontEnds() {
|
||||
if frontEnd.ID == "" || frontEnd.Name == "" {
|
||||
t.Errorf("front-end %+v is missing an identifier or a name", frontEnd)
|
||||
}
|
||||
if _, seen := got[frontEnd.ID]; seen {
|
||||
t.Errorf("front-end %q listed twice", frontEnd.ID)
|
||||
}
|
||||
got[frontEnd.ID] = frontEnd.Configured
|
||||
}
|
||||
if len(got) != len(tc.want) {
|
||||
t.Fatalf("FrontEnds() = %+v, want one entry per front-end %+v", got, tc.want)
|
||||
}
|
||||
for id, want := range tc.want {
|
||||
if got[id] != want {
|
||||
t.Errorf("front-end %q configured = %v, want %v", id, got[id], want)
|
||||
}
|
||||
}
|
||||
|
||||
var anyConfigured bool
|
||||
for _, configured := range got {
|
||||
anyConfigured = anyConfigured || configured
|
||||
}
|
||||
if got, want := tc.chat.AnyFrontEndConfigured(), anyConfigured; got != want {
|
||||
t.Errorf("AnyFrontEndConfigured() = %v, want %v", got, want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -1,93 +0,0 @@
|
||||
package config
|
||||
|
||||
import (
|
||||
"testing"
|
||||
)
|
||||
|
||||
// TestConfigCloneDeepCopiesReferenceFields pins that Clone returns a
|
||||
// value sharing no memory with the original: mutating the clone's maps
|
||||
// and slices must not touch the original. A shallow copy here would
|
||||
// silently let a failed overlay decode mutate the published snapshot.
|
||||
func TestConfigCloneDeepCopiesReferenceFields(t *testing.T) {
|
||||
enabled := true
|
||||
orig := Config{
|
||||
Models: map[string]string{"builder": "m"},
|
||||
ModelLimits: map[string]ModelLimits{"m": {ContextWindow: 128_000}},
|
||||
Repos: []Repo{{Gate: [][]string{{"task", "check"}}, Protect: []string{"p"}}},
|
||||
DiffCapLines: new(400),
|
||||
Identities: []IdentityConfig{{
|
||||
Models: map[string]string{"planner": "m2"},
|
||||
DiffCapLines: new(50),
|
||||
Repos: []Repo{{Gate: [][]string{{"go", "vet"}}}},
|
||||
}},
|
||||
Dispatch: Dispatch{Labels: map[string]string{"q": "archie:q"}},
|
||||
Tools: ToolsConfig{
|
||||
MCPServers: []MCPServer{{Headers: map[string]string{"A": "b"}, Args: []string{"x"}}},
|
||||
WebFetch: WebFetchConfig{Enabled: &enabled},
|
||||
},
|
||||
Chat: ChatConfig{Telegram: TelegramConfig{AllowedUserIDs: []int64{1}}},
|
||||
Extra: map[string]any{"custom": 1},
|
||||
Bindings: BindingsConfig{PreviousEncryptionKeys: []SecretRef{{Engine: "env", Key: "K0"}}},
|
||||
Services: Services{
|
||||
ServiceNameState: {Target: "127.0.0.1:9090", TargetToken: "secret"},
|
||||
},
|
||||
}
|
||||
|
||||
got := orig.Clone()
|
||||
got.Models["builder"] = "changed"
|
||||
got.ModelLimits["m"] = ModelLimits{ContextWindow: 1}
|
||||
got.Repos[0].Gate[0][0] = "changed"
|
||||
got.Repos[0].Protect[0] = "changed"
|
||||
got.Identities[0].Models["planner"] = "changed"
|
||||
got.Identities[0].Repos[0].Gate[0][0] = "changed"
|
||||
got.Dispatch.Labels["q"] = "changed"
|
||||
got.Tools.MCPServers[0].Headers["A"] = "changed"
|
||||
got.Tools.MCPServers[0].Args[0] = "changed"
|
||||
got.Chat.Telegram.AllowedUserIDs[0] = 99
|
||||
got.Extra["custom"] = 2
|
||||
got.Bindings.PreviousEncryptionKeys[0] = SecretRef{Engine: "env", Key: "changed"}
|
||||
*got.Tools.WebFetch.Enabled = false
|
||||
*got.DiffCapLines = 1
|
||||
*got.Identities[0].DiffCapLines = 2
|
||||
got.Services[ServiceNameState] = ServiceConnection{Target: "changed"}
|
||||
|
||||
if orig.Models["builder"] != "m" {
|
||||
t.Error("Models map is shared")
|
||||
}
|
||||
if orig.ModelLimits["m"].ContextWindow != 128_000 {
|
||||
t.Error("ModelLimits map is shared")
|
||||
}
|
||||
if orig.Repos[0].Gate[0][0] != "task" || orig.Repos[0].Protect[0] != "p" {
|
||||
t.Error("Repo nested slices are shared")
|
||||
}
|
||||
if orig.Identities[0].Models["planner"] != "m2" || orig.Identities[0].Repos[0].Gate[0][0] != "go" {
|
||||
t.Error("Identity nested fields are shared")
|
||||
}
|
||||
if orig.Dispatch.Labels["q"] != "archie:q" {
|
||||
t.Error("Dispatch.Labels map is shared")
|
||||
}
|
||||
if orig.Tools.MCPServers[0].Headers["A"] != "b" || orig.Tools.MCPServers[0].Args[0] != "x" {
|
||||
t.Error("MCP server fields are shared")
|
||||
}
|
||||
if orig.Chat.Telegram.AllowedUserIDs[0] != 1 {
|
||||
t.Error("Telegram.AllowedUserIDs is shared")
|
||||
}
|
||||
if orig.Extra["custom"] != 1 {
|
||||
t.Error("Extra map is shared")
|
||||
}
|
||||
if orig.Bindings.PreviousEncryptionKeys[0].Key != "K0" {
|
||||
t.Error("Bindings.PreviousEncryptionKeys is shared")
|
||||
}
|
||||
if orig.DiffCap() != 400 {
|
||||
t.Errorf("DiffCapLines pointer is shared: orig.DiffCap() = %d, want 400", orig.DiffCap())
|
||||
}
|
||||
if got := orig.Identities[0].DiffCapLines; got == nil || *got != 50 {
|
||||
t.Errorf("Identities[0].DiffCapLines pointer is shared: got %v, want 50", got)
|
||||
}
|
||||
if !*orig.Tools.WebFetch.Enabled {
|
||||
t.Error("WebFetch.Enabled pointer is shared")
|
||||
}
|
||||
if orig.Services[ServiceNameState].TargetToken != "secret" {
|
||||
t.Error("Services map is shared")
|
||||
}
|
||||
}
|
||||
@@ -1,538 +0,0 @@
|
||||
package config
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"reflect"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/BurntSushi/toml"
|
||||
)
|
||||
|
||||
func TestTaskConfigToConfigRoundTrip(t *testing.T) {
|
||||
cfg := Config{
|
||||
BotUser: "archie-bot",
|
||||
BotEmail: "archie-bot@users.noreply.github.com",
|
||||
DiffCapLines: new(321),
|
||||
Models: map[string]string{"builder": "anthropic/claude"},
|
||||
Budgets: Budgets{MaxSteps: 12, WallClock: Duration(45 * time.Minute), GateMaxFailures: 3},
|
||||
Dispatch: Dispatch{Trigger: "label", AckReaction: "eyes", Labels: map[string]string{"working": "bot:working"}},
|
||||
Notify: Notify{Webhook: "https://notify.example.test/hook"},
|
||||
Forge: Forge{Type: "github", Host: "https://forge.example.test", Token: SecretRef{Engine: "env", Key: "TOP_SECRET"}},
|
||||
Tools: ToolsConfig{Policy: ToolPolicy{MaxResultChars: 50_000, SpillDir: "/var/tmp/archie-spill"}},
|
||||
}
|
||||
|
||||
got := cfg.ForTask().ToConfig()
|
||||
if got.Tools.Policy != cfg.Tools.Policy {
|
||||
t.Fatalf("Tools.Policy = %#v, want %#v", got.Tools.Policy, cfg.Tools.Policy)
|
||||
}
|
||||
if !reflect.DeepEqual(got.Models, cfg.Models) {
|
||||
t.Fatalf("Models = %#v, want %#v", got.Models, cfg.Models)
|
||||
}
|
||||
if got.Budgets != cfg.Budgets {
|
||||
t.Fatalf("Budgets = %#v, want %#v", got.Budgets, cfg.Budgets)
|
||||
}
|
||||
if !reflect.DeepEqual(got.Dispatch, cfg.Dispatch) {
|
||||
t.Fatalf("Dispatch = %#v, want %#v", got.Dispatch, cfg.Dispatch)
|
||||
}
|
||||
// Compared by effective value, not pointer: the round trip through
|
||||
// TaskConfig carries the resolved cap and rebuilds a fresh pointer.
|
||||
if got.DiffCap() != cfg.DiffCap() {
|
||||
t.Fatalf("DiffCap() = %d, want %d", got.DiffCap(), cfg.DiffCap())
|
||||
}
|
||||
if got.Notify != cfg.Notify {
|
||||
t.Fatalf("Notify = %#v, want %#v", got.Notify, cfg.Notify)
|
||||
}
|
||||
if got.Forge.Host != cfg.Forge.Host {
|
||||
t.Fatalf("Forge.Host = %q, want %q", got.Forge.Host, cfg.Forge.Host)
|
||||
}
|
||||
if got.Forge.Token != (SecretRef{}) {
|
||||
t.Fatalf("Forge.Token = %#v, want zero value (never carried by TaskConfig)", got.Forge.Token)
|
||||
}
|
||||
}
|
||||
|
||||
func TestMCPServerTOMLIncludesClientWorkingDirectory(t *testing.T) {
|
||||
var cfg Config
|
||||
if _, err := toml.Decode(`
|
||||
[[tools.mcp_servers]]
|
||||
name = "desktop-commander"
|
||||
transport = "stdio"
|
||||
command = "npx"
|
||||
args = ["-y", "@wonderwhy-er/desktop-commander@0.2.46", "--no-onboarding"]
|
||||
work_dir = "/workspace"
|
||||
`, &cfg); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(cfg.Tools.MCPServers) != 1 {
|
||||
t.Fatalf("MCPServers = %#v, want one server", cfg.Tools.MCPServers)
|
||||
}
|
||||
server := cfg.Tools.MCPServers[0]
|
||||
if server.Name != "desktop-commander" || server.Command != "npx" || server.WorkDir != "/workspace" {
|
||||
t.Fatalf("MCP server = %#v", server)
|
||||
}
|
||||
if len(server.Args) != 3 || server.Args[1] != "@wonderwhy-er/desktop-commander@0.2.46" {
|
||||
t.Fatalf("MCP args = %v", server.Args)
|
||||
}
|
||||
}
|
||||
|
||||
func TestMCPServerParallelToolCallsDecodesFromTOML(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
server string
|
||||
want bool
|
||||
}{
|
||||
{
|
||||
name: "absent key leaves the server serialized",
|
||||
server: `
|
||||
[[tools.mcp_servers]]
|
||||
name = "desktop-commander"
|
||||
command = "npx"
|
||||
`,
|
||||
},
|
||||
{
|
||||
name: "parallel_tool_calls opts the server in",
|
||||
server: `
|
||||
[[tools.mcp_servers]]
|
||||
name = "desktop-commander"
|
||||
command = "npx"
|
||||
parallel_tool_calls = true
|
||||
`,
|
||||
want: true,
|
||||
},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
var cfg Config
|
||||
if _, err := toml.Decode(tt.server, &cfg); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(cfg.Tools.MCPServers) != 1 {
|
||||
t.Fatalf("MCPServers = %#v, want one server", cfg.Tools.MCPServers)
|
||||
}
|
||||
if got := cfg.Tools.MCPServers[0].ParallelToolCalls; got != tt.want {
|
||||
t.Fatalf("ParallelToolCalls = %t, want %t", got, tt.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestChatModelCatalogDecodesFromTOML(t *testing.T) {
|
||||
var cfg Config
|
||||
if _, err := toml.Decode(`
|
||||
[chat]
|
||||
models = ["openai/gpt-5.6-sol", "openrouter/openai/gpt-5.6-sol"]
|
||||
`, &cfg); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(cfg.Chat.Models) != 2 || cfg.Chat.Models[1] != "openrouter/openai/gpt-5.6-sol" {
|
||||
t.Fatalf("chat models = %v", cfg.Chat.Models)
|
||||
}
|
||||
}
|
||||
|
||||
func TestConfigForTaskJSONRoundTrip(t *testing.T) {
|
||||
cfg := Config{
|
||||
DiffCapLines: new(321),
|
||||
Models: map[string]string{
|
||||
"builder": "anthropic/claude",
|
||||
"planner": "openai/gpt",
|
||||
},
|
||||
Budgets: Budgets{
|
||||
MaxSteps: 12,
|
||||
|
||||
WallClock: Duration(45 * time.Minute),
|
||||
GateMaxFailures: 3,
|
||||
},
|
||||
MaxRetries: 7,
|
||||
Dispatch: Dispatch{
|
||||
Trigger: "label",
|
||||
AckReaction: "eyes",
|
||||
Labels: map[string]string{"working": "bot:working"},
|
||||
},
|
||||
Notify: Notify{Webhook: "https://notify.example.test/hook"},
|
||||
Forge: Forge{
|
||||
Type: "github",
|
||||
Host: "https://forge.example.test",
|
||||
Token: SecretRef{Engine: "env", Key: "TOP_SECRET_FORGE_TOKEN"},
|
||||
},
|
||||
Providers: map[string]Provider{
|
||||
"secret": {APIKeyEnv: "TOP_SECRET_PROVIDER_TOKEN"},
|
||||
},
|
||||
NATS: NATSConfig{TokenEnv: "TOP_SECRET_NATS_TOKEN"},
|
||||
Tools: ToolsConfig{Policy: ToolPolicy{MaxResultChars: 50_000, SpillDir: "/var/tmp/archie-spill"}},
|
||||
Review: Review{PrecisionGate: true, ApproveBeforePost: true},
|
||||
}
|
||||
|
||||
want := TaskConfig{
|
||||
BotUser: cfg.BotUser,
|
||||
BotEmail: cfg.BotEmail,
|
||||
Models: cfg.Models,
|
||||
Budgets: cfg.Budgets,
|
||||
MaxRetries: cfg.MaxRetries,
|
||||
Dispatch: cfg.Dispatch,
|
||||
DiffCapLines: cfg.DiffCap(),
|
||||
Notify: cfg.Notify,
|
||||
Forge: TaskForge{Host: cfg.Forge.Host},
|
||||
ToolPolicy: cfg.Tools.Policy,
|
||||
Review: cfg.Review,
|
||||
}
|
||||
got := cfg.ForTask()
|
||||
if !reflect.DeepEqual(got, want) {
|
||||
t.Fatalf("ForTask() = %#v, want %#v", got, want)
|
||||
}
|
||||
cfg.Models["source-only"] = "source/model"
|
||||
if _, ok := got.Models["source-only"]; ok {
|
||||
t.Fatal("ForTask().Models aliases Config.Models")
|
||||
}
|
||||
got.Models["task-only"] = "task/model"
|
||||
if _, ok := cfg.Models["task-only"]; ok {
|
||||
t.Fatal("Config.Models aliases ForTask().Models")
|
||||
}
|
||||
cfg.Dispatch.Labels["source-only"] = "source:label"
|
||||
if _, ok := got.Dispatch.Labels["source-only"]; ok {
|
||||
t.Fatal("ForTask().Dispatch.Labels aliases Config.Dispatch.Labels")
|
||||
}
|
||||
got.Dispatch.Labels["task-only"] = "task:label"
|
||||
if _, ok := cfg.Dispatch.Labels["task-only"]; ok {
|
||||
t.Fatal("Config.Dispatch.Labels aliases ForTask().Dispatch.Labels")
|
||||
}
|
||||
|
||||
data, err := json.Marshal(got)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
assertJSONKeys(t, data, "bot_user", "bot_email", "models", "budgets", "max_retries", "dispatch", "diff_cap_lines", "notify", "forge", "tool_policy", "review")
|
||||
|
||||
var forgePayload map[string]json.RawMessage
|
||||
var payload map[string]json.RawMessage
|
||||
if err := json.Unmarshal(data, &payload); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var budgetsPayload map[string]json.RawMessage
|
||||
if err := json.Unmarshal(payload["budgets"], &budgetsPayload); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if string(budgetsPayload["wall_clock"]) != `"45m0s"` {
|
||||
t.Fatalf("wall_clock = %s, want JSON duration string", budgetsPayload["wall_clock"])
|
||||
}
|
||||
if err := json.Unmarshal(payload["forge"], &forgePayload); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if !reflect.DeepEqual(forgePayload, map[string]json.RawMessage{
|
||||
"host": json.RawMessage(`"https://forge.example.test"`),
|
||||
}) {
|
||||
t.Fatalf("forge payload = %s, want only host", payload["forge"])
|
||||
}
|
||||
for _, ref := range []string{
|
||||
cfg.Forge.Token.Key,
|
||||
cfg.Providers["secret"].APIKeyEnv,
|
||||
cfg.NATS.TokenEnv,
|
||||
} {
|
||||
if strings.Contains(string(data), ref) {
|
||||
t.Fatalf("task config JSON contains credential reference %q: %s", ref, data)
|
||||
}
|
||||
}
|
||||
|
||||
var roundTripped TaskConfig
|
||||
if err := json.Unmarshal(data, &roundTripped); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if !reflect.DeepEqual(roundTripped, got) {
|
||||
t.Fatalf("JSON round trip = %#v, want %#v", roundTripped, got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRepoJSONRoundTrip(t *testing.T) {
|
||||
repo := Repo{
|
||||
Owner: "acme",
|
||||
Name: "widget",
|
||||
Base: "develop",
|
||||
Gate: [][]string{{"task", "check"}, {"go", "test", "./..."}},
|
||||
Protect: []string{"_templ.go", ".generated"},
|
||||
Ecosystem: "go",
|
||||
Preflight: [][]string{{"go", "version"}},
|
||||
TestGlob: "*_test.go",
|
||||
PersistentStorage: true,
|
||||
MaxRetries: 4,
|
||||
AllowConcurrent: true,
|
||||
}
|
||||
|
||||
data, err := json.Marshal(repo)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
assertJSONKeys(
|
||||
t, data,
|
||||
"owner",
|
||||
"name",
|
||||
"base",
|
||||
"gate",
|
||||
"protect",
|
||||
"ecosystem",
|
||||
"preflight",
|
||||
"test_glob",
|
||||
"persistent_storage",
|
||||
"max_retries",
|
||||
"allow_concurrent",
|
||||
)
|
||||
|
||||
var got Repo
|
||||
if err := json.Unmarshal(data, &got); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if !reflect.DeepEqual(got, repo) {
|
||||
t.Fatalf("JSON round trip = %#v, want %#v", got, repo)
|
||||
}
|
||||
}
|
||||
|
||||
func assertJSONKeys(t *testing.T, data []byte, want ...string) {
|
||||
t.Helper()
|
||||
|
||||
var payload map[string]json.RawMessage
|
||||
if err := json.Unmarshal(data, &payload); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
got := make(map[string]bool, len(payload))
|
||||
for key := range payload {
|
||||
got[key] = true
|
||||
}
|
||||
wantSet := make(map[string]bool, len(want))
|
||||
for _, key := range want {
|
||||
wantSet[key] = true
|
||||
}
|
||||
if !reflect.DeepEqual(got, wantSet) {
|
||||
t.Fatalf("JSON keys = %v, want %v", got, wantSet)
|
||||
}
|
||||
}
|
||||
|
||||
func TestDispatchDefaults(t *testing.T) {
|
||||
// Simulate a config with no [dispatch] section -- all fields zero.
|
||||
var d Dispatch
|
||||
d.Labels = map[string]string{}
|
||||
|
||||
// Per-key defaults (mimicking Load's loop).
|
||||
for k, v := range dispatchLabelDefaults {
|
||||
if d.Labels[k] == "" {
|
||||
d.Labels[k] = v
|
||||
}
|
||||
}
|
||||
if d.Trigger == "" {
|
||||
d.Trigger = "assignee"
|
||||
}
|
||||
if d.AckReaction == "" {
|
||||
d.AckReaction = "eyes"
|
||||
}
|
||||
|
||||
// StateLabel should return the default agent:* labels.
|
||||
if got := d.StateLabel("queued"); got != "agent:queued" {
|
||||
t.Errorf("queued: got %q, want agent:queued", got)
|
||||
}
|
||||
if got := d.StateLabel("working"); got != "agent:working" {
|
||||
t.Errorf("working: got %q, want agent:working", got)
|
||||
}
|
||||
if got := d.StateLabel("waiting"); got != "agent:waiting" {
|
||||
t.Errorf("waiting: got %q, want agent:waiting", got)
|
||||
}
|
||||
if got := d.StateLabel("pr"); got != "agent:pr" {
|
||||
t.Errorf("pr: got %q, want agent:pr", got)
|
||||
}
|
||||
if got := d.StateLabel("parked"); got != "agent:parked" {
|
||||
t.Errorf("parked: got %q, want agent:parked", got)
|
||||
}
|
||||
|
||||
// Unknown state returns empty.
|
||||
if got := d.StateLabel("nonexistent"); got != "" {
|
||||
t.Errorf("nonexistent: got %q, want empty", got)
|
||||
}
|
||||
|
||||
// AckReaction default.
|
||||
if d.AckReaction != "eyes" {
|
||||
t.Errorf("AckReaction: got %q, want eyes", d.AckReaction)
|
||||
}
|
||||
|
||||
// Trigger default.
|
||||
if d.Trigger != "assignee" {
|
||||
t.Errorf("Trigger: got %q, want assignee", d.Trigger)
|
||||
}
|
||||
}
|
||||
|
||||
func TestDispatchCustomLabels(t *testing.T) {
|
||||
d := Dispatch{
|
||||
Trigger: "label",
|
||||
AckReaction: "",
|
||||
Labels: map[string]string{
|
||||
"queued": "bot:queued",
|
||||
"working": "bot:working",
|
||||
"parked": "bot:parked",
|
||||
// "waiting" and "pr" intentionally missing -- should fall back.
|
||||
},
|
||||
}
|
||||
|
||||
// Custom labels.
|
||||
if got := d.StateLabel("queued"); got != "bot:queued" {
|
||||
t.Errorf("queued: got %q, want bot:queued", got)
|
||||
}
|
||||
if got := d.StateLabel("parked"); got != "bot:parked" {
|
||||
t.Errorf("parked: got %q, want bot:parked", got)
|
||||
}
|
||||
|
||||
// Missing keys fall back to defaults.
|
||||
if got := d.StateLabel("waiting"); got != "agent:waiting" {
|
||||
t.Errorf("waiting: got %q, want agent:waiting (fallback)", got)
|
||||
}
|
||||
if got := d.StateLabel("pr"); got != "agent:pr" {
|
||||
t.Errorf("pr: got %q, want agent:pr (fallback)", got)
|
||||
}
|
||||
|
||||
// Empty AckReaction.
|
||||
if d.AckReaction != "" {
|
||||
t.Errorf("AckReaction: got %q, want empty", d.AckReaction)
|
||||
}
|
||||
|
||||
// LabelValues returns all six state labels.
|
||||
vals := d.LabelValues()
|
||||
if len(vals) != 6 {
|
||||
t.Errorf("LabelValues: got %d values, want 6: %v", len(vals), vals)
|
||||
}
|
||||
seen := map[string]bool{}
|
||||
for _, v := range vals {
|
||||
seen[v] = true
|
||||
}
|
||||
for _, want := range []string{"bot:queued", "bot:working", "bot:parked", "agent:waiting", "agent:pr", "agent:dead"} {
|
||||
if !seen[want] {
|
||||
t.Errorf("LabelValues missing %q", want)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestDispatchLabelValuesDedup(t *testing.T) {
|
||||
// When two state keys map to the same label string, LabelValues
|
||||
// should deduplicate.
|
||||
d := Dispatch{
|
||||
Labels: map[string]string{
|
||||
"queued": "bot:queued",
|
||||
"working": "bot:queued", // same as queued
|
||||
"parked": "bot:queued", // same again
|
||||
},
|
||||
}
|
||||
vals := d.LabelValues()
|
||||
// Should have "bot:queued" plus fallbacks for waiting, pr, and dead.
|
||||
if len(vals) != 4 {
|
||||
t.Errorf("LabelValues: got %d values, want 4: %v", len(vals), vals)
|
||||
}
|
||||
}
|
||||
|
||||
func TestEcosystemDefaults(t *testing.T) {
|
||||
// Empty ecosystem → "go" (backward compat).
|
||||
r := Repo{}
|
||||
if got := r.effectiveEcosystem(); got != "go" {
|
||||
t.Errorf("effectiveEcosystem empty: got %q, want go", got)
|
||||
}
|
||||
if got := r.ResolvedTestGlob(); got != "*_test.go" {
|
||||
t.Errorf("ResolvedTestGlob empty: got %q, want *_test.go", got)
|
||||
}
|
||||
pre := r.ResolvedPreflight()
|
||||
if len(pre) != 1 || pre[0][0] != "go" || pre[0][1] != "version" {
|
||||
t.Errorf("ResolvedPreflight empty: got %v, want [[go version]]", pre)
|
||||
}
|
||||
|
||||
// Explicit ecosystem.
|
||||
r2 := Repo{Ecosystem: "python"}
|
||||
if got := r2.ResolvedTestGlob(); got != "test_*.py" {
|
||||
t.Errorf("ResolvedTestGlob python: got %q, want test_*.py", got)
|
||||
}
|
||||
pre2 := r2.ResolvedPreflight()
|
||||
if len(pre2) != 1 || pre2[0][0] != "python" || pre2[0][1] != "--version" {
|
||||
t.Errorf("ResolvedPreflight python: got %v, want [[python --version]]", pre2)
|
||||
}
|
||||
}
|
||||
|
||||
func TestEcosystemOverrides(t *testing.T) {
|
||||
// Explicit Preflight and TestGlob always win over ecosystem.
|
||||
r := Repo{
|
||||
Ecosystem: "go",
|
||||
Preflight: [][]string{{"make", "check"}},
|
||||
TestGlob: "spec_*.py",
|
||||
}
|
||||
if got := r.ResolvedTestGlob(); got != "spec_*.py" {
|
||||
t.Errorf("ResolvedTestGlob override: got %q, want spec_*.py", got)
|
||||
}
|
||||
pre := r.ResolvedPreflight()
|
||||
if len(pre) != 1 || pre[0][0] != "make" || pre[0][1] != "check" {
|
||||
t.Errorf("ResolvedPreflight override: got %v, want [[make check]]", pre)
|
||||
}
|
||||
}
|
||||
|
||||
func TestEcosystemCustom(t *testing.T) {
|
||||
// "custom" ecosystem has no defaults -- preflight empty, test glob empty.
|
||||
r := Repo{Ecosystem: "custom"}
|
||||
if got := r.ResolvedTestGlob(); got != "" {
|
||||
t.Errorf("ResolvedTestGlob custom: got %q, want empty", got)
|
||||
}
|
||||
if got := r.ResolvedPreflight(); got != nil {
|
||||
t.Errorf("ResolvedPreflight custom: got %v, want nil", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestWebConfigTOML(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
input string
|
||||
wantListen string
|
||||
wantTrustForwarded bool
|
||||
}{
|
||||
{
|
||||
name: "default trust_forwarded_headers is false when absent",
|
||||
input: `[web]` + "\n" + `listen = "127.0.0.1:8484"`,
|
||||
wantListen: "127.0.0.1:8484",
|
||||
wantTrustForwarded: false,
|
||||
},
|
||||
{
|
||||
name: "explicit trust_forwarded_headers true",
|
||||
input: `[web]` + "\n" + `listen = "127.0.0.1:8484"` + "\n" + `trust_forwarded_headers = true`,
|
||||
wantListen: "127.0.0.1:8484",
|
||||
wantTrustForwarded: true,
|
||||
},
|
||||
{
|
||||
name: "explicit trust_forwarded_headers false",
|
||||
input: `[web]` + "\n" + `listen = "127.0.0.1:8484"` + "\n" + `trust_forwarded_headers = false`,
|
||||
wantListen: "127.0.0.1:8484",
|
||||
wantTrustForwarded: false,
|
||||
},
|
||||
}
|
||||
|
||||
for _, tc := range tests {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
var cfg Config
|
||||
if _, err := toml.Decode(tc.input, &cfg); err != nil {
|
||||
t.Fatalf("decode: %v", err)
|
||||
}
|
||||
if cfg.Web.Listen != tc.wantListen {
|
||||
t.Errorf("Web.Listen = %q, want %q", cfg.Web.Listen, tc.wantListen)
|
||||
}
|
||||
if cfg.Web.TrustForwardedHeaders != tc.wantTrustForwarded {
|
||||
t.Errorf("Web.TrustForwardedHeaders = %v, want %v", cfg.Web.TrustForwardedHeaders, tc.wantTrustForwarded)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// TestHealthURL renders the address out-of-process tooling probes. A wrong
|
||||
// address here reads as an unhealthy release and rolls back one that came up
|
||||
// fine (archie-core-1r4g).
|
||||
func TestHealthURL(t *testing.T) {
|
||||
for _, tc := range []struct{ listen, want string }{
|
||||
{"127.0.0.1:8485", "http://127.0.0.1:8485"},
|
||||
{"localhost:8485", "http://localhost:8485"},
|
||||
{"0.0.0.0:8485", "http://localhost:8485"},
|
||||
{":8485", "http://localhost:8485"},
|
||||
{"[::]:8485", "http://localhost:8485"},
|
||||
{"100.64.1.2:9000", "http://100.64.1.2:9000"},
|
||||
{" 127.0.0.1:8485 ", "http://127.0.0.1:8485"},
|
||||
{"", ""},
|
||||
} {
|
||||
if got := (Health{Listen: tc.listen}).URL(); got != tc.want {
|
||||
t.Errorf("Health{Listen: %q}.URL() = %q, want %q", tc.listen, got, tc.want)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,115 +0,0 @@
|
||||
package config
|
||||
|
||||
import (
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
// TestBoundCredentialsIsAnIntersection is the mutation-checked isolation
|
||||
// proof docs/prds/external-agent-harness.md and orgs-and-access.md require:
|
||||
// declared (what a Kit's descriptor asks for) and granted (an identity's
|
||||
// GrantedCredentials) are independent facts, and a binding's Org is a third.
|
||||
// Flip any single one of the three and the service must fall out of the
|
||||
// result -- never partially, never because another passed.
|
||||
func TestBoundCredentialsIsAnIntersection(t *testing.T) {
|
||||
c := ContainerConfig{Credentials: []CredentialBinding{
|
||||
{Service: "openai", Org: "acme", Secret: SecretRef{Engine: "env", Key: "OPENAI_KEY"}},
|
||||
{Service: "other-org-svc", Org: "other", Secret: SecretRef{Engine: "env", Key: "X"}},
|
||||
}}
|
||||
|
||||
tests := []struct {
|
||||
name string
|
||||
org string
|
||||
granted []string
|
||||
declared []string
|
||||
want []string
|
||||
}{
|
||||
{
|
||||
name: "org, granted and declared all agree", org: "acme",
|
||||
granted: []string{"openai"}, declared: []string{"openai"},
|
||||
want: []string{"openai"},
|
||||
},
|
||||
{
|
||||
name: "declared but not granted resolves nothing", org: "acme",
|
||||
granted: nil, declared: []string{"openai"},
|
||||
want: nil,
|
||||
},
|
||||
{
|
||||
name: "granted but not declared resolves nothing", org: "acme",
|
||||
granted: []string{"openai"}, declared: nil,
|
||||
want: nil,
|
||||
},
|
||||
{
|
||||
name: "granted and declared but the wrong org resolves nothing", org: "not-acme",
|
||||
granted: []string{"openai"}, declared: []string{"openai"},
|
||||
want: nil,
|
||||
},
|
||||
{
|
||||
name: "a service bound to a different org is never returned regardless of grants", org: "acme",
|
||||
granted: []string{"other-org-svc"}, declared: []string{"other-org-svc"},
|
||||
want: nil,
|
||||
},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
got := c.BoundCredentials(tt.org, tt.granted, tt.declared)
|
||||
var names []string
|
||||
for name := range got {
|
||||
names = append(names, name)
|
||||
}
|
||||
if len(names) != len(tt.want) {
|
||||
t.Fatalf("BoundCredentials() = %v, want %v", names, tt.want)
|
||||
}
|
||||
for _, want := range tt.want {
|
||||
if _, ok := got[want]; !ok {
|
||||
t.Fatalf("BoundCredentials() = %v, want it to carry %q", names, want)
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestValidateCredentialBindings(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
c ContainerConfig
|
||||
wantErr string
|
||||
}{
|
||||
{name: "no bindings", c: ContainerConfig{}},
|
||||
{name: "one binding", c: ContainerConfig{Credentials: []CredentialBinding{{Service: "openai", Org: "acme"}}}},
|
||||
{
|
||||
name: "empty service name",
|
||||
c: ContainerConfig{Credentials: []CredentialBinding{{Service: "", Org: "acme"}}},
|
||||
wantErr: "service name must not be empty",
|
||||
},
|
||||
{
|
||||
name: "duplicate service in the same org",
|
||||
c: ContainerConfig{Credentials: []CredentialBinding{
|
||||
{Service: "openai", Org: "acme"},
|
||||
{Service: "openai", Org: "acme"},
|
||||
}},
|
||||
wantErr: "bound more than once",
|
||||
},
|
||||
{
|
||||
name: "same service, different orgs is not a duplicate",
|
||||
c: ContainerConfig{Credentials: []CredentialBinding{
|
||||
{Service: "openai", Org: "acme"},
|
||||
{Service: "openai", Org: "other"},
|
||||
}},
|
||||
},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
err := tt.c.ValidateCredentialBindings()
|
||||
if tt.wantErr == "" {
|
||||
if err != nil {
|
||||
t.Fatalf("ValidateCredentialBindings() = %v, want nil", err)
|
||||
}
|
||||
return
|
||||
}
|
||||
if err == nil || !strings.Contains(err.Error(), tt.wantErr) {
|
||||
t.Fatalf("ValidateCredentialBindings() = %v, want containing %q", err, tt.wantErr)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -1,78 +0,0 @@
|
||||
package config
|
||||
|
||||
import (
|
||||
"sync"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestHolderGetReturnsConstructorValue(t *testing.T) {
|
||||
c := Config{BotUser: "archie", PollInterval: Duration(1)}
|
||||
h := NewHolder(c)
|
||||
if got := h.Get(); got.BotUser != "archie" || got.PollInterval != Duration(1) {
|
||||
t.Fatalf("Get() = %+v, want BotUser=archie PollInterval=1", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestHolderSetReplaces(t *testing.T) {
|
||||
h := NewHolder(Config{BotUser: "old"})
|
||||
h.Set(Config{BotUser: "new"})
|
||||
if got := h.Get(); got.BotUser != "new" {
|
||||
t.Fatalf("after Set, Get().BotUser = %q, want \"new\"", got.BotUser)
|
||||
}
|
||||
}
|
||||
|
||||
func TestHolderConcurrentGetSetIsRaceFree(t *testing.T) {
|
||||
// The actual contract is that Get never tears: under -race, no data
|
||||
// race, and every observed Config is a value some Set wrote. We do
|
||||
// not assert "Get after my Set returns my value" because with N
|
||||
// concurrent writers that property is not what Get guarantees -- a
|
||||
// later Set can land between this writer's Set and this writer's
|
||||
// Get. The race detector is the real check.
|
||||
h := NewHolder(Config{BotUser: "v0"})
|
||||
|
||||
const writers = 8
|
||||
const iters = 1000
|
||||
|
||||
var wg sync.WaitGroup
|
||||
for range writers {
|
||||
wg.Add(2)
|
||||
go func() {
|
||||
defer wg.Done()
|
||||
for range iters {
|
||||
h.Set(Config{BotUser: "w"})
|
||||
}
|
||||
}()
|
||||
go func() {
|
||||
defer wg.Done()
|
||||
for range iters {
|
||||
_ = h.Get()
|
||||
}
|
||||
}()
|
||||
}
|
||||
wg.Wait()
|
||||
}
|
||||
|
||||
func TestHolderGetPanicsOnNil(t *testing.T) {
|
||||
defer func() {
|
||||
if r := recover(); r == nil {
|
||||
t.Fatalf("Get on nil Holder did not panic")
|
||||
}
|
||||
}()
|
||||
var h *Holder
|
||||
_ = h.Get()
|
||||
}
|
||||
|
||||
func TestHolderSharedReferenceField(t *testing.T) {
|
||||
// Documents the immutability invariant: maps inside the snapshot
|
||||
// are shared with all Get callers. Mutating one is visible to all
|
||||
// others -- the contract forbids this, but the test pins the
|
||||
// current behaviour so any future change (e.g. copying maps) is
|
||||
// a deliberate decision.
|
||||
original := Config{Models: map[string]string{"builder": "anthropic/claude"}}
|
||||
h := NewHolder(original)
|
||||
snapshot := h.Get()
|
||||
snapshot.Models["builder"] = "mutated"
|
||||
if got := h.Get().Models["builder"]; got != "mutated" {
|
||||
t.Fatalf("expected Get to see mutation through shared map, got %q", got)
|
||||
}
|
||||
}
|
||||
@@ -1,65 +0,0 @@
|
||||
package config
|
||||
|
||||
import (
|
||||
"slices"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestContainerProfileResolution(t *testing.T) {
|
||||
c := ContainerConfig{Image: "archie-agent:1", Profiles: map[string]AgentProfile{
|
||||
"net": {Image: "archie-agent-net:1", Tools: []string{"whois"}},
|
||||
"quiet": {Tools: []string{"notes"}},
|
||||
}}
|
||||
tests := []struct {
|
||||
name, profile, wantImage, wantErr string
|
||||
wantTools []string
|
||||
}{
|
||||
{name: "default profile", profile: "", wantImage: "archie-agent:1"},
|
||||
{name: "named profile", profile: "net", wantImage: "archie-agent-net:1", wantTools: []string{"whois"}},
|
||||
{name: "profile without an image uses the default image", profile: "quiet", wantImage: "archie-agent:1", wantTools: []string{"notes"}},
|
||||
{name: "unconfigured profile", profile: "gone", wantErr: `"gone" is not configured`},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
p, err := c.Profile(tt.profile)
|
||||
if tt.wantErr != "" {
|
||||
if err == nil || !strings.Contains(err.Error(), tt.wantErr) {
|
||||
t.Fatalf("Profile() error = %v, want containing %q", err, tt.wantErr)
|
||||
}
|
||||
return
|
||||
}
|
||||
if err != nil || p.Image != tt.wantImage || !slices.Equal(p.Tools, tt.wantTools) {
|
||||
t.Fatalf("Profile() = %+v, %v; want image %q tools %v", p, err, tt.wantImage, tt.wantTools)
|
||||
}
|
||||
})
|
||||
}
|
||||
bad := ContainerConfig{Profiles: map[string]AgentProfile{"x": {Tools: []string{" "}}}}
|
||||
if err := bad.ValidateProfiles(); err == nil {
|
||||
t.Error("ValidateProfiles accepted an empty tool name")
|
||||
}
|
||||
}
|
||||
|
||||
func TestKitProfiles(t *testing.T) {
|
||||
const pinned = "docker/claude-code-kit@sha256:0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef"
|
||||
c := ContainerConfig{Image: "archie-agent:1", Profiles: map[string]AgentProfile{
|
||||
"claude": {Kit: pinned, Adapter: "claude-code"},
|
||||
}}
|
||||
p, err := c.Profile("claude")
|
||||
if err != nil || p.Image != "" || !p.IsKit() {
|
||||
t.Fatalf("Profile() = %+v, %v; a Kit profile must not inherit the agent image", p, err)
|
||||
}
|
||||
for name, bad := range map[string]AgentProfile{
|
||||
"image and kit": {Image: "archie-agent:1", Kit: pinned},
|
||||
"unpinned kit": {Kit: "docker/claude-code-kit:latest"},
|
||||
"adapter without a kit": {Adapter: "claude-code"},
|
||||
} {
|
||||
c := ContainerConfig{Profiles: map[string]AgentProfile{"p": bad}}
|
||||
if err := c.ValidateProfiles(); err == nil {
|
||||
t.Errorf("%s: ValidateProfiles accepted %+v", name, bad)
|
||||
}
|
||||
}
|
||||
if err := c.ValidateProfiles(); err != nil {
|
||||
t.Fatalf("a digest-pinned Kit profile was refused: %v", err)
|
||||
}
|
||||
}
|
||||
@@ -1,30 +0,0 @@
|
||||
package config
|
||||
|
||||
import (
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
// TestRateLimitConfigEnabled pins Enabled as opt-in: the zero value (an
|
||||
// absent [chat.rate_limit] table) must leave rate limiting off, and both
|
||||
// fields must be positive before it counts as configured.
|
||||
func TestRateLimitConfigEnabled(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
cfg RateLimitConfig
|
||||
want bool
|
||||
}{
|
||||
{"zero value", RateLimitConfig{}, false},
|
||||
{"window only", RateLimitConfig{Window: time.Minute}, false},
|
||||
{"max requests only", RateLimitConfig{MaxRequests: 20}, false},
|
||||
{"both set", RateLimitConfig{Window: time.Minute, MaxRequests: 20}, true},
|
||||
{"negative max requests", RateLimitConfig{Window: time.Minute, MaxRequests: -1}, false},
|
||||
}
|
||||
for _, tc := range tests {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
if got := tc.cfg.Enabled(); got != tc.want {
|
||||
t.Errorf("Enabled() = %v, want %v", got, tc.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -1,225 +0,0 @@
|
||||
package config_test
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/config"
|
||||
)
|
||||
|
||||
// TestRegisterServiceIsTheSingleDeclaration pins criterion 3 of
|
||||
// docs/prds/service-registry.md: a service is declared by one call carrying the
|
||||
// five fields it actually has, and every later layer reads that declaration
|
||||
// rather than restating the name.
|
||||
func TestRegisterServiceIsTheSingleDeclaration(t *testing.T) {
|
||||
config.RegisterService(config.ServiceBoth, "widget", "127.0.0.1:7001", "127.0.0.1:7002", "WIDGET_TOKEN")
|
||||
|
||||
spec, ok := config.LookupService("widget")
|
||||
if !ok {
|
||||
t.Fatal("LookupService(widget) = false, want the service just registered")
|
||||
}
|
||||
if spec.Context != config.ServiceBoth {
|
||||
t.Errorf("Context = %q, want %q", spec.Context, config.ServiceBoth)
|
||||
}
|
||||
if spec.Target != "127.0.0.1:7001" {
|
||||
t.Errorf("Target = %q, want the registered default", spec.Target)
|
||||
}
|
||||
if spec.Listen != "127.0.0.1:7002" {
|
||||
t.Errorf("Listen = %q, want the registered default", spec.Listen)
|
||||
}
|
||||
if spec.TokenEnv != "WIDGET_TOKEN" {
|
||||
t.Errorf("TokenEnv = %q, want the registered env var", spec.TokenEnv)
|
||||
}
|
||||
}
|
||||
|
||||
// TestBuiltInServicesAreRegistered pins that the two services the daemon ships
|
||||
// are declared through the same entry point as any other, with the asymmetry
|
||||
// the old struct form left unstated: state has no default target, so the
|
||||
// operator must supply one, while gateway does.
|
||||
func TestBuiltInServicesAreRegistered(t *testing.T) {
|
||||
state, ok := config.LookupService("state")
|
||||
if !ok {
|
||||
t.Fatal("LookupService(state) = false, want the State Store registered")
|
||||
}
|
||||
if state.Target != "" {
|
||||
t.Errorf("state Target default = %q, want empty: services.state.target is operator-supplied", state.Target)
|
||||
}
|
||||
if state.Listen == "" {
|
||||
t.Error("state Listen default is empty, want an address: an empty listen reaches net.Listen as any free port")
|
||||
}
|
||||
if state.TokenEnv != "STATE_STORE_TOKEN" {
|
||||
t.Errorf("state TokenEnv = %q, want STATE_STORE_TOKEN", state.TokenEnv)
|
||||
}
|
||||
|
||||
gateway, ok := config.LookupService("gateway")
|
||||
if !ok {
|
||||
t.Fatal("LookupService(gateway) = false, want the Gateway registered")
|
||||
}
|
||||
if gateway.Target == "" {
|
||||
t.Error("gateway Target default is empty, want an address: the gateway target is defaulted, not operator-supplied")
|
||||
}
|
||||
if gateway.TokenEnv != "GATEWAY_TOKEN" {
|
||||
t.Errorf("gateway TokenEnv = %q, want GATEWAY_TOKEN", gateway.TokenEnv)
|
||||
}
|
||||
}
|
||||
|
||||
// TestUnregisteredServiceIsNotFound keeps the registry the authority on which
|
||||
// names exist, which is what lets the loader report a typo'd [services.gatway]
|
||||
// as an unknown key once Services is a map that would otherwise swallow it.
|
||||
func TestUnregisteredServiceIsNotFound(t *testing.T) {
|
||||
if _, ok := config.LookupService("gatway"); ok {
|
||||
t.Error("LookupService(gatway) = true, want false for an unregistered name")
|
||||
}
|
||||
}
|
||||
|
||||
// TestServicesGetReturnsTheNamedConnection pins lookup by name, which replaced
|
||||
// per-service struct field access, so adding a service needs no new field.
|
||||
func TestServicesGetReturnsTheNamedConnection(t *testing.T) {
|
||||
services := config.Services{
|
||||
"state": {Target: "10.0.0.1:9090", Listen: "0.0.0.0:9090", TargetToken: "explicit"},
|
||||
}
|
||||
got := services.Get("state")
|
||||
if got.Target != "10.0.0.1:9090" {
|
||||
t.Errorf("Get(state).Target = %q, want the configured target", got.Target)
|
||||
}
|
||||
if services.Get("absent") != (config.ServiceConnection{}) {
|
||||
t.Error("Get(absent) returned a non-zero connection, want the zero value")
|
||||
}
|
||||
}
|
||||
|
||||
// TestResolvedTokenPrefersTheExplicitKey pins the precedence the two
|
||||
// hand-copied resolvers used: the config key wins, and the registered env var
|
||||
// is only a fallback.
|
||||
func TestResolvedTokenPrefersTheExplicitKey(t *testing.T) {
|
||||
config.RegisterService(config.ServiceClient, "widget-explicit", "", "127.0.0.1:7003", "WIDGET_EXPLICIT_TOKEN")
|
||||
services := config.Services{"widget-explicit": {TargetToken: "from-config"}}
|
||||
|
||||
getenv := func(string) string { return "from-env" }
|
||||
if got := services.ResolvedToken("widget-explicit", getenv); got != "from-config" {
|
||||
t.Errorf("ResolvedToken = %q, want the explicit target_token to win", got)
|
||||
}
|
||||
}
|
||||
|
||||
// TestResolvedTokenFallsBackToTheRegisteredEnvVar is the half that the old
|
||||
// stateStoreResolvedToken and gatewayResolvedToken duplicated, differing only
|
||||
// in the env var name they hard-coded.
|
||||
func TestResolvedTokenFallsBackToTheRegisteredEnvVar(t *testing.T) {
|
||||
config.RegisterService(config.ServiceClient, "widget-env", "", "127.0.0.1:7004", "WIDGET_ENV_TOKEN")
|
||||
services := config.Services{"widget-env": {}}
|
||||
|
||||
var asked string
|
||||
getenv := func(name string) string {
|
||||
asked = name
|
||||
return "from-env"
|
||||
}
|
||||
if got := services.ResolvedToken("widget-env", getenv); got != "from-env" {
|
||||
t.Errorf("ResolvedToken = %q, want the env fallback", got)
|
||||
}
|
||||
if asked != "WIDGET_ENV_TOKEN" {
|
||||
t.Errorf("read env var %q, want the name from the registration", asked)
|
||||
}
|
||||
}
|
||||
|
||||
// TestResolvedTokenOfUnregisteredServiceHasNoEnvFallback keeps an unknown name
|
||||
// from reaching os.Getenv("") and returning something surprising.
|
||||
func TestResolvedTokenOfUnregisteredServiceHasNoEnvFallback(t *testing.T) {
|
||||
services := config.Services{"gatway": {}}
|
||||
getenv := func(string) string {
|
||||
t.Error("getenv called for an unregistered service, want no env fallback")
|
||||
return "leaked"
|
||||
}
|
||||
if got := services.ResolvedToken("gatway", getenv); got != "" {
|
||||
t.Errorf("ResolvedToken = %q, want empty", got)
|
||||
}
|
||||
}
|
||||
|
||||
// mustPanic runs fn and returns the recovered value, or fails if fn returned
|
||||
// normally. Registration errors are programming errors in this repository's
|
||||
// own init(), not operator input, so they abort the process rather than
|
||||
// returning an error nobody is positioned to handle.
|
||||
func mustPanic(t *testing.T, fn func()) (recovered any) {
|
||||
t.Helper()
|
||||
defer func() { recovered = recover() }()
|
||||
fn()
|
||||
t.Fatal("RegisterService returned normally, want a panic")
|
||||
return nil
|
||||
}
|
||||
|
||||
// TestRegisterServiceRejectsAnUnknownContext makes Context load-bearing. It
|
||||
// documented which addresses a service must end up with, but nothing read it,
|
||||
// so a typo'd context was accepted and silently meant nothing.
|
||||
func TestRegisterServiceRejectsAnUnknownContext(t *testing.T) {
|
||||
got := mustPanic(t, func() {
|
||||
config.RegisterService("clientt", "widget-badcontext", "", "127.0.0.1:7005", "T")
|
||||
})
|
||||
if !strings.Contains(fmt.Sprint(got), "clientt") {
|
||||
t.Errorf("panic = %v, want it to name the invalid context", got)
|
||||
}
|
||||
}
|
||||
|
||||
// TestRegisterServiceRejectsAHostedServiceWithNoListen pins the requirement
|
||||
// Context exists to express: a service this repository hosts must have a
|
||||
// default bind address, because an empty one reaches net.Listen as "any free
|
||||
// port".
|
||||
func TestRegisterServiceRejectsAHostedServiceWithNoListen(t *testing.T) {
|
||||
for _, hosted := range []string{config.ServiceServer, config.ServiceBoth} {
|
||||
t.Run(hosted, func(t *testing.T) {
|
||||
got := mustPanic(t, func() {
|
||||
config.RegisterService(hosted, "widget-nolisten-"+hosted, "127.0.0.1:1", "", "T")
|
||||
})
|
||||
if !strings.Contains(fmt.Sprint(got), "listen") {
|
||||
t.Errorf("panic = %v, want it to name the missing listen address", got)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// TestRegisterServiceAcceptsAClientWithNoTargetDefault keeps the State Store's
|
||||
// own shape legal: a dialled-only service may register an empty target, which
|
||||
// is how "the operator must supply this" is stated.
|
||||
func TestRegisterServiceAcceptsAClientWithNoTargetDefault(t *testing.T) {
|
||||
defer func() {
|
||||
if r := recover(); r != nil {
|
||||
t.Fatalf("RegisterService panicked on a legal client registration: %v", r)
|
||||
}
|
||||
}()
|
||||
config.RegisterService(config.ServiceClient, "widget-clientok", "", "127.0.0.1:7006", "T")
|
||||
}
|
||||
|
||||
// TestRequireTargetReportsAnAbsentOperatorSuppliedTarget moves the "target is
|
||||
// required" check off two hand-written consumer copies and onto the registry,
|
||||
// which is what declared the target operator-supplied in the first place.
|
||||
func TestRequireTargetReportsAnAbsentOperatorSuppliedTarget(t *testing.T) {
|
||||
for _, tt := range []struct {
|
||||
name string
|
||||
target string
|
||||
want string
|
||||
wantErr bool
|
||||
}{
|
||||
{name: "absent", wantErr: true},
|
||||
{name: "blank", target: " \t\n", wantErr: true},
|
||||
{name: "set", target: "10.0.0.1:9090", want: "10.0.0.1:9090"},
|
||||
{name: "set with padding", target: " 10.0.0.1:9090 ", want: "10.0.0.1:9090"},
|
||||
} {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
services := config.Services{config.ServiceNameState: {Target: tt.target}}
|
||||
got, err := services.RequireTarget(config.ServiceNameState)
|
||||
if tt.wantErr {
|
||||
if err == nil {
|
||||
t.Fatal("RequireTarget returned no error for an empty target")
|
||||
}
|
||||
if !strings.Contains(err.Error(), "services.state.target") {
|
||||
t.Errorf("error = %v, want it to name the config key", err)
|
||||
}
|
||||
return
|
||||
}
|
||||
if err != nil {
|
||||
t.Fatalf("RequireTarget: %v", err)
|
||||
}
|
||||
if got != tt.want {
|
||||
t.Errorf("RequireTarget = %q, want %q", got, tt.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user