cache_test.go 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. package cache
  2. import (
  3. "strconv"
  4. "testing"
  5. "time"
  6. "github.com/stretchr/testify/assert"
  7. )
  8. func TestCache(t *testing.T) {
  9. expiration := 5 * time.Second
  10. globalCache := GetGlobalCache()
  11. assert.NotNil(t, globalCache, "NewGlobalCache should return a non-nil instance")
  12. assert.Equal(t, globalCache, GetGlobalCache(), "GetGlobalCache should return the created instance")
  13. cacheName := "testCache"
  14. globalCache.CreateCache(cacheName, expiration)
  15. createdCache := globalCache.GetCache(cacheName)
  16. assert.NotNil(t, createdCache, "GetCache should return a non-nil cache")
  17. key := "testKey"
  18. value := []byte("testValue")
  19. createdCache.Set(key, value)
  20. // Wait for cache to expire
  21. time.Sleep(expiration + 1*time.Second)
  22. // Verify that the cache has expired
  23. ci := globalCache.GetCache(cacheName)
  24. cachedValue := ci.GetValueForKey(key)
  25. assert.Nil(t, cachedValue, "Cache should not contain the value after expiration")
  26. }
  27. func TestConcurrentAccess(t *testing.T) {
  28. // Test concurrent access to the cache
  29. globalCache := NewGlobalCache()
  30. cacheName := "concurrentCache"
  31. expiration := 5 * time.Second
  32. globalCache.CreateCache(cacheName, expiration)
  33. // Start multiple goroutines to access the cache concurrently
  34. numGoroutines := 10
  35. keyPrefix := "key"
  36. valuePrefix := "value"
  37. done := make(chan struct{})
  38. for i := 0; i < numGoroutines; i++ {
  39. go func(index int) {
  40. defer func() { done <- struct{}{} }()
  41. cache := globalCache.GetCache(cacheName)
  42. key := keyPrefix + strconv.Itoa(index)
  43. value := valuePrefix + strconv.Itoa(index)
  44. cache.Set(key, []byte(value))
  45. // Simulate some work
  46. time.Sleep(100 * time.Millisecond)
  47. ci := globalCache.GetCache(cacheName)
  48. cachedValue := string(ci.GetValueForKey(key))
  49. assert.Equal(t, value, cachedValue, "Cached value should match the set value")
  50. }(i)
  51. }
  52. // Wait for all goroutines to finish
  53. for i := 0; i < numGoroutines; i++ {
  54. <-done
  55. }
  56. }