simple_test.go 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121
  1. package searcher
  2. import (
  3. "testing"
  4. "time"
  5. )
  6. // TestOptimizedCache tests the basic functionality of the optimized cache
  7. func TestOptimizedCache(t *testing.T) {
  8. cache := NewOptimizedSearchCache(100)
  9. defer cache.Close()
  10. req := &SearchRequest{
  11. Query: "test",
  12. Limit: 10,
  13. Offset: 0,
  14. }
  15. result := &SearchResult{
  16. TotalHits: 5,
  17. Hits: []*SearchHit{
  18. {ID: "doc1", Score: 1.0},
  19. {ID: "doc2", Score: 0.9},
  20. },
  21. }
  22. // Test cache miss
  23. cached := cache.Get(req)
  24. if cached != nil {
  25. t.Error("expected cache miss")
  26. }
  27. // Test cache put
  28. cache.Put(req, result, 1*time.Minute)
  29. // Test cache hit
  30. cached = cache.Get(req)
  31. if cached == nil {
  32. t.Error("expected cache hit")
  33. }
  34. if !cached.FromCache {
  35. t.Error("result should be marked as from cache")
  36. }
  37. // Test stats
  38. stats := cache.GetStats()
  39. if stats == nil {
  40. t.Error("stats should not be nil")
  41. }
  42. t.Logf("Cache stats: Size=%d, HitRate=%.2f", stats.Size, stats.HitRate)
  43. }
  44. func BenchmarkOptimizedCacheKeyGeneration(b *testing.B) {
  45. cache := NewOptimizedSearchCache(1000)
  46. defer cache.Close()
  47. req := &SearchRequest{
  48. Query: "benchmark test query",
  49. Limit: 100,
  50. Offset: 0,
  51. SortBy: "score",
  52. SortOrder: SortOrderDesc,
  53. IPAddresses: []string{"192.168.1.1", "10.0.0.1"},
  54. StatusCodes: []int{200, 404, 500},
  55. Methods: []string{"GET", "POST"},
  56. }
  57. b.ResetTimer()
  58. b.ReportAllocs()
  59. for i := 0; i < b.N; i++ {
  60. _ = cache.GenerateOptimizedKey(req)
  61. }
  62. }
  63. func BenchmarkOptimizedCacheOperations(b *testing.B) {
  64. cache := NewOptimizedSearchCache(10000)
  65. defer cache.Close()
  66. req := &SearchRequest{
  67. Query: "benchmark",
  68. Limit: 50,
  69. }
  70. result := &SearchResult{
  71. TotalHits: 100,
  72. Hits: []*SearchHit{
  73. {ID: "doc1", Score: 1.0},
  74. {ID: "doc2", Score: 0.9},
  75. },
  76. }
  77. b.Run("Put", func(b *testing.B) {
  78. b.ResetTimer()
  79. b.ReportAllocs()
  80. for i := 0; i < b.N; i++ {
  81. testReq := &SearchRequest{
  82. Query: req.Query + string(rune(i%1000)),
  83. Limit: req.Limit,
  84. Offset: i,
  85. }
  86. cache.Put(testReq, result, 1*time.Minute)
  87. }
  88. })
  89. b.Run("Get", func(b *testing.B) {
  90. // Pre-populate cache
  91. cache.Put(req, result, 1*time.Minute)
  92. b.ResetTimer()
  93. b.ReportAllocs()
  94. for i := 0; i < b.N; i++ {
  95. _ = cache.Get(req)
  96. }
  97. })
  98. }