60 lines
2.3 KiB
Go
60 lines
2.3 KiB
Go
package http
|
|
|
|
import (
|
|
"context"
|
|
"net/http"
|
|
"net/http/httptest"
|
|
"strings"
|
|
"testing"
|
|
|
|
"primaya-api/cpone-middleware/internal/databaseconfig"
|
|
)
|
|
|
|
type fakeDatabaseSettingsStore struct {
|
|
setting databaseconfig.Setting
|
|
}
|
|
|
|
func (f *fakeDatabaseSettingsStore) List() []databaseconfig.PublicSetting { return nil }
|
|
func (f *fakeDatabaseSettingsStore) Get(string) (databaseconfig.PublicSetting, bool) {
|
|
return databaseconfig.PublicSetting{}, false
|
|
}
|
|
func (f *fakeDatabaseSettingsStore) Upsert(_ context.Context, setting databaseconfig.Setting) (databaseconfig.PublicSetting, bool, error) {
|
|
f.setting = setting
|
|
return databaseconfig.PublicSetting{
|
|
RSCode: setting.RSCode, Host: setting.Host, Port: setting.Port,
|
|
Database: setting.Database, Username: setting.Username, HasPassword: setting.Password != "",
|
|
}, true, nil
|
|
}
|
|
|
|
func TestStoreDatabaseSettingDoesNotExposePassword(t *testing.T) {
|
|
store := &fakeDatabaseSettingsStore{}
|
|
handler := NewDatabaseSettingsHandler(store)
|
|
body := `{"kode_rs":"RS_BEKASI","nama":"RS Bekasi","host":"10.0.0.2","port":"3306","database":"his","username":"cpone","password":"top-secret"}`
|
|
request := httptest.NewRequest(http.MethodPost, "/api/cpone/database-settings", strings.NewReader(body))
|
|
recorder := httptest.NewRecorder()
|
|
handler.Store(recorder, request)
|
|
|
|
if recorder.Code != http.StatusCreated {
|
|
t.Fatalf("status = %d, body=%s", recorder.Code, recorder.Body.String())
|
|
}
|
|
if store.setting.Password != "top-secret" {
|
|
t.Fatal("password was not passed to store")
|
|
}
|
|
if strings.Contains(recorder.Body.String(), "top-secret") || strings.Contains(recorder.Body.String(), `"password"`) {
|
|
t.Fatalf("response exposes password: %s", recorder.Body.String())
|
|
}
|
|
if !strings.Contains(recorder.Body.String(), `"has_password":true`) {
|
|
t.Fatalf("response missing has_password: %s", recorder.Body.String())
|
|
}
|
|
}
|
|
|
|
func TestStoreDatabaseSettingValidation(t *testing.T) {
|
|
handler := NewDatabaseSettingsHandler(&fakeDatabaseSettingsStore{})
|
|
request := httptest.NewRequest(http.MethodPost, "/api/cpone/database-settings", strings.NewReader(`{"kode_rs":"invalid code"}`))
|
|
recorder := httptest.NewRecorder()
|
|
handler.Store(recorder, request)
|
|
if recorder.Code != http.StatusUnprocessableEntity {
|
|
t.Fatalf("status = %d, body=%s", recorder.Code, recorder.Body.String())
|
|
}
|
|
}
|