我怎么嘲笑一个json post请求在环? [英] how do i mock a json post request in ring?
问题描述
我使用橄榄石 - https://github.com/xeqi/peridot 来测试我的环状应用程式,以及工作正常,直到我尝试用json数据模拟一个post请求:
(require'[cheshire.core:as json])
(use'compojure.core)
(defn json-post [req]
(if(:body req)
(json / parse-string body req))))
(defroutes all-routes
(POST/ test / jsonreq(json-post req)))
(def app(compojure.handler / site all-routes))
(使用'peridot.core)
( - > $ b(request/ test / json
:request-method:post
:body(java.io.ByteArrayInputStream。(.getByteshelloUTF-8)))
给出 IOException:stream closed
。
有更好的方法吗?
tldr:
( - >(session app)
$当$ peridot生成一个请求映射时,它将默认为
(request/ test / json
:request-method:post
:content-typeapplication / json
:body(.getBytes\hello\UTF-8)))
application / x-www-form(p $ p> p $ p>
作为
$ b < -urlencoded:post
请求的内容类型。使用指定的应用程序wrap-params
(包含在compojure.handler / site
)将尝试读取:body
,以便解析任何形式 - 编码的参数。然后json-post
尝试再次读取:body
。但是InputStream
设计为只读一次,并导致异常。
基本上有两种方法解决问题:
- 删除
compojure.handler / site
。
- 向请求中添加内容类型(如在tldr中执行的操作)
I'm using peridot - https://github.com/xeqi/peridot to test my ring application, and its working fine until I try to mock a post request with json data:
(require '[cheshire.core :as json]) (use 'compojure.core) (defn json-post [req] (if (:body req) (json/parse-string (slurp (:body req))))) (defroutes all-routes (POST "/test/json" req (json-response (json-post req)))) (def app (compojure.handler/site all-routes)) (use 'peridot.core) (-> (session app) (request "/test/json" :request-method :post :body (java.io.ByteArrayInputStream. (.getBytes "hello" "UTF-8")))gives
IOException: stream closed
.Is there a better way to do this?
解决方案tldr:
(-> (session app) (request "/test/json" :request-method :post :content-type "application/json" :body (.getBytes "\"hello\"" "UTF-8")))
When peridot generates a request map it will default to
application/x-www-form-urlencoded
for the content-type for a:post
request. With the app as specifiedwrap-params
(which is included bycompojure.handler/site
) will attempt to read the:body
in order to parse any form-urlencoded parameters. Thenjson-post
attempts to read the:body
again. HoweverInputStream
s are designed to be read once, and that causes the exception.There are basically two ways to solve the issue:
- Remove
compojure.handler/site
.- Add a content type to the request (as done in the tldr)
这篇关于我怎么嘲笑一个json post请求在环?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!