Skip to content

Commit

Permalink
Add Test::Unit::CoreAssertions#assert_raise_kind_of
Browse files Browse the repository at this point in the history
Similar to `Test::Unit::assert_raise`, but allows sub classes too.
  • Loading branch information
nobu committed Jan 24, 2025
1 parent ae94fca commit c51668d
Show file tree
Hide file tree
Showing 2 changed files with 49 additions and 0 deletions.
37 changes: 37 additions & 0 deletions tool/lib/core_assertions.rb
Original file line number Diff line number Diff line change
Expand Up @@ -514,6 +514,43 @@ def assert_raise_with_message(exception, expected, msg = nil, &block)
ex
end

# :call-seq:
# assert_raise_kind_of(*args, &block)
#
#Tests if the given block raises one of the given exceptions or
#sub exceptions of the given exceptions. If the last argument
#is a String, it will be used as the error message.
#
# assert_raise do #Fails, no Exceptions are raised
# end
#
# assert_raise SystemCallErr do
# Dir.chdir(__FILE__) #Raises Errno::ENOTDIR, so assertion succeeds
# end
def assert_raise_kind_of(*exp, &b)
case exp.last
when String, Proc
msg = exp.pop
end

begin
yield
rescue Test::Unit::PendedError => e
raise e unless exp.include? Test::Unit::PendedError
rescue *exp => e
pass
rescue Exception => e
flunk(message(msg) {"#{mu_pp(exp)} family exception expected, not #{mu_pp(e)}"})
ensure
unless e
exp = exp.first if exp.size == 1

flunk(message(msg) {"#{mu_pp(exp)} family expected but nothing was raised"})
end
end
e
end

TEST_DIR = File.join(__dir__, "test/unit") #:nodoc:

# :call-seq:
Expand Down
12 changes: 12 additions & 0 deletions tool/test/testunit/test_assertion.rb
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,18 @@ def test_assert_raise_with_message
end
end

def test_assert_raise_kind_of
my_error = Class.new(StandardError)

assert_raise_kind_of(my_error) do
raise my_error
end

assert_raise_kind_of(StandardError) do
raise my_error
end
end

def test_assert_pattern_list
assert_pattern_list([/foo?/], "foo")
assert_not_pattern_list([/foo?/], "afoo")
Expand Down

0 comments on commit c51668d

Please sign in to comment.