diff --git a/pkg/metrics/metrics_test.go b/pkg/metrics/metrics_test.go index c676f8bf..51eb3463 100644 --- a/pkg/metrics/metrics_test.go +++ b/pkg/metrics/metrics_test.go @@ -173,3 +173,83 @@ var _ = Describe("Metrics Server", func() { Expect(string(body)).To(ContainSubstring(`custom_metric_total 42`)) }) }) + +var _ = Describe("Metrics Server Functions", func() { + var listener net.Listener + var addr string + + AfterEach(func() { + // Ensure the listener is closed after each test + if listener != nil { + _ = listener.Close() + } + }) + + Describe("StartMetricsServer", func() { + It("should start the server successfully with a valid address", func() { + // Start the server + addr = "127.0.0.1:0" // Dynamic port + server, err := metrics.StartMetricsServer(addr) + Expect(err).NotTo(HaveOccurred()) + Expect(server).NotTo(BeNil()) + + // Use the actual address from the server + resp, err := http.Get(fmt.Sprintf("http://%s%s", server.Addr, constants.MetricsPath)) + Expect(err).NotTo(HaveOccurred()) + Expect(resp.StatusCode).To(Equal(http.StatusOK)) + Expect(resp.Body.Close()).To(Succeed()) + + // Clean up + _ = server.Close() + }) + + It("should return an error when failing to listen on the address", func() { + addr = "invalid_address" + server, err := metrics.StartMetricsServer(addr) + Expect(err).To(HaveOccurred()) + Expect(server).To(BeNil()) + }) + }) + + Describe("StartMetricsServerWithListener", func() { + It("should start the server successfully with a valid listener", func() { + // Create a valid listener + var err error + listener, err = net.Listen("tcp", "127.0.0.1:0") + Expect(err).NotTo(HaveOccurred()) + + server, err := metrics.StartMetricsServerWithListener(listener) + Expect(err).NotTo(HaveOccurred()) + Expect(server).NotTo(BeNil()) + + resp, err := http.Get(fmt.Sprintf("http://%s%s", listener.Addr().String(), constants.MetricsPath)) + Expect(err).NotTo(HaveOccurred()) + Expect(resp.StatusCode).To(Equal(http.StatusOK)) + Expect(resp.Body.Close()).To(Succeed()) + + // Clean up + _ = server.Close() + }) + + It("should handle errors during server operation gracefully", func() { + // Create a valid listener + var err error + listener, err = net.Listen("tcp", "127.0.0.1:0") + Expect(err).NotTo(HaveOccurred()) + + // Start the server + server, err := metrics.StartMetricsServerWithListener(listener) + Expect(err).NotTo(HaveOccurred()) + Expect(server).NotTo(BeNil()) + + // Close the listener to simulate an error during `srv.Serve` + _ = listener.Close() + + // Wait briefly to ensure the goroutine handling `srv.Serve` runs + time.Sleep(100 * time.Millisecond) + + // Clean up + _ = server.Close() + }) + }) +})