quintodrome/utils/singleton/singleton_test.go

Ignoring revisions in .git-blame-ignore-revs. Click here to bypass and see the normal blame view.

76 lines
1.8 KiB
Go
Raw Normal View History

2021-06-19 16:56:56 -08:00
package singleton_test
import (
2021-06-20 07:45:59 -08:00
"sync"
"sync/atomic"
2021-06-19 16:56:56 -08:00
"testing"
2021-06-20 07:45:59 -08:00
"github.com/google/uuid"
2021-06-19 16:56:56 -08:00
"github.com/navidrome/navidrome/utils/singleton"
2022-07-26 12:47:16 -08:00
. "github.com/onsi/ginkgo/v2"
2021-06-19 16:56:56 -08:00
. "github.com/onsi/gomega"
)
func TestSingleton(t *testing.T) {
RegisterFailHandler(Fail)
RunSpecs(t, "Singleton Suite")
}
var _ = Describe("Get", func() {
2021-06-20 07:45:59 -08:00
type T struct{ id string }
var numInstances int
2021-06-19 16:56:56 -08:00
constructor := func() interface{} {
2021-06-20 07:45:59 -08:00
numInstances++
return &T{id: uuid.NewString()}
2021-06-19 16:56:56 -08:00
}
It("calls the constructor to create a new instance", func() {
2021-06-20 07:45:59 -08:00
instance := singleton.Get(T{}, constructor)
Expect(numInstances).To(Equal(1))
2021-06-19 16:56:56 -08:00
Expect(instance).To(BeAssignableToTypeOf(&T{}))
})
It("does not call the constructor the next time", func() {
2021-06-20 07:45:59 -08:00
instance := singleton.Get(T{}, constructor)
2021-06-19 16:56:56 -08:00
newInstance := singleton.Get(T{}, constructor)
2021-06-20 07:45:59 -08:00
Expect(newInstance.(*T).id).To(Equal(instance.(*T).id))
Expect(numInstances).To(Equal(1))
2021-06-19 16:56:56 -08:00
})
It("does not call the constructor even if a pointer is passed as the object", func() {
2021-06-20 07:45:59 -08:00
instance := singleton.Get(T{}, constructor)
2021-06-19 16:56:56 -08:00
newInstance := singleton.Get(&T{}, constructor)
2021-06-20 07:45:59 -08:00
Expect(newInstance.(*T).id).To(Equal(instance.(*T).id))
Expect(numInstances).To(Equal(1))
})
It("only calls the constructor once when called concurrently", func() {
const maxCalls = 2000
var numCalls int32
start := sync.WaitGroup{}
start.Add(1)
prepare := sync.WaitGroup{}
prepare.Add(maxCalls)
done := sync.WaitGroup{}
done.Add(maxCalls)
for i := 0; i < maxCalls; i++ {
go func() {
start.Wait()
singleton.Get(T{}, constructor)
atomic.AddInt32(&numCalls, 1)
done.Done()
}()
prepare.Done()
}
prepare.Wait()
start.Done()
done.Wait()
Expect(numCalls).To(Equal(int32(maxCalls)))
Expect(numInstances).To(Equal(1))
2021-06-19 16:56:56 -08:00
})
})