Skip to content

Commit

Permalink
refactor(tests): clean artefacts on panic
Browse files Browse the repository at this point in the history
  • Loading branch information
byashimov committed Feb 28, 2024
1 parent a2a99bf commit 077c752
Showing 1 changed file with 26 additions and 13 deletions.
39 changes: 26 additions & 13 deletions tests/session.go
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@ import (
)

const (
suiteTimeout = time.Minute * 20
retryInterval = time.Second * 10
createTimeout = time.Second * 15
waitRunningTimeout = time.Minute * 20
Expand All @@ -45,20 +46,23 @@ type Session interface {
var _ Session = &session{}

type session struct {
k8s client.Client
avn *aiven.Client
ctx context.Context
objs map[string]client.Object
project string
k8s client.Client
avn *aiven.Client
ctx context.Context
cancelCtx func()
objs map[string]client.Object
project string
}

func NewSession(k8s client.Client, avn *aiven.Client, project string) Session {
ctx, cancel := context.WithTimeout(context.Background(), suiteTimeout)
s := &session{
k8s: k8s,
avn: avn,
ctx: context.Background(),
objs: make(map[string]client.Object),
project: project,
k8s: k8s,
avn: avn,
ctx: ctx,
cancelCtx: cancel,
objs: make(map[string]client.Object),
project: project,
}
return s
}
Expand Down Expand Up @@ -142,6 +146,12 @@ func (s *session) GetSecret(keys ...string) (*corev1.Secret, error) {
// Tolerant to "not found" error,
// because resource may have been deleted manually
func (s *session) Destroy() {
defer s.cancelCtx()

if err := recover(); err != nil {
log.Printf("panicked, deleting resources: %s", err)
}

var wg sync.WaitGroup
wg.Add(len(s.objs))
for n := range s.objs {
Expand Down Expand Up @@ -183,15 +193,18 @@ func (s *session) delete(o client.Object) error {
return fmt.Errorf("resource %q not applied", o.GetName())
}

err := s.k8s.Delete(s.ctx, o)
// Delete operation doesn't share the context,
// because it shouldn't leave artifacts
ctx := context.Background()
err := s.k8s.Delete(ctx, o)
if err != nil {
return fmt.Errorf("kubernetes error: %w", err)
}

// Waits being deleted from kube
key := types.NamespacedName{Name: o.GetName(), Namespace: o.GetNamespace()}
return retryForever(s.ctx, fmt.Sprintf("delete %s", o.GetName()), func() (bool, error) {
err := s.k8s.Get(s.ctx, key, o)
return retryForever(ctx, fmt.Sprintf("delete %s", o.GetName()), func() (bool, error) {
err := s.k8s.Get(ctx, key, o)
return !isNotFound(err), nil
})
}
Expand Down

0 comments on commit 077c752

Please sign in to comment.