manager_mutation_test.go 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. package mtproto
  2. import (
  3. "io"
  4. "net/http"
  5. "net/http/httptest"
  6. "net/url"
  7. "strconv"
  8. "testing"
  9. )
  10. // serverPort extracts the loopback port a httptest server bound to, so
  11. // scrapeStats can rebuild the same http://127.0.0.1:<port>/stats URL.
  12. func serverPort(t *testing.T, srv *httptest.Server) int {
  13. t.Helper()
  14. u, err := url.Parse(srv.URL)
  15. if err != nil {
  16. t.Fatalf("parse url: %v", err)
  17. }
  18. port, err := strconv.Atoi(u.Port())
  19. if err != nil {
  20. t.Fatalf("parse port: %v", err)
  21. }
  22. return port
  23. }
  24. func TestScrapeStats(t *testing.T) {
  25. srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  26. if r.URL.Path != "/stats" {
  27. http.NotFound(w, r)
  28. return
  29. }
  30. if r.Header.Get("Authorization") != "Bearer sesame" {
  31. w.WriteHeader(http.StatusUnauthorized)
  32. return
  33. }
  34. _, _ = io.WriteString(w, `{"started_at":"2026-01-01T00:00:00Z","total_connections":2,`+
  35. `"users":{`+
  36. `"alice":{"connections":2,"bytes_in":100,"bytes_out":200,"last_seen":"2026-01-01T00:01:00Z"},`+
  37. `"bob":{"connections":0,"bytes_in":5,"bytes_out":7,"last_seen":null}}}`)
  38. }))
  39. defer srv.Close()
  40. users, ok := scrapeStats(serverPort(t, srv), "sesame")
  41. if !ok {
  42. t.Fatal("scrapeStats should succeed against a valid /stats endpoint")
  43. }
  44. if len(users) != 2 {
  45. t.Fatalf("expected 2 users, got %d: %+v", len(users), users)
  46. }
  47. if users["alice"].BytesIn != 100 || users["alice"].BytesOut != 200 || users["alice"].Connections != 2 {
  48. t.Fatalf("alice stats parsed wrong: %+v", users["alice"])
  49. }
  50. if users["bob"].Connections != 0 || users["bob"].BytesIn != 5 {
  51. t.Fatalf("bob stats parsed wrong: %+v", users["bob"])
  52. }
  53. }
  54. func TestScrapeStatsUnreachable(t *testing.T) {
  55. srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  56. http.NotFound(w, r)
  57. }))
  58. port := serverPort(t, srv)
  59. srv.Close()
  60. if _, ok := scrapeStats(port, ""); ok {
  61. t.Fatal("scrapeStats must report ok=false when the endpoint is unreachable")
  62. }
  63. }