Skip to content

Commit a04dc3d

Browse files
nickrobinson251KristofferC
authored andcommitted
Restore support for checking for UndefVarError variable name in at-test_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.
1 parent 65be74d commit a04dc3d

File tree

2 files changed

+22
-1
lines changed

2 files changed

+22
-1
lines changed

stdlib/Test/src/Test.jl

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -812,7 +812,11 @@ function do_test_throws(result::ExecutionResult, orig_expr, extype)
812812
if extype isa LoadError && !(exc isa LoadError) && typeof(extype.error) == typeof(exc)
813813
extype = extype.error # deprecated
814814
end
815-
if isa(exc, typeof(extype))
815+
# Support `UndefVarError(:x)` meaning `UndefVarError(:x, scope)` for any `scope`.
816+
# Retains the behaviour from pre-v1.11 when `UndefVarError` didn't have `scope`.
817+
if isa(extype, UndefVarError) && !isdefined(extype, :scope)
818+
success = exc isa UndefVarError && exc.var == extype.var
819+
else isa(exc, typeof(extype))
816820
success = true
817821
for fld in 1:nfields(extype)
818822
if !isequal(getfield(extype, fld), getfield(exc, fld))

stdlib/Test/test/runtests.jl

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1736,3 +1736,20 @@ end
17361736
This is deprecated and may error in the future."""
17371737
@test_deprecated msg2 @macroexpand @testset DefaultTestSet DefaultTestSet begin end
17381738
end
1739+
1740+
# Issue #54082
1741+
module M54082 end
1742+
@testset "@test_throws UndefVarError(:var)" begin
1743+
# Single-arg `UndefVarError` should match all `UndefVarError` for the
1744+
# same variable name, regardless of scope, to keep pre-v1.11 behaviour.
1745+
f54082() = var
1746+
@test_throws UndefVarError(:var) f54082()
1747+
# But if scope is set, then it has to match.
1748+
@test_throws UndefVarError(:var, M54082) M54082.var
1749+
let result = @testset NoThrowTestSet begin
1750+
# Wrong module scope
1751+
@test_throws UndefVarError(:var, Main) M54082.var
1752+
end
1753+
@test only(result) isa Test.Fail
1754+
end
1755+
end

0 commit comments

Comments
 (0)