2022-12-02 22:56:49 +03:00
|
|
|
package api
|
|
|
|
|
|
|
|
import (
|
|
|
|
"sort"
|
|
|
|
"testing"
|
2022-12-02 23:20:20 +03:00
|
|
|
"time"
|
2022-12-02 22:56:49 +03:00
|
|
|
|
|
|
|
"github.com/sirupsen/logrus"
|
2022-12-02 23:00:01 +03:00
|
|
|
"github.com/stretchr/testify/assert"
|
|
|
|
|
2022-12-02 22:56:49 +03:00
|
|
|
"github.com/sosedoff/pgweb/pkg/client"
|
|
|
|
)
|
|
|
|
|
|
|
|
func TestSessionManager(t *testing.T) {
|
2022-12-02 22:57:56 +03:00
|
|
|
t.Run("return ids", func(t *testing.T) {
|
2022-12-02 22:56:49 +03:00
|
|
|
manager := NewSessionManager(nil)
|
|
|
|
assert.Equal(t, []string{}, manager.IDs())
|
|
|
|
|
|
|
|
manager.sessions["foo"] = &client.Client{}
|
|
|
|
manager.sessions["bar"] = &client.Client{}
|
|
|
|
|
|
|
|
ids := manager.IDs()
|
|
|
|
sort.Strings(ids)
|
|
|
|
assert.Equal(t, []string{"bar", "foo"}, ids)
|
|
|
|
})
|
|
|
|
|
|
|
|
t.Run("get session", func(t *testing.T) {
|
|
|
|
manager := NewSessionManager(nil)
|
|
|
|
assert.Nil(t, manager.Get("foo"))
|
|
|
|
|
|
|
|
manager.sessions["foo"] = &client.Client{}
|
|
|
|
assert.NotNil(t, manager.Get("foo"))
|
|
|
|
})
|
|
|
|
|
|
|
|
t.Run("set session", func(t *testing.T) {
|
|
|
|
manager := NewSessionManager(nil)
|
|
|
|
assert.Nil(t, manager.Get("foo"))
|
|
|
|
|
|
|
|
manager.Add("foo", &client.Client{})
|
|
|
|
assert.NotNil(t, manager.Get("foo"))
|
|
|
|
})
|
|
|
|
|
|
|
|
t.Run("remove session", func(t *testing.T) {
|
|
|
|
manager := NewSessionManager(nil)
|
|
|
|
assert.Nil(t, manager.Get("foo"))
|
|
|
|
|
|
|
|
manager.Add("foo", &client.Client{})
|
|
|
|
assert.NotNil(t, manager.Get("foo"))
|
|
|
|
assert.True(t, manager.Remove("foo"))
|
|
|
|
assert.False(t, manager.Remove("foo"))
|
|
|
|
assert.Nil(t, manager.Get("foo"))
|
|
|
|
})
|
|
|
|
|
2022-12-02 22:57:56 +03:00
|
|
|
t.Run("return len", func(t *testing.T) {
|
2022-12-02 22:56:49 +03:00
|
|
|
manager := NewSessionManager(nil)
|
|
|
|
manager.sessions["foo"] = &client.Client{}
|
|
|
|
manager.sessions["bar"] = &client.Client{}
|
|
|
|
|
|
|
|
assert.Equal(t, 2, manager.Len())
|
|
|
|
})
|
|
|
|
|
2022-12-02 22:57:56 +03:00
|
|
|
t.Run("clean up stale sessions", func(t *testing.T) {
|
2022-12-02 22:56:49 +03:00
|
|
|
manager := NewSessionManager(logrus.New())
|
|
|
|
conn := &client.Client{}
|
|
|
|
manager.Add("foo", conn)
|
|
|
|
|
|
|
|
assert.Equal(t, 1, manager.Len())
|
|
|
|
assert.Equal(t, 0, manager.Cleanup())
|
|
|
|
assert.Equal(t, 1, manager.Len())
|
|
|
|
|
2022-12-02 23:22:50 +03:00
|
|
|
res, err := conn.Query("select 1")
|
|
|
|
assert.Nil(t, res)
|
|
|
|
assert.Nil(t, err)
|
|
|
|
|
2022-12-02 23:20:20 +03:00
|
|
|
manager.SetIdleTimeout(time.Minute)
|
2022-12-02 22:56:49 +03:00
|
|
|
assert.Equal(t, 1, manager.Cleanup())
|
|
|
|
assert.Equal(t, 0, manager.Len())
|
2022-12-02 22:59:22 +03:00
|
|
|
assert.True(t, conn.IsClosed())
|
2022-12-02 22:56:49 +03:00
|
|
|
})
|
|
|
|
}
|