cache_test.go 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. package test
  2. import (
  3. "github.com/goflyfox/gtoken/gtoken"
  4. "github.com/gogf/gf/encoding/gjson"
  5. "github.com/gogf/gf/frame/g"
  6. "github.com/gogf/gf/os/gcache"
  7. "github.com/gogf/gf/util/gconv"
  8. "testing"
  9. "time"
  10. )
  11. func TestGCache(t *testing.T) {
  12. t.Log("gcache test ")
  13. userKey := "123123"
  14. gcache.Set(userKey, "1", 10000)
  15. if gcache.Get(userKey).(string) == userKey {
  16. t.Error("cache get error")
  17. }
  18. gcache.Remove(userKey)
  19. if gcache.Get(userKey) != nil {
  20. t.Error("cache remove error")
  21. }
  22. }
  23. func TestRedisCache(t *testing.T) {
  24. if g.Config().GetInt8("cache-mode") != gtoken.CacheModeRedis {
  25. t.Log("redis cache not test ")
  26. return
  27. }
  28. t.Log("redis cache test ")
  29. userKey := "test:a"
  30. _, err := g.Redis().Do("SETEX", userKey, 10000, "1")
  31. if err != nil {
  32. t.Error("cache set error," + err.Error())
  33. }
  34. time.Sleep(1 * time.Second)
  35. ttl, err2 := g.Redis().Do("TTL", userKey)
  36. if err2 != nil {
  37. t.Error("cache ttl error," + err.Error())
  38. }
  39. t.Log("ttl:" + gconv.String(ttl))
  40. if gconv.Int(ttl) >= 10000 || gconv.Int(ttl) < 9000 {
  41. t.Error("cache ttl error, ttl:" + gconv.String(ttl))
  42. }
  43. data, err3 := g.Redis().Do("GET", userKey)
  44. if err3 != nil {
  45. t.Error("cache get error," + err.Error())
  46. }
  47. t.Log("data:" + gconv.String(data))
  48. if gconv.String(data) != "1" {
  49. t.Error("cache get error, data:" + gconv.String(data))
  50. }
  51. g.Redis().Do("DEL", userKey)
  52. data, err4 := g.Redis().Do("GET", userKey)
  53. if err4 != nil {
  54. t.Error("cache del get error," + err.Error())
  55. }
  56. if gconv.String(data) != "" {
  57. t.Error("cache del error, data:" + gconv.String(data))
  58. }
  59. }
  60. func TestJson(t *testing.T) {
  61. t.Log("json test ")
  62. cacheValue := g.Map{
  63. "userKey": "123",
  64. "uuid": "abc",
  65. "data": "",
  66. }
  67. cacheValueJson, err1 := gjson.Encode(cacheValue)
  68. if err1 != nil {
  69. t.Error("cache json encode error:" + err1.Error())
  70. }
  71. var userCache g.Map
  72. err2 := gjson.DecodeTo(cacheValueJson, &userCache)
  73. if err2 != nil {
  74. t.Error("cache get json error:" + err2.Error())
  75. }
  76. if gconv.Map(userCache)["userKey"] != "123" {
  77. t.Error("cache get json data error:" + gconv.String(userCache))
  78. }
  79. }