Skip to content

Test: support do-block syntax in @test_throws#61157

Open
christiankadiu wants to merge 1 commit intoJuliaLang:masterfrom
christiankadiu:fix-test-throws-do-block
Open

Test: support do-block syntax in @test_throws#61157
christiankadiu wants to merge 1 commit intoJuliaLang:masterfrom
christiankadiu:fix-test-throws-do-block

Conversation

@christiankadiu
Copy link

I am opening this PR because I have identified the following issue:
Currently, using a do block with the @test_throws macro fails silently or behaves unexpectedly. For example:

@test_throws(ErrorException) do
    error("This should pass but it fails")
end

Because do blocks are parsed as anonymous functions passed as the first argument to the macro, @test_throws receives the expression as a closure (e.g., () -> begin ... end) and simply evaluates it. Since evaluating a closure definition only returns the function without executing its body, no exception is ever thrown, leading to a test failure.
This PR introduces explicit support for do-block syntax in @test_throws. It inspects the AST to detect if the passed expression is a zero-argument anonymous function (checking for :-> or :function heads with empty argument tuples). If it is, the macro rewrites the AST to wrap the escaped expression in an Expr(:call, ...) so that the closure is actually executed during the test.
This provides a much-needed quality of life improvement for testing longer blocks of code that are expected to throw exceptions.

@halleysfifthinc
Copy link
Contributor

Can you elaborate on the quality-of-life benefits of this new syntax, in comparison to the already working begin-block style? None of the other @test_* macros support the do-block syntax.

@test_throws ErrorException begin
    error("This should pass but it fails")
end

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants