github.com/astaxie/beego@v1.12.3/admin_test.go (about)

     1  package beego
     2  
     3  import (
     4  	"encoding/json"
     5  	"errors"
     6  	"fmt"
     7  	"net/http"
     8  	"net/http/httptest"
     9  	"reflect"
    10  	"strings"
    11  	"testing"
    12  
    13  	"github.com/astaxie/beego/toolbox"
    14  )
    15  
    16  type SampleDatabaseCheck struct {
    17  }
    18  
    19  type SampleCacheCheck struct {
    20  }
    21  
    22  func (dc *SampleDatabaseCheck) Check() error {
    23  	return nil
    24  }
    25  
    26  func (cc *SampleCacheCheck) Check() error {
    27  	return errors.New("no cache detected")
    28  }
    29  
    30  func TestList_01(t *testing.T) {
    31  	m := make(M)
    32  	list("BConfig", BConfig, m)
    33  	t.Log(m)
    34  	om := oldMap()
    35  	for k, v := range om {
    36  		if fmt.Sprint(m[k]) != fmt.Sprint(v) {
    37  			t.Log(k, "old-key", v, "new-key", m[k])
    38  			t.FailNow()
    39  		}
    40  	}
    41  }
    42  
    43  func oldMap() M {
    44  	m := make(M)
    45  	m["BConfig.AppName"] = BConfig.AppName
    46  	m["BConfig.RunMode"] = BConfig.RunMode
    47  	m["BConfig.RouterCaseSensitive"] = BConfig.RouterCaseSensitive
    48  	m["BConfig.ServerName"] = BConfig.ServerName
    49  	m["BConfig.RecoverPanic"] = BConfig.RecoverPanic
    50  	m["BConfig.CopyRequestBody"] = BConfig.CopyRequestBody
    51  	m["BConfig.EnableGzip"] = BConfig.EnableGzip
    52  	m["BConfig.MaxMemory"] = BConfig.MaxMemory
    53  	m["BConfig.EnableErrorsShow"] = BConfig.EnableErrorsShow
    54  	m["BConfig.Listen.Graceful"] = BConfig.Listen.Graceful
    55  	m["BConfig.Listen.ServerTimeOut"] = BConfig.Listen.ServerTimeOut
    56  	m["BConfig.Listen.ListenTCP4"] = BConfig.Listen.ListenTCP4
    57  	m["BConfig.Listen.EnableHTTP"] = BConfig.Listen.EnableHTTP
    58  	m["BConfig.Listen.HTTPAddr"] = BConfig.Listen.HTTPAddr
    59  	m["BConfig.Listen.HTTPPort"] = BConfig.Listen.HTTPPort
    60  	m["BConfig.Listen.EnableHTTPS"] = BConfig.Listen.EnableHTTPS
    61  	m["BConfig.Listen.HTTPSAddr"] = BConfig.Listen.HTTPSAddr
    62  	m["BConfig.Listen.HTTPSPort"] = BConfig.Listen.HTTPSPort
    63  	m["BConfig.Listen.HTTPSCertFile"] = BConfig.Listen.HTTPSCertFile
    64  	m["BConfig.Listen.HTTPSKeyFile"] = BConfig.Listen.HTTPSKeyFile
    65  	m["BConfig.Listen.EnableAdmin"] = BConfig.Listen.EnableAdmin
    66  	m["BConfig.Listen.AdminAddr"] = BConfig.Listen.AdminAddr
    67  	m["BConfig.Listen.AdminPort"] = BConfig.Listen.AdminPort
    68  	m["BConfig.Listen.EnableFcgi"] = BConfig.Listen.EnableFcgi
    69  	m["BConfig.Listen.EnableStdIo"] = BConfig.Listen.EnableStdIo
    70  	m["BConfig.WebConfig.AutoRender"] = BConfig.WebConfig.AutoRender
    71  	m["BConfig.WebConfig.EnableDocs"] = BConfig.WebConfig.EnableDocs
    72  	m["BConfig.WebConfig.FlashName"] = BConfig.WebConfig.FlashName
    73  	m["BConfig.WebConfig.FlashSeparator"] = BConfig.WebConfig.FlashSeparator
    74  	m["BConfig.WebConfig.DirectoryIndex"] = BConfig.WebConfig.DirectoryIndex
    75  	m["BConfig.WebConfig.StaticDir"] = BConfig.WebConfig.StaticDir
    76  	m["BConfig.WebConfig.StaticExtensionsToGzip"] = BConfig.WebConfig.StaticExtensionsToGzip
    77  	m["BConfig.WebConfig.StaticCacheFileSize"] = BConfig.WebConfig.StaticCacheFileSize
    78  	m["BConfig.WebConfig.StaticCacheFileNum"] = BConfig.WebConfig.StaticCacheFileNum
    79  	m["BConfig.WebConfig.TemplateLeft"] = BConfig.WebConfig.TemplateLeft
    80  	m["BConfig.WebConfig.TemplateRight"] = BConfig.WebConfig.TemplateRight
    81  	m["BConfig.WebConfig.ViewsPath"] = BConfig.WebConfig.ViewsPath
    82  	m["BConfig.WebConfig.EnableXSRF"] = BConfig.WebConfig.EnableXSRF
    83  	m["BConfig.WebConfig.XSRFExpire"] = BConfig.WebConfig.XSRFExpire
    84  	m["BConfig.WebConfig.Session.SessionOn"] = BConfig.WebConfig.Session.SessionOn
    85  	m["BConfig.WebConfig.Session.SessionProvider"] = BConfig.WebConfig.Session.SessionProvider
    86  	m["BConfig.WebConfig.Session.SessionName"] = BConfig.WebConfig.Session.SessionName
    87  	m["BConfig.WebConfig.Session.SessionGCMaxLifetime"] = BConfig.WebConfig.Session.SessionGCMaxLifetime
    88  	m["BConfig.WebConfig.Session.SessionProviderConfig"] = BConfig.WebConfig.Session.SessionProviderConfig
    89  	m["BConfig.WebConfig.Session.SessionCookieLifeTime"] = BConfig.WebConfig.Session.SessionCookieLifeTime
    90  	m["BConfig.WebConfig.Session.SessionAutoSetCookie"] = BConfig.WebConfig.Session.SessionAutoSetCookie
    91  	m["BConfig.WebConfig.Session.SessionDomain"] = BConfig.WebConfig.Session.SessionDomain
    92  	m["BConfig.WebConfig.Session.SessionDisableHTTPOnly"] = BConfig.WebConfig.Session.SessionDisableHTTPOnly
    93  	m["BConfig.Log.AccessLogs"] = BConfig.Log.AccessLogs
    94  	m["BConfig.Log.EnableStaticLogs"] = BConfig.Log.EnableStaticLogs
    95  	m["BConfig.Log.AccessLogsFormat"] = BConfig.Log.AccessLogsFormat
    96  	m["BConfig.Log.FileLineNum"] = BConfig.Log.FileLineNum
    97  	m["BConfig.Log.Outputs"] = BConfig.Log.Outputs
    98  	return m
    99  }
   100  
   101  func TestWriteJSON(t *testing.T) {
   102  	t.Log("Testing the adding of JSON to the response")
   103  
   104  	w := httptest.NewRecorder()
   105  	originalBody := []int{1, 2, 3}
   106  
   107  	res, _ := json.Marshal(originalBody)
   108  
   109  	writeJSON(w, res)
   110  
   111  	decodedBody := []int{}
   112  	err := json.NewDecoder(w.Body).Decode(&decodedBody)
   113  
   114  	if err != nil {
   115  		t.Fatal("Could not decode response body into slice.")
   116  	}
   117  
   118  	for i := range decodedBody {
   119  		if decodedBody[i] != originalBody[i] {
   120  			t.Fatalf("Expected %d but got %d in decoded body slice", originalBody[i], decodedBody[i])
   121  		}
   122  	}
   123  }
   124  
   125  func TestHealthCheckHandlerDefault(t *testing.T) {
   126  	endpointPath := "/healthcheck"
   127  
   128  	toolbox.AddHealthCheck("database", &SampleDatabaseCheck{})
   129  	toolbox.AddHealthCheck("cache", &SampleCacheCheck{})
   130  
   131  	req, err := http.NewRequest("GET", endpointPath, nil)
   132  	if err != nil {
   133  		t.Fatal(err)
   134  	}
   135  
   136  	w := httptest.NewRecorder()
   137  
   138  	handler := http.HandlerFunc(healthcheck)
   139  
   140  	handler.ServeHTTP(w, req)
   141  
   142  	if status := w.Code; status != http.StatusOK {
   143  		t.Errorf("handler returned wrong status code: got %v want %v",
   144  			status, http.StatusOK)
   145  	}
   146  	if !strings.Contains(w.Body.String(), "database") {
   147  		t.Errorf("Expected 'database' in generated template.")
   148  	}
   149  
   150  }
   151  
   152  func TestBuildHealthCheckResponseList(t *testing.T) {
   153  	healthCheckResults := [][]string{
   154  		[]string{
   155  			"error",
   156  			"Database",
   157  			"Error occurred while starting the db",
   158  		},
   159  		[]string{
   160  			"success",
   161  			"Cache",
   162  			"Cache started successfully",
   163  		},
   164  	}
   165  
   166  	responseList := buildHealthCheckResponseList(&healthCheckResults)
   167  
   168  	if len(responseList) != len(healthCheckResults) {
   169  		t.Errorf("invalid response map length: got %d want %d",
   170  			len(responseList), len(healthCheckResults))
   171  	}
   172  
   173  	responseFields := []string{"name", "message", "status"}
   174  
   175  	for _, response := range responseList {
   176  		for _, field := range responseFields {
   177  			_, ok := response[field]
   178  			if !ok {
   179  				t.Errorf("expected %s to be in the response %v", field, response)
   180  			}
   181  		}
   182  
   183  	}
   184  
   185  }
   186  
   187  func TestHealthCheckHandlerReturnsJSON(t *testing.T) {
   188  
   189  	toolbox.AddHealthCheck("database", &SampleDatabaseCheck{})
   190  	toolbox.AddHealthCheck("cache", &SampleCacheCheck{})
   191  
   192  	req, err := http.NewRequest("GET", "/healthcheck?json=true", nil)
   193  	if err != nil {
   194  		t.Fatal(err)
   195  	}
   196  
   197  	w := httptest.NewRecorder()
   198  
   199  	handler := http.HandlerFunc(healthcheck)
   200  
   201  	handler.ServeHTTP(w, req)
   202  	if status := w.Code; status != http.StatusOK {
   203  		t.Errorf("handler returned wrong status code: got %v want %v",
   204  			status, http.StatusOK)
   205  	}
   206  
   207  	decodedResponseBody := []map[string]interface{}{}
   208  	expectedResponseBody := []map[string]interface{}{}
   209  
   210  	expectedJSONString := []byte(`
   211  		[
   212  			{
   213  				"message":"database",
   214  				"name":"success",
   215  				"status":"OK"
   216  			},
   217  			{
   218  				"message":"cache",
   219  				"name":"error",
   220  				"status":"no cache detected"
   221  			}
   222  		]
   223  	`)
   224  
   225  	json.Unmarshal(expectedJSONString, &expectedResponseBody)
   226  
   227  	json.Unmarshal(w.Body.Bytes(), &decodedResponseBody)
   228  
   229  	if len(expectedResponseBody) != len(decodedResponseBody) {
   230  		t.Errorf("invalid response map length: got %d want %d",
   231  			len(decodedResponseBody), len(expectedResponseBody))
   232  	}
   233  
   234  	if !reflect.DeepEqual(decodedResponseBody, expectedResponseBody) {
   235  		t.Errorf("handler returned unexpected body: got %v want %v",
   236  			decodedResponseBody, expectedResponseBody)
   237  	}
   238  
   239  }