error_test.go 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  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. package beego
  15. import (
  16. "net/http"
  17. "net/http/httptest"
  18. "strconv"
  19. "strings"
  20. "testing"
  21. )
  22. type errorTestController struct {
  23. Controller
  24. }
  25. const parseCodeError = "parse code error"
  26. func (ec *errorTestController) Get() {
  27. errorCode, err := ec.GetInt("code")
  28. if err != nil {
  29. ec.Abort(parseCodeError)
  30. }
  31. if errorCode != 0 {
  32. ec.CustomAbort(errorCode, ec.GetString("code"))
  33. }
  34. ec.Abort("404")
  35. }
  36. func TestErrorCode_01(t *testing.T) {
  37. registerDefaultErrorHandler()
  38. for k := range ErrorMaps {
  39. r, _ := http.NewRequest("GET", "/error?code="+k, nil)
  40. w := httptest.NewRecorder()
  41. handler := NewControllerRegister()
  42. handler.Add("/error", &errorTestController{})
  43. handler.ServeHTTP(w, r)
  44. code, _ := strconv.Atoi(k)
  45. if w.Code != code {
  46. t.Fail()
  47. }
  48. if !strings.Contains(string(w.Body.Bytes()), http.StatusText(code)) {
  49. t.Fail()
  50. }
  51. }
  52. }
  53. func TestErrorCode_02(t *testing.T) {
  54. registerDefaultErrorHandler()
  55. r, _ := http.NewRequest("GET", "/error?code=0", nil)
  56. w := httptest.NewRecorder()
  57. handler := NewControllerRegister()
  58. handler.Add("/error", &errorTestController{})
  59. handler.ServeHTTP(w, r)
  60. if w.Code != 404 {
  61. t.Fail()
  62. }
  63. }
  64. func TestErrorCode_03(t *testing.T) {
  65. registerDefaultErrorHandler()
  66. r, _ := http.NewRequest("GET", "/error?code=panic", nil)
  67. w := httptest.NewRecorder()
  68. handler := NewControllerRegister()
  69. handler.Add("/error", &errorTestController{})
  70. handler.ServeHTTP(w, r)
  71. if w.Code != 200 {
  72. t.Fail()
  73. }
  74. if string(w.Body.Bytes()) != parseCodeError {
  75. t.Fail()
  76. }
  77. }