Skip to content

Commit 61062f5

Browse files
ericphansonLilithHafner
authored andcommitted
[Test] make TestLogger respect maxlog (JuliaLang#43641)
1 parent 483222d commit 61062f5

File tree

2 files changed

+19
-3
lines changed

2 files changed

+19
-3
lines changed

stdlib/Test/src/logging.jl

Lines changed: 14 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -26,20 +26,31 @@ mutable struct TestLogger <: AbstractLogger
2626
min_level::LogLevel
2727
catch_exceptions::Bool
2828
shouldlog_args
29+
message_limits::Dict{Any,Int}
2930
end
3031

3132
TestLogger(; min_level=Info, catch_exceptions=false) =
32-
TestLogger(LogRecord[], min_level, catch_exceptions, nothing)
33+
TestLogger(LogRecord[], min_level, catch_exceptions, nothing, Dict{Any, Int}())
3334
Logging.min_enabled_level(logger::TestLogger) = logger.min_level
3435

3536
function Logging.shouldlog(logger::TestLogger, level, _module, group, id)
36-
logger.shouldlog_args = (level, _module, group, id)
37-
true
37+
if get(logger.message_limits, id, 1) > 0
38+
logger.shouldlog_args = (level, _module, group, id)
39+
true
40+
else
41+
false
42+
end
3843
end
3944

4045
function Logging.handle_message(logger::TestLogger, level, msg, _module,
4146
group, id, file, line; kwargs...)
4247
@nospecialize
48+
maxlog = get(kwargs, :maxlog, nothing)
49+
if maxlog isa Core.BuiltinInts
50+
remaining = get!(logger.message_limits, id, Int(maxlog)::Int)
51+
logger.message_limits[id] = remaining - 1
52+
remaining > 0 || return
53+
end
4354
push!(logger.logs, LogRecord(level, msg, _module, group, id, file, line, kwargs))
4455
end
4556

stdlib/Test/test/runtests.jl

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -837,6 +837,8 @@ end
837837
@test occursin("Evaluated: 0.9 ≈ 0.1 (nans=true, atol=0.01)", msg)
838838
end
839839

840+
erronce() = @error "an error" maxlog=1
841+
840842
@testset "@test_logs" begin
841843
function foo(n)
842844
@info "Doing foo with n=$n"
@@ -865,6 +867,9 @@ end
865867

866868
@test_logs (Debug,"Iteration 5") min_level=Debug match_mode=:any foo(10)
867869

870+
# Respect `maxlog` (#41625). We check we only find one logging message.
871+
@test_logs (:error, "an error") (erronce(); erronce())
872+
868873
# Test failures
869874
fails = @testset NoThrowTestSet "check that @test_logs detects bad input" begin
870875
@test_logs (Warn,) foo(1)

0 commit comments

Comments
 (0)