package cache import ( "context" "testing" "time" "github.com/stretchr/testify/require" ) type awaitStore struct { value []byte held bool lockErr error } func (s awaitStore) Get(context.Context, string) ([]byte, error) { if s.value != nil { return s.value, nil } return nil, ErrCacheMiss } func (awaitStore) Set(context.Context, string, []byte, time.Duration) error { return nil } func (awaitStore) Delete(context.Context, ...string) error { return nil } func (awaitStore) AcquireLock(context.Context, string, string, time.Duration) (bool, error) { return false, nil } func (awaitStore) ReleaseLock(context.Context, string, string) (bool, error) { return false, nil } func (s awaitStore) LockHeld(context.Context, string) (bool, error) { return s.held, s.lockErr } func (awaitStore) Ping(context.Context) error { return nil } func (awaitStore) Close() error { return nil } func TestAwaitChecksCacheBeforePolling(t *testing.T) { t.Parallel() d, err := NewDistributed(awaitStore{value: []byte("ready")}, DistributedConfig{WaitTimeout: time.Second}, nil) require.NoError(t, err) started := time.Now() value, outcome, err := d.await(t.Context(), "key", "lock:key") require.NoError(t, err) require.Equal(t, waitHit, outcome) require.Equal(t, "ready", string(value)) require.Less(t, time.Since(started), 25*time.Millisecond, "cache must be checked before the first sleep") } func TestAwaitReturnsTimeoutWhileLockHeld(t *testing.T) { t.Parallel() d, err := NewDistributed(awaitStore{held: true}, DistributedConfig{WaitTimeout: 60 * time.Millisecond}, nil) require.NoError(t, err) _, outcome, err := d.await(t.Context(), "key", "lock:key") require.NoError(t, err) require.Equal(t, waitTimeout, outcome) }