【问题标题】:Clojure test: global fixturesClojure 测试:全局固定装置
【发布时间】:2017-04-24 10:10:10
【问题描述】:

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

现在看起来像这样:

(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 运行测试时,需要很长时间,不必要地花费时间连接和断开每个命名空间的数据库。

问题

有没有办法设置全局固定装置,这样当我运行lein test 时,它只对所有测试命名空间调用一次

谢谢!

【问题讨论】:

    标签: testing clojure


    【解决方案1】:

    如果该功能被添加到 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,这看起来很有意义......如果它有效,我会告诉你
    • 我最终使用了与您的代码类似的东西,非常感谢!
    【解决方案2】:

    使用circleci.test,支持:global-fixtures

    ...您可以定义在整个测试运行中只运行一次的全局固定装置,无论您运行多少个命名空间。

    【讨论】:

      猜你喜欢
      • 2017-05-18
      • 1970-01-01
      • 2014-01-12
      • 2018-09-22
      • 1970-01-01
      • 2023-03-11
      • 1970-01-01
      • 1970-01-01
      • 2014-09-18
      相关资源
      最近更新 更多