gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 21:16:15 26 4
gpt4 key购买 nike

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

(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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com