package main import ( "os" "path/filepath" "strings" "testing" ) // The whole reason `env set` exists: an upsert must preserve what it doesn't // name — above all the admin token, which wholesale env replacement loses. func TestEnvSetOnePreservesExistingKeys(t *testing.T) { dir := t.TempDir() old := instanceDataDir instanceDataDir = dir t.Cleanup(func() { instanceDataDir = old }) path := filepath.Join(dir, "x.example.env") if err := os.WriteFile(path, []byte("LCHAT_ADMIN_TOKEN=keepme\nLCHAT_PUSH_RELAY_TOKEN=alsokeep\nLCHAT_FETCH_URL=https://old.example\n"), 0o600); err != nil { t.Fatal(err) } if err := envSetOne("x.example", map[string]string{ "LCHAT_FETCH_URL": "https://fetch.11ch.at", // overwrite "LCHAT_NEW_FLAG": "1", // append }); err != nil { t.Fatalf("envSetOne: %v", err) } got, err := readEnvFile(path) if err != nil { t.Fatal(err) } want := map[string]string{ "LCHAT_ADMIN_TOKEN": "keepme", "LCHAT_PUSH_RELAY_TOKEN": "alsokeep", "LCHAT_FETCH_URL": "https://fetch.11ch.at", "LCHAT_NEW_FLAG": "1", } for k, v := range want { if got[k] != v { t.Fatalf("%s = %q, want %q (full: %v)", k, got[k], v, got) } } if len(got) != len(want) { t.Fatalf("unexpected keys: %v", got) } // A missing env file is an error, never a silent create — `env set` amends // real instances; a typo'd host must not mint an empty env. if err := envSetOne("nosuch.example", map[string]string{"A": "b"}); err == nil { t.Fatal("envSetOne on a missing env file should fail") } if _, err := os.Stat(filepath.Join(dir, "nosuch.example.env")); !os.IsNotExist(err) { t.Fatal("envSetOne must not create an env file for a typo'd host") } _ = strings.TrimSpace("") }