From c51668d24962602b781a7348451de807f74b05be Mon Sep 17 00:00:00 2001 From: Nobuyoshi Nakada Date: Fri, 24 Jan 2025 15:51:28 +0900 Subject: [PATCH] Add `Test::Unit::CoreAssertions#assert_raise_kind_of` Similar to `Test::Unit::assert_raise`, but allows sub classes too. --- tool/lib/core_assertions.rb | 37 ++++++++++++++++++++++++++++ tool/test/testunit/test_assertion.rb | 12 +++++++++ 2 files changed, 49 insertions(+) diff --git a/tool/lib/core_assertions.rb b/tool/lib/core_assertions.rb index 62ada2bdca0628..66822b4e3bc206 100644 --- a/tool/lib/core_assertions.rb +++ b/tool/lib/core_assertions.rb @@ -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: diff --git a/tool/test/testunit/test_assertion.rb b/tool/test/testunit/test_assertion.rb index 76f3418bc4ffa5..b0c2267b31ade3 100644 --- a/tool/test/testunit/test_assertion.rb +++ b/tool/test/testunit/test_assertion.rb @@ -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")