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

     1  // Copyright 2016 beego Author. All Rights Reserved.
     2  //
     3  // Licensed under the Apache License, Version 2.0 (the "License");
     4  // you may not use this file except in compliance with the License.
     5  // You may obtain a copy of the License at
     6  //
     7  //      http://www.apache.org/licenses/LICENSE-2.0
     8  //
     9  // Unless required by applicable law or agreed to in writing, software
    10  // distributed under the License is distributed on an "AS IS" BASIS,
    11  // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    12  // See the License for the specific language governing permissions and
    13  // limitations under the License.
    14  
    15  package beego
    16  
    17  import (
    18  	"net/http"
    19  	"net/http/httptest"
    20  	"strconv"
    21  	"strings"
    22  	"testing"
    23  )
    24  
    25  type errorTestController struct {
    26  	Controller
    27  }
    28  
    29  const parseCodeError = "parse code error"
    30  
    31  func (ec *errorTestController) Get() {
    32  	errorCode, err := ec.GetInt("code")
    33  	if err != nil {
    34  		ec.Abort(parseCodeError)
    35  	}
    36  	if errorCode != 0 {
    37  		ec.CustomAbort(errorCode, ec.GetString("code"))
    38  	}
    39  	ec.Abort("404")
    40  }
    41  
    42  func TestErrorCode_01(t *testing.T) {
    43  	registerDefaultErrorHandler()
    44  	for k := range ErrorMaps {
    45  		r, _ := http.NewRequest("GET", "/error?code="+k, nil)
    46  		w := httptest.NewRecorder()
    47  
    48  		handler := NewControllerRegister()
    49  		handler.Add("/error", &errorTestController{})
    50  		handler.ServeHTTP(w, r)
    51  		code, _ := strconv.Atoi(k)
    52  		if w.Code != code {
    53  			t.Fail()
    54  		}
    55  		if !strings.Contains(w.Body.String(), http.StatusText(code)) {
    56  			t.Fail()
    57  		}
    58  	}
    59  }
    60  
    61  func TestErrorCode_02(t *testing.T) {
    62  	registerDefaultErrorHandler()
    63  	r, _ := http.NewRequest("GET", "/error?code=0", nil)
    64  	w := httptest.NewRecorder()
    65  
    66  	handler := NewControllerRegister()
    67  	handler.Add("/error", &errorTestController{})
    68  	handler.ServeHTTP(w, r)
    69  	if w.Code != 404 {
    70  		t.Fail()
    71  	}
    72  }
    73  
    74  func TestErrorCode_03(t *testing.T) {
    75  	registerDefaultErrorHandler()
    76  	r, _ := http.NewRequest("GET", "/error?code=panic", nil)
    77  	w := httptest.NewRecorder()
    78  
    79  	handler := NewControllerRegister()
    80  	handler.Add("/error", &errorTestController{})
    81  	handler.ServeHTTP(w, r)
    82  	if w.Code != 200 {
    83  		t.Fail()
    84  	}
    85  	if w.Body.String() != parseCodeError {
    86  		t.Fail()
    87  	}
    88  }