sqlKv_test.go 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107
  1. // Copyright 2021 EMQ Technologies Co., Ltd.
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. package sqlkv
  15. import (
  16. "os"
  17. "path"
  18. "path/filepath"
  19. "reflect"
  20. "testing"
  21. )
  22. func TestSqlKVStore_Funcs(t *testing.T) {
  23. abs, _ := filepath.Abs("test")
  24. if f, _ := os.Stat(abs); f != nil {
  25. os.Remove(abs)
  26. }
  27. _, db := newSqliteDatabase(abs)
  28. db.Connect()
  29. database = db
  30. ks, _ := GetKVStore("test")
  31. if err := ks.Setnx("foo", "bar"); nil != err {
  32. t.Error(err)
  33. }
  34. var v string
  35. if ok, _ := ks.Get("foo", &v); ok {
  36. if !reflect.DeepEqual("bar", v) {
  37. t.Error("expect:bar", "get:", v)
  38. }
  39. } else {
  40. t.Errorf("Should not find the foo key.")
  41. }
  42. if err := ks.Setnx("foo1", "bar1"); nil != err {
  43. t.Error(err)
  44. }
  45. if err := ks.Set("foo1", "bar2"); nil != err {
  46. t.Error(err)
  47. }
  48. var v1 string
  49. if ok, _ := ks.Get("foo1", &v1); ok {
  50. if !reflect.DeepEqual("bar2", v1) {
  51. t.Error("expect:bar2", "get:", v1)
  52. }
  53. } else {
  54. t.Errorf("Should not find the foo1 key.")
  55. }
  56. if keys, e1 := ks.Keys(); e1 != nil {
  57. t.Errorf("Failed to get value: %s.", e1)
  58. } else {
  59. if !reflect.DeepEqual(2, len(keys)) {
  60. t.Error("expect:2", "get:", len(keys))
  61. }
  62. }
  63. var v2 string
  64. if ok, _ := ks.Get("foo", &v2); ok {
  65. if !reflect.DeepEqual("bar", v2) {
  66. t.Error("expect:bar", "get:", v)
  67. }
  68. } else {
  69. t.Errorf("Should not find the foo key.")
  70. }
  71. if err := ks.Delete("foo1"); nil != err {
  72. t.Error(err)
  73. }
  74. if keys, e1 := ks.Keys(); e1 != nil {
  75. t.Errorf("Failed to get value: %s.", e1)
  76. } else {
  77. reflect.DeepEqual(1, len(keys))
  78. }
  79. if err := ks.Clean(); nil != err {
  80. t.Error(err)
  81. }
  82. if keys, e1 := ks.Keys(); e1 != nil {
  83. t.Errorf("Failed to get value: %s.", e1)
  84. } else {
  85. reflect.DeepEqual(0, len(keys))
  86. }
  87. database.Disconnect()
  88. dir, _ := filepath.Split(abs)
  89. abs = path.Join(dir, "sqliteKV.db")
  90. os.Remove(abs)
  91. }