cache_test.go 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102
  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. value, err := gcache.Get(userKey)
  16. if err != nil {
  17. t.Error("cache set error," + err.Error())
  18. }
  19. if value.(string) == userKey {
  20. t.Error("cache get error")
  21. }
  22. gcache.Remove(userKey)
  23. value, err = gcache.Get(userKey)
  24. if err != nil {
  25. t.Error("cache set error," + err.Error())
  26. }
  27. if value != nil {
  28. t.Error("cache remove error")
  29. }
  30. }
  31. func TestRedisCache(t *testing.T) {
  32. if g.Config().GetInt8("gtoken.cache-mode") != gtoken.CacheModeRedis {
  33. t.Log("redis cache not test ")
  34. return
  35. }
  36. t.Log("redis cache test ")
  37. userKey := "test:a"
  38. _, err := g.Redis().Do("SETEX", userKey, 10000, "1")
  39. if err != nil {
  40. t.Error("cache set error," + err.Error())
  41. }
  42. time.Sleep(1 * time.Second)
  43. ttl, err2 := g.Redis().Do("TTL", userKey)
  44. if err2 != nil {
  45. t.Error("cache ttl error," + err.Error())
  46. }
  47. t.Log("ttl:" + gconv.String(ttl))
  48. if gconv.Int(ttl) >= 10000 || gconv.Int(ttl) < 9000 {
  49. t.Error("cache ttl error, ttl:" + gconv.String(ttl))
  50. }
  51. data, err3 := g.Redis().Do("GET", userKey)
  52. if err3 != nil {
  53. t.Error("cache get error," + err.Error())
  54. }
  55. t.Log("data:" + gconv.String(data))
  56. if gconv.String(data) != "1" {
  57. t.Error("cache get error, data:" + gconv.String(data))
  58. }
  59. g.Redis().Do("DEL", userKey)
  60. data, err4 := g.Redis().Do("GET", userKey)
  61. if err4 != nil {
  62. t.Error("cache del get error," + err.Error())
  63. }
  64. if gconv.String(data) != "" {
  65. t.Error("cache del error, data:" + gconv.String(data))
  66. }
  67. }
  68. func TestJson(t *testing.T) {
  69. t.Log("json test ")
  70. cacheValue := g.Map{
  71. "userKey": "123",
  72. "uuid": "abc",
  73. "data": "",
  74. }
  75. cacheValueJson, err1 := gjson.Encode(cacheValue)
  76. if err1 != nil {
  77. t.Error("cache json encode error:" + err1.Error())
  78. }
  79. var userCache g.Map
  80. err2 := gjson.DecodeTo(cacheValueJson, &userCache)
  81. if err2 != nil {
  82. t.Error("cache get json error:" + err2.Error())
  83. }
  84. if gconv.Map(userCache)["userKey"] != "123" {
  85. t.Error("cache get json data error:" + gconv.String(userCache))
  86. }
  87. }