jsonhandler_test.go 8.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290
  1. // Copyright (c) 2020 Tailscale Inc & AUTHORS All rights reserved.
  2. // Use of this source code is governed by a BSD-style
  3. // license that can be found in the LICENSE file.
  4. package tsweb
  5. import (
  6. "bytes"
  7. "compress/gzip"
  8. "encoding/json"
  9. "fmt"
  10. "io"
  11. "net/http"
  12. "net/http/httptest"
  13. "strings"
  14. "testing"
  15. "github.com/google/go-cmp/cmp"
  16. )
  17. type Data struct {
  18. Name string
  19. Price int
  20. }
  21. type Response struct {
  22. Status string
  23. Error string
  24. Data *Data
  25. }
  26. func TestNewJSONHandler(t *testing.T) {
  27. checkStatus := func(t *testing.T, w *httptest.ResponseRecorder, status string, code int) *Response {
  28. d := &Response{
  29. Data: &Data{},
  30. }
  31. bodyBytes := w.Body.Bytes()
  32. if w.Result().Header.Get("Content-Encoding") == "gzip" {
  33. zr, err := gzip.NewReader(bytes.NewReader(bodyBytes))
  34. if err != nil {
  35. t.Fatalf("gzip read error at start: %v", err)
  36. }
  37. bodyBytes, err = io.ReadAll(zr)
  38. if err != nil {
  39. t.Fatalf("gzip read error: %v", err)
  40. }
  41. }
  42. t.Logf("%s", bodyBytes)
  43. err := json.Unmarshal(bodyBytes, d)
  44. if err != nil {
  45. t.Logf(err.Error())
  46. return nil
  47. }
  48. if d.Status == status {
  49. t.Logf("ok: %s", d.Status)
  50. } else {
  51. t.Fatalf("wrong status: got: %s, want: %s", d.Status, status)
  52. }
  53. if w.Code != code {
  54. t.Fatalf("wrong status code: got: %d, want: %d", w.Code, code)
  55. }
  56. if w.Header().Get("Content-Type") != "application/json" {
  57. t.Fatalf("wrong content type: %s", w.Header().Get("Content-Type"))
  58. }
  59. return d
  60. }
  61. h21 := JSONHandlerFunc(func(r *http.Request) (int, interface{}, error) {
  62. return http.StatusOK, nil, nil
  63. })
  64. t.Run("200 simple", func(t *testing.T) {
  65. w := httptest.NewRecorder()
  66. r := httptest.NewRequest("GET", "/", nil)
  67. h21.ServeHTTPReturn(w, r)
  68. checkStatus(t, w, "success", http.StatusOK)
  69. })
  70. t.Run("403 HTTPError", func(t *testing.T) {
  71. h := JSONHandlerFunc(func(r *http.Request) (int, interface{}, error) {
  72. return 0, nil, Error(http.StatusForbidden, "forbidden", nil)
  73. })
  74. w := httptest.NewRecorder()
  75. r := httptest.NewRequest("GET", "/", nil)
  76. h.ServeHTTPReturn(w, r)
  77. checkStatus(t, w, "error", http.StatusForbidden)
  78. })
  79. h22 := JSONHandlerFunc(func(r *http.Request) (int, interface{}, error) {
  80. return http.StatusOK, &Data{Name: "tailscale"}, nil
  81. })
  82. t.Run("200 get data", func(t *testing.T) {
  83. w := httptest.NewRecorder()
  84. r := httptest.NewRequest("GET", "/", nil)
  85. h22.ServeHTTPReturn(w, r)
  86. checkStatus(t, w, "success", http.StatusOK)
  87. })
  88. h31 := JSONHandlerFunc(func(r *http.Request) (int, interface{}, error) {
  89. body := new(Data)
  90. if err := json.NewDecoder(r.Body).Decode(body); err != nil {
  91. return 0, nil, Error(http.StatusBadRequest, err.Error(), err)
  92. }
  93. if body.Name == "" {
  94. return 0, nil, Error(http.StatusBadRequest, "name is empty", nil)
  95. }
  96. return http.StatusOK, nil, nil
  97. })
  98. t.Run("200 post data", func(t *testing.T) {
  99. w := httptest.NewRecorder()
  100. r := httptest.NewRequest("POST", "/", strings.NewReader(`{"Name": "tailscale"}`))
  101. h31.ServeHTTPReturn(w, r)
  102. checkStatus(t, w, "success", http.StatusOK)
  103. })
  104. t.Run("400 bad json", func(t *testing.T) {
  105. w := httptest.NewRecorder()
  106. r := httptest.NewRequest("POST", "/", strings.NewReader(`{`))
  107. h31.ServeHTTPReturn(w, r)
  108. checkStatus(t, w, "error", http.StatusBadRequest)
  109. })
  110. t.Run("400 post data error", func(t *testing.T) {
  111. w := httptest.NewRecorder()
  112. r := httptest.NewRequest("POST", "/", strings.NewReader(`{}`))
  113. h31.ServeHTTPReturn(w, r)
  114. resp := checkStatus(t, w, "error", http.StatusBadRequest)
  115. if resp.Error != "name is empty" {
  116. t.Fatalf("wrong error")
  117. }
  118. })
  119. h32 := JSONHandlerFunc(func(r *http.Request) (int, interface{}, error) {
  120. body := new(Data)
  121. if err := json.NewDecoder(r.Body).Decode(body); err != nil {
  122. return 0, nil, Error(http.StatusBadRequest, err.Error(), err)
  123. }
  124. if body.Name == "root" {
  125. return 0, nil, fmt.Errorf("invalid name")
  126. }
  127. if body.Price == 0 {
  128. return 0, nil, Error(http.StatusBadRequest, "price is empty", nil)
  129. }
  130. return http.StatusOK, &Data{Price: body.Price * 2}, nil
  131. })
  132. t.Run("200 post data", func(t *testing.T) {
  133. w := httptest.NewRecorder()
  134. r := httptest.NewRequest("POST", "/", strings.NewReader(`{"Price": 10}`))
  135. h32.ServeHTTPReturn(w, r)
  136. resp := checkStatus(t, w, "success", http.StatusOK)
  137. t.Log(resp.Data)
  138. if resp.Data.Price != 20 {
  139. t.Fatalf("wrong price: %d %d", resp.Data.Price, 10)
  140. }
  141. })
  142. t.Run("gzipped", func(t *testing.T) {
  143. w := httptest.NewRecorder()
  144. r := httptest.NewRequest("POST", "/", strings.NewReader(`{"Price": 10}`))
  145. r.Header.Set("Accept-Encoding", "gzip")
  146. h32.ServeHTTPReturn(w, r)
  147. res := w.Result()
  148. if ct := res.Header.Get("Content-Encoding"); ct != "gzip" {
  149. t.Fatalf("encoding = %q; want gzip", ct)
  150. }
  151. resp := checkStatus(t, w, "success", http.StatusOK)
  152. t.Log(resp.Data)
  153. if resp.Data.Price != 20 {
  154. t.Fatalf("wrong price: %d %d", resp.Data.Price, 10)
  155. }
  156. })
  157. t.Run("400 post data error", func(t *testing.T) {
  158. w := httptest.NewRecorder()
  159. r := httptest.NewRequest("POST", "/", strings.NewReader(`{}`))
  160. h32.ServeHTTPReturn(w, r)
  161. resp := checkStatus(t, w, "error", http.StatusBadRequest)
  162. if resp.Error != "price is empty" {
  163. t.Fatalf("wrong error")
  164. }
  165. })
  166. t.Run("500 internal server error (unspecified error, not of type HTTPError)", func(t *testing.T) {
  167. w := httptest.NewRecorder()
  168. r := httptest.NewRequest("POST", "/", strings.NewReader(`{"Name": "root"}`))
  169. h32.ServeHTTPReturn(w, r)
  170. resp := checkStatus(t, w, "error", http.StatusInternalServerError)
  171. if resp.Error != "internal server error" {
  172. t.Fatalf("wrong error")
  173. }
  174. })
  175. t.Run("500 misuse", func(t *testing.T) {
  176. w := httptest.NewRecorder()
  177. r := httptest.NewRequest("POST", "/", nil)
  178. JSONHandlerFunc(func(r *http.Request) (int, interface{}, error) {
  179. return http.StatusOK, make(chan int), nil
  180. }).ServeHTTPReturn(w, r)
  181. resp := checkStatus(t, w, "error", http.StatusInternalServerError)
  182. if resp.Error != "json marshal error" {
  183. t.Fatalf("wrong error")
  184. }
  185. })
  186. t.Run("500 empty status code", func(t *testing.T) {
  187. w := httptest.NewRecorder()
  188. r := httptest.NewRequest("POST", "/", nil)
  189. JSONHandlerFunc(func(r *http.Request) (status int, data interface{}, err error) {
  190. return
  191. }).ServeHTTPReturn(w, r)
  192. checkStatus(t, w, "error", http.StatusInternalServerError)
  193. })
  194. t.Run("403 forbidden, status returned by JSONHandlerFunc and HTTPError agree", func(t *testing.T) {
  195. w := httptest.NewRecorder()
  196. r := httptest.NewRequest("POST", "/", nil)
  197. JSONHandlerFunc(func(r *http.Request) (int, interface{}, error) {
  198. return http.StatusForbidden, nil, Error(http.StatusForbidden, "403 forbidden", nil)
  199. }).ServeHTTPReturn(w, r)
  200. want := &Response{
  201. Status: "error",
  202. Data: &Data{},
  203. Error: "403 forbidden",
  204. }
  205. got := checkStatus(t, w, "error", http.StatusForbidden)
  206. if diff := cmp.Diff(want, got); diff != "" {
  207. t.Fatalf(diff)
  208. }
  209. })
  210. t.Run("403 forbidden, status returned by JSONHandlerFunc and HTTPError do not agree", func(t *testing.T) {
  211. w := httptest.NewRecorder()
  212. r := httptest.NewRequest("POST", "/", nil)
  213. err := JSONHandlerFunc(func(r *http.Request) (int, interface{}, error) {
  214. return http.StatusInternalServerError, nil, Error(http.StatusForbidden, "403 forbidden", nil)
  215. }).ServeHTTPReturn(w, r)
  216. if !strings.HasPrefix(err.Error(), "[unexpected]") {
  217. t.Fatalf("returned error should have `[unexpected]` to note the disagreeing status codes: %v", err)
  218. }
  219. want := &Response{
  220. Status: "error",
  221. Data: &Data{},
  222. Error: "403 forbidden",
  223. }
  224. got := checkStatus(t, w, "error", http.StatusForbidden)
  225. if diff := cmp.Diff(want, got); diff != "" {
  226. t.Fatalf("(-want,+got):\n%s", diff)
  227. }
  228. })
  229. }
  230. func TestAcceptsEncoding(t *testing.T) {
  231. tests := []struct {
  232. in, enc string
  233. want bool
  234. }{
  235. {"", "gzip", false},
  236. {"gzip", "gzip", true},
  237. {"foo,gzip", "gzip", true},
  238. {"foo, gzip", "gzip", true},
  239. {"foo, gzip ", "gzip", true},
  240. {"gzip, foo ", "gzip", true},
  241. {"gzip, foo ", "br", false},
  242. {"gzip, foo ", "fo", false},
  243. {"gzip;q=1.2, foo ", "gzip", true},
  244. {" gzip;q=1.2, foo ", "gzip", true},
  245. }
  246. for i, tt := range tests {
  247. h := make(http.Header)
  248. if tt.in != "" {
  249. h.Set("Accept-Encoding", tt.in)
  250. }
  251. got := AcceptsEncoding(&http.Request{Header: h}, tt.enc)
  252. if got != tt.want {
  253. t.Errorf("%d. got %v; want %v", i, got, tt.want)
  254. }
  255. }
  256. }