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_CAPTURE_LENGTH =
2200
MAX_BINDING_INFOS =
2
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 =
[
  :@association_cache,
  :@_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']
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']
}

Class Attribute Summary collapse

Class Method Summary collapse

Class Attribute Details

.config_blockObject

Returns the value of attribute config_block.



22
23
24
# File 'lib/enhanced_errors.rb', line 22

def config_block
  @config_block
end

.eligible_for_capture(&block) ⇒ Object

Returns the value of attribute eligible_for_capture.



22
23
24
# File 'lib/enhanced_errors.rb', line 22

def eligible_for_capture
  @eligible_for_capture
end

.enabledObject

Returns the value of attribute enabled.



22
23
24
# File 'lib/enhanced_errors.rb', line 22

def enabled
  @enabled
end

.exception_traceObject

Returns the value of attribute exception_trace.



22
23
24
# File 'lib/enhanced_errors.rb', line 22

def exception_trace
  @exception_trace
end

.on_capture_hookObject

Returns the value of attribute on_capture_hook.



22
23
24
# File 'lib/enhanced_errors.rb', line 22

def on_capture_hook
  @on_capture_hook
end

.override_messagesObject

Returns the value of attribute override_messages.



22
23
24
# File 'lib/enhanced_errors.rb', line 22

def override_messages
  @override_messages
end

Class Method Details

.add_to_skip_list(*vars) ⇒ Object



182
183
184
185
186
# File 'lib/enhanced_errors.rb', line 182

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

.apply_skip_list(binding_info) ⇒ Object



463
464
465
466
467
468
469
470
# File 'lib/enhanced_errors.rb', line 463

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

.binding_info_string(binding_info) ⇒ Object



487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
# File 'lib/enhanced_errors.rb', line 487

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_capture_length || DEFAULT_MAX_CAPTURE_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



433
434
435
436
437
438
439
# File 'lib/enhanced_errors.rb', line 433

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_rescueObject



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

def capture_rescue
  mutex.synchronize { @capture_rescue }
end

.capture_rescue=(val) ⇒ Object



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

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

.class_to_string(klass) ⇒ Object



255
256
257
258
259
260
261
262
# File 'lib/enhanced_errors.rb', line 255

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



328
329
330
331
332
333
334
335
336
337
338
339
340
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
# File 'lib/enhanced_errors.rb', line 328

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
  return unless safe_to_inspect?(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: 'test_context'
  }

  default_on_capture(binding_info)
end

.disable_capturing!Object



129
130
131
132
133
134
135
136
# File 'lib/enhanced_errors.rb', line 129

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

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



188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
# File 'lib/enhanced_errors.rb', line 188

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

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

    @override_messages = override_messages
    @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)

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

    @exception_trace&.enable if @enabled
  end
end

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



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 413

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



441
442
443
444
445
446
447
448
449
450
451
452
453
454
# File 'lib/enhanced_errors.rb', line 441

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'
                       running_in_ci? ? :plaintext : :terminal
                     when 'production'
                       :json
                     else
                       :terminal
                     end
  end
end

.is_a_minitest?(klass) ⇒ Boolean

Returns:

  • (Boolean)


229
230
231
# File 'lib/enhanced_errors.rb', line 229

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

.is_rspec_example?(tracepoint) ⇒ Boolean

Returns:

  • (Boolean)


264
265
266
# File 'lib/enhanced_errors.rb', line 264

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

.max_capture_lengthObject



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

def max_capture_length
  mutex.synchronize { @max_capture_length || DEFAULT_MAX_CAPTURE_LENGTH }
end

.max_capture_length=(value) ⇒ Object



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

def max_capture_length=(value)
  mutex.synchronize { @max_capture_length = value }
end

.mutexObject



18
19
20
# File 'lib/enhanced_errors.rb', line 18

def mutex
  @monitor ||= Monitor.new
end

.on_capture(&block) ⇒ Object



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

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



391
392
393
394
395
# File 'lib/enhanced_errors.rb', line 391

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

.on_format(&block) ⇒ Object



397
398
399
400
401
402
403
404
405
# File 'lib/enhanced_errors.rb', line 397

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



407
408
409
410
411
# File 'lib/enhanced_errors.rb', line 407

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

.override_exception_message(exception, binding_or_bindings) ⇒ Object



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

def override_exception_message(exception, binding_or_bindings)
  variable_str = EnhancedErrors.format(binding_or_bindings)
  message_str = exception.message
  exception.define_singleton_method(:unaltered_message) { message_str }
  exception.define_singleton_method(:message) do
    "#{message_str}#{variable_str}"
  end
end

