testing - 是否有一种(惯用的)方法来测试 Clojure 中 IO 函数的结果?

标签 testing clojure clojure.test

我有一个将一些文本保存到文件的函数:

(defn save-keypair
  "saves keypair to ~/.ssb-clj/secret"
  [pair file-path]
  (let [public-key-string (->> (:public pair) (.array) (byte-array) (b64/encode) (bs/to-string))
        secret-key-string (->> (:secret pair) (.array) (byte-array) (b64/encode) (bs/to-string))]
    (spit file-path (str "Public Key: " public-key-string))
    (spit file-path (str "\nPrivate Key: " secret-key-string) :append true)))

它工作正常(目前通过打开文件并自己查看来检查)。但是,我想编写一个实际测试来检查一切是否正常工作。在 Clojure 中是否有一种惯用的方法来做到这一点?

最佳答案

考虑使用 with-redefs ,作为单元测试的一部分。在您的情况下,您可能希望将公钥和私钥的写入合并为一种形式,我们可以利用这种形式进行测试:

;; compute public-key-string and private-key-string as before
(let [contents (format "Public Key: %s\nPrivate Key: %s"
                        public-key-string secret-key-string)]
 (spit file-path contents)

测试可能是这样的:

(deftest saving-keypair
  (testing "Successful save"
    (let [file-mock (atom nil)]

      ;; During this test we redefine `spit` to save into the atom defined above
      (with-redefs [spit (fn [path data] (reset! file-mock {:path path :data data}))]

        ;; Perform IO action
        (save-keypair "~/.ssb-clj/secret" {:public "XXXX" :private "YYYYY"})

        ;; Test if the expected data was saved in the file-mock
        (is (= {:path "~/.ssb-clj/secret" :data "Public key: XXXYYYZZZ\nXXXYYYZZ"}
               @file-mock))

关于testing - 是否有一种(惯用的)方法来测试 Clojure 中 IO 函数的结果?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57845492/

相关文章:

android - 使用monkeytalk测试android应用程序,录音按钮被禁用

clojure - 减少像 Clojure 中带有条件的循环这样的惰性序列

断言抛出的 Clojure 测试

Clojure.test 和 Leiningen : How to run just a single test from command line

testing - Flex Builder : Asset file or directory name cannot be more than 100 bytes long

node.js - 用于 e2e 前端测试的暂存后端

laravel - 功能测试和浏览器测试之间的区别

Clojure 数据结构函数

vector - Clojure 引用向量