欢迎!请参阅关于页面以获取更多如何使用此功能的信息。
(submap? m1 m2) 递归检查 m1 是否包含在 m2 中
(submap? m1 m2)
用法
(deftest submap (is (submap? {} {})) (is (not (submap? {:k 1} {}))) (is (submap? {:k 1} {:k 1 :j 2})) (is (submap? {:k {:kk 1}} {:k {:kk 1 :j 2}})) (is (not (submap? {:k {:kk 1}} {:j 2}))))
这种需求通常在测试中出现,其中你想要检查被测试函数返回的映射具有特定的形状,同时在假设一个开放世界 - 即你想要忽略任何额外的键,这样改变被测试函数不会破坏测试
;; BAD: doesn't assume open world (is (= {:k :v} (function-under-test))) ;; BAD: not expressive (is (= :v (:k (function-under-test)))) ;; BAD: not expressive, need to write :k twice (is (= {:k :v} (select-keys (function-under-test) [:k]))) ;; GOOD: expressive (is (submap? {:k :v} (function-under-test)))
许多代码库中已经存在实现(在 GitHub 代码搜索中找到 400 多个结果)。示例
https://github.com/clojure/tools.deps/blob/ecc80420c1b734b384f7a42df91684cdbc37ddc6/src/test/clojure/clojure/tools/deps/util.clj#LL12-L25C18
https://github.com/ptaoussanis/encore/blob/96547700c03a5e81d784bcc9253980d7355f2f2b/src/taoensso/encore.cljc#L2071
登录https://clojure.atlassian.net/browse/CLJ-2755