.override_rspec_message(example, binding_or_bindings) ⇒ Object



156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
# File 'lib/enhanced_errors.rb', line 156

def override_rspec_message(example, binding_or_bindings)
  exception_obj = example.exception
  return if exception_obj.nil?

  from_bindings = [binding_or_bindings].flatten.compact
  case exception_obj.class.to_s
  when 'RSpec::Core::MultipleExceptionError'
    exception_obj.all_exceptions.each do |exception|
      override_exception_message(exception, from_bindings + exception.binding_infos)
    end
  when 'RSpec::Expectations::ExpectationNotMetError'
    override_exception_message(exception_obj, binding_or_bindings)
  else
    override_exception_message(exception_obj, from_bindings + exception_obj.binding_infos)
  end
end

.reset!Object



138
139
140
141
142
143
144
145
146
147
148
# File 'lib/enhanced_errors.rb', line 138

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

.running_in_ci?Boolean

Returns:

  • (Boolean)


456
457
458
459
460
461
# File 'lib/enhanced_errors.rb', line 456

def running_in_ci?
  mutex.synchronize do
    return @running_in_ci if defined?(@running_in_ci)
    @running_in_ci = CI_ENV_VARS.any? { |_, value| value.to_s.downcase == 'true' }
  end
end

.safe_to_inspect?(obj) ⇒ Boolean

Here, we are detecting BasicObject, which is surprisingly annoying. We also, importantly, need to detect descendants, as they will also present with a lack of :respond_to? and any other useful method for us.

Returns:

  • (Boolean)


479
480
481
482
483
484
485
# File 'lib/enhanced_errors.rb', line 479

def safe_to_inspect?(obj)
  begin
    obj.class
  rescue NoMethodError
    return false
  end
end

.skip_listObject



150
151
152
153
154
# File 'lib/enhanced_errors.rb', line 150

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

.start_minitest_binding_captureObject



233
234
235
236
237
238
239
240
241
242
243
244
245
# File 'lib/enhanced_errors.rb', line 233

def start_minitest_binding_capture
  ensure_extensions_are_required
  Enhanced::ExceptionContext.clear_all
  @enabled = true if @enabled.nil?
  return unless @enabled
  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
    end
    @minitest_trace&.enable
  end
end

.start_rspec_binding_captureObject



268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
# File 'lib/enhanced_errors.rb', line 268

def start_rspec_binding_capture
  ensure_extensions_are_required
  Enhanced::ExceptionContext.clear_all
  @enabled = true if @enabled.nil?
  return unless @enabled

  mutex.synchronize do
    @rspec_example_binding = nil
    @capture_next_binding = false
    @rspec_tracepoint&.disable
    @rspec_tracepoint = TracePoint.new(:raise) do |tp|
      case tp.raised_exception.class.name
      when 'RSpec::Expectations::ExpectationNotMetError'
        start_rspec_binding_trap
      else
        handle_tracepoint_event(tp)
      end
    rescue => e
      puts "Error in RSpec binding capture #{e} #{e.backtrace}"
    end
  end
  @rspec_tracepoint&.enable
end

.start_rspec_binding_trapObject

Behavior: Grabs the next rspec spec binding that goes by, and stops the more-expensive b_return trace. This part of RSpec has been stable, since 2015, so although this is kluge-y, it is stable. The optimization does a 2-3x on spec speed vs. opening up the Tracepoint. With it, things are pretty close in speed to plain rspec. Should the behavior change this can be updated by using a trace to print out items and their local variables then, find the exception or call that goes by right before the spec blocks with the variables, and use that to narrow-down the costly part of the probe to just this point in time. The good news is that this part is test-time only, and this optimization and kluge only applies to RSpec.



301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
# File 'lib/enhanced_errors.rb', line 301

def start_rspec_binding_trap
  @rspec_binding_trap = TracePoint.new(:b_return) do |tp|
    # kluge-y hack and will be a pain to maintain
    if tp.callee_id == :handle_matcher
      @capture_next_binding = :next
      next
    end
    next unless @capture_next_binding
    @capture_next_binding = false
    @rspec_example_binding = tp.binding
    @rspec_binding_trap&.disable
    @rspec_binding_trap = nil
  end
  @rspec_binding_trap&.enable
end

.stop_minitest_binding_captureObject



247
248
249
250
251
252
253
# File 'lib/enhanced_errors.rb', line 247

def stop_minitest_binding_capture
  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



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

def stop_rspec_binding_capture
  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
    return binding_info
  end
end

.validate_binding_format(binding_info) ⇒ Object



472
473
474
# File 'lib/enhanced_errors.rb', line 472

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