From 8d1a9bc92e758e6e174076fcae16ccebb4bc7fba Mon Sep 17 00:00:00 2001 From: Eyitayo Ogunbiyi Date: Mon, 6 Jul 2020 19:34:48 +0100 Subject: [PATCH] added tests for health check endpoints --- admin_test.go | 73 +++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 73 insertions(+) diff --git a/admin_test.go b/admin_test.go index b7a9af9c..3875a4bb 100644 --- a/admin_test.go +++ b/admin_test.go @@ -2,11 +2,30 @@ package beego import ( "encoding/json" + "errors" "fmt" + "net/http" "net/http/httptest" + "strings" "testing" + + "github.com/astaxie/beego/toolbox" ) +type SampleDatabaseCheck struct { +} + +type SampleCacheCheck struct { +} + +func (dc *SampleDatabaseCheck) Check() error { + return nil +} + +func (cc *SampleCacheCheck) Check() error { + return errors.New("no cache detected") +} + func TestList_01(t *testing.T) { m := make(M) list("BConfig", BConfig, m) @@ -101,3 +120,57 @@ func TestExecJSON(t *testing.T) { } } } + +func TestHealthCheckHandlerDefault(t *testing.T) { + endpointPath := "/healthcheck" + + toolbox.AddHealthCheck("database", &SampleDatabaseCheck{}) + toolbox.AddHealthCheck("cache", &SampleCacheCheck{}) + + req, err := http.NewRequest("GET", endpointPath, nil) + if err != nil { + t.Fatal(err) + } + + w := httptest.NewRecorder() + + handler := http.HandlerFunc(healthcheck) + + handler.ServeHTTP(w, req) + + if status := w.Code; status != http.StatusOK { + t.Errorf("handler returned wrong status code: got %v want %v", + status, http.StatusOK) + } + if !strings.Contains(w.Body.String(), "database") { + t.Errorf("Expected 'database' in generated template.") + } + +} + +func TestHealthCheckHandlerReturnsJSON(t *testing.T) { + + toolbox.AddHealthCheck("database", &SampleDatabaseCheck{}) + toolbox.AddHealthCheck("cache", &SampleCacheCheck{}) + + req, err := http.NewRequest("GET", "/healthcheck?json=true", nil) + if err != nil { + t.Fatal(err) + } + + w := httptest.NewRecorder() + + handler := http.HandlerFunc(healthcheck) + + handler.ServeHTTP(w, req) + if status := w.Code; status != http.StatusOK { + t.Errorf("handler returned wrong status code: got %v want %v", + status, http.StatusOK) + } + + expectedResponseBody := `[{"message":"database","name":"success","status":"OK"},{"message":"cache","name":"error","status":"no cache detected"}]` + if w.Body.String() != expectedResponseBody { + t.Errorf("handler returned unexpected body: got %v want %v", + w.Body.String(), expectedResponseBody) + } +}