From d8a0c2e492c3b483c2ca7f65e2968b37cad8ccf5 Mon Sep 17 00:00:00 2001 From: Samuel Williams Date: Wed, 6 Nov 2024 03:35:18 +1300 Subject: [PATCH] Fix handling of `uplevel`. --- lib/console/warn.rb | 5 +++-- test/console/warn.rb | 22 +++++++++++++++------- 2 files changed, 18 insertions(+), 9 deletions(-) diff --git a/lib/console/warn.rb b/lib/console/warn.rb index e269202..70c4b4c 100644 --- a/lib/console/warn.rb +++ b/lib/console/warn.rb @@ -12,10 +12,11 @@ def warn(*arguments, uplevel: nil, **options) fiber = Fiber.current # We do this to be extra pendantic about avoiding infinite recursion, i.e. if `Console.warn` some how calls `Kernel.warn` again, it would potentially cause infinite recursion. I'm not sure if this is a problem in practice, but I'd rather not find out the hard way... - return super if fiber.console_warn + return if fiber.console_warn if uplevel - options[:backtrace] = caller(uplevel, 1) + # Add one to uplevel to skip the current frame. + options[:backtrace] = caller(uplevel+1, 1) end if arguments.last.is_a?(Exception) diff --git a/test/console/warn.rb b/test/console/warn.rb index f277e0e..6e35300 100644 --- a/test/console/warn.rb +++ b/test/console/warn.rb @@ -17,14 +17,22 @@ ) end - it "supports uplevel" do - warn "It did not work as expected!", uplevel: 1 + with "uplevel" do + def print_warning + warn "It did not work as expected!", uplevel: 0 + end - expect(console_capture.last).to have_keys( - severity: be == :warn, - subject: be == "It did not work as expected!", - backtrace: be_a(Array) - ) + it "includes appropriate backtrace" do + print_warning + + expect(console_capture.last).to have_keys( + severity: be == :warn, + subject: be == "It did not work as expected!", + backtrace: be_a(Array) + ) + + expect(console_capture.last[:backtrace].first).to be =~ /print_warning/ + end end it "supports exceptions" do