memory_test.go 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. package cache
  2. import (
  3. "context"
  4. "testing"
  5. "time"
  6. )
  7. func TestMemorySetGetDelete(t *testing.T) {
  8. // 创建一个新的 memory Cache 实例
  9. memCache := NewMemory()
  10. // 设置一个键值对
  11. key := "testKey"
  12. val := "testValue"
  13. ttl := 1 * time.Minute
  14. _, err := memCache.Set(context.Background(), key, val, ttl)
  15. if err != nil {
  16. t.Errorf("Failed to set key-value pair: %v", err)
  17. }
  18. // 获取键对应的值
  19. result, err := memCache.Get(context.Background(), key)
  20. if err != nil {
  21. t.Errorf("Failed to get value for key: %v", err)
  22. }
  23. if result != val {
  24. t.Errorf("Expected value %s, but got %s", val, result)
  25. }
  26. // 删除键值对
  27. _, err = memCache.Delete(context.Background(), key)
  28. if err != nil {
  29. t.Errorf("Failed to delete key-value pair: %v", err)
  30. }
  31. // 再次尝试获取键对应的值,应该返回 ErrorCacheNotFound 错误
  32. _, err = memCache.Get(context.Background(), key)
  33. if err != ErrorCacheNotFound {
  34. t.Errorf("Expected error ErrorCacheNotFound, but got %v", err)
  35. }
  36. }
  37. func BenchmarkMemorySet(b *testing.B) {
  38. memCache := NewMemory()
  39. key := "testKey"
  40. val := "testValue"
  41. ttl := 1 * time.Minute
  42. for i := 0; i < b.N; i++ {
  43. _, _ = memCache.Set(context.Background(), key, val, ttl)
  44. }
  45. }
  46. func BenchmarkMemoryGet(b *testing.B) {
  47. memCache := NewMemory()
  48. key := "testKey"
  49. val := "testValue"
  50. ttl := 1 * time.Minute
  51. _, _ = memCache.Set(context.Background(), key, val, ttl)
  52. for i := 0; i < b.N; i++ {
  53. _, _ = memCache.Get(context.Background(), key)
  54. }
  55. }
  56. func BenchmarkMemoryDelete(b *testing.B) {
  57. memCache := NewMemory()
  58. key := "testKey"
  59. val := "testValue"
  60. ttl := 1 * time.Minute
  61. _, _ = memCache.Set(context.Background(), key, val, ttl)
  62. for i := 0; i < b.N; i++ {
  63. _, _ = memCache.Delete(context.Background(), key)
  64. }
  65. }