Skip to content
Katabench
Try free

Test Fenced Lease Ownership

Hard About 40 min Free, no account needed

Exercise expiry, renewal, ownership transfer, and stale-token rejection in a lease that must never reuse authority.

The brief

FencedLease models one exclusive lease. Use explicit integer times; never sleep.

  • Acquire(holder, now, duration) returns 0 while any holder's lease is active, even for the same holder. Otherwise it grants a lease expiring at now + duration and returns the next strictly increasing token, starting at 1. Rejected attempts do not consume tokens.
  • A lease is active only while now < expiresAt; equality permits a new acquisition.
  • Renew(holder, token, now, duration) succeeds only for the current holder and token while active. It replaces the expiry with now + duration, which may shorten the lease. Failure changes nothing.
  • Release(holder, token) succeeds only for the currently recorded holder and token, clears that ownership, and never resets the token counter. It has no clock parameter, so expiry alone does not prevent releasing an otherwise current recorded lease. Releasing twice fails.

Holder strings are nonempty and compare case-sensitively. Duration is positive; calls are sequential with nondecreasing nonnegative times, and sums/tokens fit in 64 bits. A stale token must remain powerless even when the same holder name later acquires again. This class models authority allocation; downstream storage would separately enforce fencing tokens.

Write a Tests class. Every public, parameterless method is a test; a test passes if it does not throw. Use Assert.Equal, True, False, and Throws<TException> as needed. Your suite must pass on the correct subject and catch every hidden mutant. Construct fresh state in each test.

Starter code

C#
public class Tests
{
    public void First_lease()
    {
        Assert.Equal(1L, new FencedLease().Acquire("worker-a", 0, 10));
    }
}

How it is graded

You write the tests. A suite passes only when it stays green on correct code and turns enough faulty implementations red.

C# unit testing exercises →

Related guides

What it practices

Stateful testing
Drive call sequences and state-machine transitions, not just single calls.
Leases and ownership
Grant time-bounded ownership of work or a resource, with fencing tokens so a stale owner cannot act.
Boundary value testing
Pin behavior exactly at, just below and just above every boundary.

Related katas