func startServer() { log.Printf("cpumonitor listening on %d \n", *port) cpuCalculator := new(stats.CPUOps) runInterval := time.Duration(int32(*runInterval)) * time.Millisecond cpuInterval := time.Duration(int32(*cpuInterval)) * time.Second cpuCollector := stats.NewCPUCollector(cpuCalculator, stats.DefaultTicker(), runInterval, cpuInterval, *perCPU) statsHandler := stats.NewStatHandler(cpuCollector) http.HandleFunc("/start", statsHandler.Start) http.HandleFunc("/stop", statsHandler.Stop) err := http.ListenAndServe(fmt.Sprintf(":%d", *port), nil) if err != nil { log.Fatal("ListenAndServe: ", err) } }
"net/http/httptest" "time" . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" ) var _ = Describe("Handler", func() { var ( cpuCollector *fakes.FakeCollector statsHandler *stats.Handler ) BeforeEach(func() { cpuCollector = new(fakes.FakeCollector) statsHandler = stats.NewStatHandler(cpuCollector) }) Describe("Start", func() { It("returns 200 status if CPUCollector started successfully", func() { testServer := httptest.NewServer(http.HandlerFunc(statsHandler.Start)) resp, err := http.Get(testServer.URL) Expect(err).ToNot(HaveOccurred()) Expect(resp.StatusCode).To(Equal(http.StatusOK)) Expect(responseString(resp.Body)).To(ContainSubstring("Collecting CPU stats")) }) It("does not start CPUCollector if already started", func() { testServer := httptest.NewServer(http.HandlerFunc(statsHandler.Start)) resp, err := http.Get(testServer.URL) Expect(err).ToNot(HaveOccurred())