我怎么嘲笑一个json post请求在环? [英] how do i mock a json post request in ring?

查看:122
本文介绍了我怎么嘲笑一个json post请求在环?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用橄榄石 - 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)
(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 设计为只读一次,并导致异常。



基本上有两种方法解决问题:


  1. 删除 compojure.handler / site

  2. 向请求中添加内容类型(如在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 specified wrap-params (which is included by compojure.handler/site) will attempt to read the :body in order to parse any form-urlencoded parameters. Then json-post attempts to read the :body again. However InputStreams are designed to be read once, and that causes the exception.

There are basically two ways to solve the issue:

  1. Remove compojure.handler/site.
  2. Add a content type to the request (as done in the tldr)

这篇关于我怎么嘲笑一个json post请求在环?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