首页 > 解决方案 > 如何将 Ruby 测试/单元日志记录设置为 quiet_mode?

问题描述

我正在尝试为我在 test/unit 中运行的测试设置日志记录级别

require 'test/unit'
require 'logger'
class MyMath
  def self.adder(a,b)
    a+b
  end
end

class Tester < Test::Unit::TestCase
  $logger = Logger.new($stdout)
  def test_adder()
    $logger.info "Starting Test"
    assert_equal(4, MyMath.adder(2,2) )
    $logger.info "Ending   Test"
  end
end

输出是

Loaded suite ruby.test
Started
I, [2021-07-23T13:12:26.497311 #49542]  INFO -- : Starting Test
I, [2021-07-23T13:12:26.497375 #49542]  INFO -- : Ending   Test
.
Finished in 0.000358 seconds.
---------------------------------------------------------------------------------------------------------------------------------------------------------------------
1 tests, 1 assertions, 0 failures, 0 errors, 0 pendings, 0 omissions, 0 notifications
100% passed
---------------------------------------------------------------------------------------------------------------------------------------------------------------------
2793.30 tests/s, 2793.30 assertions/s

如何让它不打印日志消息?在它谈到的 Test::Unit::UI::Console::TestRunner 代码中

      # Creates a new TestRunner for running the passed
      # suite. If quiet_mode is true, the output while
      # running is limited to progress dots, errors and
      # failures, and the final result. io specifies
      # where runner output should go to; defaults to
      # STDOUT.

什么是 quiet_mode,我该如何设置?

标签: rubyloggingtestunit

解决方案


我认为您的问题是您需要相应地设置记录器的日志级别。

$logger = Logger.new($stdout)
$logger.level = Logger::WARN

https://ruby-doc.org/stdlib-2.4.0/libdoc/logger/rdoc/Logger.html

不确定您是否使用任何框架,因此您可以在测试中设置日志级别,例如

if ENV["test"]
  $logger.level = Logger::WARN
end

推荐阅读