Skip to content

Commit

Permalink
updated unit tests
Browse files Browse the repository at this point in the history
  • Loading branch information
anurag4DSB committed Dec 19, 2024
1 parent 1915125 commit b0108f0
Showing 1 changed file with 80 additions and 0 deletions.
80 changes: 80 additions & 0 deletions pkg/metrics/metrics_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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()
})
})
})

0 comments on commit b0108f0

Please sign in to comment.