http_handler_test.go 4.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131
  1. // Copyright (c) 2016 Uber Technologies, Inc.
  2. //
  3. // Permission is hereby granted, free of charge, to any person obtaining a copy
  4. // of this software and associated documentation files (the "Software"), to deal
  5. // in the Software without restriction, including without limitation the rights
  6. // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  7. // copies of the Software, and to permit persons to whom the Software is
  8. // furnished to do so, subject to the following conditions:
  9. //
  10. // The above copyright notice and this permission notice shall be included in
  11. // all copies or substantial portions of the Software.
  12. //
  13. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  14. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  15. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  16. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  17. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  18. // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  19. // THE SOFTWARE.
  20. package zap_test
  21. import (
  22. "encoding/json"
  23. "fmt"
  24. "io"
  25. "io/ioutil"
  26. "net/http"
  27. "net/http/httptest"
  28. "strings"
  29. "testing"
  30. . "go.uber.org/zap"
  31. "go.uber.org/zap/zapcore"
  32. "github.com/stretchr/testify/assert"
  33. "github.com/stretchr/testify/require"
  34. )
  35. func newHandler() (AtomicLevel, *Logger) {
  36. lvl := NewAtomicLevel()
  37. logger := New(zapcore.NewNopCore())
  38. return lvl, logger
  39. }
  40. func assertCodeOK(t testing.TB, code int) {
  41. assert.Equal(t, http.StatusOK, code, "Unexpected response status code.")
  42. }
  43. func assertCodeBadRequest(t testing.TB, code int) {
  44. assert.Equal(t, http.StatusBadRequest, code, "Unexpected response status code.")
  45. }
  46. func assertCodeMethodNotAllowed(t testing.TB, code int) {
  47. assert.Equal(t, http.StatusMethodNotAllowed, code, "Unexpected response status code.")
  48. }
  49. func assertResponse(t testing.TB, expectedLevel zapcore.Level, actualBody string) {
  50. assert.Equal(t, fmt.Sprintf(`{"level":"%s"}`, expectedLevel)+"\n", actualBody, "Unexpected response body.")
  51. }
  52. func assertJSONError(t testing.TB, body string) {
  53. // Don't need to test exact error message, but one should be present.
  54. var payload map[string]interface{}
  55. require.NoError(t, json.Unmarshal([]byte(body), &payload), "Expected error response to be JSON.")
  56. msg, ok := payload["error"]
  57. require.True(t, ok, "Error message is an unexpected type.")
  58. assert.NotEqual(t, "", msg, "Expected an error message in response.")
  59. }
  60. func makeRequest(t testing.TB, method string, handler http.Handler, reader io.Reader) (int, string) {
  61. ts := httptest.NewServer(handler)
  62. defer ts.Close()
  63. req, err := http.NewRequest(method, ts.URL, reader)
  64. require.NoError(t, err, "Error constructing %s request.", method)
  65. res, err := http.DefaultClient.Do(req)
  66. require.NoError(t, err, "Error making %s request.", method)
  67. defer res.Body.Close()
  68. body, err := ioutil.ReadAll(res.Body)
  69. require.NoError(t, err, "Error reading request body.")
  70. return res.StatusCode, string(body)
  71. }
  72. func TestHTTPHandlerGetLevel(t *testing.T) {
  73. lvl, _ := newHandler()
  74. code, body := makeRequest(t, "GET", lvl, nil)
  75. assertCodeOK(t, code)
  76. assertResponse(t, lvl.Level(), body)
  77. }
  78. func TestHTTPHandlerPutLevel(t *testing.T) {
  79. lvl, _ := newHandler()
  80. code, body := makeRequest(t, "PUT", lvl, strings.NewReader(`{"level":"warn"}`))
  81. assertCodeOK(t, code)
  82. assertResponse(t, lvl.Level(), body)
  83. }
  84. func TestHTTPHandlerPutUnrecognizedLevel(t *testing.T) {
  85. lvl, _ := newHandler()
  86. code, body := makeRequest(t, "PUT", lvl, strings.NewReader(`{"level":"unrecognized-level"}`))
  87. assertCodeBadRequest(t, code)
  88. assertJSONError(t, body)
  89. }
  90. func TestHTTPHandlerNotJSON(t *testing.T) {
  91. lvl, _ := newHandler()
  92. code, body := makeRequest(t, "PUT", lvl, strings.NewReader(`{`))
  93. assertCodeBadRequest(t, code)
  94. assertJSONError(t, body)
  95. }
  96. func TestHTTPHandlerNoLevelSpecified(t *testing.T) {
  97. lvl, _ := newHandler()
  98. code, body := makeRequest(t, "PUT", lvl, strings.NewReader(`{}`))
  99. assertCodeBadRequest(t, code)
  100. assertJSONError(t, body)
  101. }
  102. func TestHTTPHandlerMethodNotAllowed(t *testing.T) {
  103. lvl, _ := newHandler()
  104. code, body := makeRequest(t, "POST", lvl, strings.NewReader(`{`))
  105. assertCodeMethodNotAllowed(t, code)
  106. assertJSONError(t, body)
  107. }