github.com/gogf/gf/v2@v2.7.4/os/gsession/gsession_z_unit_storage_memory_test.go (about)

     1  // Copyright GoFrame Author(https://goframe.org). All Rights Reserved.
     2  //
     3  // This Source Code Form is subject to the terms of the MIT License.
     4  // If a copy of the MIT was not distributed with this file,
     5  // You can obtain one at https://github.com/gogf/gf.
     6  
     7  package gsession_test
     8  
     9  import (
    10  	"context"
    11  	"testing"
    12  	"time"
    13  
    14  	"github.com/gogf/gf/v2/frame/g"
    15  	"github.com/gogf/gf/v2/os/gsession"
    16  	"github.com/gogf/gf/v2/test/gtest"
    17  )
    18  
    19  func Test_StorageMemory(t *testing.T) {
    20  	storage := gsession.NewStorageMemory()
    21  	manager := gsession.New(time.Second, storage)
    22  	sessionId := ""
    23  	gtest.C(t, func(t *gtest.T) {
    24  		s := manager.New(context.TODO())
    25  		defer s.Close()
    26  		s.Set("k1", "v1")
    27  		s.Set("k2", "v2")
    28  		s.SetMap(g.Map{
    29  			"k3": "v3",
    30  			"k4": "v4",
    31  		})
    32  		t.Assert(s.IsDirty(), true)
    33  		sessionId = s.MustId()
    34  	})
    35  
    36  	time.Sleep(500 * time.Millisecond)
    37  	gtest.C(t, func(t *gtest.T) {
    38  		s := manager.New(context.TODO(), sessionId)
    39  		t.Assert(s.MustGet("k1"), "v1")
    40  		t.Assert(s.MustGet("k2"), "v2")
    41  		t.Assert(s.MustGet("k3"), "v3")
    42  		t.Assert(s.MustGet("k4"), "v4")
    43  		t.Assert(len(s.MustData()), 4)
    44  		t.Assert(s.MustData()["k1"], "v1")
    45  		t.Assert(s.MustData()["k4"], "v4")
    46  		t.Assert(s.MustId(), sessionId)
    47  		t.Assert(s.MustSize(), 4)
    48  		t.Assert(s.MustContains("k1"), true)
    49  		t.Assert(s.MustContains("k3"), true)
    50  		t.Assert(s.MustContains("k5"), false)
    51  		s.Remove("k4")
    52  		t.Assert(s.MustSize(), 3)
    53  		t.Assert(s.MustContains("k3"), true)
    54  		t.Assert(s.MustContains("k4"), false)
    55  		s.RemoveAll()
    56  		t.Assert(s.MustSize(), 0)
    57  		t.Assert(s.MustContains("k1"), false)
    58  		t.Assert(s.MustContains("k2"), false)
    59  		s.SetMap(g.Map{
    60  			"k5": "v5",
    61  			"k6": "v6",
    62  		})
    63  		t.Assert(s.MustSize(), 2)
    64  		t.Assert(s.MustContains("k5"), true)
    65  		t.Assert(s.MustContains("k6"), true)
    66  	})
    67  
    68  	time.Sleep(1000 * time.Millisecond)
    69  	gtest.C(t, func(t *gtest.T) {
    70  		s := manager.New(context.TODO(), sessionId)
    71  		t.Assert(s.MustSize(), 0)
    72  		t.Assert(s.MustGet("k5"), nil)
    73  		t.Assert(s.MustGet("k6"), nil)
    74  	})
    75  }