metrics_test.go 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  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. readyWorkers: make(map[string]prometheus.Gauge),
  39. mu: sync.Mutex{},
  40. }
  41. }
  42. func TestPrometheusMetrics_TotalWorkers(t *testing.T) {
  43. m := createPrometheusMetrics()
  44. tests := []struct {
  45. name string
  46. worker string
  47. num int
  48. }{
  49. {"SetWorkers", "test_worker", 5},
  50. }
  51. for _, tt := range tests {
  52. t.Run(tt.name, func(t *testing.T) {
  53. m.TotalWorkers(tt.worker, tt.num)
  54. actualName, _ := m.getIdentity(tt.worker)
  55. _, ok := m.totalWorkers[actualName]
  56. require.True(t, ok)
  57. })
  58. }
  59. }
  60. func TestPrometheusMetrics_StopWorkerRequest(t *testing.T) {
  61. m := createPrometheusMetrics()
  62. m.StopWorkerRequest("test_worker", 2*time.Second)
  63. name := "test_worker"
  64. _, ok := m.workerRequestTime[name]
  65. require.False(t, ok)
  66. }
  67. func TestPrometheusMetrics_StartWorkerRequest(t *testing.T) {
  68. m := createPrometheusMetrics()
  69. m.StartWorkerRequest("test_worker")
  70. name := "test_worker"
  71. _, ok := m.workerRequestCount[name]
  72. require.False(t, ok)
  73. }