|
| 1 | +(ns ring.middleware.test.content-length |
| 2 | + (:require [clojure.test :refer [deftest is testing]] |
| 3 | + [ring.middleware.content-length :refer [content-length-response |
| 4 | + wrap-content-length]])) |
| 5 | + |
| 6 | +(deftest test-content-length-response |
| 7 | + (testing "strings" |
| 8 | + (is (= "5" (-> (content-length-response |
| 9 | + {:status 200 |
| 10 | + :headers {"Content-Type" "text/plain; charset=UTF-8"} |
| 11 | + :body "hello"}) |
| 12 | + (get-in [:headers "Content-Length"]))))) |
| 13 | + (testing "strings without a defined charset" |
| 14 | + (is (nil? (-> (content-length-response |
| 15 | + {:status 200 |
| 16 | + :headers {"Content-Type" "text/plain"} |
| 17 | + :body "hello"}) |
| 18 | + (get-in [:headers "Content-Length"]))))) |
| 19 | + (testing "byte arrays" |
| 20 | + (is (= "11" (-> (content-length-response |
| 21 | + {:status 200 |
| 22 | + :headers {} |
| 23 | + :body (.getBytes "hello world" "UTF-8")}) |
| 24 | + (get-in [:headers "Content-Length"]))))) |
| 25 | + (testing "files" |
| 26 | + (is (= "6" (-> (content-length-response |
| 27 | + {:status 200 |
| 28 | + :headers {} |
| 29 | + :body (java.io.File. "test/ring/assets/plain.txt")}) |
| 30 | + (get-in [:headers "Content-Length"]))))) |
| 31 | + (testing "nil" |
| 32 | + (is (= "0" (-> (content-length-response |
| 33 | + {:status 200, :headers {}, :body nil}) |
| 34 | + (get-in [:headers "Content-Length"]))))) |
| 35 | + (testing "other data" |
| 36 | + (is (nil? (-> (content-length-response |
| 37 | + {:status 200 |
| 38 | + :headers {"Content-Type" "text/plain; charset=UTF-8"} |
| 39 | + :body (list "hello" "world")}) |
| 40 | + (get-in [:headers "Content-Length"]))))) |
| 41 | + (testing "manual content-length overrides middleware" |
| 42 | + (is (= "10" (-> (content-length-response |
| 43 | + {:status 200 |
| 44 | + :headers {"Content-Length" "10"} |
| 45 | + :body (.getBytes "hello world" "UTF-8")}) |
| 46 | + (get-in [:headers "Content-Length"])))))) |
| 47 | + |
| 48 | +(deftest test-wrap-content-length |
| 49 | + (testing "synchronous handlers" |
| 50 | + (let [handler (wrap-content-length |
| 51 | + (constantly |
| 52 | + {:status 200 |
| 53 | + :headers {"Content-Type" "text/plain; charset=UTF-8"} |
| 54 | + :body "hello"}))] |
| 55 | + (is (= "5" (-> (handler {:request-method :get, :uri "/"}) |
| 56 | + (get-in [:headers "Content-Length"])))))) |
| 57 | + (testing "asynchronous handlers" |
| 58 | + (let [response (promise) |
| 59 | + error (promise) |
| 60 | + request {:request-method :get, :url "/"} |
| 61 | + handler (wrap-content-length |
| 62 | + (fn [_ respond _] |
| 63 | + (respond |
| 64 | + {:status 200 |
| 65 | + :headers {"Content-Type" "text/plain; charset=UTF-8"} |
| 66 | + :body "hello"})))] |
| 67 | + (handler request response error) |
| 68 | + (is (not (realized? error))) |
| 69 | + (is (realized? response)) |
| 70 | + (is (= "5" (get-in @response [:headers "Content-Length"])))))) |
0 commit comments