2015-12-26 20:23:09 +00:00
|
|
|
package memorylocker
|
|
|
|
|
|
|
|
import (
|
2022-03-19 22:21:17 +00:00
|
|
|
"context"
|
2015-12-26 20:23:09 +00:00
|
|
|
"testing"
|
2022-03-19 22:21:17 +00:00
|
|
|
"time"
|
2015-12-26 20:23:09 +00:00
|
|
|
|
2016-01-20 15:40:13 +00:00
|
|
|
"github.com/stretchr/testify/assert"
|
2019-06-11 16:23:20 +00:00
|
|
|
"github.com/tus/tusd/pkg/handler"
|
2015-12-26 20:23:09 +00:00
|
|
|
)
|
|
|
|
|
2019-09-11 08:28:38 +00:00
|
|
|
var _ handler.Locker = &MemoryLocker{}
|
|
|
|
|
2022-03-19 22:21:17 +00:00
|
|
|
func TestMemoryLocker_LockAndUnlock(t *testing.T) {
|
2016-01-20 15:40:13 +00:00
|
|
|
a := assert.New(t)
|
|
|
|
|
2019-09-11 08:28:38 +00:00
|
|
|
locker := New()
|
|
|
|
|
|
|
|
lock1, err := locker.NewLock("one")
|
|
|
|
a.NoError(err)
|
|
|
|
|
2022-03-19 22:21:17 +00:00
|
|
|
a.NoError(lock1.Lock(context.Background(), func() {
|
|
|
|
panic("must not be called")
|
|
|
|
}))
|
|
|
|
a.NoError(lock1.Unlock())
|
|
|
|
}
|
|
|
|
|
|
|
|
func TestMemoryLocker_Timeout(t *testing.T) {
|
|
|
|
a := assert.New(t)
|
|
|
|
|
|
|
|
locker := New()
|
|
|
|
releaseRequestCalled := false
|
|
|
|
|
|
|
|
lock1, err := locker.NewLock("one")
|
|
|
|
a.NoError(err)
|
|
|
|
a.NoError(lock1.Lock(context.Background(), func() {
|
|
|
|
releaseRequestCalled = true
|
|
|
|
// We note that the function has been called, but do not
|
|
|
|
// release the lock
|
|
|
|
}))
|
|
|
|
|
|
|
|
ctx, cancel := context.WithTimeout(context.Background(), time.Millisecond)
|
|
|
|
defer cancel()
|
2019-09-11 08:28:38 +00:00
|
|
|
|
|
|
|
lock2, err := locker.NewLock("one")
|
|
|
|
a.NoError(err)
|
2022-03-19 22:21:17 +00:00
|
|
|
err = lock2.Lock(ctx, func() {
|
|
|
|
panic("must not be called")
|
|
|
|
})
|
2015-12-26 20:23:09 +00:00
|
|
|
|
2022-03-19 22:21:17 +00:00
|
|
|
a.Equal(err, handler.ErrLockTimeout)
|
|
|
|
a.True(releaseRequestCalled)
|
|
|
|
}
|
|
|
|
|
|
|
|
func TestMemoryLocker_RequestUnlock(t *testing.T) {
|
|
|
|
a := assert.New(t)
|
|
|
|
|
|
|
|
locker := New()
|
|
|
|
releaseRequestCalled := false
|
|
|
|
|
|
|
|
lock1, err := locker.NewLock("one")
|
|
|
|
a.NoError(err)
|
|
|
|
a.NoError(lock1.Lock(context.Background(), func() {
|
|
|
|
releaseRequestCalled = true
|
|
|
|
<-time.After(10 * time.Millisecond)
|
|
|
|
a.NoError(lock1.Unlock())
|
|
|
|
}))
|
|
|
|
|
|
|
|
ctx, cancel := context.WithTimeout(context.Background(), time.Second)
|
|
|
|
defer cancel()
|
|
|
|
|
|
|
|
lock2, err := locker.NewLock("one")
|
|
|
|
a.NoError(err)
|
|
|
|
a.NoError(lock2.Lock(ctx, func() {
|
|
|
|
panic("must not be called")
|
|
|
|
}))
|
|
|
|
a.NoError(lock2.Unlock())
|
|
|
|
|
|
|
|
a.True(releaseRequestCalled)
|
2015-12-26 20:23:09 +00:00
|
|
|
}
|