package controlplanestore import ( "context" "errors" "slices" "testing" "github.com/samcharles93/archie-core/internal/config" "github.com/samcharles93/archie-core/internal/domain/storecontract" ) type memStore struct { resource storecontract.Resource history []storecontract.Resource } func (m *memStore) ListResources(context.Context) ([]storecontract.Resource, error) { return []storecontract.Resource{m.resource}, nil } func (m *memStore) Resource(context.Context, string, string) (storecontract.Resource, error) { return m.resource, nil } func (m *memStore) ResourceHistory(context.Context, string, string, int) ([]storecontract.Resource, error) { return m.history, nil } func (m *memStore) PutResource(_ context.Context, w storecontract.ResourceWrite) (storecontract.Resource, error) { m.resource = storecontract.Resource{OrgID: w.OrgID, Kind: w.Kind, Value: w.Value, Version: m.resource.Version + 1} return m.resource, nil } // A shipped document an operator edited is kept, unless it no longer validates: // then it is repaired, or replaced by the build's copy when it has no repair. func TestSeedRefreshesStoredShippedDocumentOnlyWhenInvalid(t *testing.T) { definition := Definition{ Kind: "shipped", Seed: func(config.Config) any { return "current" }, Defaults: func() any { return "current" }, Validate: func(in []byte) error { if string(in) != `"current"` && string(in) != `"edited"` { return errors.New("names a deleted step type") } return nil }, } repair := func([]byte) ([]byte, []string, error) { return []byte(`"edited"`), []string{"gone"}, nil } tests := []struct { name string stored string repair func([]byte) ([]byte, []string, error) want string wantRemoved []string }{ {"edited and valid is kept", `"edited"`, repair, `"edited"`, nil}, {"invalid is repaired", `"deleted-step"`, repair, `"edited"`, []string{"gone"}}, {"invalid without a repair is replaced", `"deleted-step"`, nil, `"current"`, nil}, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { store := &memStore{ resource: storecontract.Resource{Kind: "shipped", Value: []byte(tt.stored), Version: 3}, history: []storecontract.Resource{{Actor: "operator", Source: "dashboard"}}, } s := &Server{store: store} definition.Repair = tt.repair _, removed, err := s.seedKind(context.Background(), storecontract.DefaultOrgID, definition, config.Config{}) if err != nil { t.Fatal(err) } if !slices.Equal(removed, tt.wantRemoved) { t.Fatalf("removed %v, want %v", removed, tt.wantRemoved) } if got := string(store.resource.Value); got != tt.want { t.Fatalf("stored %s, want %s", got, tt.want) } }) } }