Skip to content

Commit

Permalink
Restore support for checking for UndefVarError variable name in at-te…
Browse files Browse the repository at this point in the history
…st_throws (#56231)

Fix #54082 

Arguably this was a breaking change (as a consequence of
#51979). But regardless, it seems
like useful functionality to have a public API for testing that an
`UndefVarError` was thrown for the expected variable name (regardless of
scope). This is particularly useful if you don't know what the scope is
(for example, in my use-case i want to test that a specific
`UndefVarError` is thrown from a module with a `gensym`'d name).

Pre-v1.11 the syntax for this was 
```julia
@test_throws UndefVarError(:x) foo()
```
but that stopped working in v1.11 when `UndefVarError` got a second
field (in fact in v1.11.1 this is an error when before it would pass)

This PR restores that functionality.

We might want to backport it to v1.11.x so that v1.11 isn't the only
version that doesn't support this.
  • Loading branch information
nickrobinson251 authored Oct 19, 2024
1 parent aa51abe commit b0c1525
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 1 deletion.
6 changes: 5 additions & 1 deletion stdlib/Test/src/Test.jl
Original file line number Diff line number Diff line change
Expand Up @@ -812,7 +812,11 @@ function do_test_throws(result::ExecutionResult, orig_expr, extype)
if extype isa LoadError && !(exc isa LoadError) && typeof(extype.error) == typeof(exc)
extype = extype.error # deprecated
end
if isa(exc, typeof(extype))
# Support `UndefVarError(:x)` meaning `UndefVarError(:x, scope)` for any `scope`.
# Retains the behaviour from pre-v1.11 when `UndefVarError` didn't have `scope`.
if isa(extype, UndefVarError) && !isdefined(extype, :scope)
success = exc isa UndefVarError && exc.var == extype.var
else isa(exc, typeof(extype))
success = true
for fld in 1:nfields(extype)
if !isequal(getfield(extype, fld), getfield(exc, fld))
Expand Down
17 changes: 17 additions & 0 deletions stdlib/Test/test/runtests.jl
Original file line number Diff line number Diff line change
Expand Up @@ -1736,3 +1736,20 @@ end
This is deprecated and may error in the future."""
@test_deprecated msg2 @macroexpand @testset DefaultTestSet DefaultTestSet begin end
end

# Issue #54082
module M54082 end
@testset "@test_throws UndefVarError(:var)" begin
# Single-arg `UndefVarError` should match all `UndefVarError` for the
# same variable name, regardless of scope, to keep pre-v1.11 behaviour.
f54082() = var
@test_throws UndefVarError(:var) f54082()
# But if scope is set, then it has to match.
@test_throws UndefVarError(:var, M54082) M54082.var
let result = @testset NoThrowTestSet begin
# Wrong module scope
@test_throws UndefVarError(:var, Main) M54082.var
end
@test only(result) isa Test.Fail
end
end

0 comments on commit b0c1525

Please sign in to comment.