package adminapi import ( "context" "errors" "strings" "testing" "time" "gitea.mynodes.xyz/ilker/llmgw/internal/store" ) type memSettings struct{ versions []store.SettingsVersion } func (m *memSettings) ClusterSettings(context.Context) (store.SettingsVersion, error) { if len(m.versions) == 0 { return store.SettingsVersion{}, nil } return m.versions[len(m.versions)-1], nil } func (m *memSettings) ClusterSettingsAt(_ context.Context, v int64) (store.SettingsVersion, error) { if v < 1 || int(v) > len(m.versions) { return store.SettingsVersion{}, nil } return m.versions[v-1], nil } func (m *memSettings) ClusterSettingsHistory(context.Context, int) ([]store.SettingsVersion, error) { var out []store.SettingsVersion for i := len(m.versions) - 1; i >= 0; i-- { out = append(out, m.versions[i]) } return out, nil } func (m *memSettings) PutClusterSettings(_ context.Context, base int64, body, by, note string) (int64, error) { if base != int64(len(m.versions)) { return 0, store.ErrSettingsChanged } m.versions = append(m.versions, store.SettingsVersion{Version: base + 1, Body: body, By: by, Note: note, At: time.Now()}) return base + 1, nil } func TestSettingsAreCheckedKeptAndRolledBack(t *testing.T) { a, _ := setup(t, testModels()) st := &memSettings{} a.SetSettings(&Settings{Store: st, Check: func(b []byte) error { if strings.Contains(string(b), "listen") { return errors.New("listen is each machine's") } return nil }}) var v SettingsView if code := call(t, a, "PUT", "/api/v1/settings", `{"base":0,"body":"router:\n retries: 2\n"}`, &v); code != 200 || v.Version != 1 { t.Fatalf("first: %d %+v", code, v) } if code := call(t, a, "PUT", "/api/v1/settings", `{"base":1,"body":"listen: :1\n"}`, nil); code != 400 { t.Errorf("a document the check refuses: %d", code) } if code := call(t, a, "PUT", "/api/v1/settings", `{"base":0,"body":"router: {}\n"}`, nil); code != 409 { t.Errorf("a change from an old version: %d", code) } if code := call(t, a, "PUT", "/api/v1/settings", `{"base":1,"body":"router:\n retries: 5\n"}`, nil); code != 200 { t.Fatalf("second: %d", code) } if code := call(t, a, "POST", "/api/v1/settings/rollback", `{"version":1}`, &v); code != 200 || v.Version != 3 || v.Body != "router:\n retries: 2\n" || v.Note != "back to version 1" { t.Errorf("rollback: %d %+v", code, v) } var h []SettingsView if code := call(t, a, "GET", "/api/v1/settings/history", "", &h); code != 200 || len(h) != 3 || h[0].Version != 3 { t.Errorf("history: %d %+v", code, h) } if code := call(t, a, "GET", "/api/v1/settings?version=9", "", nil); code != 404 { t.Errorf("a version that is not there: %d", code) } }