2018-12-11 14:00:09 +01:00
|
|
|
package serverlock
|
|
|
|
|
|
|
|
|
|
import (
|
|
|
|
|
"context"
|
|
|
|
|
"testing"
|
|
|
|
|
"time"
|
|
|
|
|
|
2021-12-02 12:53:21 +01:00
|
|
|
"github.com/stretchr/testify/require"
|
2018-12-11 14:00:09 +01:00
|
|
|
)
|
|
|
|
|
|
2022-08-10 10:28:25 -03:00
|
|
|
func TestIntegrationServerLock_LockAndExecute(t *testing.T) {
|
2022-06-10 11:46:21 -04:00
|
|
|
if testing.Short() {
|
|
|
|
|
t.Skip("skipping integration test")
|
|
|
|
|
}
|
2018-12-11 14:00:09 +01:00
|
|
|
sl := createTestableServerLock(t)
|
|
|
|
|
|
2019-05-14 15:38:18 +02:00
|
|
|
counter := 0
|
2021-10-04 15:46:09 +02:00
|
|
|
fn := func(context.Context) { counter++ }
|
2021-12-02 12:53:21 +01:00
|
|
|
atInterval := time.Hour
|
2019-05-14 15:38:18 +02:00
|
|
|
ctx := context.Background()
|
|
|
|
|
|
|
|
|
|
//this time `fn` should be executed
|
2021-12-02 12:53:21 +01:00
|
|
|
require.Nil(t, sl.LockAndExecute(ctx, "test-operation", atInterval, fn))
|
|
|
|
|
require.Equal(t, 1, counter)
|
2019-05-14 15:38:18 +02:00
|
|
|
|
|
|
|
|
//this should not execute `fn`
|
2021-12-02 12:53:21 +01:00
|
|
|
require.Nil(t, sl.LockAndExecute(ctx, "test-operation", atInterval, fn))
|
|
|
|
|
require.Nil(t, sl.LockAndExecute(ctx, "test-operation", atInterval, fn))
|
|
|
|
|
require.Equal(t, 1, counter)
|
2019-05-14 15:38:18 +02:00
|
|
|
|
2021-12-02 12:53:21 +01:00
|
|
|
atInterval = time.Millisecond
|
2019-05-14 15:38:18 +02:00
|
|
|
|
|
|
|
|
// now `fn` should be executed again
|
|
|
|
|
err := sl.LockAndExecute(ctx, "test-operation", atInterval, fn)
|
2021-12-02 12:53:21 +01:00
|
|
|
require.Nil(t, err)
|
|
|
|
|
require.Equal(t, 2, counter)
|
2018-12-11 14:00:09 +01:00
|
|
|
}
|
2022-08-10 10:28:25 -03:00
|
|
|
|
|
|
|
|
func TestIntegrationServerLock_LockExecuteAndRelease(t *testing.T) {
|
|
|
|
|
if testing.Short() {
|
|
|
|
|
t.Skip("skipping integration test")
|
|
|
|
|
}
|
|
|
|
|
sl := createTestableServerLock(t)
|
|
|
|
|
|
|
|
|
|
counter := 0
|
|
|
|
|
fn := func(context.Context) { counter++ }
|
|
|
|
|
atInterval := time.Hour
|
|
|
|
|
ctx := context.Background()
|
|
|
|
|
|
|
|
|
|
//
|
|
|
|
|
err := sl.LockExecuteAndRelease(ctx, "test-operation", atInterval, fn)
|
|
|
|
|
require.NoError(t, err)
|
|
|
|
|
require.Equal(t, 1, counter)
|
|
|
|
|
|
|
|
|
|
// the function will be executed again, as everytime the lock is released
|
|
|
|
|
err = sl.LockExecuteAndRelease(ctx, "test-operation", atInterval, fn)
|
|
|
|
|
require.NoError(t, err)
|
|
|
|
|
err = sl.LockExecuteAndRelease(ctx, "test-operation", atInterval, fn)
|
|
|
|
|
require.NoError(t, err)
|
|
|
|
|
err = sl.LockExecuteAndRelease(ctx, "test-operation", atInterval, fn)
|
|
|
|
|
require.NoError(t, err)
|
|
|
|
|
|
|
|
|
|
require.Equal(t, 4, counter)
|
|
|
|
|
}
|