【问题标题】:Set timeout to ruby Test::unit run将超时设置为 ruby​​ Test::unit run
【发布时间】:2018-01-01 15:41:27
【问题描述】:

我正在使用 rake 任务来运行用 Ruby 编写的测试。 耙子任务:

desc "This Run Tests on my ruby app"
Rake::TestTask.new do |t|
  t.libs << File.dirname(__FILE__)
  t.test_files = FileList['test*.rb']
  t.verbose = true
end

我想创建一个超时,以便如果任何测试(或整个套件)挂起,将引发超时异常并且测试将失败。

我尝试创建一个新任务来运行超时的测试任务:

desc "Run Tests with timeout"
task :run_tests do
  Timeout::timeout(200) do
    Rake::Task['test'].invoke
  end
end

结果是抛出了超时,但测试继续运行。

【问题讨论】:

  • 我不知道只使用 Ruby 的干净方法。您可以将您的Timeout 调用包装在begin/rescue 块中以捕获它抛出的异常并使用此处提出的bash 解决方案之一stackoverflow.com/questions/6930157/…

标签: ruby rake testunit


【解决方案1】:

我一直在寻找类似的东西,最后写了这个:

require 'timeout'

# Provides an individual timeout for every test.
#
# In general tests should run for less then 1s so 5s is quite a generous timeout.
#
# Timeouts can be overridden per-class (in rare cases where tests should take more time)
# by setting for example `self.test_timeout = 10 #s`
module TestTimeoutHelper
  def self.included(base)
    class << base
      attr_accessor :test_timeout
    end

    base.test_timeout = 5 # s
  end

  # This overrides the default minitest behaviour of measuring time, with extra timeout :)
  # This helps out with: (a) keeping tests fast :) (b) detecting infinite loops
  #
  # In general however benchmarks test should be used instead.
  # Timeout is very unreliable by the way but in general works.
  def time_it
    t0 = Minitest.clock_time

    Timeout.timeout(self.class.test_timeout, Timeout::Error, 'Test took to long (infinite loop?)') do
      yield
    end
  ensure
    self.time = Minitest.clock_time - t0
  end
end

此模块应包含在特定测试用例或一般测试用例中。

它适用于 MiniTest 5.x

【讨论】:

    【解决方案2】:

    此代码为整个套件添加超时:

    def self.suite
        mysuite = super
        def mysuite.run(*args)
            Timeout::timeout(600) do
                super
            end
        end
        mysuite
    end
    

    【讨论】:

    • 你把它放在哪里了?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-12-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-05-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多