Created
February 3, 2009 19:36
-
-
Save robey/57702 to your computer and use it in GitHub Desktop.
draw a progress bar during tests
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require 'test/unit/ui/console/testrunner' | |
def running_under_textmate? | |
ENV.keys.any? { |key| key =~ /^TM_/ } | |
end | |
begin | |
require 'redgreen' unless running_under_textmate? | |
rescue LoadError | |
end | |
module Test | |
module Unit | |
module UI | |
module Console | |
PROGRESS_BAR_WIDTH = 60 | |
SuperClass = const_defined?("RedGreenTestRunner") ? RedGreenTestRunner : TestRunner | |
class QuickFeedbackRunner < SuperClass | |
def initialize(*args) | |
super(*args) | |
@had_a_failure = false | |
@suite.tests.delete_if { |s| s.tests.map { |t| t.method_name }.uniq == [ "default_test" ] } | |
end | |
def output_single_with_progress_bar(text, level = NORMAL) | |
if running_under_textmate? | |
output_single_without_progress_bar(text, level) | |
else | |
return unless output?(level) | |
print update_displays_for_terminal | |
end | |
end | |
alias_method_chain :output_single, :progress_bar unless method_defined?(:output_single_without_progress_bar) | |
def add_fault(fault) | |
super(fault) | |
@had_a_failure = true | |
nl | |
output color_failing_test(fault.long_display) | |
end | |
def finished(elapsed_time) | |
nl | |
output("Finished in #{elapsed_time} seconds.") | |
nl | |
output(@result) | |
end | |
private | |
def update_displays_for_terminal | |
movement = "/-\\|" | |
@count ||= 0 | |
@count += 1 | |
spinner = movement[(@count % movement.size)..(@count % movement.size)] | |
num_hashes = (PROGRESS_BAR_WIDTH * @count.to_f / @suite.size).floor | |
progress = '#' * num_hashes | |
remaining = ' ' * [0, PROGRESS_BAR_WIDTH - num_hashes].max | |
green = 32 | |
red = 31 | |
color = @had_a_failure ? red : green | |
bar = "\e[#{color}m#{progress}#{remaining}\e[0m" | |
"\r #{spinner} [#{bar}] #{@count}/#{@suite.size} " | |
end | |
def color_failing_test(output) | |
return output if running_under_textmate? | |
color_failing_test_for_terminal(output) | |
end | |
def color_failing_test_for_terminal(output) | |
output.split(/\n/).map do |line| | |
if is_test_file_line?(line) | |
"\e[33m" + line + "\e[0m" | |
else | |
line | |
end | |
end.join("\n") | |
end | |
def is_test_file_line?(line) | |
line =~ /_test\.rb:.*in `test_/ | |
end | |
end | |
end | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment