Clojure测试:全局装置

6

我有一些在我的项目中启动和关闭数据库的固定配置。

现在它看起来像这样:

(use-fixtures :once with-embedded-db)

在夹具本身中,我有一个动态变量,我在不同的地方使用:

(def ^:dynamic *db*)

(defn with-embedded-db [f]
  (binding [*db* (db/connect args)]
    (f)
    (finally
      (db/clean-up *db)))

现在假设db/connectdb/clean-up需要一些时间。

问题:

当我使用lein test运行测试时,它花费了很长时间,在每个命名空间中连接和断开与数据库的连接,浪费了不必要的时间。

问题:

是否存在一种设置全局夹具(global fixtures)的方式,使得当我运行lein test时,它只对所有测试命名空间调用一次?

谢谢!

2个回答

3

如果这个功能被添加到Leiningen本身会更好。至少应该开一个票,如果不是一个PR。

下面的解决方案很粗糙,但你可以理解并将其转化为更智能的解决方案。

;; profect.clj
:profiles 
 {:dev {:dependencies [[robert/hooke "1.1.2"]]

 :injections   [(require '[robert.hooke :as hooke])
  (defn run-all-test-hook [f & nss]
  (doall (map (fn [a]
   (when (intern a '*db*)
    (intern a '*db* "1234"))) nss))
  (apply f nss))
  (hooke/add-hook #'clojure.test/run-tests #'run-all-test-hook)
 ]}}

注意:Leiningen本身在其核心中使用robert/hooke。然后在某个测试中:
(ns reagenttest.cli
    (:require [clojure.test :refer :all]))

(def ^:dynamic *db*) ;; should be defined in every NS where it is needed

(deftest Again
    (testing "new"
        (prn *db*)))

哦,我一定会去看看的!:) 我试着写插件,我想使用 robert/hooke,这看起来很有道理... 如果它起作用了,我会告诉你的。 - andrusieczko
我最终使用了类似于你的代码,非常感谢! - andrusieczko

1
使用 circleci.test,它支持 :全局夹具

... 您可以定义全局夹具,它仅在整个测试运行期间运行一次,无论您运行多少个命名空间。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接