Files
software-station/internal/stats/stats_test.go
Sudo-Ivan 2f0af4c988 Refactor API and background updater functionality
- Updated the StartBackgroundUpdater function to accept a callback for software list updates, improving flexibility.
- Refactored the API handlers to utilize a proxied software list, enhancing data handling and response efficiency.
- Introduced a new method for refreshing the proxied software list, ensuring accurate data representation.
- Added unit tests for API handlers to validate functionality and response correctness.
2025-12-27 03:30:18 -06:00

69 lines
1.6 KiB
Go

package stats
import (
"encoding/json"
"net/http"
"net/http/httptest"
"os"
"software-station/internal/models"
"testing"
)
func TestStats(t *testing.T) {
tempFile := "test_hashes.json"
defer os.Remove(tempFile)
service := NewService(tempFile)
// Test SaveHashes
service.KnownHashes.Lock()
service.KnownHashes.Data["test"] = &models.FingerprintData{Known: true, TotalBytes: 100}
service.KnownHashes.Unlock()
service.FlushHashes()
if _, err := os.Stat(tempFile); os.IsNotExist(err) {
t.Error("SaveHashes did not create file")
}
// Test LoadHashes
service.KnownHashes.Lock()
delete(service.KnownHashes.Data, "test")
service.KnownHashes.Unlock()
service.LoadHashes()
service.KnownHashes.RLock()
if data, ok := service.KnownHashes.Data["test"]; !ok || data.TotalBytes != 100 {
t.Errorf("LoadHashes did not restore data correctly: %+v", data)
}
service.KnownHashes.RUnlock()
// Test APIStatsHandler
req := httptest.NewRequest("GET", "/api/stats", nil)
rr := httptest.NewRecorder()
service.APIStatsHandler(rr, req)
if rr.Code != http.StatusOK {
t.Errorf("expected 200, got %d", rr.Code)
}
var stats map[string]interface{}
json.Unmarshal(rr.Body.Bytes(), &stats)
if stats["status"] != "healthy" {
t.Errorf("expected healthy status, got %v", stats["status"])
}
// Test ResetGlobalStats
service.GlobalStats.Lock()
service.GlobalStats.TotalRequests = 10
service.GlobalStats.Unlock()
service.ResetGlobalStats()
if service.GlobalStats.TotalRequests != 0 {
t.Error("ResetGlobalStats did not reset TotalRequests")
}
// Test Start/Stop/SaveHashes
service.Start()
service.SaveHashes()
service.Stop()
}