builder_test.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457
  1. // SPDX-FileCopyrightText: Copyright The Miniflux Authors. All rights reserved.
  2. // SPDX-License-Identifier: Apache-2.0
  3. package response // import "miniflux.app/v2/internal/http/response"
  4. import (
  5. "bytes"
  6. "net/http"
  7. "net/http/httptest"
  8. "strings"
  9. "testing"
  10. "time"
  11. )
  12. func TestResponseHasCommonHeaders(t *testing.T) {
  13. r, err := http.NewRequest("GET", "/", nil)
  14. if err != nil {
  15. t.Fatal(err)
  16. }
  17. w := httptest.NewRecorder()
  18. handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  19. NewBuilder(w, r).Write()
  20. })
  21. handler.ServeHTTP(w, r)
  22. resp := w.Result()
  23. headers := map[string]string{
  24. "X-Content-Type-Options": "nosniff",
  25. "X-Frame-Options": "DENY",
  26. }
  27. for header, expected := range headers {
  28. actual := resp.Header.Get(header)
  29. if actual != expected {
  30. t.Fatalf(`Unexpected header value, got %q instead of %q`, actual, expected)
  31. }
  32. }
  33. }
  34. func TestBuildResponseWithCustomStatusCode(t *testing.T) {
  35. r, err := http.NewRequest("GET", "/", nil)
  36. if err != nil {
  37. t.Fatal(err)
  38. }
  39. w := httptest.NewRecorder()
  40. handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  41. NewBuilder(w, r).WithStatus(http.StatusNotAcceptable).Write()
  42. })
  43. handler.ServeHTTP(w, r)
  44. resp := w.Result()
  45. expectedStatusCode := http.StatusNotAcceptable
  46. if resp.StatusCode != expectedStatusCode {
  47. t.Fatalf(`Unexpected status code, got %d instead of %d`, resp.StatusCode, expectedStatusCode)
  48. }
  49. }
  50. func TestBuildResponseWithCustomHeader(t *testing.T) {
  51. r, err := http.NewRequest("GET", "/", nil)
  52. if err != nil {
  53. t.Fatal(err)
  54. }
  55. w := httptest.NewRecorder()
  56. handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  57. NewBuilder(w, r).WithHeader("X-My-Header", "Value").Write()
  58. })
  59. handler.ServeHTTP(w, r)
  60. resp := w.Result()
  61. expected := "Value"
  62. actual := resp.Header.Get("X-My-Header")
  63. if actual != expected {
  64. t.Fatalf(`Unexpected header value, got %q instead of %q`, actual, expected)
  65. }
  66. }
  67. func TestBuildResponseWithAttachment(t *testing.T) {
  68. r, err := http.NewRequest("GET", "/", nil)
  69. if err != nil {
  70. t.Fatal(err)
  71. }
  72. w := httptest.NewRecorder()
  73. handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  74. NewBuilder(w, r).WithAttachment("my_file.pdf").Write()
  75. })
  76. handler.ServeHTTP(w, r)
  77. resp := w.Result()
  78. expected := "attachment; filename=my_file.pdf"
  79. actual := resp.Header.Get("Content-Disposition")
  80. if actual != expected {
  81. t.Fatalf(`Unexpected header value, got %q instead of %q`, actual, expected)
  82. }
  83. }
  84. func TestBuildResponseWithByteBody(t *testing.T) {
  85. r, err := http.NewRequest("GET", "/", nil)
  86. if err != nil {
  87. t.Fatal(err)
  88. }
  89. w := httptest.NewRecorder()
  90. handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  91. NewBuilder(w, r).WithBodyAsBytes([]byte("body")).Write()
  92. })
  93. handler.ServeHTTP(w, r)
  94. expectedBody := `body`
  95. actualBody := w.Body.String()
  96. if actualBody != expectedBody {
  97. t.Fatalf(`Unexpected body, got %s instead of %s`, actualBody, expectedBody)
  98. }
  99. }
  100. func TestBuildResponseWithCachingEnabled(t *testing.T) {
  101. r, err := http.NewRequest("GET", "/", nil)
  102. if err != nil {
  103. t.Fatal(err)
  104. }
  105. w := httptest.NewRecorder()
  106. handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  107. NewBuilder(w, r).WithCaching("etag", 1*time.Minute, func(b *Builder) {
  108. b.WithBodyAsString("cached body")
  109. b.Write()
  110. })
  111. })
  112. handler.ServeHTTP(w, r)
  113. resp := w.Result()
  114. expectedStatusCode := http.StatusOK
  115. if resp.StatusCode != expectedStatusCode {
  116. t.Fatalf(`Unexpected status code, got %d instead of %d`, resp.StatusCode, expectedStatusCode)
  117. }
  118. expectedBody := `cached body`
  119. actualBody := w.Body.String()
  120. if actualBody != expectedBody {
  121. t.Fatalf(`Unexpected body, got %s instead of %s`, actualBody, expectedBody)
  122. }
  123. expectedHeader := "public, immutable"
  124. actualHeader := resp.Header.Get("Cache-Control")
  125. if actualHeader != expectedHeader {
  126. t.Fatalf(`Unexpected cache control header, got %q instead of %q`, actualHeader, expectedHeader)
  127. }
  128. if actualETag := resp.Header.Get("ETag"); actualETag != `"etag"` {
  129. t.Fatalf(`Unexpected etag header, got %q instead of %q`, actualETag, `"etag"`)
  130. }
  131. if resp.Header.Get("Expires") == "" {
  132. t.Fatalf(`Expires header should not be empty`)
  133. }
  134. }
  135. func TestBuildResponseWithCachingAndIfNoneMatch(t *testing.T) {
  136. tests := []struct {
  137. name string
  138. ifNoneMatch string
  139. expectedStatus int
  140. expectedBody string
  141. }{
  142. {"matching strong etag", `"etag"`, http.StatusNotModified, ""},
  143. {"matching weak etag", `W/"etag"`, http.StatusNotModified, ""},
  144. {"multiple etags with match", `"other", W/"etag"`, http.StatusNotModified, ""},
  145. {"wildcard", `*`, http.StatusNotModified, ""},
  146. {"non-matching etag", `"different"`, http.StatusOK, "cached body"},
  147. }
  148. for _, tt := range tests {
  149. t.Run(tt.name, func(t *testing.T) {
  150. r, err := http.NewRequest("GET", "/", nil)
  151. if err != nil {
  152. t.Fatal(err)
  153. }
  154. r.Header.Set("If-None-Match", tt.ifNoneMatch)
  155. w := httptest.NewRecorder()
  156. handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  157. NewBuilder(w, r).WithCaching("etag", 1*time.Minute, func(b *Builder) {
  158. b.WithBodyAsString("cached body")
  159. b.Write()
  160. })
  161. })
  162. handler.ServeHTTP(w, r)
  163. resp := w.Result()
  164. if resp.StatusCode != tt.expectedStatus {
  165. t.Fatalf(`Unexpected status code, got %d instead of %d`, resp.StatusCode, tt.expectedStatus)
  166. }
  167. if actual := w.Body.String(); actual != tt.expectedBody {
  168. t.Fatalf(`Unexpected body, got %q instead of %q`, actual, tt.expectedBody)
  169. }
  170. if resp.Header.Get("Cache-Control") != "public, immutable" {
  171. t.Fatalf(`Unexpected Cache-Control header: %q`, resp.Header.Get("Cache-Control"))
  172. }
  173. if resp.Header.Get("Expires") == "" {
  174. t.Fatalf(`Expires header should not be empty`)
  175. }
  176. })
  177. }
  178. }
  179. func TestNormalizeETag(t *testing.T) {
  180. tests := []struct {
  181. input string
  182. expected string
  183. }{
  184. {"abc", `"abc"`},
  185. {`"already-quoted"`, `"already-quoted"`},
  186. {`W/"weak"`, `W/"weak"`},
  187. {"", ""},
  188. {" spaced ", `"spaced"`},
  189. }
  190. for _, tt := range tests {
  191. t.Run(tt.input, func(t *testing.T) {
  192. if actual := normalizeETag(tt.input); actual != tt.expected {
  193. t.Fatalf(`normalizeETag(%q) = %q, want %q`, tt.input, actual, tt.expected)
  194. }
  195. })
  196. }
  197. }
  198. func TestIfNoneMatch(t *testing.T) {
  199. tests := []struct {
  200. name string
  201. headerValue string
  202. etag string
  203. expected bool
  204. }{
  205. {"empty header", "", `"etag"`, false},
  206. {"empty etag", `"etag"`, "", false},
  207. {"exact match", `"etag"`, `"etag"`, true},
  208. {"weak vs strong match", `W/"etag"`, `"etag"`, true},
  209. {"wildcard", `*`, `"etag"`, true},
  210. {"no match", `"other"`, `"etag"`, false},
  211. {"match in list", `"a", "etag", "b"`, `"etag"`, true},
  212. {"no match in list", `"a", "b", "c"`, `"etag"`, false},
  213. }
  214. for _, tt := range tests {
  215. t.Run(tt.name, func(t *testing.T) {
  216. if actual := ifNoneMatch(tt.headerValue, tt.etag); actual != tt.expected {
  217. t.Fatalf(`ifNoneMatch(%q, %q) = %v, want %v`, tt.headerValue, tt.etag, actual, tt.expected)
  218. }
  219. })
  220. }
  221. }
  222. func TestBuildResponseWithBrotliCompression(t *testing.T) {
  223. body := strings.Repeat("a", compressionThreshold+1)
  224. r, err := http.NewRequest("GET", "/", nil)
  225. r.Header.Set("Accept-Encoding", "gzip, deflate, br")
  226. if err != nil {
  227. t.Fatal(err)
  228. }
  229. w := httptest.NewRecorder()
  230. handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  231. NewBuilder(w, r).WithBodyAsString(body).Write()
  232. })
  233. handler.ServeHTTP(w, r)
  234. resp := w.Result()
  235. expected := "br"
  236. actual := resp.Header.Get("Content-Encoding")
  237. if actual != expected {
  238. t.Fatalf(`Unexpected header value, got %q instead of %q`, actual, expected)
  239. }
  240. }
  241. func TestBuildResponseWithGzipCompression(t *testing.T) {
  242. body := strings.Repeat("a", compressionThreshold+1)
  243. r, err := http.NewRequest("GET", "/", nil)
  244. r.Header.Set("Accept-Encoding", "gzip, deflate")
  245. if err != nil {
  246. t.Fatal(err)
  247. }
  248. w := httptest.NewRecorder()
  249. handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  250. NewBuilder(w, r).WithBodyAsString(body).Write()
  251. })
  252. handler.ServeHTTP(w, r)
  253. resp := w.Result()
  254. expected := "gzip"
  255. actual := resp.Header.Get("Content-Encoding")
  256. if actual != expected {
  257. t.Fatalf(`Unexpected header value, got %q instead of %q`, actual, expected)
  258. }
  259. }
  260. func TestBuildResponseWithDeflateCompression(t *testing.T) {
  261. body := strings.Repeat("a", compressionThreshold+1)
  262. r, err := http.NewRequest("GET", "/", nil)
  263. r.Header.Set("Accept-Encoding", "deflate")
  264. if err != nil {
  265. t.Fatal(err)
  266. }
  267. w := httptest.NewRecorder()
  268. handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  269. NewBuilder(w, r).WithBodyAsString(body).Write()
  270. })
  271. handler.ServeHTTP(w, r)
  272. resp := w.Result()
  273. expected := "deflate"
  274. actual := resp.Header.Get("Content-Encoding")
  275. if actual != expected {
  276. t.Fatalf(`Unexpected header value, got %q instead of %q`, actual, expected)
  277. }
  278. expectedVary := "Accept-Encoding"
  279. actualVary := resp.Header.Get("Vary")
  280. if actualVary != expectedVary {
  281. t.Fatalf(`Unexpected vary header value, got %q instead of %q`, actualVary, expectedVary)
  282. }
  283. }
  284. func TestBuildResponseWithCompressionDisabled(t *testing.T) {
  285. body := strings.Repeat("a", compressionThreshold+1)
  286. r, err := http.NewRequest("GET", "/", nil)
  287. r.Header.Set("Accept-Encoding", "deflate")
  288. if err != nil {
  289. t.Fatal(err)
  290. }
  291. w := httptest.NewRecorder()
  292. handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  293. NewBuilder(w, r).WithBodyAsString(body).WithoutCompression().Write()
  294. })
  295. handler.ServeHTTP(w, r)
  296. resp := w.Result()
  297. expected := ""
  298. actual := resp.Header.Get("Content-Encoding")
  299. if actual != expected {
  300. t.Fatalf(`Unexpected header value, got %q instead of %q`, actual, expected)
  301. }
  302. expectedVary := ""
  303. actualVary := resp.Header.Get("Vary")
  304. if actualVary != expectedVary {
  305. t.Fatalf(`Unexpected vary header value, got %q instead of %q`, actualVary, expectedVary)
  306. }
  307. }
  308. func TestBuildResponseWithDeflateCompressionAndSmallPayload(t *testing.T) {
  309. body := strings.Repeat("a", compressionThreshold)
  310. r, err := http.NewRequest("GET", "/", nil)
  311. r.Header.Set("Accept-Encoding", "deflate")
  312. if err != nil {
  313. t.Fatal(err)
  314. }
  315. w := httptest.NewRecorder()
  316. handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  317. NewBuilder(w, r).WithBodyAsString(body).Write()
  318. })
  319. handler.ServeHTTP(w, r)
  320. resp := w.Result()
  321. expected := ""
  322. actual := resp.Header.Get("Content-Encoding")
  323. if actual != expected {
  324. t.Fatalf(`Unexpected header value, got %q instead of %q`, actual, expected)
  325. }
  326. expectedVary := ""
  327. actualVary := resp.Header.Get("Vary")
  328. if actualVary != expectedVary {
  329. t.Fatalf(`Unexpected vary header value, got %q instead of %q`, actualVary, expectedVary)
  330. }
  331. }
  332. func TestBuildResponseWithoutCompressionHeader(t *testing.T) {
  333. body := strings.Repeat("a", compressionThreshold+1)
  334. r, err := http.NewRequest("GET", "/", nil)
  335. if err != nil {
  336. t.Fatal(err)
  337. }
  338. w := httptest.NewRecorder()
  339. handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  340. NewBuilder(w, r).WithBodyAsString(body).Write()
  341. })
  342. handler.ServeHTTP(w, r)
  343. resp := w.Result()
  344. expected := ""
  345. actual := resp.Header.Get("Content-Encoding")
  346. if actual != expected {
  347. t.Fatalf(`Unexpected header value, got %q instead of %q`, actual, expected)
  348. }
  349. expectedVary := "Accept-Encoding"
  350. actualVary := resp.Header.Get("Vary")
  351. if actualVary != expectedVary {
  352. t.Fatalf(`Unexpected vary header value, got %q instead of %q`, actualVary, expectedVary)
  353. }
  354. }
  355. func TestBuildResponseWithReaderBody(t *testing.T) {
  356. r, err := http.NewRequest("GET", "/", nil)
  357. if err != nil {
  358. t.Fatal(err)
  359. }
  360. w := httptest.NewRecorder()
  361. handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  362. NewBuilder(w, r).WithBodyAsReader(bytes.NewBufferString("body")).Write()
  363. })
  364. handler.ServeHTTP(w, r)
  365. if actualBody := w.Body.String(); actualBody != "body" {
  366. t.Fatalf(`Unexpected body, got %s instead of %s`, actualBody, "body")
  367. }
  368. }