package config import ( "os" "path/filepath" "testing" ) func writeCreds(t *testing.T, body string) string { t.Helper() p := filepath.Join(t.TempDir(), "api_credentials.txt") if err := os.WriteFile(p, []byte(body), 0o600); err != nil { t.Fatal(err) } return p } // The shape the engine actually writes. This is the whole point of the file: // on a stock install it is the ONLY place the credential exists. func TestItReadsWhatTheEngineWrites(t *testing.T) { p := writeCreds(t, "username=behavision\npassword=qQTGFpetJ5Py613XwcbARQ\n") u, pw := EngineCredentials(p) if u != "behavision" || pw != "qQTGFpetJ5Py613XwcbARQ" { t.Fatalf("got %q / %q", u, pw) } } func TestColonSeparatedIsReadToo(t *testing.T) { p := writeCreds(t, " username: behavision\n password: hunter2\n") if u, pw := EngineCredentials(p); u != "behavision" || pw != "hunter2" { t.Fatalf("got %q / %q", u, pw) } } // A missing file is normal - an operator who set BEHAVISION_API_USER has none. func TestAMissingFileIsNotAnError(t *testing.T) { if u, pw := EngineCredentials("/nope/nothing.txt"); u != "" || pw != "" { t.Fatalf("got %q / %q", u, pw) } } // Configured values win. Reading the file over an operator's own credential // would silently ignore what they set. func TestAConfiguredCredentialIsNotOverwritten(t *testing.T) { p := writeCreds(t, "username=generated\npassword=generated\n") c := Config{APIUser: "mine", APIPassword: "secret"}.WithEngineCredentials(p) if c.APIUser != "mine" || c.APIPassword != "secret" { t.Fatalf("configured credential was replaced: %q / %q", c.APIUser, c.APIPassword) } } func TestAnEmptyCredentialIsFilledIn(t *testing.T) { p := writeCreds(t, "username=behavision\npassword=abc\n") c := Config{}.WithEngineCredentials(p) if c.APIUser != "behavision" || c.APIPassword != "abc" { t.Fatalf("not filled in: %q / %q", c.APIUser, c.APIPassword) } }