1# Author:: Nathaniel Talbott.
2# Copyright:: Copyright (c) 2000-2003 Nathaniel Talbott. All rights reserved.
3#             Copyright (c) 2009-2013 Kouhei Sutou. All rights reserved.
4# License:: Ruby license.
5
6require 'test/unit/assertion-failed-error'
7require 'test/unit/util/backtracefilter'
8require 'test/unit/util/method-owner-finder'
9require 'test/unit/diff'
10
11begin
12  require 'power_assert'
13rescue LoadError, SyntaxError
14end
15
16module Test
17  module Unit
18
19    ##
20    # Test::Unit::Assertions contains the standard Test::Unit assertions.
21    # Assertions is included in Test::Unit::TestCase.
22    #
23    # To include it in your own code and use its functionality, you simply
24    # need to rescue Test::Unit::AssertionFailedError. Additionally you may
25    # override add_assertion to get notified whenever an assertion is made.
26    #
27    # Notes:
28    #
29    # * The message to each assertion, if given, will be propagated with the
30    #   failure.
31    # * It is easy to add your own assertions based on assert_block().
32    #
33    # @example Example Custom Assertion
34    #
35    #   def deny(boolean, message = nil)
36    #     message = build_message message, '<?> is not false or nil.', boolean
37    #     assert_block message do
38    #       not boolean
39    #     end
40    #   end
41
42    module Assertions
43
44      ##
45      # The assertion upon which all other assertions are based. Passes if the
46      # block yields true.
47      #
48      # @example
49      #   assert_block "Couldn't do the thing" do
50      #     do_the_thing
51      #   end
52      def assert_block(message="assert_block failed.")
53        _wrap_assertion do
54          if (! yield)
55            raise AssertionFailedError.new(message.to_s)
56          end
57        end
58      end
59
60      # @private
61      NOT_SPECIFIED = Object.new
62
63      # @overload assert(object, message=nil)
64      #
65      #   Asserts that `object` is not false nor nil.
66      #
67      #   Normally, you don't need to use this assertion. Use more
68      #   specific assertions such as #assert_equal and
69      #   #assert_include.
70      #
71      #   @example Pass patterns
72      #     assert(true)               # => pass
73      #     assert([1, 2].include?(1)) # => pass
74      #
75      #   @example Failure patterns
76      #     assert(nil)                # => failure
77      #     assert(false)              # => failure
78      #     assert([1, 2].include?(5)) # => failure
79      #
80      #   @param [Object] object The check target.
81      #   @param [String] message The additional user message. It is
82      #     showed when the assertion is failed.
83      #   @return [void]
84      #
85      # @overload assert(message=nil) {}
86      #
87      #   Asserts that the givens block returns not false nor nil.
88      #
89      #   This style uses Power Assert. It means that you can see each
90      #   object values in method chains on failure. See the following
91      #   example about Power Assert.
92      #
93      #   @example Power Assert
94      #     coins = [1, 5, 50]
95      #     target_coin = 10
96      #     assert do
97      #       coins.include?(target_coin)
98      #     end
99      #     # =>
100      #     #  coins.include?(target_coin)
101      #     #  |     |        |
102      #     #  |     |        10
103      #     #  |     false
104      #     #  [1, 5, 50]
105      #
106      #   We recommend you to use Power Assert for predicate method
107      #   checks rather than existing assertions such as
108      #   #assert_include and #assert_predicate. Power Assert shows
109      #   useful message for debugging.
110      #
111      #   We don't recommend you use Power Assert for equality
112      #   check. You should use #assert_equal for the case. Because
113      #   #assert_equal shows more useful message for debugging.
114      #
115      #   @example Pass patterns
116      #     assert {true}               # => pass
117      #     assert {[1, 2].include?(1)} # => pass
118      #
119      #   @example Failure patterns
120      #     assert {nil}                # => failure
121      #     assert {false}              # => failure
122      #     assert {[1, 2].include?(5)} # => failure
123      #
124      #   @param [String] message The additional user message. It is
125      #     showed when the assertion is failed.
126      #   @yield [] Given no parameters to the block.
127      #   @yieldreturn [Object] The checked object.
128      #   @return [void]
129      def assert(object=NOT_SPECIFIED, message=nil, &block)
130        _wrap_assertion do
131          have_object = !NOT_SPECIFIED.equal?(object)
132          if block
133            message = object if have_object
134            if defined?(PowerAssert)
135              PowerAssert.start(block, :assertion_method => __callee__) do |pa|
136                pa_message = AssertionMessage.delayed_literal(&pa.message_proc)
137                assertion_message = build_message(message, "?", pa_message)
138                assert_block(assertion_message) do
139                  pa.yield
140                end
141              end
142            else
143              assert(yield, message)
144            end
145          else
146            unless have_object
147              raise ArgumentError, "wrong number of arguments (0 for 1..2)"
148            end
149            assertion_message = nil
150            case message
151            when nil, String, Proc
152            when AssertionMessage
153              assertion_message = message
154            else
155              error_message = "assertion message must be String, Proc or "
156              error_message += "#{AssertionMessage}: "
157              error_message += "<#{message.inspect}>(<#{message.class}>)"
158              raise ArgumentError, error_message, filter_backtrace(caller)
159            end
160            assertion_message ||= build_message(message,
161                                                "<?> is not true.",
162                                                object)
163            assert_block(assertion_message) do
164              object
165            end
166          end
167        end
168      end
169
170      # Asserts that +object+ is false or nil.
171      #
172      # @note Just for minitest compatibility. :<
173      #
174      # @param [Object] object The object to be asserted.
175      # @return [void]
176      #
177      # @example Pass patterns
178      #   refute(false)    # => pass
179      #   refute(nil)      # => pass
180      #
181      # @example Failure patterns
182      #   refute(true)     # => failure
183      #   refute("string") # => failure
184      #
185      # @since 2.5.3
186      def refute(object, message=nil)
187        _wrap_assertion do
188          assertion_message = nil
189          case message
190          when nil, String, Proc
191          when AssertionMessage
192            assertion_message = message
193          else
194            error_message = "assertion message must be String, Proc or "
195            error_message += "#{AssertionMessage}: "
196            error_message += "<#{message.inspect}>(<#{message.class}>)"
197            raise ArgumentError, error_message, filter_backtrace(caller)
198          end
199          assert_block("refute should not be called with a block.") do
200            !block_given?
201          end
202          assertion_message ||= build_message(message,
203                                              "<?> is neither nil or false.",
204                                              object)
205          assert_block(assertion_message) do
206            not object
207          end
208        end
209      end
210
211      ##
212      # Passes if +expected+ == +actual+.
213      #
214      # Note that the ordering of arguments is important, since a helpful
215      # error message is generated when this one fails that tells you the
216      # values of expected and actual.
217      #
218      # @example
219      #   assert_equal 'MY STRING', 'my string'.upcase
220      def assert_equal(expected, actual, message=nil)
221        diff = AssertionMessage.delayed_diff(expected, actual)
222        if expected.respond_to?(:encoding) and
223            actual.respond_to?(:encoding) and
224            expected.encoding != actual.encoding
225          format = <<EOT
226<?>(?) expected but was
227<?>(?).?
228EOT
229          full_message = build_message(message, format,
230                                       expected, expected.encoding.name,
231                                       actual, actual.encoding.name,
232                                       diff)
233        else
234          full_message = build_message(message, <<EOT, expected, actual, diff)
235<?> expected but was
236<?>.?
237EOT
238        end
239        begin
240          assert_block(full_message) { expected == actual }
241        rescue AssertionFailedError => failure
242          _set_failed_information(failure, expected, actual, message)
243          raise failure # For JRuby. :<
244        end
245      end
246
247      ##
248      # Passes if the block raises one of the expected
249      # exceptions. When an expected exception is an Exception
250      # object, passes if expected_exception == actual_exception.
251      #
252      # @example
253      #   assert_raise(RuntimeError, LoadError) do
254      #     raise 'Boom!!!'
255      #   end # -> pass
256      #
257      #   assert_raise do
258      #     raise Exception, 'Any exception should be raised!!!'
259      #   end # -> pass
260      #
261      #   assert_raise(RuntimeError.new("XXX")) {raise "XXX"} # -> pass
262      #   assert_raise(MyError.new("XXX"))      {raise "XXX"} # -> fail
263      #   assert_raise(RuntimeError.new("ZZZ")) {raise "XXX"} # -> fail
264      def assert_raise(*args, &block)
265        assert_expected_exception = Proc.new do |*_args|
266          message, assert_exception_helper, actual_exception = _args
267          expected = assert_exception_helper.expected_exceptions
268          diff = AssertionMessage.delayed_diff(expected, actual_exception)
269          full_message = build_message(message,
270                                       "<?> exception expected but was\n<?>.?",
271                                       expected, actual_exception, diff)
272          begin
273            assert_block(full_message) do
274              expected == [] or
275                assert_exception_helper.expected?(actual_exception)
276            end
277          rescue AssertionFailedError => failure
278            _set_failed_information(failure, expected, actual_exception,
279                                    message)
280            raise failure # For JRuby. :<
281          end
282        end
283        _assert_raise(assert_expected_exception, *args, &block)
284      end
285
286      # Just for minitest compatibility. :<
287      alias_method :assert_raises, :assert_raise
288
289      ##
290      # Passes if the block raises one of the given
291      # exceptions or sub exceptions of the given exceptions.
292      #
293      # @example
294      #   assert_raise_kind_of(SystemCallError) do
295      #     raise Errno::EACCES
296      #   end
297      def assert_raise_kind_of(*args, &block)
298        assert_expected_exception = Proc.new do |*_args|
299          message, assert_exception_helper, actual_exception = _args
300          expected = assert_exception_helper.expected_exceptions
301          full_message = build_message(message,
302                                       "<?> family exception expected " +
303                                       "but was\n<?>.",
304                                       expected, actual_exception)
305          assert_block(full_message) do
306            assert_exception_helper.expected?(actual_exception, :kind_of?)
307          end
308        end
309        _assert_raise(assert_expected_exception, *args, &block)
310      end
311
312
313      ##
314      # Passes if +object+.instance_of?(+klass+). When +klass+ is
315      # an array of classes, it passes if any class
316      # satisfies +object.instance_of?(class).
317      #
318      # @example
319      #   assert_instance_of(String, 'foo')            # -> pass
320      #   assert_instance_of([Fixnum, NilClass], 100)  # -> pass
321      #   assert_instance_of([Numeric, NilClass], 100) # -> fail
322      def assert_instance_of(klass, object, message="")
323        _wrap_assertion do
324          if klass.is_a?(Array)
325            klasses = klass
326          else
327            klasses = [klass]
328          end
329          assert_block("The first parameter to assert_instance_of should be " +
330                       "a Class or an Array of Class.") do
331            klasses.all? {|k| k.is_a?(Class)}
332          end
333          klass_message = AssertionMessage.maybe_container(klass) do |value|
334            "<#{value}>"
335          end
336          full_message = build_message(message, <<EOT, object, klass_message, object.class)
337<?> was expected to be instance_of\\?
338? but was
339<?>.
340EOT
341          assert_block(full_message) do
342            klasses.any? {|k| object.instance_of?(k)}
343          end
344        end
345      end
346
347      ##
348      # Passes if +object+.instance_of?(+klass+) does not hold.
349      # When +klass+ is an array of classes, it passes if no class
350      # satisfies +object.instance_of?(class).
351      #
352      # @example
353      #   assert_not_instance_of(String, 100)                # -> pass
354      #   assert_not_instance_of([Fixnum, NilClass], '100')  # -> pass
355      #   assert_not_instance_of([Numeric, NilClass], 100)   # -> fail
356      #
357      # @since 3.0.0
358      def assert_not_instance_of(klass, object, message="")
359        _wrap_assertion do
360          if klass.is_a?(Array)
361            klasses = klass
362          else
363            klasses = [klass]
364          end
365          assert_block("The first parameter to assert_not_instance_of should be " +
366                       "a Class or an Array of Class.") do
367            klasses.all? {|k| k.is_a?(Class)}
368          end
369          klass_message = AssertionMessage.maybe_container(klass) do |value|
370            "<#{value}>"
371          end
372          full_message = build_message(message,
373                                       "<?> was expected to not be instance_of\\?\n" +
374                                       "? but was.",
375                                       object,
376                                       klass_message)
377          assert_block(full_message) do
378            klasses.none? {|k| object.instance_of?(k)}
379          end
380        end
381      end
382
383      # Just for minitest compatibility. :<
384      #
385      # @since 3.0.0
386      alias_method :refute_instance_of, :assert_not_instance_of
387
388      ##
389      # Passes if +object+ is nil.
390      #
391      # @example
392      #   assert_nil [1, 2].uniq!
393      def assert_nil(object, message="")
394        full_message = build_message(message, <<EOT, object)
395<?> was expected to be nil.
396EOT
397        assert_block(full_message) { object.nil? }
398      end
399
400      ##
401      # Passes if +object+.kind_of?(+klass+). When +klass+ is
402      # an array of classes or modules, it passes if any
403      # class or module satisfies +object.kind_of?(class_or_module).
404      #
405      # @example
406      #   assert_kind_of(Object, 'foo')                # -> pass
407      #   assert_kind_of([Fixnum, NilClass], 100)      # -> pass
408      #   assert_kind_of([Fixnum, NilClass], "string") # -> fail
409      def assert_kind_of(klass, object, message="")
410        _wrap_assertion do
411          if klass.is_a?(Array)
412            klasses = klass
413          else
414            klasses = [klass]
415          end
416          assert_block("The first parameter to assert_kind_of should be " +
417                       "a kind_of Module or an Array of a kind_of Module.") do
418            klasses.all? {|k| k.kind_of?(Module)}
419          end
420          klass_message = AssertionMessage.maybe_container(klass) do |value|
421            "<#{value}>"
422          end
423          full_message = build_message(message,
424                                       "<?> was expected to be kind_of\\?\n" +
425                                       "? but was\n" +
426                                       "<?>.",
427                                       object,
428                                       klass_message,
429                                       object.class)
430          assert_block(full_message) do
431            klasses.any? {|k| object.kind_of?(k)}
432          end
433        end
434      end
435
436      ##
437      # Passes if +object+.kind_of?(+klass+) does not hold.
438      # When +klass+ is an array of classes or modules, it passes only if all
439      # classes (and modules) do not satisfy +object.kind_of?(class_or_module).
440      #
441      # @example
442      #   assert_not_kind_of(Fixnum, 'foo')           # -> pass
443      #   assert_not_kind_of([Fixnum, NilClass], '0') # -> pass
444      #   assert_not_kind_of([Fixnum, NilClass], 100) # -> fail
445      #
446      # @since 3.0.0
447      def assert_not_kind_of(klass, object, message="")
448        _wrap_assertion do
449          if klass.is_a?(Array)
450            klasses = klass
451          else
452            klasses = [klass]
453          end
454          assert_block("The first parameter to assert_not_kind_of should be " +
455                       "a kind_of Module or an Array of a kind_of Module.") do
456            klasses.all? {|k| k.kind_of?(Module)}
457          end
458          klass_message = AssertionMessage.maybe_container(klass) do |value|
459            "<#{value}>"
460          end
461          full_message = build_message(message,
462                                       "<?> was expected to not be kind_of\\?\n" +
463                                       "? but was.",
464                                       object,
465                                       klass_message)
466          assert_block(full_message) do
467            klasses.none? {|k| object.kind_of?(k)}
468          end
469        end
470      end
471
472      # Just for minitest compatibility. :<
473      #
474      # @since 3.0.0
475      alias_method :refute_kind_of, :assert_not_kind_of
476
477      ##
478      # Passes if +object+ .respond_to? +method+
479      #
480      # @example
481      #   assert_respond_to 'bugbear', :slice
482      def assert_respond_to(object, method, message="")
483        _wrap_assertion do
484          full_message = build_message(message,
485                                       "<?>.kind_of\\?(Symbol) or\n" +
486                                       "<?>.respond_to\\?(:to_str) expected",
487                                       method, method)
488          assert_block(full_message) do
489            method.kind_of?(Symbol) or method.respond_to?(:to_str)
490          end
491          full_message = build_message(message,
492                                       "<?>.respond_to\\?(?) expected\n" +
493                                       "(Class: <?>)",
494                                       object, method, object.class)
495          assert_block(full_message) {object.respond_to?(method)}
496        end
497      end
498
499      ##
500      # Passes if +object+ does not .respond_to? +method+.
501      #
502      # @example
503      #   assert_not_respond_to('bugbear', :nonexistence) # -> pass
504      #   assert_not_respond_to('bugbear', :size)         # -> fail
505      def assert_not_respond_to(object, method, message="")
506        _wrap_assertion do
507          full_message = build_message(message,
508                                       "<?>.kind_of\\?(Symbol) or\n" +
509                                       "<?>.respond_to\\?(:to_str) expected",
510                                       method, method)
511          assert_block(full_message) do
512            method.kind_of?(Symbol) or method.respond_to?(:to_str)
513          end
514          full_message = build_message(message,
515                                       "!<?>.respond_to\\?(?) expected\n" +
516                                       "(Class: <?>)",
517                                       object, method, object.class)
518          assert_block(full_message) {!object.respond_to?(method)}
519        end
520      end
521
522      # Just for minitest compatibility. :<
523      #
524      # @since 2.5.3
525      alias_method :refute_respond_to, :assert_not_respond_to
526
527      ##
528      # Passes if +pattern+ =~ +string+.
529      #
530      # @example
531      #   assert_match(/\d+/, 'five, 6, seven')
532      def assert_match(pattern, string, message="")
533        _wrap_assertion do
534          pattern = case(pattern)
535            when String
536              Regexp.new(Regexp.escape(pattern))
537            else
538              pattern
539          end
540          full_message = build_message(message,
541                                       "<?> was expected to be =~\n<?>.",
542                                       pattern, string)
543          assert_block(full_message) { pattern =~ string }
544        end
545      end
546
547      ##
548      # Passes if +actual+ .equal? +expected+ (i.e. they are the same
549      # instance).
550      #
551      # @example
552      #   o = Object.new
553      #   assert_same o, o
554      def assert_same(expected, actual, message="")
555        full_message = build_message(message, <<EOT, expected, expected.__id__, actual, actual.__id__)
556<?>
557with id <?> was expected to be equal\\? to
558<?>
559with id <?>.
560EOT
561        assert_block(full_message) { actual.equal?(expected) }
562      end
563
564      ##
565      # Compares the +object1+ with +object2+ using +operator+.
566      #
567      # Passes if object1.__send__(operator, object2) is true.
568      #
569      # @example
570      #   assert_operator 5, :>=, 4
571      def assert_operator(object1, operator, object2, message="")
572        _wrap_assertion do
573          full_message = build_message(nil, "<?>\ngiven as the operator for #assert_operator must be a Symbol or #respond_to\\?(:to_str).", operator)
574          assert_block(full_message){operator.kind_of?(Symbol) || operator.respond_to?(:to_str)}
575          full_message = build_message(message, <<EOT, object1, AssertionMessage.literal(operator), object2)
576<?> was expected to be
577?
578<?>.
579EOT
580          assert_block(full_message) { object1.__send__(operator, object2) }
581        end
582      end
583
584      ##
585      # Compares the +object1+ with +object2+ using +operator+.
586      #
587      # Passes if object1.__send__(operator, object2) is not true.
588      #
589      # @example
590      #   assert_not_operator(5, :<, 4) # => pass
591      #   assert_not_operator(5, :>, 4) # => fail
592      #
593      # @since 3.0.0
594      def assert_not_operator(object1, operator, object2, message="")
595        _wrap_assertion do
596          full_message = build_message(nil, "<?>\ngiven as the operator for #assert_not_operator must be a Symbol or #respond_to\\?(:to_str).", operator)
597          assert_block(full_message){operator.kind_of?(Symbol) || operator.respond_to?(:to_str)}
598          full_message = build_message(message, <<EOT, object1, AssertionMessage.literal(operator), object2)
599<?> was expected to not be
600?
601<?>.
602EOT
603          assert_block(full_message) { ! object1.__send__(operator, object2) }
604        end
605      end
606
607      # Just for minitest compatibility. :<
608      #
609      # @since 3.0.0
610      alias_method :refute_operator, :assert_not_operator
611
612      ##
613      # Passes if block does not raise an exception.
614      #
615      # @example
616      #   assert_nothing_raised do
617      #     [1, 2].uniq
618      #   end
619      def assert_nothing_raised(*args)
620        _wrap_assertion do
621          if args.last.is_a?(String)
622            message = args.pop
623          else
624            message = ""
625          end
626
627          assert_exception_helper = AssertExceptionHelper.new(self, args)
628          begin
629            yield
630          rescue Exception => e
631            if ((args.empty? && !e.instance_of?(AssertionFailedError)) ||
632                assert_exception_helper.expected?(e))
633              failure_message = build_message(message, "Exception raised:\n?", e)
634              assert_block(failure_message) {false}
635            else
636              raise
637            end
638          end
639        end
640      end
641
642      ##
643      # Flunk always fails.
644      #
645      # @example
646      #   flunk 'Not done testing yet.'
647      def flunk(message="Flunked")
648        assert_block(build_message(message)){false}
649      end
650
651      ##
652      # Passes if ! +actual+ .equal? +expected+
653      #
654      # @example
655      #   assert_not_same Object.new, Object.new
656      def assert_not_same(expected, actual, message="")
657        full_message = build_message(message, <<EOT, expected, expected.__id__, actual, actual.__id__)
658<?>
659with id <?> was expected to not be equal\\? to
660<?>
661with id <?>.
662EOT
663        assert_block(full_message) { !actual.equal?(expected) }
664      end
665
666      # Just for minitest compatibility. :<
667      #
668      # @since 2.5.3
669      alias_method :refute_same, :assert_not_same
670
671      ##
672      # Passes if +expected+ != +actual+
673      #
674      # @example
675      #   assert_not_equal 'some string', 5
676      def assert_not_equal(expected, actual, message="")
677        full_message = build_message(message,
678                                     "<?> was expected to be != to\n<?>.",
679                                     expected, actual)
680        assert_block(full_message) { expected != actual }
681      end
682
683      # Just for minitest compatibility. :<
684      #
685      # @since 2.5.3
686      alias_method :refute_equal, :assert_not_equal
687
688      ##
689      # Passes if ! +object+ .nil?
690      #
691      # @example
692      #   assert_not_nil '1 two 3'.sub!(/two/, '2')
693      def assert_not_nil(object, message="")
694        full_message = build_message(message,
695                                     "<?> was expected to not be nil.",
696                                     object)
697        assert_block(full_message){!object.nil?}
698      end
699
700      # Just for minitest compatibility. :<
701      #
702      # @since 2.5.3
703      alias_method :refute_nil, :assert_not_nil
704
705      ##
706      # Passes if +regexp+ !~ +string+
707      #
708      # @example
709      #   assert_not_match(/two/, 'one 2 three')   # -> pass
710      #   assert_not_match(/three/, 'one 2 three') # -> fail
711      def assert_not_match(regexp, string, message="")
712        _wrap_assertion do
713          assert_instance_of(Regexp, regexp,
714                             "<REGEXP> in assert_not_match(<REGEXP>, ...) " +
715                             "should be a Regexp.")
716          full_message = build_message(message,
717                                       "<?> was expected to not match\n<?>.",
718                                       regexp, string)
719          assert_block(full_message) { regexp !~ string }
720        end
721      end
722
723      # Just for minitest compatibility. :<
724      #
725      # @since 2.5.3
726      alias_method :refute_match, :assert_not_match
727
728      ##
729      # Deprecated. Use #assert_not_match instead.
730      #
731      # Passes if +regexp+ !~ +string+
732      #
733      # @example
734      #   assert_no_match(/two/, 'one 2 three')   # -> pass
735      #   assert_no_match(/three/, 'one 2 three') # -> fail
736      def assert_no_match(regexp, string, message="")
737        _wrap_assertion do
738          assert_instance_of(Regexp, regexp,
739                             "The first argument to assert_no_match " +
740                             "should be a Regexp.")
741          assert_not_match(regexp, string, message)
742        end
743      end
744
745      # @private
746      class ThrowTagExtractor
747        @@have_uncaught_throw_error = const_defined?(:UncaughtThrowError)
748
749        UncaughtThrowPatterns = {
750          NameError => /^uncaught throw `(.+)'$/,
751          ArgumentError => /^uncaught throw (`.+'|.+)$/,
752          ThreadError => /^uncaught throw `(.+)' in thread /,
753        }
754
755        def initialize(error)
756          @error = error
757        end
758
759        def extract_tag
760          tag = nil
761          if @@have_uncaught_throw_error
762            return nil unless @error.is_a?(UncaughtThrowError)
763            tag = @error.tag
764          else
765            pattern = UncaughtThrowPatterns[@error.class]
766            return nil if pattern.nil?
767            return nil unless pattern =~ @error.message
768            tag = $1
769          end
770          normalize_tag(tag)
771        end
772
773        private
774        def normalize_tag(tag)
775          case tag
776          when /\A:/
777            tag[1..-1].intern
778          when /\A`(.+)'\z/
779            $1.intern
780          when String
781            tag.intern
782          else
783            tag
784          end
785        end
786      end
787
788      ##
789      # Passes if the block throws +expected_object+
790      #
791      # @example
792      #   assert_throw(:done) do
793      #     throw(:done)
794      #   end
795      def assert_throw(expected_object, message="", &proc)
796        _wrap_assertion do
797          begin
798            catch([]) {}
799          rescue TypeError
800            assert_instance_of(Symbol, expected_object,
801                               "assert_throws expects the symbol that should be thrown for its first argument")
802          end
803          assert_block("Should have passed a block to assert_throw.") do
804            block_given?
805          end
806          caught = true
807          begin
808            catch(expected_object) do
809              proc.call
810              caught = false
811            end
812            full_message = build_message(message,
813                                         "<?> should have been thrown.",
814                                         expected_object)
815            assert_block(full_message) {caught}
816          rescue => error
817            extractor = ThrowTagExtractor.new(error)
818            tag = extractor.extract_tag
819            raise if tag.nil?
820            full_message = build_message(message,
821                                         "<?> was expected to be thrown but\n" +
822                                         "<?> was thrown.",
823                                         expected_object, tag)
824            flunk(full_message)
825          end
826        end
827      end
828
829      # Just for minitest compatibility. :<
830      #
831      # @since 2.5.3
832      alias_method :assert_throws, :assert_throw
833
834      ##
835      # Passes if block does not throw anything.
836      #
837      # @example
838      #  assert_nothing_thrown do
839      #    [1, 2].uniq
840      #  end
841      def assert_nothing_thrown(message="", &proc)
842        _wrap_assertion do
843          assert(block_given?, "Should have passed a block to assert_nothing_thrown")
844          begin
845            proc.call
846          rescue => error
847            extractor = ThrowTagExtractor.new(error)
848            tag = extractor.extract_tag
849            raise if tag.nil?
850            full_message = build_message(message,
851                                         "<?> was thrown when nothing was expected",
852                                         tag)
853            flunk(full_message)
854          end
855          assert(true, "Expected nothing to be thrown")
856        end
857      end
858
859      ##
860      # Passes if +expected_float+ and +actual_float+ are equal
861      # within +delta+ tolerance.
862      #
863      # @example
864      #   assert_in_delta 0.05, (50000.0 / 10**6), 0.00001
865      def assert_in_delta(expected_float, actual_float, delta=0.001, message="")
866        _wrap_assertion do
867          _assert_in_delta_validate_arguments(expected_float,
868                                              actual_float,
869                                              delta)
870          full_message = _assert_in_delta_message(expected_float,
871                                                  actual_float,
872                                                  delta,
873                                                  message)
874          assert_block(full_message) do
875            (expected_float.to_f - actual_float.to_f).abs <= delta.to_f
876          end
877        end
878      end
879
880      ##
881      # Passes if +expected_float+ and +actual_float+ are
882      # not equal within +delta+ tolerance.
883      #
884      # @example
885      #   assert_not_in_delta(0.05, (50000.0 / 10**6), 0.00002) # -> pass
886      #   assert_not_in_delta(0.05, (50000.0 / 10**6), 0.00001) # -> fail
887      def assert_not_in_delta(expected_float, actual_float, delta=0.001, message="")
888        _wrap_assertion do
889          _assert_in_delta_validate_arguments(expected_float,
890                                              actual_float,
891                                              delta)
892          full_message = _assert_in_delta_message(expected_float,
893                                                  actual_float,
894                                                  delta,
895                                                  message,
896                                                  :negative_assertion => true)
897          assert_block(full_message) do
898            (expected_float.to_f - actual_float.to_f).abs > delta.to_f
899          end
900        end
901      end
902
903      # Just for minitest compatibility. :<
904      #
905      # @since 2.5.3
906      alias_method :refute_in_delta, :assert_not_in_delta
907
908      private
909      def _assert_in_delta_validate_arguments(expected_float,
910                                              actual_float,
911                                              delta)
912        {
913          expected_float => "first float",
914          actual_float => "second float",
915          delta => "delta"
916        }.each do |float, name|
917          assert_respond_to(float, :to_f,
918                            "The arguments must respond to to_f; " +
919                            "the #{name} did not")
920        end
921        delta = delta.to_f
922        assert_operator(delta, :>=, 0.0, "The delta should not be negative")
923      end
924
925      def _assert_in_delta_message(expected_float, actual_float, delta,
926                                   message, options={})
927        if options[:negative_assertion]
928          format = <<-EOT
929<?> -/+ <?> was expected to not include
930<?>.
931EOT
932        else
933          format = <<-EOT
934<?> -/+ <?> was expected to include
935<?>.
936EOT
937        end
938        arguments = [expected_float, delta, actual_float]
939        normalized_expected = expected_float.to_f
940        normalized_actual = actual_float.to_f
941        normalized_delta = delta.to_f
942        relation_format = nil
943        relation_arguments = nil
944        if normalized_actual < normalized_expected - normalized_delta
945          relation_format = "<<?> < <?>-<?>[?] <= <?>+<?>[?]>"
946          relation_arguments = [actual_float,
947                                expected_float, delta,
948                                normalized_expected - normalized_delta,
949                                expected_float, delta,
950                                normalized_expected + normalized_delta]
951        elsif normalized_actual <= normalized_expected + normalized_delta
952          relation_format = "<<?>-<?>[?] <= <?> <= <?>+<?>[?]>"
953          relation_arguments = [expected_float, delta,
954                                normalized_expected - normalized_delta,
955                                actual_float,
956                                expected_float, delta,
957                                normalized_expected + normalized_delta]
958        else
959          relation_format = "<<?>-<?>[?] <= <?>+<?>[?] < <?>>"
960          relation_arguments = [expected_float, delta,
961                                normalized_expected - normalized_delta,
962                                expected_float, delta,
963                                normalized_expected + normalized_delta,
964                                actual_float]
965        end
966
967        if relation_format
968          format += <<-EOT
969
970Relation:
971#{relation_format}
972EOT
973          arguments.concat(relation_arguments)
974        end
975
976        build_message(message, format, *arguments)
977      end
978
979      public
980      ##
981      # Passes if +expected_float+ and +actual_float+ are equal
982      # within +epsilon+ relative error of +expected_float+.
983      #
984      # @example
985      #   assert_in_epsilon(10000.0, 9900.0, 0.1) # -> pass
986      #   assert_in_epsilon(10000.0, 9899.0, 0.1) # -> fail
987      def assert_in_epsilon(expected_float, actual_float, epsilon=0.001,
988                            message="")
989        _wrap_assertion do
990          _assert_in_epsilon_validate_arguments(expected_float,
991                                                actual_float,
992                                                epsilon)
993          full_message = _assert_in_epsilon_message(expected_float,
994                                                    actual_float,
995                                                    epsilon,
996                                                    message)
997          assert_block(full_message) do
998            normalized_expected_float = expected_float.to_f
999            if normalized_expected_float.zero?
1000              delta = epsilon.to_f ** 2
1001            else
1002              delta = normalized_expected_float * epsilon.to_f
1003            end
1004            delta = delta.abs
1005            (normalized_expected_float - actual_float.to_f).abs <= delta
1006          end
1007        end
1008      end
1009
1010      ##
1011      # Passes if +expected_float+ and +actual_float+ are
1012      # not equal within +epsilon+ relative error of
1013      # +expected_float+.
1014      #
1015      # @example
1016      #   assert_not_in_epsilon(10000.0, 9900.0, 0.1) # -> fail
1017      #   assert_not_in_epsilon(10000.0, 9899.0, 0.1) # -> pass
1018      def assert_not_in_epsilon(expected_float, actual_float, epsilon=0.001,
1019                                message="")
1020        _wrap_assertion do
1021          _assert_in_epsilon_validate_arguments(expected_float,
1022                                                actual_float,
1023                                                epsilon)
1024          full_message = _assert_in_epsilon_message(expected_float,
1025                                                    actual_float,
1026                                                    epsilon,
1027                                                    message,
1028                                                    :negative_assertion => true)
1029          assert_block(full_message) do
1030            normalized_expected_float = expected_float.to_f
1031            delta = normalized_expected_float * epsilon.to_f
1032            (normalized_expected_float - actual_float.to_f).abs > delta
1033          end
1034        end
1035      end
1036
1037      # Just for minitest compatibility. :<
1038      #
1039      # @since 3.0.0
1040      alias_method :refute_in_epsilon, :assert_not_in_epsilon
1041
1042      private
1043      def _assert_in_epsilon_validate_arguments(expected_float,
1044                                                actual_float,
1045                                                epsilon)
1046        {
1047          expected_float => "first float",
1048          actual_float => "second float",
1049          epsilon => "epsilon"
1050        }.each do |float, name|
1051          assert_respond_to(float, :to_f,
1052                            "The arguments must respond to to_f; " +
1053                            "the #{name} did not")
1054        end
1055        epsilon = epsilon.to_f
1056        assert_operator(epsilon, :>=, 0.0, "The epsilon should not be negative")
1057      end
1058
1059      def _assert_in_epsilon_message(expected_float, actual_float, epsilon,
1060                                     message, options={})
1061        normalized_expected = expected_float.to_f
1062        normalized_actual = actual_float.to_f
1063        normalized_epsilon = epsilon.to_f
1064        delta = normalized_expected * normalized_epsilon
1065
1066        if options[:negative_assertion]
1067          format = <<-EOT
1068<?> -/+ (<?> * <?>)[?] was expected to not include
1069<?>.
1070EOT
1071        else
1072          format = <<-EOT
1073<?> -/+ (<?> * <?>)[?] was expected to include
1074<?>.
1075EOT
1076        end
1077        arguments = [expected_float, expected_float, epsilon, delta,
1078                     actual_float]
1079
1080        relation_format = nil
1081        relation_arguments = nil
1082        if normalized_actual < normalized_expected - delta
1083          relation_format = "<<?> < <?>-(<?>*<?>)[?] <= <?>+(<?>*<?>)[?]>"
1084          relation_arguments = [actual_float,
1085                                expected_float, expected_float, epsilon,
1086                                normalized_expected - delta,
1087                                expected_float, expected_float, epsilon,
1088                                normalized_expected + delta]
1089        elsif normalized_actual <= normalized_expected + delta
1090          relation_format = "<<?>-(<?>*<?>)[?] <= <?> <= <?>+(<?>*<?>)[?]>"
1091          relation_arguments = [expected_float, expected_float, epsilon,
1092                                normalized_expected - delta,
1093                                actual_float,
1094                                expected_float, expected_float, epsilon,
1095                                normalized_expected + delta]
1096        else
1097          relation_format = "<<?>-(<?>*<?>)[?] <= <?>+(<?>*<?>)[?] < <?>>"
1098          relation_arguments = [expected_float, expected_float, epsilon,
1099                                normalized_expected - delta,
1100                                expected_float, expected_float, epsilon,
1101                                normalized_expected + delta,
1102                                actual_float]
1103        end
1104
1105        if relation_format
1106          format += <<-EOT
1107
1108Relation:
1109#{relation_format}
1110EOT
1111          arguments.concat(relation_arguments)
1112        end
1113
1114        build_message(message, format, *arguments)
1115      end
1116
1117      public
1118      ##
1119      # Passes if the method send returns a true value.
1120      #
1121      # +send_array+ is composed of:
1122      # * A receiver
1123      # * A method
1124      # * Arguments to the method
1125      #
1126      # @example
1127      #   assert_send([[1, 2], :member?, 1]) # -> pass
1128      #   assert_send([[1, 2], :member?, 4]) # -> fail
1129      def assert_send(send_array, message=nil)
1130        _wrap_assertion do
1131          assert_instance_of(Array, send_array,
1132                             "assert_send requires an array " +
1133                             "of send information")
1134          assert_operator(send_array.size, :>=, 2,
1135                          "assert_send requires at least a receiver " +
1136                          "and a message name")
1137          format = <<EOT
1138<?> was expected to respond to
1139<?(*?)> with a true value but was
1140<?>.
1141EOT
1142          receiver, message_name, *arguments = send_array
1143          result = nil
1144          full_message =
1145            build_message(message,
1146                          format,
1147                          receiver,
1148                          AssertionMessage.literal(message_name.to_s),
1149                          arguments,
1150                          AssertionMessage.delayed_literal {result})
1151          assert_block(full_message) do
1152            result = receiver.__send__(message_name, *arguments)
1153            result
1154          end
1155        end
1156      end
1157
1158      ##
1159      # Passes if the method send doesn't return a true value.
1160      #
1161      # +send_array+ is composed of:
1162      # * A receiver
1163      # * A method
1164      # * Arguments to the method
1165      #
1166      # @example
1167      #   assert_not_send([[1, 2], :member?, 1]) # -> fail
1168      #   assert_not_send([[1, 2], :member?, 4]) # -> pass
1169      def assert_not_send(send_array, message=nil)
1170        _wrap_assertion do
1171          assert_instance_of(Array, send_array,
1172                             "assert_not_send requires an array " +
1173                             "of send information")
1174          assert_operator(send_array.size, :>=, 2,
1175                          "assert_not_send requires at least a receiver " +
1176                          "and a message name")
1177          format = <<EOT
1178<?> was expected to respond to
1179<?(*?)> with not a true value but was
1180<?>.
1181EOT
1182          receiver, message_name, *arguments = send_array
1183          result = nil
1184          full_message =
1185            build_message(message,
1186                          format,
1187                          receiver,
1188                          AssertionMessage.literal(message_name.to_s),
1189                          arguments,
1190                          AssertionMessage.delayed_literal {result})
1191          assert_block(full_message) do
1192            result = receiver.__send__(message_name, *arguments)
1193            not result
1194          end
1195        end
1196      end
1197
1198      ##
1199      # Passes if +actual+ is a boolean value.
1200      #
1201      # @example
1202      #   assert_boolean(true) # -> pass
1203      #   assert_boolean(nil)  # -> fail
1204      def assert_boolean(actual, message=nil)
1205        _wrap_assertion do
1206          assert_block(build_message(message,
1207                                     "<true> or <false> expected but was\n<?>",
1208                                     actual)) do
1209            [true, false].include?(actual)
1210          end
1211        end
1212      end
1213
1214      ##
1215      # Passes if +actual+ is true.
1216      #
1217      # @example
1218      #   assert_true(true)  # -> pass
1219      #   assert_true(:true) # -> fail
1220      def assert_true(actual, message=nil)
1221        _wrap_assertion do
1222          assert_block(build_message(message,
1223                                     "<true> expected but was\n<?>",
1224                                     actual)) do
1225            actual == true
1226          end
1227        end
1228      end
1229
1230      ##
1231      # Passes if +actual+ is false.
1232      #
1233      # @example
1234      #   assert_false(false)  # -> pass
1235      #   assert_false(nil)    # -> fail
1236      def assert_false(actual, message=nil)
1237        _wrap_assertion do
1238          assert_block(build_message(message,
1239                                     "<false> expected but was\n<?>",
1240                                     actual)) do
1241            actual == false
1242          end
1243        end
1244      end
1245
1246      ##
1247      # Passes if expression "+expected+ +operator+
1248      # +actual+" is true.
1249      #
1250      # @example
1251      #   assert_compare(1, "<", 10)  # -> pass
1252      #   assert_compare(1, ">=", 10) # -> fail
1253      def assert_compare(expected, operator, actual, message=nil)
1254        _wrap_assertion do
1255          assert_send([["<", "<=", ">", ">="], :include?, operator.to_s])
1256          case operator.to_s
1257          when "<"
1258            operator_description = "less than"
1259          when "<="
1260            operator_description = "less than or equal to"
1261          when ">"
1262            operator_description = "greater than"
1263          when ">="
1264            operator_description = "greater than or equal to"
1265          end
1266          template = <<-EOT
1267<?> #{operator} <?> should be true
1268<?> was expected to be #{operator_description}
1269<?>.
1270EOT
1271          full_message = build_message(message, template,
1272                                       expected, actual,
1273                                       expected, actual)
1274          assert_block(full_message) do
1275            expected.__send__(operator, actual)
1276          end
1277        end
1278      end
1279
1280      ##
1281      # Passes if assertion is failed in block.
1282      #
1283      # @example
1284      #   assert_fail_assertion {assert_equal("A", "B")}  # -> pass
1285      #   assert_fail_assertion {assert_equal("A", "A")}  # -> fail
1286      def assert_fail_assertion(message=nil)
1287        _wrap_assertion do
1288          full_message = build_message(message,
1289                                       "Failed assertion was expected.")
1290          assert_block(full_message) do
1291            begin
1292              yield
1293              false
1294            rescue AssertionFailedError
1295              true
1296            end
1297          end
1298        end
1299      end
1300
1301      ##
1302      # Passes if an exception is raised in block and its
1303      # message is +expected+.
1304      #
1305      # @example
1306      #   assert_raise_message("exception") {raise "exception"}  # -> pass
1307      #   assert_raise_message(/exc/i) {raise "exception"}       # -> pass
1308      #   assert_raise_message("exception") {raise "EXCEPTION"}  # -> fail
1309      #   assert_raise_message("exception") {}                   # -> fail
1310      def assert_raise_message(expected, message=nil)
1311        _wrap_assertion do
1312          full_message = build_message(message,
1313                                       "<?> exception message was expected " +
1314                                       "but none was thrown.",
1315                                       expected)
1316          exception = nil
1317          assert_block(full_message) do
1318            begin
1319              yield
1320              false
1321            rescue Exception => exception
1322              true
1323            end
1324          end
1325
1326          actual = exception.message
1327          diff = AssertionMessage.delayed_diff(expected, actual)
1328          full_message =
1329            build_message(message,
1330                          "<?> exception message expected but was\n" +
1331                          "<?>.?", expected, actual, diff)
1332          assert_block(full_message) do
1333            if expected.is_a?(Regexp)
1334              expected =~ actual
1335            else
1336              expected == actual
1337            end
1338          end
1339        end
1340      end
1341
1342      ##
1343      # Passes if +object+.const_defined?(+constant_name+)
1344      #
1345      # @example
1346      #   assert_const_defined(Test, :Unit)          # -> pass
1347      #   assert_const_defined(Object, :Nonexistent) # -> fail
1348      def assert_const_defined(object, constant_name, message=nil)
1349        _wrap_assertion do
1350          full_message = build_message(message,
1351                                       "<?>.const_defined\\?(<?>) expected.",
1352                                       object, constant_name)
1353          assert_block(full_message) do
1354            object.const_defined?(constant_name)
1355          end
1356        end
1357      end
1358
1359      ##
1360      # Passes if !+object+.const_defined?(+constant_name+)
1361      #
1362      # @example
1363      #   assert_not_const_defined(Object, :Nonexistent) # -> pass
1364      #   assert_not_const_defined(Test, :Unit)          # -> fail
1365      def assert_not_const_defined(object, constant_name, message=nil)
1366        _wrap_assertion do
1367          full_message = build_message(message,
1368                                       "!<?>.const_defined\\?(<?>) expected.",
1369                                       object, constant_name)
1370          assert_block(full_message) do
1371            !object.const_defined?(constant_name)
1372          end
1373        end
1374      end
1375
1376      ##
1377      # Passes if +object+.+predicate+ is _true_.
1378      #
1379      # @example
1380      #   assert_predicate([], :empty?)  # -> pass
1381      #   assert_predicate([1], :empty?) # -> fail
1382      def assert_predicate(object, predicate, message=nil)
1383        _wrap_assertion do
1384          assert_respond_to(object, predicate, message)
1385          actual = object.__send__(predicate)
1386          full_message = build_message(message,
1387                                       "<?>.? is true value expected but was\n" +
1388                                       "<?>",
1389                                       object,
1390                                       AssertionMessage.literal(predicate),
1391                                       actual)
1392          assert_block(full_message) do
1393            actual
1394          end
1395        end
1396      end
1397
1398      ##
1399      # Passes if +object+.+predicate+ is not _true_.
1400      #
1401      # @example
1402      #   assert_not_predicate([1], :empty?) # -> pass
1403      #   assert_not_predicate([], :empty?)  # -> fail
1404      def assert_not_predicate(object, predicate, message=nil)
1405        _wrap_assertion do
1406          assert_respond_to(object, predicate, message)
1407          actual = object.__send__(predicate)
1408          full_message = build_message(message,
1409                                       "<?>.? is false value expected but was\n" +
1410                                       "<?>",
1411                                       object,
1412                                       AssertionMessage.literal(predicate),
1413                                       actual)
1414          assert_block(full_message) do
1415            not actual
1416          end
1417        end
1418      end
1419
1420      # Just for minitest compatibility. :<
1421      #
1422      # @since 3.0.0
1423      alias_method :refute_predicate, :assert_not_predicate
1424
1425      ##
1426      # Passes if +object+#+alias_name+ is an alias method of
1427      # +object+#+original_name+.
1428      #
1429      # @example
1430      #   assert_alias_method([], :length, :size)  # -> pass
1431      #   assert_alias_method([], :size, :length)  # -> pass
1432      #   assert_alias_method([], :each, :size)    # -> fail
1433      def assert_alias_method(object, alias_name, original_name, message=nil)
1434        _wrap_assertion do
1435          find_method_failure_message = Proc.new do |method_name|
1436            build_message(message,
1437                          "<?>.? doesn't exist\n" +
1438                          "(Class: <?>)",
1439                          object,
1440                          AssertionMessage.literal(method_name),
1441                          object.class)
1442          end
1443
1444          alias_method = original_method = nil
1445          assert_block(find_method_failure_message.call(alias_name)) do
1446            begin
1447              alias_method = object.method(alias_name)
1448              true
1449            rescue NameError
1450              false
1451            end
1452          end
1453          assert_block(find_method_failure_message.call(original_name)) do
1454            begin
1455              original_method = object.method(original_name)
1456              true
1457            rescue NameError
1458              false
1459            end
1460          end
1461
1462          full_message = build_message(message,
1463                                       "<?> is alias of\n" +
1464                                       "<?> expected",
1465                                       alias_method,
1466                                       original_method)
1467          assert_block(full_message) do
1468            alias_method == original_method
1469          end
1470        end
1471      end
1472
1473      ##
1474      # Passes if +path+ exists.
1475      #
1476      # @example
1477      #   assert_path_exist("/tmp")          # -> pass
1478      #   assert_path_exist("/bin/sh")       # -> pass
1479      #   assert_path_exist("/nonexistent")  # -> fail
1480      def assert_path_exist(path, message=nil)
1481        _wrap_assertion do
1482          failure_message = build_message(message,
1483                                          "<?> was expected to exist",
1484                                          path)
1485          assert_block(failure_message) do
1486            File.exist?(path)
1487          end
1488        end
1489      end
1490
1491      ##
1492      # Passes if +path+ doesn't exist.
1493      #
1494      # @example
1495      #   assert_path_not_exist("/nonexistent")  # -> pass
1496      #   assert_path_not_exist("/tmp")          # -> fail
1497      #   assert_path_not_exist("/bin/sh")       # -> fail
1498      def assert_path_not_exist(path, message=nil)
1499        _wrap_assertion do
1500          failure_message = build_message(message,
1501                                          "<?> was expected to not exist",
1502                                          path)
1503          assert_block(failure_message) do
1504            not File.exist?(path)
1505          end
1506        end
1507      end
1508
1509      ##
1510      # Passes if +collection+ includes +object+.
1511      #
1512      # @example
1513      #   assert_include([1, 10], 1)            # -> pass
1514      #   assert_include(1..10, 5)              # -> pass
1515      #   assert_include([1, 10], 5)            # -> fail
1516      #   assert_include(1..10, 20)             # -> fail
1517      def assert_include(collection, object, message=nil)
1518        _wrap_assertion do
1519          assert_respond_to(collection, :include?,
1520                            "The collection must respond to :include?.")
1521          full_message = build_message(message,
1522                                       "<?> was expected to include\n<?>.",
1523                                       collection,
1524                                       object)
1525          assert_block(full_message) do
1526            collection.include?(object)
1527          end
1528        end
1529      end
1530
1531      # Just for minitest compatibility. :<
1532      #
1533      # @since 2.5.3
1534      alias_method :assert_includes, :assert_include
1535
1536      ##
1537      # Passes if +collection+ doesn't include +object+.
1538      #
1539      # @example
1540      #   assert_not_include([1, 10], 5)            # -> pass
1541      #   assert_not_include(1..10, 20)             # -> pass
1542      #   assert_not_include([1, 10], 1)            # -> fail
1543      #   assert_not_include(1..10, 5)              # -> fail
1544      def assert_not_include(collection, object, message=nil)
1545        _wrap_assertion do
1546          assert_respond_to(collection, :include?,
1547                            "The collection must respond to :include?.")
1548          full_message = build_message(message,
1549                                       "<?> was expected to not include\n<?>.",
1550                                       collection,
1551                                       object)
1552          assert_block(full_message) do
1553            not collection.include?(object)
1554          end
1555        end
1556      end
1557
1558      # Just for minitest compatibility. :<
1559      #
1560      # @since 3.0.0
1561      alias_method :assert_not_includes, :assert_not_include
1562
1563      # Just for minitest compatibility. :<
1564      #
1565      # @since 3.0.0
1566      alias_method :refute_includes, :assert_not_include
1567
1568      ##
1569      # Passes if +object+ is empty.
1570      #
1571      # @example
1572      #   assert_empty("")                       # -> pass
1573      #   assert_empty([])                       # -> pass
1574      #   assert_empty({})                       # -> pass
1575      #   assert_empty(" ")                      # -> fail
1576      #   assert_empty([nil])                    # -> fail
1577      #   assert_empty({1 => 2})                 # -> fail
1578      def assert_empty(object, message=nil)
1579        _wrap_assertion do
1580          assert_respond_to(object, :empty?,
1581                            "The object must respond to :empty?.")
1582          full_message = build_message(message,
1583                                       "<?> was expected to be empty.",
1584                                       object)
1585          assert_block(full_message) do
1586            object.empty?
1587          end
1588        end
1589      end
1590
1591      ##
1592      # Passes if +object+ is not empty.
1593      #
1594      # @example
1595      #   assert_not_empty(" ")                      # -> pass
1596      #   assert_not_empty([nil])                    # -> pass
1597      #   assert_not_empty({1 => 2})                 # -> pass
1598      #   assert_not_empty("")                       # -> fail
1599      #   assert_not_empty([])                       # -> fail
1600      #   assert_not_empty({})                       # -> fail
1601      def assert_not_empty(object, message=nil)
1602        _wrap_assertion do
1603          assert_respond_to(object, :empty?,
1604                            "The object must respond to :empty?.")
1605          full_message = build_message(message,
1606                                       "<?> was expected to not be empty.",
1607                                       object)
1608          assert_block(full_message) do
1609            not object.empty?
1610          end
1611        end
1612      end
1613
1614      # Just for minitest compatibility. :<
1615      #
1616      # @since 3.0.0
1617      alias_method :refute_empty, :assert_not_empty
1618
1619      ##
1620      # Builds a failure message.  +head+ is added before the +template+ and
1621      # +arguments+ replaces the '?'s positionally in the template.
1622      def build_message(head, template=nil, *arguments)
1623        template &&= template.chomp
1624        return AssertionMessage.new(head, template, arguments)
1625      end
1626
1627      private
1628      def _wrap_assertion(&block)
1629        @_assertion_wrapped ||= false
1630        if @_assertion_wrapped
1631          block.call
1632        else
1633          @_assertion_wrapped = true
1634          begin
1635            add_assertion
1636            block.call
1637          ensure
1638            @_assertion_wrapped = false
1639          end
1640        end
1641      end
1642
1643      public
1644      # Called whenever an assertion is made. Define this in classes
1645      # that include Test::Unit::Assertions to record assertion
1646      # counts.
1647      #
1648      # This is a public API for developers who extend test-unit.
1649      #
1650      # @return [void]
1651      def add_assertion
1652      end
1653
1654      ##
1655      # Select whether or not to use the pretty-printer. If this option is set
1656      # to false before any assertions are made, pp.rb will not be required.
1657      def self.use_pp=(value)
1658        AssertionMessage.use_pp = value
1659      end
1660
1661      private
1662      def _assert_raise(assert_expected_exception, *args, &block)
1663        _wrap_assertion do
1664          if args.last.is_a?(String)
1665            message = args.pop
1666          else
1667            message = ""
1668          end
1669
1670          assert_exception_helper = AssertExceptionHelper.new(self, args)
1671          expected = assert_exception_helper.expected_exceptions
1672          actual_exception = nil
1673          full_message = build_message(message,
1674                                       "<?> exception was expected " +
1675                                       "but none was thrown.",
1676                                       expected)
1677          assert_block(full_message) do
1678            begin
1679              yield
1680              false
1681            rescue Exception => actual_exception
1682              true
1683            end
1684          end
1685          assert_expected_exception.call(message, assert_exception_helper,
1686                                         actual_exception)
1687          actual_exception
1688        end
1689      end
1690
1691      def _set_failed_information(failure, expected, actual, user_message)
1692        failure.expected = expected
1693        failure.actual = actual
1694        failure.inspected_expected = AssertionMessage.convert(expected)
1695        failure.inspected_actual = AssertionMessage.convert(actual)
1696        failure.user_message = user_message
1697      end
1698
1699      class AssertionMessage
1700        @use_pp = true
1701        class << self
1702          attr_accessor :use_pp
1703
1704          def literal(value)
1705            Literal.new(value)
1706          end
1707
1708          def delayed_literal(&block)
1709            DelayedLiteral.new(block)
1710          end
1711
1712          def maybe_container(value, &formatter)
1713            MaybeContainer.new(value, &formatter)
1714          end
1715
1716          MAX_DIFF_TARGET_STRING_SIZE = 1000
1717          def max_diff_target_string_size
1718            return @@max_diff_target_string_size if @@max_diff_target_string_size
1719
1720            size = ENV["TEST_UNIT_MAX_DIFF_TARGET_STRING_SIZE"]
1721            if size
1722              begin
1723                size = Integer(size)
1724              rescue ArgumentError
1725                size = nil
1726              end
1727            end
1728            size || MAX_DIFF_TARGET_STRING_SIZE
1729          end
1730
1731          @@max_diff_target_string_size = nil
1732          def max_diff_target_string_size=(size)
1733            @@max_diff_target_string_size = size
1734          end
1735
1736          def diff_target_string?(string)
1737            if string.respond_to?(:bytesize)
1738              string.bytesize < max_diff_target_string_size
1739            else
1740              string.size < max_diff_target_string_size
1741            end
1742          end
1743
1744          def ensure_diffable_string(string)
1745            if string.respond_to?(:encoding) and
1746                !string.encoding.ascii_compatible?
1747              string = string.dup.force_encoding("ASCII-8BIT")
1748            end
1749            string
1750          end
1751
1752          def prepare_for_diff(from, to)
1753            if !from.is_a?(String) or !to.is_a?(String)
1754              from = convert(from)
1755              to = convert(to)
1756            end
1757
1758            if diff_target_string?(from) and diff_target_string?(to)
1759              from = ensure_diffable_string(from)
1760              to = ensure_diffable_string(to)
1761              [from, to]
1762            else
1763              [nil, nil]
1764            end
1765          end
1766
1767          def delayed_diff(from, to)
1768            delayed_literal do
1769              from, to = prepare_for_diff(from, to)
1770
1771              diff = "" if from.nil? or to.nil?
1772              diff ||= Diff.readable(from, to)
1773              if /^[-+]/ !~ diff
1774                diff = ""
1775              elsif /^[ ?]/ =~ diff or /(?:.*\n){2,}/ =~ diff
1776                diff = "\n\ndiff:\n#{diff}"
1777              else
1778                diff = ""
1779              end
1780
1781              if Diff.need_fold?(diff)
1782                folded_diff = Diff.folded_readable(from, to)
1783                diff += "\n\nfolded diff:\n#{folded_diff}"
1784              end
1785
1786              diff
1787            end
1788          end
1789
1790          def convert(object)
1791            if object.is_a?(Exception)
1792              object = AssertExceptionHelper::WrappedException.new(object)
1793            end
1794            inspector = Inspector.new(object)
1795            if use_pp
1796              begin
1797                require "pp" unless defined?(PP)
1798                begin
1799                  return PP.pp(inspector, String.new).chomp
1800                rescue NameError
1801                end
1802              rescue LoadError
1803                self.use_pp = false
1804              end
1805            end
1806            inspector.inspect
1807          end
1808        end
1809
1810        class Inspector
1811          include Comparable
1812
1813          class << self
1814            def cached_new(object, inspected_objects)
1815              inspected_objects[object.object_id] ||=
1816                new(object, inspected_objects)
1817            end
1818
1819            @@inspector_classes = []
1820            def inspector_classes
1821              @@inspector_classes
1822            end
1823
1824            def register_inspector_class(inspector_class)
1825              @@inspector_classes << inspector_class
1826            end
1827
1828            def unregister_inspector_class(inspector_class)
1829              @@inspector_classes.delete(inspector_class)
1830            end
1831          end
1832
1833          attr_reader :object
1834          def initialize(object, inspected_objects={})
1835            @inspected_objects = inspected_objects
1836            @object = object
1837            @inspected_objects[@object.object_id] = self
1838            @inspect_target = inspect_target
1839          end
1840
1841          alias_method :native_inspect, :inspect
1842          def inspect
1843            @inspect_target.inspect
1844          end
1845
1846          def pretty_print(q)
1847            @inspect_target.pretty_print(q)
1848          end
1849
1850          def pretty_print_cycle(q)
1851            @inspect_target.pretty_print_cycle(q)
1852          end
1853
1854          def <=>(other)
1855            if other.is_a?(self.class)
1856              @object <=> other.object
1857            else
1858              @object <=> other
1859            end
1860          end
1861
1862          private
1863          def inspect_target
1864            self.class.inspector_classes.each do |inspector_class|
1865              if inspector_class.target?(@object)
1866                return inspector_class.new(@object, @inspected_objects)
1867              end
1868            end
1869            @object
1870          end
1871        end
1872
1873        class NumericInspector
1874          Inspector.register_inspector_class(self)
1875
1876          class << self
1877            def target?(object)
1878              object.is_a?(Numeric)
1879            end
1880          end
1881
1882          def initialize(numeric, inspected_objects)
1883            @inspected_objects = inspected_objects
1884            @numeric = numeric
1885          end
1886
1887          def inspect
1888            @numeric.to_s
1889          end
1890
1891          def pretty_print(q)
1892            q.text(@numeric.to_s)
1893          end
1894
1895          def pretty_print_cycle(q)
1896            q.text(@numeric.to_s)
1897          end
1898        end
1899
1900        class HashInspector
1901          Inspector.register_inspector_class(self)
1902
1903          class << self
1904            def target?(object)
1905              object.is_a?(Hash) or ENV.equal?(object)
1906            end
1907          end
1908
1909          def initialize(hash, inspected_objects)
1910            @inspected_objects = inspected_objects
1911            @hash = {}
1912            hash.each do |key, value|
1913              key = Inspector.cached_new(key, @inspected_objects)
1914              value = Inspector.cached_new(value, @inspected_objects)
1915              @hash[key] = value
1916            end
1917          end
1918
1919          def inspect
1920            @hash.inspect
1921          end
1922
1923          def pretty_print(q)
1924            q.group(1, '{', '}') do
1925              q.seplist(self, nil, :each_pair) do |k, v|
1926                q.group do
1927                  q.pp(k)
1928                  q.text('=>')
1929                  q.group(1) do
1930                    q.breakable('')
1931                    q.pp(v)
1932                  end
1933                end
1934              end
1935            end
1936          end
1937
1938          def pretty_print_cycle(q)
1939            @hash.pretty_print_cycle(q)
1940          end
1941
1942          def each_pair
1943            keys = @hash.keys
1944            begin
1945              keys = keys.sort # FIXME: more cleverly
1946            rescue ArgumentError
1947            end
1948            keys.each do |key|
1949              yield(key, @hash[key])
1950            end
1951          end
1952        end
1953
1954        class ArrayInspector
1955          Inspector.register_inspector_class(self)
1956
1957          class << self
1958            def target?(object)
1959              object.is_a?(Array)
1960            end
1961          end
1962
1963          def initialize(array, inspected_objects)
1964            @inspected_objects = inspected_objects
1965            @array = array.collect do |element|
1966              Inspector.cached_new(element, @inspected_objects)
1967            end
1968          end
1969
1970          def inspect
1971            @array.inspect
1972          end
1973
1974          def pretty_print(q)
1975            q.group(1, '[', ']') do
1976              q.seplist(self) do |v|
1977                q.pp(v)
1978              end
1979            end
1980          end
1981
1982          def pretty_print_cycle(q)
1983            @array.pretty_print_cycle(q)
1984          end
1985
1986          def each(&block)
1987            @array.each(&block)
1988          end
1989        end
1990
1991        class Literal
1992          def initialize(value)
1993            @value = value
1994          end
1995
1996          def inspect
1997            @value.to_s
1998          end
1999        end
2000
2001        class DelayedLiteral
2002          def initialize(value)
2003            @value = value
2004          end
2005
2006          def inspect
2007            @value.call.to_s
2008          end
2009        end
2010
2011        class MaybeContainer
2012          def initialize(value, &formatter)
2013            @value = value
2014            @formatter = formatter
2015          end
2016
2017          def inspect
2018            if @value.is_a?(Array)
2019              values = @value.collect do |value|
2020                @formatter.call(AssertionMessage.convert(value))
2021              end
2022              "[#{values.join(', ')}]"
2023            else
2024              @formatter.call(AssertionMessage.convert(@value))
2025            end
2026          end
2027        end
2028
2029        class Template
2030          def self.create(string)
2031            parts = (string ? string.scan(/(?=[^\\])\?|(?:\\\?|[^\?])+/m) : [])
2032            self.new(parts)
2033          end
2034
2035          attr_reader :count
2036
2037          def initialize(parts)
2038            @parts = parts
2039            @count = parts.find_all{|e| e == '?'}.size
2040          end
2041
2042          def result(parameters)
2043            raise "The number of parameters does not match the number of substitutions." if(parameters.size != count)
2044            params = parameters.dup
2045            expanded_template = ""
2046            @parts.each do |part|
2047              if part == '?'
2048                param = params.shift
2049                if Object.const_defined?(:Encoding)
2050                  expanded_template += concatenatable(param,
2051                                                      expanded_template.encoding)
2052                else
2053                  expanded_template += param
2054                end
2055              else
2056                expanded_template += part.gsub(/\\\?/m, '?')
2057              end
2058            end
2059            expanded_template
2060          end
2061
2062          private
2063          def concatenatable(text, encoding)
2064            if Encoding.compatible?(text, encoding)
2065              text
2066            else
2067              text.dup.force_encoding(encoding)
2068            end
2069          end
2070        end
2071
2072        include Util::BacktraceFilter
2073
2074        def initialize(head, template_string, parameters)
2075          @head = head
2076          @template_string = template_string
2077          @parameters = parameters
2078        end
2079
2080        def convert(object)
2081          self.class.convert(object)
2082        end
2083
2084        def template
2085          @template ||= Template.create(@template_string)
2086        end
2087
2088        def add_period(string)
2089          (string =~ /\.\Z/ ? string : string + '.')
2090        end
2091
2092        def to_s
2093          message_parts = []
2094          if (@head)
2095            head = @head
2096            head = head.call if head.respond_to?(:call)
2097            head = head.to_s
2098            unless(head.empty?)
2099              message_parts << add_period(head)
2100            end
2101          end
2102          tail = template.result(@parameters.collect{|e| convert(e)})
2103          message_parts << tail unless(tail.empty?)
2104          message_parts.join("\n")
2105        end
2106      end
2107
2108      class AssertExceptionHelper
2109        class WrappedException
2110          attr_reader :exception
2111          def initialize(exception)
2112            @exception = exception
2113          end
2114
2115          def inspect
2116            if default_inspect?
2117              "#{@exception.class.inspect}(<#{@exception.message}>)"
2118            else
2119              @exception.inspect
2120            end
2121          end
2122
2123          def method_missing(name, *args, &block)
2124            @exception.__send__(name, *args, &block)
2125          end
2126
2127          private
2128          def default_inspect?
2129            inspect_method = @exception.method(:inspect)
2130            if inspect_method.respond_to?(:owner) and
2131                inspect_method.owner == Exception
2132              true
2133            else
2134              default_inspect_method = Exception.instance_method(:inspect)
2135              default_inspect_method.bind(@exception).call == @exception.inspect
2136            end
2137          end
2138        end
2139
2140        def initialize(test_case, expected_exceptions)
2141          @test_case = test_case
2142          @expected_exceptions = expected_exceptions
2143          @expected_classes, @expected_modules, @expected_objects =
2144            split_expected_exceptions(expected_exceptions)
2145        end
2146
2147        def expected_exceptions
2148          exceptions = @expected_exceptions.collect do |exception|
2149            if exception.is_a?(Exception)
2150              WrappedException.new(exception)
2151            else
2152              exception
2153            end
2154          end
2155          if exceptions.size == 1
2156            exceptions[0]
2157          else
2158            exceptions
2159          end
2160        end
2161
2162        def expected?(actual_exception, equality=nil)
2163          equality ||= :instance_of?
2164          expected_class?(actual_exception, equality) or
2165            expected_module?(actual_exception) or
2166            expected_object?(actual_exception)
2167        end
2168
2169        private
2170        def split_expected_exceptions(expected_exceptions)
2171          exception_modules = []
2172          exception_objects = []
2173          exception_classes = []
2174          expected_exceptions.each do |exception_type|
2175            if exception_type.instance_of?(Module)
2176              exception_modules << exception_type
2177            elsif exception_object?(exception_type)
2178              exception_objects << exception_type
2179            elsif exception_class?(exception_type)
2180              exception_classes << exception_type
2181            else
2182              full_message =
2183                @test_case.__send__(:build_message,
2184                                    nil,
2185                                    "<?> must be " +
2186                                    "a subclass of Exception, " +
2187                                    "an object of Exception subclasses " +
2188                                    "or a Module",
2189                                    exception_type)
2190              @test_case.flunk(full_message)
2191            end
2192          end
2193          [exception_classes, exception_modules, exception_objects]
2194        end
2195
2196        def exception_object?(exception_type)
2197          return true if exception_type.is_a?(Exception)
2198
2199          if Object.const_defined?(:Java)
2200            return true if exception_type.is_a?(Java::JavaLang::Throwable)
2201          end
2202
2203          false
2204        end
2205
2206        def exception_class?(exception_type)
2207          return true if exception_type <= Exception
2208
2209          if Object.const_defined?(:Java)
2210            return true if exception_type <= Java::JavaLang::Throwable
2211          end
2212
2213          false
2214        end
2215
2216        def expected_class?(actual_exception, equality)
2217          @expected_classes.any? do |expected_class|
2218            actual_exception.__send__(equality, expected_class)
2219          end
2220        end
2221
2222        def expected_module?(actual_exception)
2223          @expected_modules.any? do |expected_module|
2224            actual_exception.is_a?(expected_module)
2225          end
2226        end
2227
2228        def expected_object?(actual_exception)
2229          @expected_objects.any? do |expected_object|
2230            expected_object == actual_exception or
2231              fallback_exception_object_equal(expected_object, actual_exception)
2232          end
2233        end
2234
2235        def fallback_exception_object_equal(expected_object, actual_exception)
2236          owner = Util::MethodOwnerFinder.find(expected_object, :==)
2237          if owner == Kernel or owner == Exception
2238            expected_object.class == actual_exception.class and
2239              expected_object.message == actual_exception.message
2240          else
2241            false
2242          end
2243        end
2244      end
2245
2246      # :startdoc:
2247    end
2248  end
2249end
2250