ajhahn.de
← eeco
Go 86 lines
package cockpit

import (
	"os"
	"reflect"
	"testing"

	"github.com/ajhahnde/eeco/internal/config"
)

// TestMain pins the user-global config dir to an empty temp dir so the global
// cockpit-selection fallback is a hermetic no-op and these tests never read the
// dev box's ~/.config/eeco. Tests that exercise the fallback override via
// t.Setenv(config.GlobalConfigEnv, ...).
func TestMain(m *testing.M) {
	gdir, err := os.MkdirTemp("", "eeco-global-")
	if err != nil {
		panic(err)
	}
	os.Setenv(config.GlobalConfigEnv, gdir)
	code := m.Run()
	os.RemoveAll(gdir)
	os.Exit(code)
}

func TestLoadSelection_GlobalFallback(t *testing.T) {
	cfg := testConfig(t) // fresh workspace, no cockpit.json
	gdir := t.TempDir()
	t.Setenv(config.GlobalConfigEnv, gdir)
	if err := SaveGlobalSelection(Selection{Targets: []string{"claude", "cursor"}}); err != nil {
		t.Fatal(err)
	}
	got := LoadSelection(cfg)
	if !reflect.DeepEqual(got.Targets, []string{"claude", "cursor"}) {
		t.Errorf("LoadSelection targets = %v, want inherited [claude cursor]", got.Targets)
	}
}

func TestLoadSelection_WorkspaceWinsOverGlobal(t *testing.T) {
	cfg := testConfig(t)
	gdir := t.TempDir()
	t.Setenv(config.GlobalConfigEnv, gdir)
	if err := SaveGlobalSelection(Selection{Targets: []string{"cursor", "gemini"}}); err != nil {
		t.Fatal(err)
	}
	if err := SaveSelection(cfg, Selection{Targets: []string{"claude", "agents"}}); err != nil {
		t.Fatal(err)
	}
	got := LoadSelection(cfg)
	if !reflect.DeepEqual(got.Targets, []string{"claude", "agents"}) {
		t.Errorf("LoadSelection targets = %v, want workspace [claude agents]", got.Targets)
	}
}

func TestLoadSelection_DefaultWhenNeitherSet(t *testing.T) {
	cfg := testConfig(t)
	gdir := t.TempDir() // empty: no global cockpit.json
	t.Setenv(config.GlobalConfigEnv, gdir)
	got := LoadSelection(cfg)
	if !reflect.DeepEqual(got.Targets, []string{"claude"}) {
		t.Errorf("LoadSelection targets = %v, want default [claude]", got.Targets)
	}
}

func TestGlobalSelection_SaveLoadRoundTripAndSanitize(t *testing.T) {
	gdir := t.TempDir()
	t.Setenv(config.GlobalConfigEnv, gdir)
	// Duplicates, unknowns, and blanks dropped; order preserved.
	if err := SaveGlobalSelection(Selection{Targets: []string{"cursor", "cursor", "bogus", "", "claude"}}); err != nil {
		t.Fatal(err)
	}
	got := LoadGlobalSelection()
	if !reflect.DeepEqual(got.Targets, []string{"cursor", "claude"}) {
		t.Errorf("global round-trip targets = %v, want [cursor claude]", got.Targets)
	}
}

func TestLoadGlobalSelection_DefaultWhenMissing(t *testing.T) {
	gdir := t.TempDir()
	t.Setenv(config.GlobalConfigEnv, gdir)
	got := LoadGlobalSelection()
	if !reflect.DeepEqual(got.Targets, []string{"claude"}) {
		t.Errorf("LoadGlobalSelection targets = %v, want default [claude]", got.Targets)
	}
}