Class: EnhancedErrors

Inherits:
Object
  • Object
show all
Extended by:
Enhanced
Defined in:
lib/enhanced_errors.rb

Constant Summary collapse

GEMS_REGEX =
%r{[\/\\]gems[\/\\]}
DEFAULT_MAX_LENGTH =
2000
MAX_BINDING_INFOS =
3
RSPEC_SKIP_LIST =
[
  :@__inspect_output,
  :@__memoized,
  :@assertion_delegator,
  :@assertion_instance,
  :@assertions,
  :@connection_subscriber,
  :@example,
  :@fixture_cache,
  :@fixture_cache_key,
  :@fixture_connection_pools,
  :@fixture_connections,
  :@integration_session,
  :@legacy_saved_pool_configs,
  :@loaded_fixtures,
  :@matcher_definitions,
  :@saved_pool_configs
].freeze
RAILS_SKIP_LIST =
[
  :@new_record,
  :@attributes,
  :@association_cache,
  :@readonly,
  :@previously_new_record,
  :@_routes,
  :@routes,
  :@app,
  :@arel_table,
  :@assertion_instance,
  :@association_cache,
  :@attributes,
  :@destroyed,
  :@destroyed_by_association,
  :@find_by_statement_cache,
  :@generated_relation_method,
  :@integration_session,
  :@marked_for_destruction,
  :@mutations_before_last_save,
  :@mutations_from_database,
  :@new_record,
  :@predicate_builder,
  :@previously_new_record,
  :@primary_key,
  :@readonly,
  :@relation_delegate_cache,
  :@response,
  :@response_klass,
  :@routes,
  :@strict_loading,
  :@strict_loading_mode
].freeze
MINITEST_SKIP_LIST =
[:@NAME, :@failures, :@time].freeze
DEFAULT_SKIP_LIST =
(RAILS_SKIP_LIST + RSPEC_SKIP_LIST + MINITEST_SKIP_LIST)
RSPEC_HANDLER_NAMES =
['RSpec::Expectations::PositiveExpectationHandler', 'RSpec::Expectations::NegativeExpectationHandler']

Class Attribute Summary collapse

Class Method Summary collapse

Class Attribute Details

.config_blockObject

Returns the value of attribute config_block.



24
25
26
# File 'lib/enhanced_errors.rb', line 24

def config_block
  @config_block
end

.eligible_for_capture(&block) ⇒ Object

Returns the value of attribute eligible_for_capture.



24
25
26
# File 'lib/enhanced_errors.rb', line 24

def eligible_for_capture
  @eligible_for_capture
end

.enabledObject

Returns the value of attribute enabled.



24
25
26
# File 'lib/enhanced_errors.rb', line 24

def enabled
  @enabled
end

.exception_traceObject

Returns the value of attribute exception_trace.



24
25
26
# File 'lib/enhanced_errors.rb', line 24

def exception_trace
  @exception_trace
end

.on_capture_hookObject

Returns the value of attribute on_capture_hook.



24
25
26
# File 'lib/enhanced_errors.rb', line 24

def on_capture_hook
  @on_capture_hook
end

.override_messagesObject

Returns the value of attribute override_messages.



24
25
26
# File 'lib/enhanced_errors.rb', line 24

def override_messages
  @override_messages
end

Class Method Details

.add_to_skip_list(*vars) ⇒ Object



231
232
233
234
235
# File 'lib/enhanced_errors.rb', line 231

def add_to_skip_list(*vars)
  mutex.synchronize do
    @skip_list.concat(vars)
  end
end

.apply_skip_list(binding_info) ⇒ Object



538
539
540
541
542
543
544
545
546
547
548
# File 'lib/enhanced_errors.rb', line 538

def apply_skip_list(binding_info)
  mutex.synchronize do
    variables = binding_info[:variables]
    variables[:instances]&.reject! { |var, _| skip_list.include?(var) || (var.to_s.start_with?('@_') && !@debug) }
    variables[:locals]&.reject! { |var, _| skip_list.include?(var) }
    if @debug
      variables[:globals]&.reject! { |var, _| skip_list.include?(var) }
    end
  end
  binding_info
end

.binding_info_string(binding_info) ⇒ Object



557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
# File 'lib/enhanced_errors.rb', line 557

