111 lines
2.0 KiB
Go
111 lines
2.0 KiB
Go
package ocean_test
|
|
|
|
import (
|
|
"sync"
|
|
"testing"
|
|
|
|
"git.akyoto.dev/go/assert"
|
|
"git.akyoto.dev/go/ocean"
|
|
)
|
|
|
|
type User struct {
|
|
Name string `json:"name"`
|
|
}
|
|
|
|
func TestCollection(t *testing.T) {
|
|
users, err := ocean.New[User]("test", nil)
|
|
assert.Nil(t, err)
|
|
|
|
defer users.Sync()
|
|
defer users.Clear()
|
|
|
|
users.Set("1", &User{Name: "User 1"})
|
|
users.Set("2", &User{Name: "User 2"})
|
|
users.Set("3", &User{Name: "User 3"})
|
|
|
|
t.Run("All", func(t *testing.T) {
|
|
count := 0
|
|
|
|
for range users.All() {
|
|
count++
|
|
}
|
|
|
|
assert.Equal(t, count, 3)
|
|
})
|
|
|
|
t.Run("Filter", func(t *testing.T) {
|
|
count := 0
|
|
|
|
f := func(user *User) bool {
|
|
return user.Name == "User 2"
|
|
}
|
|
|
|
for range users.Filter(f) {
|
|
count++
|
|
}
|
|
|
|
assert.Equal(t, count, 1)
|
|
})
|
|
|
|
t.Run("Get", func(t *testing.T) {
|
|
user, err := users.Get("1")
|
|
assert.Nil(t, err)
|
|
assert.NotNil(t, user)
|
|
assert.Equal(t, user.Name, "User 1")
|
|
})
|
|
|
|
t.Run("Exists", func(t *testing.T) {
|
|
assert.True(t, users.Exists("1"))
|
|
assert.True(t, users.Exists("2"))
|
|
assert.True(t, users.Exists("3"))
|
|
assert.True(t, !users.Exists("4"))
|
|
})
|
|
|
|
t.Run("Parallel Get and Set", func(t *testing.T) {
|
|
wg := sync.WaitGroup{}
|
|
|
|
for i := 0; i < 100; i++ {
|
|
wg.Add(2)
|
|
|
|
go func() {
|
|
defer wg.Done()
|
|
user, err := users.Get("1")
|
|
assert.Nil(t, err)
|
|
assert.NotNil(t, user)
|
|
assert.Equal(t, user.Name, "User 1")
|
|
}()
|
|
|
|
go func() {
|
|
defer wg.Done()
|
|
users.Set("1", &User{Name: "User 1"})
|
|
}()
|
|
}
|
|
|
|
wg.Wait()
|
|
})
|
|
|
|
t.Run("Delete", func(t *testing.T) {
|
|
assert.True(t, users.Exists("1"))
|
|
assert.True(t, users.Exists("2"))
|
|
assert.True(t, users.Exists("3"))
|
|
|
|
users.Delete("1")
|
|
|
|
assert.True(t, !users.Exists("1"))
|
|
assert.True(t, users.Exists("2"))
|
|
assert.True(t, users.Exists("3"))
|
|
|
|
users.Delete("2")
|
|
|
|
assert.True(t, !users.Exists("1"))
|
|
assert.True(t, !users.Exists("2"))
|
|
assert.True(t, users.Exists("3"))
|
|
|
|
users.Delete("3")
|
|
|
|
assert.True(t, !users.Exists("1"))
|
|
assert.True(t, !users.Exists("2"))
|
|
assert.True(t, !users.Exists("3"))
|
|
})
|
|
}
|