【问题标题】:How to disable test fixtures when no tests are running in the current namespace?当前命名空间中没有运行测试时如何禁用测试夹具?
【发布时间】:2016-12-06 16:02:46
【问题描述】:

我见过很多 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 中处理这个问题的正确方法是什么?

【问题讨论】:

    标签: clojure clojure.test clojure-testing


    【解决方案1】:

    实现不运行昂贵计算的一种方法是利用这样一个事实:即使 :once 固定装置将运行而不管是否有测试在 ns 中运行,:each 固定装置只会在每个实际运行的测试上运行。

    我们不是在:once 夹具中进行实际计算(或获取数据库连接之类的资源,或做任何副作用),而是只在第一次做(我们只想做一次!)@ 987654324@夹具,例如如下:

    (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 将只运行一次:

    › lein test :integration
    
    lein test fixture.core-test
    enabling expensive fixture...
    doing expensive computation and acquiring resources...
    first integration test
    yay, expensive thing is done!
    second integration test
    
    Ran 2 tests containing 0 assertions.
    0 failures, 0 errors.
    

    【讨论】:

      【解决方案2】:

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

      (defn run-all-tests []
        (do-test-1)
        ...
        (do-test-N))
      
      (deftest ^:slow mytest
        (do-setup)
        (run-all-tests)
        (do-teardown))
      

      【讨论】:

        猜你喜欢
        • 2014-12-28
        • 2014-08-23
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-02-16
        相关资源
        最近更新 更多