-
-
Notifications
You must be signed in to change notification settings - Fork 6
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
1 parent
d83c3a4
commit 66c8fef
Showing
12 changed files
with
1,026 additions
and
22 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,231 @@ | ||
package main | ||
|
||
import ( | ||
"encoding/json" | ||
"fmt" | ||
"os" | ||
"path/filepath" | ||
|
||
libpack_logger "github.com/lukaszraczylo/graphql-monitoring-proxy/logging" | ||
) | ||
|
||
func (suite *Tests) Test_PeriodicallyReloadBannedUsers() { | ||
// Setup | ||
cfg = &config{} | ||
parseConfig() | ||
cfg.Logger = libpack_logger.New() | ||
cfg.Api.BannedUsersFile = filepath.Join(os.TempDir(), "banned_users_reload_test.json") | ||
|
||
// Initial empty banned users | ||
bannedUsersIDsMutex.Lock() | ||
bannedUsersIDs = make(map[string]string) | ||
bannedUsersIDsMutex.Unlock() | ||
|
||
// Create a test version of periodicallyReloadBannedUsers that executes once and signals completion | ||
done := make(chan bool) | ||
testPeriodicallyReloadBannedUsers := func() { | ||
// Just call loadBannedUsers once | ||
loadBannedUsers() | ||
done <- true | ||
} | ||
|
||
// Run the test with initial empty banned users file | ||
suite.Run("reload with empty file", func() { | ||
// Clear existing file if any | ||
os.Remove(cfg.Api.BannedUsersFile) | ||
os.Remove(fmt.Sprintf("%s.lock", cfg.Api.BannedUsersFile)) | ||
|
||
// Ensure banned users map is empty | ||
bannedUsersIDsMutex.Lock() | ||
bannedUsersIDs = make(map[string]string) | ||
bannedUsersIDsMutex.Unlock() | ||
|
||
// Execute reloader once | ||
go testPeriodicallyReloadBannedUsers() | ||
<-done | ||
|
||
// Verify file was created | ||
_, err := os.Stat(cfg.Api.BannedUsersFile) | ||
assert.NoError(err) | ||
|
||
// Safely check the map | ||
bannedUsersIDsMutex.RLock() | ||
mapSize := len(bannedUsersIDs) | ||
bannedUsersIDsMutex.RUnlock() | ||
|
||
// Verify map is still empty | ||
assert.Equal(0, mapSize) | ||
}) | ||
|
||
// Run the test with a populated banned users file | ||
suite.Run("reload with populated file", func() { | ||
// Create file with test data | ||
testData := map[string]string{ | ||
"test-user-reload-1": "reason reload 1", | ||
"test-user-reload-2": "reason reload 2", | ||
} | ||
data, _ := json.Marshal(testData) | ||
err := os.WriteFile(cfg.Api.BannedUsersFile, data, 0644) | ||
assert.NoError(err) | ||
|
||
// Clear the banned users map | ||
bannedUsersIDsMutex.Lock() | ||
bannedUsersIDs = make(map[string]string) | ||
bannedUsersIDsMutex.Unlock() | ||
|
||
// Execute reloader once | ||
go testPeriodicallyReloadBannedUsers() | ||
<-done | ||
|
||
// Safely check the map | ||
bannedUsersIDsMutex.RLock() | ||
mapSize := len(bannedUsersIDs) | ||
value1 := bannedUsersIDs["test-user-reload-1"] | ||
value2 := bannedUsersIDs["test-user-reload-2"] | ||
bannedUsersIDsMutex.RUnlock() | ||
|
||
// Verify banned users map was loaded | ||
assert.Equal(2, mapSize) | ||
assert.Equal("reason reload 1", value1) | ||
assert.Equal("reason reload 2", value2) | ||
}) | ||
|
||
// Test updating banned users file while reloader is running | ||
suite.Run("reload with updated file", func() { | ||
// Start with initial data | ||
initialData := map[string]string{ | ||
"test-user-initial": "initial reason", | ||
} | ||
data, _ := json.Marshal(initialData) | ||
err := os.WriteFile(cfg.Api.BannedUsersFile, data, 0644) | ||
assert.NoError(err) | ||
|
||
// Clear the banned users map | ||
bannedUsersIDsMutex.Lock() | ||
bannedUsersIDs = make(map[string]string) | ||
bannedUsersIDsMutex.Unlock() | ||
|
||
// Execute reloader once to load initial data | ||
go testPeriodicallyReloadBannedUsers() | ||
<-done | ||
|
||
// Safely check the map | ||
bannedUsersIDsMutex.RLock() | ||
mapSize := len(bannedUsersIDs) | ||
initialValue := bannedUsersIDs["test-user-initial"] | ||
bannedUsersIDsMutex.RUnlock() | ||
|
||
// Verify initial data was loaded | ||
assert.Equal(1, mapSize) | ||
assert.Equal("initial reason", initialValue) | ||
|
||
// Update the file with new data | ||
updatedData := map[string]string{ | ||
"test-user-updated-1": "updated reason 1", | ||
"test-user-updated-2": "updated reason 2", | ||
} | ||
data, _ = json.Marshal(updatedData) | ||
err = os.WriteFile(cfg.Api.BannedUsersFile, data, 0644) | ||
assert.NoError(err) | ||
|
||
// Execute reloader again to load updated data | ||
go testPeriodicallyReloadBannedUsers() | ||
<-done | ||
|
||
// Safely check the map | ||
bannedUsersIDsMutex.RLock() | ||
mapSize = len(bannedUsersIDs) | ||
value1 := bannedUsersIDs["test-user-updated-1"] | ||
value2 := bannedUsersIDs["test-user-updated-2"] | ||
_, exists := bannedUsersIDs["test-user-initial"] | ||
bannedUsersIDsMutex.RUnlock() | ||
|
||
// Verify updated data was loaded | ||
assert.Equal(2, mapSize) | ||
assert.Equal("updated reason 1", value1) | ||
assert.Equal("updated reason 2", value2) | ||
assert.False(exists) | ||
}) | ||
|
||
// Cleanup | ||
os.Remove(cfg.Api.BannedUsersFile) | ||
os.Remove(fmt.Sprintf("%s.lock", cfg.Api.BannedUsersFile)) | ||
} | ||
|
||
// This is a better approach instead of the ticker-based test | ||
func (suite *Tests) Test_LoadUnloadBannedUsers() { | ||
// Setup | ||
cfg = &config{} | ||
parseConfig() | ||
cfg.Logger = libpack_logger.New() | ||
cfg.Api.BannedUsersFile = filepath.Join(os.TempDir(), "banned_users_update_test.json") | ||
|
||
// Create a test banned users file with initial content | ||
initialData := map[string]string{ | ||
"user1": "reason1", | ||
"user2": "reason2", | ||
} | ||
data, _ := json.Marshal(initialData) | ||
err := os.WriteFile(cfg.Api.BannedUsersFile, data, 0644) | ||
assert.NoError(err) | ||
defer os.Remove(cfg.Api.BannedUsersFile) | ||
defer os.Remove(fmt.Sprintf("%s.lock", cfg.Api.BannedUsersFile)) | ||
|
||
// Test loading banned users | ||
suite.Run("load banned users", func() { | ||
// Clear the banned users map | ||
bannedUsersIDsMutex.Lock() | ||
bannedUsersIDs = make(map[string]string) | ||
bannedUsersIDsMutex.Unlock() | ||
|
||
// Load banned users | ||
loadBannedUsers() | ||
|
||
// Check the banned users map | ||
bannedUsersIDsMutex.RLock() | ||
count := len(bannedUsersIDs) | ||
reason1 := bannedUsersIDs["user1"] | ||
reason2 := bannedUsersIDs["user2"] | ||
bannedUsersIDsMutex.RUnlock() | ||
|
||
assert.Equal(2, count) | ||
assert.Equal("reason1", reason1) | ||
assert.Equal("reason2", reason2) | ||
}) | ||
|
||
// Test updating banned users | ||
suite.Run("update banned users", func() { | ||
// Update the banned users map | ||
bannedUsersIDsMutex.Lock() | ||
bannedUsersIDs = map[string]string{ | ||
"user3": "reason3", | ||
"user4": "reason4", | ||
} | ||
bannedUsersIDsMutex.Unlock() | ||
|
||
// Store the updated banned users | ||
err := storeBannedUsers() | ||
assert.NoError(err) | ||
|
||
// Clear the banned users map | ||
bannedUsersIDsMutex.Lock() | ||
bannedUsersIDs = make(map[string]string) | ||
bannedUsersIDsMutex.Unlock() | ||
|
||
// Load banned users again | ||
loadBannedUsers() | ||
|
||
// Check the banned users map | ||
bannedUsersIDsMutex.RLock() | ||
count := len(bannedUsersIDs) | ||
reason3 := bannedUsersIDs["user3"] | ||
reason4 := bannedUsersIDs["user4"] | ||
_, user1Exists := bannedUsersIDs["user1"] | ||
bannedUsersIDsMutex.RUnlock() | ||
|
||
assert.Equal(2, count) | ||
assert.Equal("reason3", reason3) | ||
assert.Equal("reason4", reason4) | ||
assert.False(user1Exists) | ||
}) | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,90 @@ | ||
package libpack_cache_memory | ||
|
||
import ( | ||
"testing" | ||
"time" | ||
|
||
"github.com/stretchr/testify/assert" | ||
) | ||
|
||
// Default constants for testing | ||
const ( | ||
DefaultTestExpiration = 5 * time.Second | ||
) | ||
|
||
func TestMemoryCacheClear(t *testing.T) { | ||
cache := New(DefaultTestExpiration) | ||
|
||
// Add some entries | ||
cache.Set("key1", []byte("value1"), DefaultTestExpiration) | ||
cache.Set("key2", []byte("value2"), DefaultTestExpiration) | ||
|
||
// Verify entries exist | ||
_, found := cache.Get("key1") | ||
assert.True(t, found, "Expected key1 to exist before clearing cache") | ||
|
||
// Clear the cache | ||
cache.Clear() | ||
|
||
// Verify cache is empty | ||
_, found = cache.Get("key1") | ||
assert.False(t, found, "Expected key1 to be removed after clearing cache") | ||
_, found = cache.Get("key2") | ||
assert.False(t, found, "Expected key2 to be removed after clearing cache") | ||
|
||
// Check that counter was reset | ||
assert.Equal(t, int64(0), cache.CountQueries(), "Expected count to be 0 after clearing cache") | ||
} | ||
|
||
func TestMemoryCacheCountQueries(t *testing.T) { | ||
cache := New(DefaultTestExpiration) | ||
|
||
// Check initial count | ||
assert.Equal(t, int64(0), cache.CountQueries(), "Expected initial count to be 0") | ||
|
||
// Add some entries | ||
cache.Set("key1", []byte("value1"), DefaultTestExpiration) | ||
cache.Set("key2", []byte("value2"), DefaultTestExpiration) | ||
cache.Set("key3", []byte("value3"), DefaultTestExpiration) | ||
|
||
// Check count | ||
assert.Equal(t, int64(3), cache.CountQueries(), "Expected count to be 3 after adding 3 entries") | ||
|
||
// Delete an entry | ||
cache.Delete("key1") | ||
|
||
// Check count after deletion | ||
assert.Equal(t, int64(2), cache.CountQueries(), "Expected count to be 2 after deleting 1 entry") | ||
} | ||
|
||
func TestMemoryCacheCleanExpiredEntries(t *testing.T) { | ||
// Create a cache with default expiration | ||
cache := New(10 * time.Second) | ||
|
||
// Add an entry that will expire quickly | ||
cache.Set("expire-soon", []byte("value1"), 10*time.Millisecond) | ||
|
||
// Add an entry that will not expire during the test | ||
cache.Set("expire-later", []byte("value3"), 10*time.Minute) | ||
|
||
// Initial count should be 2 | ||
assert.Equal(t, int64(2), cache.CountQueries(), "Expected count to be 2 after adding entries") | ||
|
||
// Wait for short expiration | ||
time.Sleep(20 * time.Millisecond) | ||
|
||
// Get the expired key directly to verify it's expired | ||
_, expiredFound := cache.Get("expire-soon") | ||
assert.False(t, expiredFound, "Key 'expire-soon' should be expired now") | ||
|
||
// Verify the not-expired key is still there | ||
val, nonExpiredFound := cache.Get("expire-later") | ||
assert.True(t, nonExpiredFound, "Key 'expire-later' should not be expired") | ||
assert.Equal(t, []byte("value3"), val, "Expected correct value for 'expire-later'") | ||
|
||
// Manually clean expired entries | ||
cache.CleanExpiredEntries() | ||
|
||
// Count should be 1 now (only the non-expired entry) | ||
assert.Equal(t, int64(1), cache.CountQueries(), "Expected count to be 1 after cleaning expired entries") | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,50 @@ | ||
package libpack_cache_redis | ||
|
||
import ( | ||
"testing" | ||
"time" | ||
|
||
"github.com/alicebob/miniredis/v2" | ||
"github.com/stretchr/testify/assert" | ||
) | ||
|
||
func TestRedisClear(t *testing.T) { | ||
// Create a mock Redis server | ||
s, err := miniredis.Run() | ||
if err != nil { | ||
t.Fatalf("Failed to create mock redis server: %v", err) | ||
} | ||
defer s.Close() | ||
|
||
// Create a Redis client | ||
redisConfig := New(&RedisClientConfig{ | ||
RedisServer: s.Addr(), | ||
RedisPassword: "", | ||
RedisDB: 0, | ||
}) | ||
|
||
// Add some test data | ||
ttl := time.Duration(60) * time.Second | ||
redisConfig.Set("key1", []byte("value1"), ttl) | ||
redisConfig.Set("key2", []byte("value2"), ttl) | ||
redisConfig.Set("key3", []byte("value3"), ttl) | ||
|
||
// Verify keys exist | ||
count := redisConfig.CountQueries() | ||
assert.Equal(t, int64(3), count, "Expected 3 keys before clearing cache") | ||
|
||
// Clear the cache | ||
redisConfig.Clear() | ||
|
||
// Verify all keys are gone | ||
count = redisConfig.CountQueries() | ||
assert.Equal(t, int64(0), count, "Expected 0 keys after clearing cache") | ||
|
||
// Verify individual keys are gone | ||
_, found := redisConfig.Get("key1") | ||
assert.False(t, found, "Key1 should be deleted after Clear") | ||
_, found = redisConfig.Get("key2") | ||
assert.False(t, found, "Key2 should be deleted after Clear") | ||
_, found = redisConfig.Get("key3") | ||
assert.False(t, found, "Key3 should be deleted after Clear") | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,13 @@ | ||
package libpack_config | ||
|
||
import ( | ||
"testing" | ||
|
||
"github.com/stretchr/testify/assert" | ||
) | ||
|
||
func TestConfigConstants(t *testing.T) { | ||
// Verify package constants are defined | ||
assert.NotEmpty(t, PKG_NAME, "PKG_NAME should be defined") | ||
assert.NotEmpty(t, PKG_VERSION, "PKG_VERSION should be defined") | ||
} |
Oops, something went wrong.