2

Here's a (somewhat simplified) bit of code that exposes a boolean if we've become leader via K8s leader election and false otherwise:

type SimpleLeader struct {
    amLeader atomic.Value
}

func (s *SimpleLeader) run(ctx context.Context, client coordinationv1client.LeasesGetter) {

    lock := &resourcelock.LeaseLock{
        LeaseMeta: metav1.ObjectMeta{
            Name:      "testname",
            Namespace: "testnamespace",
        },
        Client: client,
        LockConfig: resourcelock.ResourceLockConfig{
            Identity: "testidentity",
        },
    }

    leaderelection.RunOrDie(ctx, leaderelection.LeaderElectionConfig{
        Lock:            lock,
        ReleaseOnCancel: true,
        LeaseDuration:   15 * time.Second,
        RenewDeadline:   10 * time.Second,
        RetryPeriod:     2 * time.Second,
        Callbacks: leaderelection.LeaderCallbacks{
            OnStartedLeading: func(c context.Context) {
                s.amLeader.Store(true)
            },
            OnStoppedLeading: func() {
                s.amLeader.Store(false)
            },
        },
    })
}

My question is how one would go about unit testing this? I'm aware of client-go/fake which does at least allow me to call run. What's not clear is how to manipulate the fake client go so as to deterministically control whether I hold the lock at any given point in time.

Adrian
  • 42,911
  • 6
  • 107
  • 99
d80tb7
  • 863
  • 2
  • 9
  • 20

0 Answers0