metrics_test.go 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. package frankenphp
  2. import (
  3. "github.com/prometheus/client_golang/prometheus"
  4. "github.com/stretchr/testify/require"
  5. "sync"
  6. "testing"
  7. "time"
  8. "github.com/stretchr/testify/assert"
  9. )
  10. func TestGetWorkerNameForMetrics(t *testing.T) {
  11. tests := []struct {
  12. input string
  13. expected string
  14. }{
  15. {"worker-1", "worker_1"},
  16. {"worker@name", "worker_name"},
  17. {"worker name", "worker_name"},
  18. {"worker/name", "worker_name"},
  19. {"worker.name", "worker_name"},
  20. {"////worker////name...//worker", "worker_name_worker"},
  21. }
  22. for _, test := range tests {
  23. result := getWorkerNameForMetrics(test.input)
  24. assert.Equal(t, test.expected, result)
  25. }
  26. }
  27. func createPrometheusMetrics() *PrometheusMetrics {
  28. return &PrometheusMetrics{
  29. registry: prometheus.NewRegistry(),
  30. totalThreads: prometheus.NewCounter(prometheus.CounterOpts{Name: "total_threads"}),
  31. busyThreads: prometheus.NewGauge(prometheus.GaugeOpts{Name: "busy_threads"}),
  32. totalWorkers: make(map[string]prometheus.Gauge),
  33. busyWorkers: make(map[string]prometheus.Gauge),
  34. workerRequestTime: make(map[string]prometheus.Counter),
  35. workerRequestCount: make(map[string]prometheus.Counter),
  36. workerCrashes: make(map[string]prometheus.Counter),
  37. workerRestarts: make(map[string]prometheus.Counter),
  38. workerQueueDepth: make(map[string]prometheus.Gauge),
  39. readyWorkers: make(map[string]prometheus.Gauge),
  40. mu: sync.Mutex{},
  41. }
  42. }
  43. func TestPrometheusMetrics_TotalWorkers(t *testing.T) {
  44. m := createPrometheusMetrics()
  45. tests := []struct {
  46. name string
  47. worker string
  48. num int
  49. }{
  50. {"SetWorkers", "test_worker", 5},
  51. }
  52. for _, tt := range tests {
  53. t.Run(tt.name, func(t *testing.T) {
  54. m.TotalWorkers(tt.worker, tt.num)
  55. actualName, _ := m.getIdentity(tt.worker)
  56. _, ok := m.totalWorkers[actualName]
  57. require.True(t, ok)
  58. })
  59. }
  60. }
  61. func TestPrometheusMetrics_StopWorkerRequest(t *testing.T) {
  62. m := createPrometheusMetrics()
  63. m.StopWorkerRequest("test_worker", 2*time.Second)
  64. name := "test_worker"
  65. _, ok := m.workerRequestTime[name]
  66. require.False(t, ok)
  67. }
  68. func TestPrometheusMetrics_StartWorkerRequest(t *testing.T) {
  69. m := createPrometheusMetrics()
  70. m.StartWorkerRequest("test_worker")
  71. name := "test_worker"
  72. _, ok := m.workerRequestCount[name]
  73. require.False(t, ok)
  74. }