Files
gitea/modules/globallock/globallock_test.go
T
76a81b24f9 chore: enable forcetypeassert linter, fix issues (#38804)
Enable [`forcetypeassert`](https://github.com/gostaticanalysis/forcetypeassert)
linter to prevent unchecked type assertions. ~650 issues fixed, most
fixes were clean, some use `setting.PanicInDevOrTesting`.

The only behaviour changes are where code would previously send a 500 error
or panic, a 4xx error is now emitted.

Co-authored-by: wxiaoguang <wxiaoguang@gmail.com>
2026-08-09 10:25:06 +00:00

60 lines
1.3 KiB
Go

// Copyright 2024 The Gitea Authors. All rights reserved.
// SPDX-License-Identifier: MIT
package globallock
import (
"context"
"sync"
"testing"
"time"
"gitea.dev/modules/test"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
func TestLockAndDo(t *testing.T) {
t.Run("redis", func(t *testing.T) {
defer test.MockVariableValue(&redisLockExpiry, 5*time.Second)() // Close waits for the extend goroutine's next tick
locker := newTestRedisLocker(t)
defaultLocker.Store(new(locker))
testLockAndDo(t)
rl, ok := locker.(*redisLocker)
require.True(t, ok)
require.NoError(t, rl.Close())
})
t.Run("memory", func(t *testing.T) {
defaultLocker.Store(new(NewMemoryLocker()))
testLockAndDo(t)
})
}
func testLockAndDo(t *testing.T) {
const concurrency = 50
ctx := t.Context()
count := 0
wg := sync.WaitGroup{}
for range concurrency {
wg.Go(func() {
err := LockAndDo(ctx, "test", func(ctx context.Context) error {
count++
// It's impossible to acquire the lock inner the function
ok, err := TryLockAndDo(ctx, "test", func(ctx context.Context) error {
assert.Fail(t, "should not acquire the lock")
return nil
})
assert.False(t, ok)
assert.NoError(t, err)
return nil
})
assert.NoError(t, err)
})
}
wg.Wait()
assert.Equal(t, concurrency, count)
}