package apiserver import ( "testing" ) // The deployed contract is these six variables and these defaults; nothing else // is consulted for the database connection. func TestLoadConfig_DatabaseEnvContract(t *testing.T) { // Set by a deployment that would confuse a DATABASE_URL/PG*-aware loader. t.Setenv("DATABASE_URL", "postgres://someone@elsewhere:5432/other") t.Setenv("PGHOST", "elsewhere") cfg, err := LoadConfig() if err != nil { t.Fatalf("LoadConfig: %v", err) } if got, want := cfg.DatabaseDSN(), "postgres://forgebot:@localhost:5432/forgebot?sslmode=disable"; got != want { t.Fatalf("default DSN = %q, want %q", got, want) } t.Setenv("DBHOST", "db.example") t.Setenv("DBPORT", "6432") t.Setenv("DBUSER", "bot") t.Setenv("DBPASS", "hunter2") t.Setenv("DBNAME", "tasks") t.Setenv("DBSSL", "require") cfg, err = LoadConfig() if err != nil { t.Fatalf("LoadConfig: %v", err) } if got, want := cfg.DatabaseDSN(), "postgres://bot:hunter2@db.example:6432/tasks?sslmode=require"; got != want { t.Fatalf("DSN = %q, want %q", got, want) } } func TestLoadConfig_RejectsBadPort(t *testing.T) { t.Setenv("DBPORT", "not-a-port") if _, err := LoadConfig(); err == nil { t.Fatal("expected an error for a non-numeric DBPORT") } } // A password with reserved characters used to truncate the DSN; the builder // percent-escapes the credentials so it round-trips through pgx intact. func TestDatabaseDSN_EscapesCredentials(t *testing.T) { cfg := &Config{ DBHost: "db.example", DBPort: 5432, DBUser: "bo/t", DBPass: "p@ss/word", DBName: "tasks", DBSSL: "disable", } if got, want := cfg.DatabaseDSN(), "postgres://bo%2Ft:p%40ss%2Fword@db.example:5432/tasks?sslmode=disable"; got != want { t.Fatalf("DSN = %q, want %q", got, want) } }