heartbeat_test.go 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. package exporter
  2. import (
  3. "encoding/json"
  4. "fmt"
  5. "path"
  6. "path/filepath"
  7. "slices"
  8. "testing"
  9. "time"
  10. "github.com/opencost/opencost/core/pkg/heartbeat"
  11. "github.com/opencost/opencost/core/pkg/storage"
  12. "github.com/opencost/opencost/core/pkg/util/sliceutil"
  13. )
  14. const (
  15. MockClusterId = "mock-cluster-1"
  16. MockApplicationName = "mock-agent"
  17. MockVersion = "1.0.0"
  18. )
  19. type MockHeartbeatMetadataProvider struct{}
  20. func NewMockHeartbeatMetadataProvider() *MockHeartbeatMetadataProvider {
  21. return &MockHeartbeatMetadataProvider{}
  22. }
  23. func (m *MockHeartbeatMetadataProvider) GetMetadata() map[string]any {
  24. return map[string]any{
  25. "cluster_id": MockClusterId,
  26. }
  27. }
  28. func TestHeartbeatExporter(t *testing.T) {
  29. t.Parallel()
  30. mdp := NewMockHeartbeatMetadataProvider()
  31. store := storage.NewMemoryStorage()
  32. controller := NewHeartbeatExportController(MockClusterId, MockApplicationName, MockVersion, store, mdp)
  33. if !controller.Start(time.Second) {
  34. t.Fatal("Failed to start controller")
  35. }
  36. time.Sleep(10 * time.Second)
  37. controller.Stop()
  38. files, _ := store.List(path.Join("federated", MockClusterId, heartbeat.HeartbeatEventName, MockApplicationName))
  39. if len(files) == 0 {
  40. t.Fatal("No files found in storage")
  41. }
  42. fileNames := sliceutil.Map(files, func(stat *storage.StorageInfo) string {
  43. return stat.Name
  44. })
  45. slices.Sort(fileNames)
  46. lastCheck := time.Time{}
  47. for _, f := range fileNames {
  48. fpath := filepath.Join("federated", MockClusterId, "heartbeat", MockApplicationName, f)
  49. data, err := store.Read(fpath)
  50. if err != nil {
  51. t.Fatalf("Failed to read file %s: %v", fpath, err)
  52. }
  53. hb := new(heartbeat.Heartbeat)
  54. if err := json.Unmarshal(data, hb); err != nil {
  55. t.Fatalf("Failed to unmarshal heartbeat data: %v", err)
  56. }
  57. fmt.Printf("%s: %d bytes\n%s\n\n", f, len(data), string(data))
  58. if hb.Metadata["cluster_id"] != MockClusterId {
  59. t.Fatalf("Expected cluster ID %s, got %s", MockClusterId, hb.Metadata["cluster_id"])
  60. }
  61. if hb.Timestamp.Before(lastCheck) {
  62. t.Fatalf("Expected timestamp %s to be after %s", hb.Timestamp, lastCheck)
  63. }
  64. lastCheck = hb.Timestamp
  65. }
  66. }