github.com/sohaha/zlsgo@v1.7.13-0.20240501141223-10dd1a906f76/zcache/tofile/tofile_test.go (about) 1 package tofile 2 3 import ( 4 "testing" 5 "time" 6 7 "github.com/sohaha/zlsgo" 8 "github.com/sohaha/zlsgo/zcache" 9 "github.com/sohaha/zlsgo/zfile" 10 ) 11 12 type testSt struct { 13 Name string 14 Key int 15 } 16 17 func TestToFile(t *testing.T) { 18 tt := zlsgo.NewTest(t) 19 cache := zcache.New("file") 20 err := zfile.WriteFile("tmp.json", []byte(`{"tmp1":"XhAAFSp0b2ZpbGUucGVyc2lzdGVuY2VTdP+BAwEBDXBlcnNpc3RlbmNlU3QB/4IAAQMBBERhdGEBEAABCExpZmVTcGFuAQQAARBJbnRlcnZhbExpZmVTcGFuAQIAAABP/4I1AQ4qdG9maWxlLnRlc3RTdP+DAwEBBnRlc3RTdAH/hAABAgEETmFtZQEMAAEDS2V5AQQAAAAW/4QJAQZpc05hbWUAAfsFloLwAAEBAA==","tmp3":"XhAAFSp0b2ZpbGUucGVyc2lzdGVuY2VTdP+BAwEBDXBlcnNpc3RlbmNlU3QB/4IAAQMBBERhdGEBEAABCExpZmVTcGFuAQQAARBJbnRlcnZhbExpZmVTcGFuAQIAAAAg/4IdAQZzdHJpbmcMCwAJaXMgc3RyaW5nAfsBZaC8AAA=","tmp2":"XhAAFSp0b2ZpbGUucGVyc2lzdGVuY2VTdP+BAwEBDXBlcnNpc3RlbmNlU3QB/4IAAQMBBERhdGEBEAABCExpZmVTcGFuAQQAARBJbnRlcnZhbExpZmVTcGFuAQIAAAAW/4ITAQNpbnQEBAD+BTQB+wFloLwAAA=="}`)) 21 tt.EqualExit(nil, err) 22 save, err := PersistenceToFile(cache, "tmp.json", false, &testSt{}) 23 tt.EqualExit(nil, err) 24 25 cache.Set("tmp1", &testSt{ 26 Name: "isName", 27 Key: 0, 28 }, 3, true) 29 cache.Set("tmp2", 666, 3) 30 cache.Set("tmp3", "is string", 3) 31 32 cache.ForEach(func(key string, value interface{}) bool { 33 tt.Log(key) 34 return true 35 }) 36 tmp1, err := cache.Get("tmp1") 37 tt.EqualExit(nil, err) 38 tt.Equal("isName", tmp1.(*testSt).Name) 39 tmp2, err := cache.GetInt("tmp2") 40 tt.EqualNil(err) 41 tt.Equal(666, tmp2) 42 tmp3, err := cache.GetString("tmp3") 43 tt.EqualNil(err) 44 tt.Equal("is string", tmp3) 45 go func() { 46 time.Sleep(500 * time.Millisecond) 47 _, _ = cache.Get("tmp1") 48 }() 49 time.Sleep(3*time.Second + 300*time.Millisecond) 50 tmp1, err = cache.Get("tmp1") 51 tt.EqualNil(err) 52 t.Log(tmp1) 53 _, err = cache.GetInt("tmp2") 54 tt.EqualTrue(err != nil) 55 _, err = cache.GetString("tmp3") 56 tt.EqualTrue(err != nil) 57 58 cache.Set("tmp0", 1, 2) 59 tt.Equal(2, cache.Count()) 60 zfile.Rmdir("tmp.json") 61 62 err = save() 63 tt.EqualNil(err) 64 tt.EqualTrue(zfile.FileExist("tmp.json")) 65 66 _ = zfile.WriteFile("tmp.json", []byte(`{"tmp1":"XhAAFSp0b2ZpbGUucGVyc2lzdGVuY2VTdP+BAwEBDXBlcnNpc3RlbmNlU3QB/4IAAQMBBERhdGEBEAABCExpZmVTcGFuAQQAARBJbnRlcnZhbExpZmVTcGFuAQIAAABP/4I1AQ4qdG9maWxlLnRlc3RTdP+DAwEBBnRlc3RTdAH/hAABAgEETmFtZQEMAAEDS2V"}`)) 67 _, err = PersistenceToFile(cache, "tmp.json", false) 68 tt.EqualTrue(err != nil) 69 70 zfile.Rmdir("tmp.json") 71 }