如何使用Test / Unit,MiniTest在自动测试中获得颜色输出?

时间:2012-02-21 20:54:58

标签: ruby-on-rails ruby-on-rails-3 testunit

Rails 3.2.1 app,使用minitest和autotest-rails gems。

如果我跑'#34; rake test"输出是彩色的。但是,如果我运行自动测试,输出不是彩色的。

使用自动测试时如何获得颜色输出?

这是我的test_helper.rb:

ENV["RAILS_ENV"] = "test"
require File.expand_path('../../config/environment', __FILE__)
require 'rails/test_help'
require 'turn/autorun'

Turn.config do |c|
 # use one of output formats:
 # :outline  - turn's original case/test outline mode [default]
 # :progress - indicates progress with progress bar
 # :dotted   - test/unit's traditional dot-progress mode
 # :pretty   - new pretty reporter
 # :marshal  - dump output as YAML (normal run mode only)
 # :cue      - interactive testing
 c.format  = :pretty
 # turn on invoke/execute tracing, enable full backtrace
 c.trace   = true
 # use humanized test names (works only with :outline format)
 c.natural = true
end

class ActiveSupport::TestCase
  # Setup all fixtures in test/fixtures/*.(yml|csv) for all tests in alphabetical order.
  #
  # Note: You'll currently still have to declare fixtures explicitly in integration tests
  # -- they do not yet inherit this setting
  fixtures :all

  # Add more helper methods to be used by all tests here...
end

1 个答案:

答案 0 :(得分:8)

  

如果我运行“rake test”,则输出为彩色。

这是因为在自动测试中,运行测试过程的“终端”不是tty,而当你直接运行时,它就是。

首先它是如何工作的,颜色代码在转义序列中定义,如果你把它们写下来就像\E[48mPRINT ME IN RED\E[0mdetails)。

您的终端了解这些转义序列(通常),将其替换为颜色,从而改善输出的外观。

通过使用终端仿真器定义的环境变量,并查看它的输入,输出流(即$stdin$stdout$stderr)进程可以确定颜色支持,以及它是否连接到终端(tty)或文件,或其他进程,等等。

当一个进程启动另一个进程时,您的进程,而不是终端是所有者,因此您的test输出不与正在理解彩色转义序列的终端通话,它正在与自动测试通话,而不是

同样的行为会发生,运行测试,但将输出重定向到文件,转义码和序列将毫无意义。

这种关系看起来像这样:

# rake test
Terminal Application
 \- Bash
     \- rake         # Rake's $stdout.tty? => true 
                     # (Bash is a terminal emulator)

# autotest
Terminal Application
 \- Bash
     \- autotest
         \- rake      # Rake's $stdout.tty? => false
                      # (Autotest is not a terminal emulator)

有几种方法来伪造支持,因此自动测试以彩色运行,单向documented here似乎是最强大的,而不是自己测试。

另一方面,只是短路“检查颜色支持”using this technique

流上的方法#tty?不仅对上述方法有用,而且还考虑了当控制进程不是a时,运行Ruby-debug或其他一些“交互式”命令的情况。 tty,没有办法ruby-debug可以提示用户,如果它连接到另一个可能不理解提示的应用程序,那么当流输出到文件,或者在另一个内部运行一个进程时,智能软件总是先检查,看看如果父进程可能会因提示输入或发送非标准输出而混淆。

如果你想做一些额外的阅读,请看一下Ruby文档中的$stdin.tty?,它解释了被认为是ttys的进程输入和输出流之间的区别以及对事物的影响执行。