Class: EnhancedErrors
- Inherits:
-
Object
- Object
- EnhancedErrors
- 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
-
.config_block ⇒ Object
Returns the value of attribute config_block.
-
.eligible_for_capture(&block) ⇒ Object
Returns the value of attribute eligible_for_capture.
-
.enabled ⇒ Object
Returns the value of attribute enabled.
-
.exception_trace ⇒ Object
Returns the value of attribute exception_trace.
-
.on_capture_hook ⇒ Object
Returns the value of attribute on_capture_hook.
-
.override_messages ⇒ Object
Returns the value of attribute override_messages.
Class Method Summary collapse
- .add_to_skip_list(*vars) ⇒ Object
- .apply_skip_list(binding_info) ⇒ Object
- .binding_info_string(binding_info) ⇒ Object
- .binding_infos_array_to_string(captured_bindings, format = :terminal) ⇒ Object
- .capture_rescue ⇒ Object
- .capture_rescue=(val) ⇒ Object
- .class_to_string(klass) ⇒ Object
- .convert_binding_to_binding_info(b, capture_let_variables: true) ⇒ Object
- .disable_capturing! ⇒ Object
- .enhance_exceptions!(enabled: true, debug: false, capture_events: nil, override_messages: false, **options, &block) ⇒ Object
- .format(captured_binding_infos = [], output_format = get_default_format_for_environment) ⇒ Object
- .get_default_format_for_environment ⇒ Object
- .is_a_minitest?(klass) ⇒ Boolean
- .is_rspec_example?(tracepoint) ⇒ Boolean
- .max_capture_length ⇒ Object
- .max_capture_length=(val) ⇒ Object
- .mutex ⇒ Object
- .on_capture(&block) ⇒ Object
- .on_capture=(value) ⇒ Object
- .on_format(&block) ⇒ Object
- .on_format=(value) ⇒ Object
- .override_exception_message(exception, binding_or_bindings) ⇒ Object
- .override_rspec_message(example, binding_or_bindings) ⇒ Object
- .reset! ⇒ Object
- .running_in_ci? ⇒ Boolean
-
.safe_to_inspect?(obj) ⇒ Boolean
Here, we are detecting BasicObject, which is surprisingly annoying.
- .skip_list ⇒ Object
- .start_minitest_binding_capture ⇒ Object
- .start_rspec_binding_capture ⇒ Object
-
.start_rspec_binding_trap ⇒ Object
Behavior: Grabs the next rspec spec binding that goes by, and stops the more-expensive b_return trace.
- .stop_minitest_binding_capture ⇒ Object
- .stop_rspec_binding_capture ⇒ Object
- .validate_binding_format(binding_info) ⇒ Object
Class Attribute Details
.config_block ⇒ Object
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 |
.enabled ⇒ Object
Returns the value of attribute enabled.
22 23 24 |
# File 'lib/enhanced_errors.rb', line 22 def enabled @enabled end |
.exception_trace ⇒ Object
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_hook ⇒ Object
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_messages ⇒ Object
Returns the value of attribute override_messages.
22 23 24 |
# File 'lib/enhanced_errors.rb', line 22 def @override_messages end |
Class Method Details
.add_to_skip_list(*vars) ⇒ Object
181 182 183 184 185 |
# File 'lib/enhanced_errors.rb', line 181 def add_to_skip_list(*vars) mutex.synchronize do @skip_list.add(*vars) end end |
.apply_skip_list(binding_info) ⇒ Object
462 463 464 465 466 467 468 469 |
# File 'lib/enhanced_errors.rb', line 462 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
486 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 |
# File 'lib/enhanced_errors.rb', line 486 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.}" '' end |
.binding_infos_array_to_string(captured_bindings, format = :terminal) ⇒ Object
432 433 434 435 436 437 438 |
# File 'lib/enhanced_errors.rb', line 432 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_rescue ⇒ Object
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
254 255 256 257 258 259 260 261 |
# File 'lib/enhanced_errors.rb', line 254 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
327 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 |
# File 'lib/enhanced_errors.rb', line 327 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
130 131 132 133 134 135 136 137 |
# File 'lib/enhanced_errors.rb', line 130 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
187 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 |
# File 'lib/enhanced_errors.rb', line 187 def enhance_exceptions!(enabled: true, debug: false, capture_events: nil, override_messages: false, **, &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 = @rspec_failure_message_loaded = true @enabled = enabled @debug = debug @original_global_variables = global_variables if @debug .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| return 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
412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 |
# File 'lib/enhanced_errors.rb', line 412 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_environment ⇒ Object
440 441 442 443 444 445 446 447 448 449 450 451 452 453 |
# File 'lib/enhanced_errors.rb', line 440 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
228 229 230 |
# File 'lib/enhanced_errors.rb', line 228 def is_a_minitest?(klass) klass.ancestors.include?(Minitest::Test) && klass.name != 'Minitest::Test' end |
.is_rspec_example?(tracepoint) ⇒ Boolean
263 264 265 |
# File 'lib/enhanced_errors.rb', line 263 def is_rspec_example?(tracepoint) tracepoint.method_id.nil? && !(tracepoint.path.include?('rspec')) && tracepoint.path.end_with?('_spec.rb') end |
.max_capture_length ⇒ Object
122 123 124 |
# File 'lib/enhanced_errors.rb', line 122 def max_capture_length mutex.synchronize { @max_capture_length || DEFAULT_MAX_CAPTURE_LENGTH } end |
.max_capture_length=(val) ⇒ Object
126 127 128 |
# File 'lib/enhanced_errors.rb', line 126 def max_capture_length=(val) mutex.synchronize { @max_capture_length = value } end |
.mutex ⇒ Object
18 19 20 |
# File 'lib/enhanced_errors.rb', line 18 def mutex @monitor ||= Monitor.new end |
.on_capture(&block) ⇒ Object
380 381 382 383 384 385 386 387 388 |
# File 'lib/enhanced_errors.rb', line 380 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
390 391 392 393 394 |
# File 'lib/enhanced_errors.rb', line 390 def on_capture=(value) mutex.synchronize do @on_capture_hook = value end end |
.on_format(&block) ⇒ Object
396 397 398 399 400 401 402 403 404 |
# File 'lib/enhanced_errors.rb', line 396 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
406 407 408 409 410 |
# File 'lib/enhanced_errors.rb', line 406 def on_format=(value) mutex.synchronize do @on_format_hook = value end end |
.override_exception_message(exception, binding_or_bindings) ⇒ Object
172 173 174 175 176 177 178 179 |
# File 'lib/enhanced_errors.rb', line 172 def (exception, binding_or_bindings) variable_str = EnhancedErrors.format(binding_or_bindings) = exception. exception.define_singleton_method(:unaltered_message) { } exception.define_singleton_method(:message) do "#{}#{variable_str}" end end |
.override_rspec_message(example, binding_or_bindings) ⇒ Object
155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 |
# File 'lib/enhanced_errors.rb', line 155 def (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| (exception, from_bindings + exception.binding_infos) end when 'RSpec::Expectations::ExpectationNotMetError' (exception_obj, binding_or_bindings) else (exception_obj, from_bindings + exception_obj.binding_infos) end end |
.reset! ⇒ Object
139 140 141 142 143 144 145 146 147 148 149 |
# File 'lib/enhanced_errors.rb', line 139 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
455 456 457 458 459 460 |
# File 'lib/enhanced_errors.rb', line 455 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.
478 479 480 481 482 483 484 |
# File 'lib/enhanced_errors.rb', line 478 def safe_to_inspect?(obj) begin obj.class rescue NoMethodError return false end end |
.skip_list ⇒ Object
151 152 153 |
# File 'lib/enhanced_errors.rb', line 151 def skip_list @skip_list ||= DEFAULT_SKIP_LIST.to_set end |
.start_minitest_binding_capture ⇒ Object
232 233 234 235 236 237 238 239 240 241 242 243 244 |
# File 'lib/enhanced_errors.rb', line 232 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_capture ⇒ Object
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 267 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| return unless exception_is_handleable?(tp.raised_exception) class_name = tp.raised_exception.class.name case class_name when 'RSpec::Expectations::ExpectationNotMetError' start_rspec_binding_trap else handle_tracepoint_event(tp) end end end @rspec_tracepoint&.enable end |
.start_rspec_binding_trap ⇒ Object
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.
300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 |
# File 'lib/enhanced_errors.rb', line 300 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_capture ⇒ Object
246 247 248 249 250 251 252 |
# File 'lib/enhanced_errors.rb', line 246 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_capture ⇒ Object
316 317 318 319 320 321 322 323 324 325 |
# File 'lib/enhanced_errors.rb', line 316 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
471 472 473 |
# File 'lib/enhanced_errors.rb', line 471 def validate_binding_format(binding_info) binding_info.keys.include?(:capture_event) && binding_info[:variables].is_a?(Hash) end |