clojure - 如何将字符串包装在输入流中?

标签 clojure

如何将字符串包装在输入流中以便可以测试下面的函数?

(defn parse-body [body]
    (cheshire/parse-stream  (clojure.java.io/reader body) true))

(deftest test-parse-body
    (testing "read body"
        (let [body "{\"age\": 28}"]  ;; must wrap string
            (is (= (parse-body body) {:age 28}))
            )))

最佳答案

通过首先转换为字节数组,使用主机互操作从字符串构造输入流非常简单:

(defn string->stream
  ([s] (string->stream s "UTF-8"))
  ([s encoding]
   (-> s
       (.getBytes encoding)
       (java.io.ByteArrayInputStream.))))

作为另一个流和字节互操作示例,下面是一个函数,它返回将字符串编码为给定格式时生成的字节向量:

(defn show-bytes
  [s encoding]
  (let [buf (java.io.ByteArrayOutputStream.)
        stream (string->stream s encoding)
        ;; worst case, 8 bytes per char?
        data (byte-array (* (count s) 8))
        size (.read stream data 0 (count data))]
    (.write buf data 0 size)
    (.flush buf)
    (apply vector-of :byte (.toByteArray buf))))

+user=> (string->stream "hello")
#object[java.io.ByteArrayInputStream 0x39b43d60 "java.io.ByteArrayInputStream@39b43d60"]
+user=> (isa? (class *1) java.io.InputStream)
true
+user=> (show-bytes "hello" "UTF-8")
[104 101 108 108 111]
+user=> (show-bytes "hello" "UTF-32")
[0 0 0 104 0 0 0 101 0 0 0 108 0 0 0 108 0 0 0 111]

关于clojure - 如何将字符串包装在输入流中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38283891/

相关文章:

clojure - 函数 seq?、sequential 之间有什么区别?和科尔?

binding - Clojure 绑定(bind)不起作用

clojure 循环与命令式循环

unit-testing - 如何防止 Clojure 测试之间的符号污染?

clojure - 如何从post返回json数据! Clojure 解放者中的处理程序?

clojure - assoc-in 可以创建一个新向量而不是新 map 吗?

function - 如何在 Clojure 中为函数参数创建默认值

Clojure:序列回向量

clojure - 在 Clojure 中编写累加器函数