jsonhandler_test.go 8.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307
  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, any, 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, any, 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, any, 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, any, 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, any, 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("gzipped_400", func(t *testing.T) {
  158. w := httptest.NewRecorder()
  159. r := httptest.NewRequest("POST", "/", strings.NewReader(`{"Price": 10}`))
  160. r.Header.Set("Accept-Encoding", "gzip")
  161. value := []string{"foo", "foo", "foo"}
  162. JSONHandlerFunc(func(r *http.Request) (int, any, error) {
  163. return 400, value, nil
  164. }).ServeHTTPReturn(w, r)
  165. res := w.Result()
  166. if ct := res.Header.Get("Content-Encoding"); ct != "gzip" {
  167. t.Fatalf("encoding = %q; want gzip", ct)
  168. }
  169. if res.StatusCode != 400 {
  170. t.Errorf("Status = %v; want 400", res.StatusCode)
  171. }
  172. })
  173. t.Run("400 post data error", func(t *testing.T) {
  174. w := httptest.NewRecorder()
  175. r := httptest.NewRequest("POST", "/", strings.NewReader(`{}`))
  176. h32.ServeHTTPReturn(w, r)
  177. resp := checkStatus(t, w, "error", http.StatusBadRequest)
  178. if resp.Error != "price is empty" {
  179. t.Fatalf("wrong error")
  180. }
  181. })
  182. t.Run("500 internal server error (unspecified error, not of type HTTPError)", func(t *testing.T) {
  183. w := httptest.NewRecorder()
  184. r := httptest.NewRequest("POST", "/", strings.NewReader(`{"Name": "root"}`))
  185. h32.ServeHTTPReturn(w, r)
  186. resp := checkStatus(t, w, "error", http.StatusInternalServerError)
  187. if resp.Error != "internal server error" {
  188. t.Fatalf("wrong error")
  189. }
  190. })
  191. t.Run("500 misuse", func(t *testing.T) {
  192. w := httptest.NewRecorder()
  193. r := httptest.NewRequest("POST", "/", nil)
  194. JSONHandlerFunc(func(r *http.Request) (int, any, error) {
  195. return http.StatusOK, make(chan int), nil
  196. }).ServeHTTPReturn(w, r)
  197. resp := checkStatus(t, w, "error", http.StatusInternalServerError)
  198. if resp.Error != "json marshal error" {
  199. t.Fatalf("wrong error")
  200. }
  201. })
  202. t.Run("500 empty status code", func(t *testing.T) {
  203. w := httptest.NewRecorder()
  204. r := httptest.NewRequest("POST", "/", nil)
  205. JSONHandlerFunc(func(r *http.Request) (status int, data any, err error) {
  206. return
  207. }).ServeHTTPReturn(w, r)
  208. checkStatus(t, w, "error", http.StatusInternalServerError)
  209. })
  210. t.Run("403 forbidden, status returned by JSONHandlerFunc and HTTPError agree", func(t *testing.T) {
  211. w := httptest.NewRecorder()
  212. r := httptest.NewRequest("POST", "/", nil)
  213. JSONHandlerFunc(func(r *http.Request) (int, any, error) {
  214. return http.StatusForbidden, nil, Error(http.StatusForbidden, "403 forbidden", nil)
  215. }).ServeHTTPReturn(w, r)
  216. want := &Response{
  217. Status: "error",
  218. Data: &Data{},
  219. Error: "403 forbidden",
  220. }
  221. got := checkStatus(t, w, "error", http.StatusForbidden)
  222. if diff := cmp.Diff(want, got); diff != "" {
  223. t.Fatalf(diff)
  224. }
  225. })
  226. t.Run("403 forbidden, status returned by JSONHandlerFunc and HTTPError do not agree", func(t *testing.T) {
  227. w := httptest.NewRecorder()
  228. r := httptest.NewRequest("POST", "/", nil)
  229. err := JSONHandlerFunc(func(r *http.Request) (int, any, error) {
  230. return http.StatusInternalServerError, nil, Error(http.StatusForbidden, "403 forbidden", nil)
  231. }).ServeHTTPReturn(w, r)
  232. if !strings.HasPrefix(err.Error(), "[unexpected]") {
  233. t.Fatalf("returned error should have `[unexpected]` to note the disagreeing status codes: %v", err)
  234. }
  235. want := &Response{
  236. Status: "error",
  237. Data: &Data{},
  238. Error: "403 forbidden",
  239. }
  240. got := checkStatus(t, w, "error", http.StatusForbidden)
  241. if diff := cmp.Diff(want, got); diff != "" {
  242. t.Fatalf("(-want,+got):\n%s", diff)
  243. }
  244. })
  245. }
  246. func TestAcceptsEncoding(t *testing.T) {
  247. tests := []struct {
  248. in, enc string
  249. want bool
  250. }{
  251. {"", "gzip", false},
  252. {"gzip", "gzip", true},
  253. {"foo,gzip", "gzip", true},
  254. {"foo, gzip", "gzip", true},
  255. {"foo, gzip ", "gzip", true},
  256. {"gzip, foo ", "gzip", true},
  257. {"gzip, foo ", "br", false},
  258. {"gzip, foo ", "fo", false},
  259. {"gzip;q=1.2, foo ", "gzip", true},
  260. {" gzip;q=1.2, foo ", "gzip", true},
  261. }
  262. for i, tt := range tests {
  263. h := make(http.Header)
  264. if tt.in != "" {
  265. h.Set("Accept-Encoding", tt.in)
  266. }
  267. got := AcceptsEncoding(&http.Request{Header: h}, tt.enc)
  268. if got != tt.want {
  269. t.Errorf("%d. got %v; want %v", i, got, tt.want)
  270. }
  271. }
  272. }