You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何让tasty测试中的指定测试组按顺序执行?

解决方案:让指定测试串行执行

要实现部分测试串行、其余测试并行的需求,核心是将需要互斥的测试打包为测试组,再限制该组的并发线程数为1,具体实现如下:

核心代码示例

import Test.Tasty
import Test.Tasty.Options
import Test.Tasty.HUnit

myTests :: TestTree
myTests = testGroup "All Tests"
  [ testCase "1" $ assertBool "test 1 passes" True
  , testCase "2" $ assertBool "test 2 passes" True
  -- 把需要串行的测试打包成组,强制组内仅用1线程执行
  , localOption @NumThreads 1 $ testGroup "Serial Resource Tests"
      [ testCase "3" $ do
          -- 操作共享文件/资源的逻辑
          assertBool "test 3 passes" True
      , testCase "4" $ do
          -- 操作共享文件/资源的逻辑
          assertBool "test 4 passes" True
      ]
  ]

关键逻辑说明

  1. testGroup的作用:将多个TestTree(如测试3、4)合并为单个TestTree,这样localOption就能对整个组生效。
  2. localOption @NumThreads 1的作用:覆盖全局并发设置,强制该测试组内的测试只能用1个线程执行,自然实现串行运行,避免资源冲突。

对其他思路的补充说明

  • 你之前单独用testGroup无效,是因为默认情况下测试组仍遵循全局并发配置,必须配合NumThreads 1的局部选项才能限制串行。
  • 用after声明依赖的方式也能实现顺序执行(需tasty-dependencies包支持),但它是强制指定测试顺序,而非限制并发。如果仅需资源互斥,用NumThreads 1的方式更通用:
    import Test.Tasty.Dependencies
    
    myTests :: TestTree
    myTests = testGroup "All Tests"
      [ testCase "1" $ assertBool "test 1 passes" True
      , testCase "2" $ assertBool "test 2 passes" True
      , let test3 = testCase "3" $ ...
            test4 = after test3 $ testCase "4" $ ...
          in testGroup "Ordered Tests" [test3, test4]
      ]
    

内容的提问来源于stack exchange,提问作者RandomB

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.03 18:05:47