test.go 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  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 common
  15. import (
  16. "fmt"
  17. "github.com/lf-edge/ekuiper/pkg/kv"
  18. "reflect"
  19. "testing"
  20. )
  21. func TestKvSetnx(ks kv.KeyValue, t *testing.T) {
  22. if err := ks.Setnx("foo", "bar"); nil != err {
  23. t.Error(err)
  24. }
  25. if err := ks.Setnx("foo", "bar1"); nil == err {
  26. t.Errorf("Can't overwrite an existing intem")
  27. }
  28. }
  29. func TestKvSet(ks kv.KeyValue, t *testing.T) {
  30. if err := ks.Set("foo", "bar"); nil != err {
  31. t.Error(err)
  32. }
  33. if err := ks.Set("foo", "bar1"); nil != err {
  34. t.Errorf("Set should overwrite an existing record")
  35. }
  36. }
  37. func TestKvGet(ks kv.KeyValue, t *testing.T) {
  38. if err := ks.Setnx("foo", "bar"); nil != err {
  39. t.Error(err)
  40. }
  41. var v string
  42. if ok, _ := ks.Get("foo", &v); ok {
  43. if !reflect.DeepEqual("bar", v) {
  44. t.Error("expect:bar", "get:", v)
  45. }
  46. } else {
  47. t.Errorf("Should find the foo key")
  48. }
  49. }
  50. func TestKvKeys(length int, ks kv.KeyValue, t *testing.T) {
  51. expected := make([]string, 0)
  52. for i := 0; i < length; i++ {
  53. key := fmt.Sprintf("key-%d", i)
  54. value := fmt.Sprintf("value-%d", i)
  55. if err := ks.Setnx(key, value); err != nil {
  56. t.Errorf("It should be set")
  57. }
  58. expected = append(expected, key)
  59. }
  60. var keys []string
  61. var err error
  62. if keys, err = ks.Keys(); err != nil {
  63. t.Errorf("Failed to get value: %s.", err)
  64. } else if !reflect.DeepEqual(length, len(keys)) {
  65. t.Errorf("expect: %d, got: %d", length, len(keys))
  66. }
  67. if !reflect.DeepEqual(keys, expected) {
  68. t.Errorf("Keys do not match expected %s != %s", keys, expected)
  69. }
  70. }