Skip to content

Commit

Permalink
simplifies the definitions of @test_[no]warn (JuliaLang#56525)
Browse files Browse the repository at this point in the history
Since the expressions generated by those macros are almost identical,
the implementation could be changed to use a common helper function to
create expressions for each case.
  • Loading branch information
aviatesk authored Nov 12, 2024
1 parent c4802e1 commit 366a38e
Showing 1 changed file with 27 additions and 45 deletions.
72 changes: 27 additions & 45 deletions stdlib/Test/src/Test.jl
Original file line number Diff line number Diff line change
Expand Up @@ -887,28 +887,7 @@ Note: Warnings generated by `@warn` cannot be tested with this macro. Use
[`@test_logs`](@ref) instead.
"""
macro test_warn(msg, expr)
quote
let fname = tempname()
try
f = open(fname, "w")
stdold = stderr
redirect_stderr(f)
ret = try
# We deliberately don't use the thunk versions of open/redirect
# to ensure that adding the macro does not change the toplevel-ness
# of the resulting expression.
$(esc(expr))
finally
redirect_stderr(stdold)
close(f)
end
@test contains_warn(read(fname, String), $(esc(msg)))
ret
finally
rm(fname, force=true)
end
end
end
test_warn_expr(expr, msg)
end

"""
Expand All @@ -921,32 +900,35 @@ Note: The absence of warnings generated by `@warn` cannot be tested
with this macro. Use [`@test_logs`](@ref) instead.
"""
macro test_nowarn(expr)
quote
# Duplicate some code from `@test_warn` to allow printing the content of
# `stderr` again to `stderr` here while suppressing it for `@test_warn`.
# If that shouldn't be used, it would be possible to just use
# @test_warn isempty $(esc(expr))
# here.
let fname = tempname()
try
f = open(fname, "w")
stdold = stderr
redirect_stderr(f)
ret = try
$(esc(expr))
finally
redirect_stderr(stdold)
close(f)
end
stderr_content = read(fname, String)
print(stderr, stderr_content) # this is helpful for debugging
@test isempty(stderr_content)
ret
# allow printing the content of `stderr` again to `stderr` here while suppressing it
# for `@test_warn`. If that shouldn't be used, this could just be `test_warn_expr(expr, #=msg=#isempty)`
test_warn_expr(expr, function (s)
print(stderr, s) # this is helpful for debugging
isempty(s)
end)
end

function test_warn_expr(@nospecialize(expr), @nospecialize(msg))
return :(let fname = tempname()
try
f = open(fname, "w")
stdold = stderr
redirect_stderr(f)
ret = try
# We deliberately don't use the thunk versions of open/redirect
# to ensure that adding the macro does not change the toplevel-ness
# of the resulting expression.
$(esc(expr))
finally
rm(fname, force=true)
redirect_stderr(stdold)
close(f)
end
@test contains_warn(read(fname, String), $(esc(msg)))
ret
finally
rm(fname, force=true)
end
end
end)
end

#-----------------------------------------------------------------------
Expand Down

0 comments on commit 366a38e

Please sign in to comment.