如何在当前命名空间中没有运行测试时禁用测试夹具?

时间:2016-12-06 16:02:46

标签: clojure clojure.test clojure-testing

我看到很多clojure项目默认情况下通过将此设置添加到project.clj来禁用集成测试:

:test-selectors {:default (complement :integration)
                 :integration :integration}

但是,如果命名空间只包含集成测试,那么当我运行lein test时,其中的灯具仍会运行!

例如,如果我运行lein new app test并将core_test.clj的内容设为:

(defn fixture [f]
  (println "Expensive setup fixture is running")
  (f))
(use-fixtures :once fixture)

(deftest ^:integration a-test
  (println "integration test running"))

然后当我运行lein test时,即使没有运行任何测试,我也会看到灯具正在运行。

在clojure中处理此问题的正确方法是什么?

2 个答案:

答案 0 :(得分:3)

实现不运行昂贵计算的一种方法是利用这样一个事实:即使:once灯具将运行而不管是否在ns中运行测试,{{1} fixtures只会在每个实际运行的测试中运行。

我们不是在:each灯具中进行实际计算(或获取像db连接这样的资源,或做任何副作用),而是只在第一次执行(我们只想做一次! ):once fixture,例如,如下所示:

:each

(def run-fixture? (atom true)) (defn enable-fixture [f] (println "enabling expensive fixture...") (try (f) (finally (reset! run-fixture? true)))) (defn expensive-fixture [f] (if @run-fixture? (do (println "doing expensive computation and acquiring resources...") (reset! run-fixture? false)) (println "yay, expensive thing is done!")) (f)) (use-fixtures :once enable-fixture) (use-fixtures :each expensive-fixture) (deftest ^:integration integration-test (println "first integration test")) (deftest ^:integration second-integration-test (println "second integration test")) 的输出如下(注意lein test的运行情况,但不是昂贵的enable-fixture):

expensive-fixture

运行› lein test lein test fixture.core-test enabling expensive fixture... Ran 0 tests containing 0 assertions. 0 failures, 0 errors. 时,lein test :integration将只运行一次:

expensive-fixture

答案 1 :(得分:1)

无论测试是否运行,似乎灯具都在运行。然后,您可以将夹具功能放入测试本身,以“手动”控制该设置/拆卸。伪代码:

range(1,len(t))