| 1 | package main |
| 2 | |
| 3 | import ( |
| 4 | "os" |
| 5 | "path/filepath" |
| 6 | "strings" |
| 7 | "testing" |
| 8 | ) |
| 9 | |
| 10 | // The whole reason `env set` exists: an upsert must preserve what it doesn't |
| 11 | // name — above all the admin token, which wholesale env replacement loses. |
| 12 | func TestEnvSetOnePreservesExistingKeys(t *testing.T) { |
| 13 | dir := t.TempDir() |
| 14 | old := instanceDataDir |
| 15 | instanceDataDir = dir |
| 16 | t.Cleanup(func() { instanceDataDir = old }) |
| 17 | |
| 18 | path := filepath.Join(dir, "x.example.env") |
| 19 | if err := os.WriteFile(path, |
| 20 | []byte("LCHAT_ADMIN_TOKEN=keepme\nLCHAT_PUSH_RELAY_TOKEN=alsokeep\nLCHAT_FETCH_URL=https://old.example\n"), |
| 21 | 0o600); err != nil { |
| 22 | t.Fatal(err) |
| 23 | } |
| 24 | |
| 25 | if err := envSetOne("x.example", map[string]string{ |
| 26 | "LCHAT_FETCH_URL": "https://fetch.11ch.at", // overwrite |
| 27 | "LCHAT_NEW_FLAG": "1", // append |
| 28 | }); err != nil { |
| 29 | t.Fatalf("envSetOne: %v", err) |
| 30 | } |
| 31 | |
| 32 | got, err := readEnvFile(path) |
| 33 | if err != nil { |
| 34 | t.Fatal(err) |
| 35 | } |
| 36 | want := map[string]string{ |
| 37 | "LCHAT_ADMIN_TOKEN": "keepme", |
| 38 | "LCHAT_PUSH_RELAY_TOKEN": "alsokeep", |
| 39 | "LCHAT_FETCH_URL": "https://fetch.11ch.at", |
| 40 | "LCHAT_NEW_FLAG": "1", |
| 41 | } |
| 42 | for k, v := range want { |
| 43 | if got[k] != v { |
| 44 | t.Fatalf("%s = %q, want %q (full: %v)", k, got[k], v, got) |
| 45 | } |
| 46 | } |
| 47 | if len(got) != len(want) { |
| 48 | t.Fatalf("unexpected keys: %v", got) |
| 49 | } |
| 50 | // A missing env file is an error, never a silent create — `env set` amends |
| 51 | // real instances; a typo'd host must not mint an empty env. |
| 52 | if err := envSetOne("nosuch.example", map[string]string{"A": "b"}); err == nil { |
| 53 | t.Fatal("envSetOne on a missing env file should fail") |
| 54 | } |
| 55 | if _, err := os.Stat(filepath.Join(dir, "nosuch.example.env")); !os.IsNotExist(err) { |
| 56 | t.Fatal("envSetOne must not create an env file for a typo'd host") |
| 57 | } |
| 58 | _ = strings.TrimSpace("") |
| 59 | } |
| 60 | |