def binding_info_string(binding_info)
  exception = safe_to_s(binding_info[:exception])
  capture_event = safe_to_s(binding_info[:capture_event]).capitalize
  source = safe_to_s(binding_info[:source])
  result = ''
  unless exception.to_s == 'NoException'
    origination = "#{capture_event.capitalize}d"
    result += "#{Colors.green(origination)}: #{Colors.blue(source)}"
  end
  method_desc = method_and_args_desc(binding_info[:method_and_args])
  result += method_desc

  variables = binding_info[:variables] || {}

  if variables[:locals] && !variables[:locals].empty?
    result += "\n#{Colors.green('Locals:')}\n#{variable_description(variables[:locals])}"
  end

  instance_vars_to_display = variables[:instances] || {}

  unless instance_vars_to_display.empty?
    result += "\n#{Colors.green('Instances:')}\n#{variable_description(instance_vars_to_display)}"
  end

  if variables[:lets] && !variables[:lets].empty?
    result += "\n#{Colors.green('Let Variables:')}\n#{variable_description(variables[:lets])}"
  end

  if variables[:globals] && !variables[:globals].empty?
    result += "\n#{Colors.green('Globals:')}\n#{variable_description(variables[:globals])}"
  end

  mutex.synchronize do
    max_len = @max_length || DEFAULT_MAX_LENGTH
    if result.length > max_len
      result = result[0...max_len] + "... (truncated)"
    end
  end

  result + "\n"
rescue => e
  puts "#{e.message}"
  ''
end

.binding_infos_array_to_string(captured_bindings, format = :terminal) ⇒ Object



495
496
497
498
499
500
501
# File 'lib/enhanced_errors.rb', line 495

def binding_infos_array_to_string(captured_bindings, format = :terminal)
  return '' if captured_bindings.nil? || captured_bindings.empty?
  captured_bindings = [captured_bindings] unless captured_bindings.is_a?(Array)
  Colors.enabled = (format == :terminal)
  formatted_bindings = captured_bindings.to_a.map { |binding_info| binding_info_string(binding_info) }
  format == :json ? JSON.pretty_generate(captured_bindings) : "\n#{formatted_bindings.join("\n")}"
end

.capture_events_countObject



122
123
124
# File 'lib/enhanced_errors.rb', line 122

def capture_events_count
  mutex.synchronize { @capture_events_count || 0 }
end

.capture_events_count=(val) ⇒ Object



126
127
128
# File 'lib/enhanced_errors.rb', line 126

def capture_events_count=(val)
  mutex.synchronize { @capture_events_count = val }
end

.capture_limit_exceeded?Boolean

Returns:

  • (Boolean)


146
147
148
149
150
# File 'lib/enhanced_errors.rb', line 146

def capture_limit_exceeded?
  mutex.synchronize do
   max_capture_events > 0 && capture_events_count >= max_capture_events
  end
end

.capture_rescueObject



118
119
120
# File 'lib/enhanced_errors.rb', line 118

def capture_rescue
  mutex.synchronize { @capture_rescue }
end

.capture_rescue=(val) ⇒ Object



114
115
116
# File 'lib/enhanced_errors.rb', line 114

def capture_rescue=(val)
  mutex.synchronize { @capture_rescue = val }
end

.class_to_string(klass) ⇒ Object



328
329
330
331
332
333
334
335
# File 'lib/enhanced_errors.rb', line 328

