metrics_test.go 2.0 KB

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