package config import ( "errors" "os" "path/filepath" "reflect" "strings" "testing" "go.maximumdirect.net/configkit" ) func useConfigSearchPaths(t *testing.T, paths ...string) { t.Helper() previous := defaultConfigSearchPaths defaultConfigSearchPaths = paths t.Cleanup(func() { defaultConfigSearchPaths = previous }) } func writeApplicationFile(t *testing.T, path, body string) { t.Helper() if err := os.WriteFile(path, []byte(body), 0o600); err != nil { t.Fatal(err) } } func TestLoadSelectsOrderedSourceAndKeepsItsSnapshot(t *testing.T) { dir := t.TempDir() first := filepath.Join(dir, "first.yml") second := filepath.Join(dir, "second.yml") writeApplicationFile(t, first, "promptkit_sources:\n - file: ./first.yml\n") writeApplicationFile(t, second, "promptkit_sources:\n - directory: ./second\n") useConfigSearchPaths(t, first, second) result, err := Load(LoadOptions{Path: filepath.Join(dir, "ignored.yml")}) if err != nil { t.Fatalf("load first implicit source: %v", err) } if !reflect.DeepEqual(result.Config.PromptKitSources, []SourceSelection{{File: "first.yml"}}) || len(result.Sources()) != 1 || result.Sources()[0].Path != first { t.Fatalf("unexpected implicit source: config=%+v sources=%+v", result.Config, result.Sources()) } writeApplicationFile(t, first, "promptkit_sources:\n - file: ./changed.yml\n") if !reflect.DeepEqual(result.Config.PromptKitSources, []SourceSelection{{File: "first.yml"}}) { t.Fatalf("result did not retain resolved snapshot: %+v", result.Config) } if err := os.Remove(first); err != nil { t.Fatal(err) } result, err = Load(LoadOptions{}) if err != nil || !reflect.DeepEqual(result.Config.PromptKitSources, []SourceSelection{{Directory: "second"}}) || result.Sources()[0].Path != second { t.Fatalf("second implicit source not selected: result=%+v err=%v", result, err) } result, err = Load(LoadOptions{Path: first, Explicit: true}) if result != nil || err == nil { t.Fatalf("missing explicit source was accepted: result=%+v err=%v", result, err) } var loadError *configkit.LoadError if !errors.As(err, &loadError) { t.Fatalf("typed load error was lost: %v", err) } } func TestLoadRejectsExplicitEmptyAndDistinguishesEmptyFile(t *testing.T) { useConfigSearchPaths(t, filepath.Join(t.TempDir(), "absent.yml")) if _, err := Load(LoadOptions{Explicit: true, Path: ""}); err == nil { t.Fatal("explicit empty path was accepted") } else { var loadError *configkit.LoadError if !errors.As(err, &loadError) { t.Fatalf("expected upstream source diagnostic, got %v", err) } } dir := t.TempDir() empty := filepath.Join(dir, "empty.yml") writeApplicationFile(t, empty, "") if _, err := Load(LoadOptions{Path: empty, Explicit: true}); err == nil { t.Fatal("empty file was treated as defaults-only") } writeApplicationFile(t, empty, "{}\n") result, err := Load(LoadOptions{Path: empty, Explicit: true}) if err != nil || !reflect.DeepEqual(result.Config, documentDefaults()) { t.Fatalf("empty mapping did not load defaults: result=%+v err=%v", result, err) } } func TestLoadDefaultsOnlyAndOverridesBeforeValidation(t *testing.T) { useConfigSearchPaths(t, filepath.Join(t.TempDir(), "absent.yml")) result, err := Load(LoadOptions{}) if err != nil || !reflect.DeepEqual(result.Config, documentDefaults()) || len(result.Sources()) != 0 { t.Fatalf("defaults-only load: result=%+v err=%v", result, err) } var effective strings.Builder if err := result.WriteEffective(&effective); err != nil || !strings.Contains(effective.String(), "render_format: text") || len(result.Sources()) != 0 { t.Fatalf("defaults-only inspection changed: effective=%q err=%v sources=%+v", effective.String(), err, result.Sources()) } result, err = Load(LoadOptions{Overrides: []configkit.Override{{ Path: configkit.Keys("server", "max_request_bytes"), Value: int64(0), Flag: "--max-request-bytes", }}}) if err != nil || result.Config.Server.MaxRequestBytes != 0 || len(result.Sources()) != 1 || result.Sources()[0].Layer != configkit.LayerCLI { t.Fatalf("defaults-only override lost: result=%+v err=%v", result, err) } path := filepath.Join(t.TempDir(), "invalid.yml") writeApplicationFile(t, path, "defaults:\n render_format: invalid-choice\n") result, err = Load(LoadOptions{Path: path, Explicit: true, Overrides: []configkit.Override{{ Path: configkit.Keys("defaults", "render_format"), Value: "json", Flag: "--render-format", }}}) if err != nil || result.Config.Defaults.RenderFormat != "json" { t.Fatalf("override did not precede validation: result=%+v err=%v", result, err) } if len(result.Sources()) != 2 || result.Sources()[0].Layer != configkit.LayerMain || result.Sources()[1].Layer != configkit.LayerCLI { t.Fatalf("source order changed: %+v", result.Sources()) } writeApplicationFile(t, path, "defaults: [\n") if _, err := Load(LoadOptions{Path: path, Explicit: true, Overrides: []configkit.Override{{ Path: configkit.Keys("defaults", "render_format"), Value: "json", Flag: "--render-format", }}}); err == nil { t.Fatal("override bypassed malformed lower-level YAML") } } func TestSettingsCopiesResolvedValuesAndSourceOrder(t *testing.T) { result, err := loadDocumentBytes(`schema_dir: "" promptkit_sources: - directory: ./profiles - file: ./framework.yml transient_retries: 0 server: addr: "" artifact_root: "" max_request_bytes: 0 defaults: render_format: json `) if err != nil { t.Fatal(err) } settings := Settings(result.Config) if settings.SchemaDir != "" || settings.ServerAddr != "" || settings.MaxRequestBytes != 0 || settings.DefaultRenderFormat != "json" { t.Fatalf("resolved scalar values changed: %+v", settings) } if settings.TransientRetries == nil || *settings.TransientRetries != 0 { t.Fatalf("retry presence lost: %+v", settings.TransientRetries) } if want := []SourceSelection{{Directory: "profiles"}, {File: "framework.yml"}}; !reflect.DeepEqual(settings.PromptKitSources, want) { t.Fatalf("source ordering changed: got=%+v want=%+v", settings.PromptKitSources, want) } if got := Settings(documentDefaults()); got.TransientRetries != nil || got.PromptKitSources != nil { t.Fatalf("default nullable values changed: %+v", got) } } func TestLoadDiscoveryErrorQuotesPath(t *testing.T) { dir := t.TempDir() path := filepath.Join(dir, "directory-\n.yml") if err := os.Mkdir(path, 0o700); err != nil { t.Fatal(err) } useConfigSearchPaths(t, path) _, err := Load(LoadOptions{}) var loadError *configkit.LoadError if !errors.As(err, &loadError) { t.Fatalf("expected structured error: %v", err) } var diagnostics strings.Builder if err := configkit.WriteDiagnostics(&diagnostics, loadError.Diagnostics()); err != nil { t.Fatal(err) } if !strings.Contains(diagnostics.String(), string(configkit.CodeSourceNotRegular)) || strings.Contains(diagnostics.String(), "directory-\n.yml") { t.Fatalf("discovery diagnostics exposed an unescaped path: %s", diagnostics.String()) } } func TestLoadComposesExplicitImportsAndSelectedOverlay(t *testing.T) { dir := t.TempDir() if err := os.MkdirAll(filepath.Join(dir, "fragments"), 0o700); err != nil { t.Fatal(err) } if err := os.MkdirAll(filepath.Join(dir, "overlays"), 0o700); err != nil { t.Fatal(err) } base := filepath.Join(dir, "config.yml") writeApplicationFile(t, base, "config:\n imports:\n - glob: fragments/*.yml\n required: true\npromptkit_sources:\n - file: ./base-framework.yml\n") writeApplicationFile(t, filepath.Join(dir, "fragments", "a.yml"), "server:\n addr: :8081\n") writeApplicationFile(t, filepath.Join(dir, "fragments", "b.yml"), "defaults:\n render_format: json\n") writeApplicationFile(t, filepath.Join(dir, "overlays", "local.yml"), "promptkit_sources:\n - directory: ./overlay-framework\nserver:\n addr: :9090\n") result, err := Load(LoadOptions{Path: base, Explicit: true}) if err != nil || !reflect.DeepEqual(result.Config.PromptKitSources, []SourceSelection{{File: "base-framework.yml"}}) || result.Config.Server.Addr != ":8081" || result.Config.Defaults.RenderFormat != "json" || len(result.Sources()) != 3 { t.Fatalf("disjoint imports did not compose: result=%+v err=%v", result, err) } result, err = Load(LoadOptions{Path: base, Explicit: true, Overlay: "local", Overrides: []configkit.Override{{ Path: configkit.Keys("promptkit_sources"), Value: []any{map[string]any{"file": "./cli-framework.yml"}}, Flag: "--promptkit-source", }}}) if err != nil || !reflect.DeepEqual(result.Config.PromptKitSources, []SourceSelection{{File: "cli-framework.yml"}}) || result.Config.Server.Addr != ":9090" || len(result.Sources()) != 5 { t.Fatalf("overlay or explicit override changed: result=%+v err=%v", result, err) } result, err = Load(LoadOptions{Path: base, Explicit: true, Overlay: "local"}) if err != nil || !reflect.DeepEqual(result.Config.PromptKitSources, []SourceSelection{{Directory: "overlay-framework"}}) { t.Fatalf("overlay did not replace the source list: result=%+v err=%v", result, err) } if _, err := Load(LoadOptions{Path: base, Explicit: true, Overlay: "missing"}); err == nil { t.Fatal("missing selected overlay accepted") } writeApplicationFile(t, filepath.Join(dir, "fragments", "b.yml"), "server:\n addr: :8082\n") if _, err := Load(LoadOptions{Path: base, Explicit: true}); err == nil { t.Fatal("conflicting import accepted") } else { var loadError *configkit.LoadError if !errors.As(err, &loadError) { t.Fatalf("conflict lost structured diagnostic: %v", err) } } } func TestLoadOverlayWithoutMainContext(t *testing.T) { useConfigSearchPaths(t, filepath.Join(t.TempDir(), "absent.yml")) if _, err := Load(LoadOptions{Overlay: "local"}); err == nil { t.Fatal("overlay without a main context accepted") } else { var loadError *configkit.LoadError if !errors.As(err, &loadError) { t.Fatalf("no-context overlay lost structured diagnostic: %v", err) } } if _, err := Load(LoadOptions{Overlay: "default"}); err != nil { t.Fatalf("default must select no overlay: %v", err) } } func TestLoadDoesNotFallThroughSelectedInvalidSource(t *testing.T) { dir := t.TempDir() first, second := filepath.Join(dir, "first.yml"), filepath.Join(dir, "second.yml") writeApplicationFile(t, first, "server: [\n") writeApplicationFile(t, second, "server:\n addr: ':9090'\n") useConfigSearchPaths(t, first, second) if _, err := Load(LoadOptions{}); err == nil { t.Fatal("malformed selected file fell through to the second candidate") } } func TestLoadImportRequirednessAndDestination(t *testing.T) { dir := t.TempDir() main := filepath.Join(dir, "config.yml") for _, tc := range []struct { name, declaration string wantError bool }{ {"optional by default", "- path: absent.yml", false}, {"required", "- path: absent.yml\n required: true", true}, {"removed optional field", "- path: absent.yml\n optional: true", true}, } { t.Run(tc.name, func(t *testing.T) { writeApplicationFile(t, main, "config:\n imports:\n "+tc.declaration+"\n") _, err := Load(LoadOptions{Path: main, Explicit: true}) if (err != nil) != tc.wantError { t.Fatalf("load error = %v, want error %t", err, tc.wantError) } }) } fragments := filepath.Join(dir, "fragments") if err := os.Mkdir(fragments, 0o700); err != nil { t.Fatal(err) } writeApplicationFile(t, filepath.Join(fragments, "server.yml"), "addr: ':8181'\n") writeApplicationFile(t, main, "config:\n imports:\n - dir: fragments\n pattern: '*.yml'\n destination: [server]\n required: true\n") result, err := Load(LoadOptions{Path: main, Explicit: true}) if err != nil { t.Fatal(err) } info, ok := result.Metadata().Lookup(configkit.Keys("server", "addr")) if result.Config.Server.Addr != ":8181" || !ok || len(info.Origin.Locations) == 0 { t.Fatalf("mounted value or origin missing: config=%+v origin=%+v", result.Config.Server, info) } } func TestLoadAuthoredSelectorCollection(t *testing.T) { dir := t.TempDir() for _, subdir := range []string{"fragments", "overlays"} { if err := os.Mkdir(filepath.Join(dir, subdir), 0o700); err != nil { t.Fatal(err) } } main := filepath.Join(dir, "config.yml") writeApplicationFile(t, main, "config:\n sequences:\n - destination: [promptkit_sources]\n key: file\n mode: upsert\n imports:\n - dir: fragments\n pattern: '*.yml'\n required: true\n") writeApplicationFile(t, filepath.Join(dir, "fragments", "a.yml"), "promptkit_sources:\n - file: a.yml\n") peer := filepath.Join(dir, "fragments", "b.yml") writeApplicationFile(t, peer, "promptkit_sources:\n - file: b.yml\n") writeApplicationFile(t, filepath.Join(dir, "overlays", "local.yml"), "promptkit_sources:\n - file: c.yml\n") result, err := Load(LoadOptions{Path: main, Explicit: true, Overlay: "local"}) if err != nil || !reflect.DeepEqual(result.Config.PromptKitSources, []SourceSelection{{File: "a.yml"}, {File: "b.yml"}, {File: "c.yml"}}) { t.Fatalf("authored upsert did not retain selectors: result=%+v err=%v", result, err) } result, err = Load(LoadOptions{Path: main, Explicit: true, Overlay: "local", Overrides: []configkit.Override{{ Path: configkit.Keys("promptkit_sources"), Value: []any{map[string]any{"file": "cli.yml"}}, Flag: "--promptkit-source", }}}) if err != nil || !reflect.DeepEqual(result.Config.PromptKitSources, []SourceSelection{{File: "cli.yml"}}) { t.Fatalf("CLI list did not replace selectors: result=%+v err=%v", result, err) } writeApplicationFile(t, peer, "promptkit_sources:\n - file: a.yml\n") if _, err := Load(LoadOptions{Path: main, Explicit: true}); err == nil { t.Fatal("duplicate authored peer identity accepted") } } func TestLoadOverrideCannotRepairDecodeError(t *testing.T) { path := filepath.Join(t.TempDir(), "config.yml") writeApplicationFile(t, path, "server:\n max_request_bytes: not-a-number\n") _, err := Load(LoadOptions{Path: path, Explicit: true, Overrides: []configkit.Override{{ Path: configkit.Keys("server", "max_request_bytes"), Value: int64(12), Flag: "--max-request-bytes", }}}) if err == nil { t.Fatal("override repaired an undecodable source value") } }