Class: TestProf::TagProf::RSpecListener

Inherits:
Object
  • Object
show all
Includes:
Logging
Defined in:
lib/test_prof/tag_prof/rspec.rb

Overview

:nodoc:

Constant Summary collapse

NOTIFICATIONS =
%i[
  example_started
  example_finished
].freeze

Constants included from Logging

Logging::COLORS

Instance Method Summary collapse

Methods included from Logging

#build_log_msg, #colorize, #log

Constructor Details

#initializeRSpecListener

Returns a new instance of RSpecListener.



16
17
18
19
20
21
# File 'lib/test_prof/tag_prof/rspec.rb', line 16

def initialize
  @tag = ENV['TAG_PROF'].to_sym
  @tags = Hash.new { |h, k| h[k] = { val: k, count: 0, time: 0.0 } }

  log :info, "TagProf enabled (#{@tag})"
end

Instance Method Details

#example_finished(notification) ⇒ Object



27
28
29
30
31
32
33
34
# File 'lib/test_prof/tag_prof/rspec.rb', line 27

def example_finished(notification)
  return if notification.example.pending?

  tag = notification.example..fetch(@tag, :__unknown__)

  @tags[tag][:count] += 1
  @tags[tag][:time] += (Time.now - @ts)
end

#example_started(_notification) ⇒ Object



23
24
25
# File 'lib/test_prof/tag_prof/rspec.rb', line 23

def example_started(_notification)
  @ts = Time.now
end


36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
# File 'lib/test_prof/tag_prof/rspec.rb', line 36

def print
  msgs = []

  msgs <<
    <<~MSG
      TagProf report for #{@tag}
    MSG

  msgs << format(
    "%15s  %12s  %6s  %6s  %6s  %12s",
    @tag,
    'time', 'total', '%total', '%time', 'avg'
  )

  msgs << ""

  total = @tags.values.inject(0) { |acc, v| acc + v[:count] }
  total_time = @tags.values.inject(0) { |acc, v| acc + v[:time] }

  @tags.values.sort_by { |v| -v[:time] }.each do |tag|
    msgs << format(
      "%15s  %12s  %6d  %6.2f  %6.2f  %12s",
      tag[:val], tag[:time].duration, tag[:count],
      100 * tag[:count].to_f / total,
      100 * tag[:time] / total_time,
      (tag[:time] / tag[:count]).duration
    )
  end

  log :info, msgs.join("\n")
end