From 1fe1fe8cc024081b72fff8216324c17f38e709c1 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Tom=C3=A1=C5=A1=20Drvo=C5=A1t=C4=9Bp?= Date: Wed, 14 Jun 2023 14:20:57 +0200 Subject: [PATCH] Use with_logger to handle non-default loggers in suppress as well --- src/Suppressor.jl | 18 ++++++++++++++---- test/runtests.jl | 28 ++++++++++++++++++++++++++++ 2 files changed, 42 insertions(+), 4 deletions(-) diff --git a/src/Suppressor.jl b/src/Suppressor.jl index 9d418b9..df5f6ff 100644 --- a/src/Suppressor.jl +++ b/src/Suppressor.jl @@ -27,13 +27,18 @@ macro suppress(block) logstate = Base.CoreLogging._global_logstate logger = logstate.logger if :stream in propertynames(logger) && logger.stream == original_stderr - new_logstate = Base.CoreLogging.LogState(typeof(logger)(err_wr, logger.min_level)) + _logger = typeof(logger)(err_wr, logger.min_level) + new_logstate = Base.CoreLogging.LogState(_logger) Core.eval(Base.CoreLogging, Expr(:(=), :(_global_logstate), new_logstate)) + else + _logger = logger end end try - $(esc(block)) + Logging.with_logger(_logger) do + $(esc(block)) + end finally if ccall(:jl_generating_output, Cint, ()) == 0 redirect_stdout(original_stdout) @@ -90,13 +95,18 @@ macro suppress_err(block) logstate = Base.CoreLogging._global_logstate logger = logstate.logger if :stream in propertynames(logger) && logger.stream == original_stderr - new_logstate = Base.CoreLogging.LogState(typeof(logger)(err_wr, logger.min_level)) + _logger = typeof(logger)(err_wr, logger.min_level) + new_logstate = Base.CoreLogging.LogState(_logger) Core.eval(Base.CoreLogging, Expr(:(=), :(_global_logstate), new_logstate)) + else + _logger = logger end end try - $(esc(block)) + Logging.with_logger(_logger) do + $(esc(block)) + end finally if ccall(:jl_generating_output, Cint, ()) == 0 redirect_stderr(original_stderr) diff --git a/test/runtests.jl b/test/runtests.jl index a640afc..50bfba3 100644 --- a/test/runtests.jl +++ b/test/runtests.jl @@ -168,4 +168,32 @@ end @test startswith(out, "┌ Error: @error") end +@testset "suppress_err within with_logger" begin + mktemp() do path, io + redirect_stderr(io) do + with_logger(ConsoleLogger(stderr)) do + @suppress_err begin + @error "@error" + end + end + end + flush(io) + @test read(path, String) == "" + end +end + +@testset "suppress within with_logger" begin + mktemp() do path, io + redirect_stderr(io) do + with_logger(ConsoleLogger(stderr)) do + @suppress begin + @error "@error" + end + end + end + flush(io) + @test read(path, String) == "" + end +end + end # @testset "Suppressor"