def class_to_string(klass)
  return '' if klass.nil?
  if klass.singleton_class?
    (match = klass.to_s.match(/#<Class:(.*?)>/)) ? match[1] : klass.to_s
  else
    klass.to_s
  end
end

.convert_binding_to_binding_info(b, capture_let_variables: true) ⇒ Object



392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
# File 'lib/enhanced_errors.rb', line 392

def convert_binding_to_binding_info(b, capture_let_variables: true)
  file = b.eval("__FILE__") rescue nil
  line = b.eval("__LINE__") rescue nil
  location = [file, line].compact.join(":")

  locals = b.local_variables.map { |var| [var, safe_local_variable_get(b, var)] }.to_h
  receiver = b.receiver
  instance_vars = receiver.instance_variables
  instances = instance_vars.map { |var| [var, safe_instance_variable_get(receiver, var)] }.to_h

  lets = {}
  if capture_let_variables && instance_vars.include?(:@__memoized)
    outer_memoized = receiver.instance_variable_get(:@__memoized)
    memoized = outer_memoized.instance_variable_get(:@memoized) if outer_memoized.respond_to?(:instance_variable_get)
    if memoized.is_a?(Hash)
      lets = memoized.transform_keys(&:to_sym)
    end
  end

  binding_info = {
    source: location,
    object: receiver,
    library: !!GEMS_REGEX.match?(location.to_s),
    method_and_args: {
      object_name: '',
      args: ''
    },
    test_name: test_name,
    variables: {
      locals: locals,
      instances: instances,
      lets: lets,
      globals: {}
    },
    exception: 'NoException',
    capture_event: 'RSpecContext'
  }

  default_on_capture(binding_info)
end

.disable_capturing!Object



152
153
154
155
156
157
158
159
# File 'lib/enhanced_errors.rb', line 152

def disable_capturing!
  mutex.synchronize do
    @enabled = false
    @rspec_tracepoint&.disable
    @minitest_trace&.disable
    @exception_trace&.disable
  end
end

.enforce_capture_limitObject



140
141
142
143
144
# File 'lib/enhanced_errors.rb', line 140

def enforce_capture_limit
  exceeded = capture_limit_exceeded?
  disable_capturing! if capture_limit_exceeded?
  exceeded
end

.enhance_exceptions!(enabled: true, debug: false, capture_events: nil, override_messages: false, **options, &block) ⇒ Object



237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
# File 'lib/enhanced_errors.rb', line 237

def enhance_exceptions!(enabled: true, debug: false, capture_events: nil, override_messages: false, **options, &block)
  mutex.synchronize do
    @exception_trace&.disable
    @exception_trace = nil

    @output_format = nil
    @eligible_for_capture = nil
    @original_global_variables = nil
    @override_messages = override_messages

    # Ensure these are not nil
    if @max_capture_events.nil?
      @max_capture_events = -1
    end
    @capture_events_count ||= 0

    @rspec_failure_message_loaded = true

    @enabled = enabled
    @debug = debug
    @original_global_variables = global_variables if @debug

    options.each do |key, value|
      setter_method = "#{key}="
      if respond_to?(setter_method)
        send(setter_method, value)
      elsif respond_to?(key)
        send(key, value)
      end
    end

    @config_block = block_given? ? block : nil
    instance_eval(&@config_block) if @config_block

    validate_and_set_capture_events(capture_events)

    # If max_capture_events == 0, capturing is off from the start.
    if @max_capture_events == 0
      @enabled = false
      return
    end

    events = @capture_events ? @capture_events.to_a : default_capture_events
    @exception_trace = TracePoint.new(*events) do |tp|
      handle_tracepoint_event(tp)
    end

    # Only enable trace if still enabled and not limited
    if @enabled && (@max_capture_events == -1 || @capture_events_count < @max_capture_events)
      @exception_trace.enable
    end
  end
end

.format(captured_binding_infos = [], output_format = get_default_format_for_environment) ⇒ Object



475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
# File 'lib/enhanced_errors.rb', line 475

def format(captured_binding_infos = [], output_format = get_default_format_for_environment)
  return '' if captured_binding_infos.nil? || captured_binding_infos.empty?

  result = binding_infos_array_to_string(captured_binding_infos, output_format)

  mutex.synchronize do
    if @on_format_hook
      begin
        result = @on_format_hook.call(result)
      rescue
        result = ''
      end
    else
      result = default_on_format(result)
    end
  end

  result
end

.get_default_format_for_environmentObject



503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
# File 'lib/enhanced_errors.rb', line 503

def get_default_format_for_environment
  mutex.synchronize do
    return @output_format unless @output_format.nil?
    env = ENV['RAILS_ENV'] || ENV['RACK_ENV'] || 'development'
    @output_format = case env
                     when 'development', 'test'
                       if running_in_ci?
                         :plaintext
                       else
                         :terminal
                       end
                     when 'production'
                       :json
                     else
                       :terminal
                     end
  end
end

.increment_capture_events_countObject



161
162
163
164
165
166
167
# File 'lib/enhanced_errors.rb', line 161

def increment_capture_events_count
  mutex.synchronize do
    @capture_events_count ||= 0
    @max_capture_events ||= -1
    @capture_events_count += 1
  end
end

.is_a_minitest?(klass) ⇒ Boolean

Returns:

  • (Boolean)


302
303
304
# File 'lib/enhanced_errors.rb', line 302

def is_a_minitest?(klass)
  klass.ancestors.include?(Minitest::Test) && klass.name != 'Minitest::Test'
end

.is_rspec_example?(tracepoint) ⇒ Boolean

Returns:

  • (Boolean)


337
338
339
# File 'lib/enhanced_errors.rb', line 337

def is_rspec_example?(tracepoint)
  tracepoint.method_id.nil? && !(tracepoint.path.include?('rspec')) && tracepoint.path.end_with?('_spec.rb')
end

.max_capture_eventsObject



130
131
132
# File 'lib/enhanced_errors.rb', line 130

def max_capture_events
  mutex.synchronize { @max_capture_events || -1 }
end

.max_capture_events=(value) ⇒ Object



134
135
136
137
138
# File 'lib/enhanced_errors.rb', line 134

def max_capture_events=(value)
  mutex.synchronize do
    @max_capture_events = value
  end
end

.max_length(value = nil) ⇒ Object



182
183
184
185
186
187
188
189
190
191
# File 'lib/enhanced_errors.rb', line 182

def max_length(value = nil)
  mutex.synchronize do
    if value.nil?
      @max_length ||= DEFAULT_MAX_LENGTH
    else
      @max_length = value
    end
    @max_length
  end
end

.mutexObject



20
21
22
# File 'lib/enhanced_errors.rb', line 20

def mutex
  @monitor ||= Monitor.new
end

.on_capture(&block) ⇒ Object



443
444
445
446
447
448
449
450
451
# File 'lib/enhanced_errors.rb', line 443

def on_capture(&block)
  mutex.synchronize do
    if block_given?
      @on_capture_hook = block
    else
      @on_capture_hook ||= method(:default_on_capture)
    end
  end
end

.on_capture=(value) ⇒ Object



453
454
455
456
457
# File 'lib/enhanced_errors.rb', line 453

def on_capture=(value)
  mutex.synchronize do
    @on_capture_hook = value
  end
end

.on_format(&block) ⇒ Object



459
460
461
462
463
464
465
466
467
# File 'lib/enhanced_errors.rb', line 459

def on_format(&block)
  mutex.synchronize do
    if block_given?
      @on_format_hook = block
    else
      @on_format_hook ||= method(:default_on_format)
    end
  end
end

.on_format=(value) ⇒ Object



469
470
471
472
473
# File 'lib/enhanced_errors.rb', line 469

def on_format=(value)
  mutex.synchronize do
    @on_format_hook = value
  end
end

.override_exception_message(exception, binding_or_bindings) ⇒ Object



212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
# File 'lib/enhanced_errors.rb', line 212

def override_exception_message(exception, binding_or_bindings)
  return nil unless exception
  rspec_binding = !(binding_or_bindings.nil? || binding_or_bindings.empty?)
  exception_binding = (exception.binding_infos.length > 0)
  has_message = !(exception.respond_to?(:unaltered_message))
  return nil unless (rspec_binding || exception_binding) && has_message

  variable_str = EnhancedErrors.format(binding_or_bindings)
  message_str = exception.message
  if exception.respond_to?(:captured_variables) && !message_str.include?(exception.captured_variables)
    message_str += exception.captured_variables
  end
  exception.define_singleton_method(:unaltered_message) { message_str }
  exception.define_singleton_method(:message) do
    "#{message_str}#{variable_str}"
  end
  exception
end

.override_rspec_message(example, binding_or_bindings) ⇒ Object



199
200
201
202
203
204
205
206
207
208
209
210
# File 'lib/enhanced_errors.rb', line 199

def override_rspec_message(example, binding_or_bindings)
  exception_obj = example.exception
  case exception_obj
  when nil
    return nil
  when RSpec::Core::MultipleExceptionError
    override_exception_message(exception_obj.all_exceptions.first, binding_or_bindings)
  else
    override_exception_message(exception_obj, binding_or_bindings)
  end

end

.reset!Object



169
170
171
172
173
174
175
176
177
178
179
180
# File 'lib/enhanced_errors.rb', line 169

def reset!
  mutex.synchronize do
    @rspec_tracepoint&.disable
    @minitest_trace&.disable
    @exception_trace&.disable
    @rspec_tracepoint = nil
    @minitest_trace = nil
    @exception_trace = nil
    @capture_events_count = 0
    @enabled = true
  end
end

.running_in_ci?Boolean

Returns:

  • (Boolean)


522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
# File 'lib/enhanced_errors.rb', line 522

def running_in_ci?
  mutex.synchronize do
    return @running_in_ci if defined?(@running_in_ci)
    ci_env_vars = {
      'CI' => ENV['CI'],
      'JENKINS' => ENV['JENKINS'],
      'GITHUB_ACTIONS' => ENV['GITHUB_ACTIONS'],
      'CIRCLECI' => ENV['CIRCLECI'],
      'TRAVIS' => ENV['TRAVIS'],
      'APPVEYOR' => ENV['APPVEYOR'],
      'GITLAB_CI' => ENV['GITLAB_CI']
    }
    @running_in_ci = ci_env_vars.any? { |_, value| value.to_s.downcase == 'true' }
  end
end

.safe_prepend_module(target_class, mod) ⇒ Object



291
292
293
294
295
296
297
298
299
300
# File 'lib/enhanced_errors.rb', line 291

def safe_prepend_module(target_class, mod)
  mutex.synchronize do
    if defined?(target_class) && target_class.is_a?(Module)
      target_class.prepend(mod)
      true
    else
      false
    end
  end
end

.skip_listObject



193
194
195
196
197
# File 'lib/enhanced_errors.rb', line 193

def skip_list
  mutex.synchronize do
    @skip_list ||= DEFAULT_SKIP_LIST
  end
end

.start_minitest_binding_captureObject



306
307
308
309
310
311
312
313
314
315
316
317
# File 'lib/enhanced_errors.rb', line 306

def start_minitest_binding_capture
  return if enforce_capture_limit
  @enabled = true if @enabled.nil?
  mutex.synchronize do
    @minitest_trace = TracePoint.new(:return) do |tp|
      next unless tp.method_id.to_s.start_with?('test_') && is_a_minitest?(tp.defined_class)
      @minitest_test_binding = tp.binding
      increment_capture_events_count
    end
    @minitest_trace.enable
  end
end

.start_rspec_binding_captureObject



341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
# File 'lib/enhanced_errors.rb', line 341

def start_rspec_binding_capture
  return if enforce_capture_limit
  @enabled = true if @enabled.nil?
  mutex.synchronize do
    @rspec_example_binding = nil
    @capture_next_binding = false
    @rspec_tracepoint&.disable

    @rspec_tracepoint = TracePoint.new(:raise, :b_return) do |tp|
      # puts "name #{tp.raised_exception.class.name rescue ''} method:#{tp.method_id} tp.binding:#{tp.binding.local_variables rescue ''}"
      # puts "event: #{tp.event} defined_class#{class_to_string(tp.defined_class)} #{tp.path}:#{tp.lineno} #{tp.callee_id} "
      # This trickery below is to help us identify the anonymous block return we want to grab
      # Very kluge-y and edge cases have grown it, but it works
      if tp.event == :b_return
        if RSPEC_HANDLER_NAMES.include?(class_to_string(tp.defined_class))
          @capture_next_binding = :next
          next
        end
        next unless @capture_next_binding

        if @capture_next_binding == :next || @capture_next_binding == :next_matching && is_rspec_example?(tp)
          @capture_next_binding = false
          increment_capture_events_count
          @rspec_example_binding = tp.binding
        end
      elsif tp.event == :raise
        class_name = tp.raised_exception.class.name
        case class_name
        when 'RSpec::Expectations::ExpectationNotMetError'
          @capture_next_binding = :next_matching
        else
          handle_tracepoint_event(tp)
        end
      end
    end
    @rspec_tracepoint.enable
  end
end

.stop_minitest_binding_captureObject



319
320
321
322
323
324
325
326
# File 'lib/enhanced_errors.rb', line 319

def stop_minitest_binding_capture
  disable_capturing! if capture_limit_exceeded?
  mutex.synchronize do
    @minitest_trace&.disable
    @minitest_trace = nil
    convert_binding_to_binding_info(@minitest_test_binding) if @minitest_test_binding
  end
end

.stop_rspec_binding_captureObject



380
381
382
383
384
385
386
387
388
389
390
# File 'lib/enhanced_errors.rb', line 380

def stop_rspec_binding_capture
  disable_capturing! if capture_limit_exceeded?
  mutex.synchronize do
    @rspec_tracepoint&.disable
    @rspec_tracepoint = nil
    binding_info = convert_binding_to_binding_info(@rspec_example_binding) if @rspec_example_binding
    @capture_next_binding = false
    @rspec_example_binding = nil
    binding_info
  end
end

.validate_binding_format(binding_info) ⇒ Object



550
551
552
553
554
555
# File 'lib/enhanced_errors.rb', line 550

def validate_binding_format(binding_info)
  unless binding_info.keys.include?(:capture_event) && binding_info[:variables].is_a?(Hash)
    return nil
  end
  binding_info
end