Module: Test::Unit::Assertions

Included in:
TestCase
Defined in:
lib/test/unit/assertions.rb

Overview

Test::Unit::Assertions contains the standard Test::Unit assertions. Assertions is included in Test::Unit::TestCase.

To include it in your own code and use its functionality, you simply need to rescue Test::Unit::AssertionFailedError. Additionally you may override add_assertion to get notified whenever an assertion is made.

Notes:

  • The message to each assertion, if given, will be propagated with the failure.

  • It is easy to add your own assertions based on assert_block().

Example Custom Assertion

def deny(boolean, message = nil)
  message = build_message message, '<?> is not false or nil.', boolean
  assert_block message do
    not boolean
  end
end

Defined Under Namespace

Classes: AssertExceptionHelper, AssertionMessage

Constant Summary collapse

UncaughtThrow =
{
  NameError => /^uncaught throw \`(.+)\'$/, #`
  ArgumentError => /^uncaught throw (.+)$/,
  ThreadError => /^uncaught throw \`(.+)\' in thread / #`
}

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.use_pp=(value) ⇒ Object



1464
1465
1466
# File 'lib/test/unit/assertions.rb', line 1464

def self.use_pp=(value)
  AssertionMessage.use_pp = value
end

Instance Method Details

#add_assertionvoid

This method returns an undefined value.

Called whenever an assertion is made. Define this in classes that include Test::Unit::Assertions to record assertion counts.

This is a public API for developers who extend test-unit.



1456
1457
# File 'lib/test/unit/assertions.rb', line 1456

def add_assertion
end

#assert(boolean, message = nil) ⇒ Object



63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
# File 'lib/test/unit/assertions.rb', line 63

def assert(boolean, message=nil)
  _wrap_assertion do
    assertion_message = nil
    case message
    when nil, String, Proc
    when AssertionMessage
      assertion_message = message
    else
      error_message = "assertion message must be String, Proc or "
      error_message << "#{AssertionMessage}: "
      error_message << "<#{message.inspect}>(<#{message.class}>)"
      raise ArgumentError, error_message, filter_backtrace(caller)
    end
    assert_block("assert should not be called with a block.") do
      !block_given?
    end
    assertion_message ||= build_message(message,
                                        "<?> is not true.",
                                        boolean)
    assert_block(assertion_message) do
      boolean
    end
  end
end

#assert_alias_method(object, alias_name, original_name, message = nil) ⇒ Object

Passes if object#alias_name is an alias method of object#original_name.

Example:

assert_alias_method([], :length, :size)  # -> pass
assert_alias_method([], :size, :length)  # -> pass
assert_alias_method([], :each, :size)    # -> fail


1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
# File 'lib/test/unit/assertions.rb', line 1251

def assert_alias_method(object, alias_name, original_name, message=nil)
  _wrap_assertion do
    find_method_failure_message = Proc.new do |method_name|
      build_message(message,
                    "<?>.? doesn't exist\n" +
                    "(Class: <?>)",
                    object,
                    AssertionMessage.literal(method_name),
                    object.class)
    end

    alias_method = original_method = nil
    assert_block(find_method_failure_message.call(alias_name)) do
      begin
        alias_method = object.method(alias_name)
        true
      rescue NameError
        false
      end
    end
    assert_block(find_method_failure_message.call(original_name)) do
      begin
        original_method = object.method(original_name)
        true
      rescue NameError
        false
      end
    end

    full_message = build_message(message,
                                 "<?> is alias of\n" +
                                 "<?> expected",
                                 alias_method,
                                 original_method)
    assert_block(full_message) do
      alias_method == original_method
    end
  end
end

#assert_block(message = "assert_block failed.") ⇒ Object

:yields:



48
49
50
51
52
53
54
# File 'lib/test/unit/assertions.rb', line 48

def assert_block(message="assert_block failed.") # :yields:
  _wrap_assertion do
    if (! yield)
      raise AssertionFailedError.new(message.to_s)
    end
  end
end

#assert_boolean(actual, message = nil) ⇒ Object

Passes if actual is a boolean value.

Example:

assert_boolean(true) # -> pass
assert_boolean(nil)  # -> fail


1027
1028
1029
1030
1031
1032
1033
1034
1035
# File 'lib/test/unit/assertions.rb', line 1027

def assert_boolean(actual, message=nil)
  _wrap_assertion do
    assert_block(build_message(message,
                               "<true> or <false> expected but was\n<?>",
                               actual)) do
      [true, false].include?(actual)
    end
  end
end

#assert_compare(expected, operator, actual, message = nil) ⇒ Object

Passes if expression “expected operator actual” is true.

Example:

assert_compare(1, "<", 10)  # -> pass
assert_compare(1, ">=", 10) # -> fail


1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
# File 'lib/test/unit/assertions.rb', line 1076

def assert_compare(expected, operator, actual, message=nil)
  _wrap_assertion do
    assert_send([["<", "<=", ">", ">="], :include?, operator.to_s])
    case operator.to_s
    when "<"
      operator_description = "less than"
    when "<="
      operator_description = "less than or equal to"
    when ">"
      operator_description = "greater than"
    when ">="
      operator_description = "greater than or equal to"
    end
    template = <<-EOT
<?> #{operator} <?> should be true
<?> expected #{operator_description}
<?>.
EOT
    full_message = build_message(message, template,
                                 expected, actual,
                                 expected, actual)
    assert_block(full_message) do
      expected.__send__(operator, actual)
    end
  end
end

#assert_const_defined(object, constant_name, message = nil) ⇒ Object

Passes if object.const_defined?(constant_name)

Example:

assert_const_defined(Test, :Unit)          # -> pass
assert_const_defined(Object, :Nonexistent) # -> fail


1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
# File 'lib/test/unit/assertions.rb', line 1171

def assert_const_defined(object, constant_name, message=nil)
  _wrap_assertion do
    full_message = build_message(message,
                                 "<?>.const_defined\\?(<?>) expected.",
                                 object, constant_name)
    assert_block(full_message) do
      object.const_defined?(constant_name)
    end
  end
end

#assert_empty(object, message = nil) ⇒ Object

Passes if object is empty.

Example:

assert_empty("")                       # -> pass
assert_empty([])                       # -> pass
assert_empty({})                       # -> pass
assert_empty(" ")                      # -> fail
assert_empty([nil])                    # -> fail
assert_empty({1 => 2})                 # -> fail


1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
# File 'lib/test/unit/assertions.rb', line 1386

def assert_empty(object, message=nil)
  _wrap_assertion do
    assert_respond_to(object, :empty?,
                      "The object must respond to :empty?.")
    full_message = build_message(message,
                                 "<?> expected to be empty.",
                                 object)
    assert_block(full_message) do
      object.empty?
    end
  end
end

#assert_equal(expected, actual, message = nil) ⇒ Object



140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
# File 'lib/test/unit/assertions.rb', line 140

def assert_equal(expected, actual, message=nil)
  diff = AssertionMessage.delayed_diff(expected, actual)
  if expected.respond_to?(:encoding) and
      actual.respond_to?(:encoding) and
      expected.encoding != actual.encoding
    format = <<EOT
<?>(?) expected but was
<?>(?).?
EOT
    full_message = build_message(message, format,
                                 expected, expected.encoding.name,
                                 actual, actual.encoding.name,
                                 diff)
  else
    full_message = build_message(message, <<EOT, expected, actual, diff)
<?> expected but was
<?>.?
EOT
  end
  begin
    assert_block(full_message) { expected == actual }
  rescue AssertionFailedError => failure
    _set_failed_information(failure, expected, actual, message)
    raise failure # For JRuby. :<
  end
end

#assert_fail_assertion(message = nil) ⇒ Object

Passes if assertion is failed in block.

Example:

assert_fail_assertion {assert_equal("A", "B")}  # -> pass
assert_fail_assertion {assert_equal("A", "A")}  # -> fail


1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
# File 'lib/test/unit/assertions.rb', line 1109

def assert_fail_assertion(message=nil)
  _wrap_assertion do
    full_message = build_message(message,
                                 "Failed assertion was expected.")
    assert_block(full_message) do
      begin
        yield
        false
      rescue AssertionFailedError
        true
      end
    end
  end
end

#assert_false(actual, message = nil) ⇒ Object

Passes if actual is false.

Example:

assert_false(false)  # -> pass
assert_false(nil)    # -> fail


1059
1060
1061
1062
1063
1064
1065
1066
1067
# File 'lib/test/unit/assertions.rb', line 1059

def assert_false(actual, message=nil)
  _wrap_assertion do
    assert_block(build_message(message,
                               "<false> expected but was\n<?>",
                               actual)) do
      actual == false
    end
  end
end

#assert_in_delta(expected_float, actual_float, delta = 0.001, message = "") ⇒ Object



680
681
682
683
684
685
686
687
688
689
690
691
692
693
# File 'lib/test/unit/assertions.rb', line 680

def assert_in_delta(expected_float, actual_float, delta=0.001, message="")
  _wrap_assertion do
    _assert_in_delta_validate_arguments(expected_float,
                                        actual_float,
                                        delta)
    full_message = _assert_in_delta_message(expected_float,
                                            actual_float,
                                            delta,
                                            message)
    assert_block(full_message) do
      (expected_float.to_f - actual_float.to_f).abs <= delta.to_f
    end
  end
end

#assert_in_epsilon(expected_float, actual_float, epsilon = 0.001, message = "") ⇒ Object



809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
# File 'lib/test/unit/assertions.rb', line 809

def assert_in_epsilon(expected_float, actual_float, epsilon=0.001,
                      message="")
  _wrap_assertion do
    _assert_in_epsilon_validate_arguments(expected_float,
                                          actual_float,
                                          epsilon)
    full_message = _assert_in_epsilon_message(expected_float,
                                              actual_float,
                                              epsilon,
                                              message)
    assert_block(full_message) do
      normalized_expected_float = expected_float.to_f
      if normalized_expected_float.zero?
        delta = epsilon.to_f ** 2
      else
        delta = normalized_expected_float * epsilon.to_f
      end
      (normalized_expected_float - actual_float.to_f).abs <= delta
    end
  end
end

#assert_include(collection, object, message = nil) ⇒ Object Also known as: assert_includes

Passes if collection includes object.

Example:

assert_include([1, 10], 1)            # -> pass
assert_include(1..10, 5)              # -> pass
assert_include([1, 10], 5)            # -> fail
assert_include(1..10, 20)             # -> fail


1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
# File 'lib/test/unit/assertions.rb', line 1335

def assert_include(collection, object, message=nil)
  _wrap_assertion do
    assert_respond_to(collection, :include?,
                      "The collection must respond to :include?.")
    full_message = build_message(message,
                                 "<?> expected to include\n<?>.",
                                 collection,
                                 object)
    assert_block(full_message) do
      collection.include?(object)
    end
  end
end

#assert_instance_of(klass, object, message = "") ⇒ Object



245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
# File 'lib/test/unit/assertions.rb', line 245

def assert_instance_of(klass, object, message="")
  _wrap_assertion do
    klasses = nil
    klasses = klass if klass.is_a?(Array)
    assert_block("The first parameter to assert_instance_of should be " +
                 "a Class or an Array of Class.") do
      if klasses
        klasses.all? {|k| k.is_a?(Class)}
      else
        klass.is_a?(Class)
      end
    end
    klass_message = AssertionMessage.maybe_container(klass) do |value|
      "<#{value}>"
    end
    full_message = build_message(message, <<EOT, object, klass_message, object.class)
<?> expected to be an instance of
? but was
<?>.
EOT
    assert_block(full_message) do
      if klasses
        klasses.any? {|k| object.instance_of?(k)}
      else
        object.instance_of?(klass)
      end
    end
  end
end

#assert_kind_of(klass, object, message = "") ⇒ Object



300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
# File 'lib/test/unit/assertions.rb', line 300

def assert_kind_of(klass, object, message="")
  _wrap_assertion do
    klasses = nil
    klasses = klass if klass.is_a?(Array)
    assert_block("The first parameter to assert_kind_of should be " +
                 "a kind_of Module or an Array of a kind_of Module.") do
      if klasses
        klasses.all? {|k| k.kind_of?(Module)}
      else
        klass.kind_of?(Module)
      end
    end
    klass_message = AssertionMessage.maybe_container(klass) do |value|
      "<#{value}>"
    end
    full_message = build_message(message,
                                 "<?> expected to be kind_of\\?\n" +
                                 "? but was\n" +
                                 "<?>.",
                                 object,
                                 klass_message,
                                 object.class)
    assert_block(full_message) do
      if klasses
        klasses.any? {|k| object.kind_of?(k)}
      else
        object.kind_of?(klass)
      end
    end
  end
end

#assert_match(pattern, string, message = "") ⇒ Object



393
394
395
396
397
398
399
400
401
402
403
404
# File 'lib/test/unit/assertions.rb', line 393

def assert_match(pattern, string, message="")
  _wrap_assertion do
    pattern = case(pattern)
      when String
        Regexp.new(Regexp.escape(pattern))
      else
        pattern
    end
    full_message = build_message(message, "<?> expected to be =~\n<?>.", string, pattern)
    assert_block(full_message) { string =~ pattern }
  end
end

#assert_nil(object, message = "") ⇒ Object



282
283
284
285
286
287
# File 'lib/test/unit/assertions.rb', line 282

def assert_nil(object, message="")
  full_message = build_message(message, <<EOT, object)
<?> expected to be nil.
EOT
  assert_block(full_message) { object.nil? }
end

#assert_no_match(regexp, string, message = "") ⇒ Object



582
583
584
585
586
587
588
589
# File 'lib/test/unit/assertions.rb', line 582

def assert_no_match(regexp, string, message="")
  _wrap_assertion do
    assert_instance_of(Regexp, regexp,
                       "The first argument to assert_no_match " +
                       "should be a Regexp.")
    assert_not_match(regexp, string, message)
  end
end

#assert_not_const_defined(object, constant_name, message = nil) ⇒ Object

Passes if !object.const_defined?(constant_name)

Example:

assert_not_const_defined(Object, :Nonexistent) # -> pass
assert_not_const_defined(Test, :Unit)          # -> fail


1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
# File 'lib/test/unit/assertions.rb', line 1188

def assert_not_const_defined(object, constant_name, message=nil)
  _wrap_assertion do
    full_message = build_message(message,
                                 "!<?>.const_defined\\?(<?>) expected.",
                                 object, constant_name)
    assert_block(full_message) do
      !object.const_defined?(constant_name)
    end
  end
end

#assert_not_empty(object, message = nil) ⇒ Object

Passes if object is not empty.

Example:

assert_not_empty(" ")                      # -> pass
assert_not_empty([nil])                    # -> pass
assert_not_empty({1 => 2})                 # -> pass
assert_not_empty("")                       # -> fail
assert_not_empty([])                       # -> fail
assert_not_empty({})                       # -> fail


1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
# File 'lib/test/unit/assertions.rb', line 1409

def assert_not_empty(object, message=nil)
  _wrap_assertion do
    assert_respond_to(object, :empty?,
                      "The object must respond to :empty?.")
    full_message = build_message(message,
                                 "<?> expected to not be empty.",
                                 object)
    assert_block(full_message) do
      not object.empty?
    end
  end
end

#assert_not_equal(expected, actual, message = "") ⇒ Object Also known as: refute_equal



520
521
522
523
# File 'lib/test/unit/assertions.rb', line 520

def assert_not_equal(expected, actual, message="")
  full_message = build_message(message, "<?> expected to be != to\n<?>.", expected, actual)
  assert_block(full_message) { expected != actual }
end

#assert_not_in_delta(expected_float, actual_float, delta = 0.001, message = "") ⇒ Object Also known as: refute_in_delta



704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
# File 'lib/test/unit/assertions.rb', line 704

def assert_not_in_delta(expected_float, actual_float, delta=0.001, message="")
  _wrap_assertion do
    _assert_in_delta_validate_arguments(expected_float,
                                        actual_float,
                                        delta)
    full_message = _assert_in_delta_message(expected_float,
                                            actual_float,
                                            delta,
                                            message,
                                            :negative_assertion => true)
    assert_block(full_message) do
      (expected_float.to_f - actual_float.to_f).abs > delta.to_f
    end
  end
end

#assert_not_in_epsilon(expected_float, actual_float, epsilon = 0.001, message = "") ⇒ Object



841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
# File 'lib/test/unit/assertions.rb', line 841

def assert_not_in_epsilon(expected_float, actual_float, epsilon=0.001,
                          message="")
  _wrap_assertion do
    _assert_in_epsilon_validate_arguments(expected_float,
                                          actual_float,
                                          epsilon)
    full_message = _assert_in_epsilon_message(expected_float,
                                              actual_float,
                                              epsilon,
                                              message,
                                              :negative_assertion => true)
    assert_block(full_message) do
      normalized_expected_float = expected_float.to_f
      delta = normalized_expected_float * epsilon.to_f
      (normalized_expected_float - actual_float.to_f).abs > delta
    end
  end
end

#assert_not_include(collection, object, message = nil) ⇒ Object

Passes if collection doesn’t include object.

Example:

assert_not_include([1, 10], 5)            # -> pass
assert_not_include(1..10, 20)             # -> pass
assert_not_include([1, 10], 1)            # -> fail
assert_not_include(1..10, 5)              # -> fail


1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
# File 'lib/test/unit/assertions.rb', line 1362

def assert_not_include(collection, object, message=nil)
  _wrap_assertion do
    assert_respond_to(collection, :include?,
                      "The collection must respond to :include?.")
    full_message = build_message(message,
                                 "<?> expected to not include\n<?>.",
                                 collection,
                                 object)
    assert_block(full_message) do
      not collection.include?(object)
    end
  end
end

#assert_not_match(regexp, string, message = "") ⇒ Object Also known as: refute_match



555
556
557
558
559
560
561
562
563
564
565
# File 'lib/test/unit/assertions.rb', line 555

def assert_not_match(regexp, string, message="")
  _wrap_assertion do
    assert_instance_of(Regexp, regexp,
                       "<REGEXP> in assert_not_match(<REGEXP>, ...) " +
                       "should be a Regexp.")
    full_message = build_message(message,
                                 "<?> expected to not match\n<?>.",
                                 regexp, string)
    assert_block(full_message) { regexp !~ string }
  end
end

#assert_not_nil(object, message = "") ⇒ Object Also known as: refute_nil



537
538
539
540
# File 'lib/test/unit/assertions.rb', line 537

def assert_not_nil(object, message="")
  full_message = build_message(message, "<?> expected to not be nil.", object)
  assert_block(full_message){!object.nil?}
end

#assert_not_predicate(object, predicate, message = nil) ⇒ Object

Passes if object.predicate is not true.

Example:

assert_not_predicate([1], :empty?) # -> pass
assert_not_predicate([], :empty?)  # -> fail


1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
# File 'lib/test/unit/assertions.rb', line 1227

def assert_not_predicate(object, predicate, message=nil)
  _wrap_assertion do
    assert_respond_to(object, predicate, message)
    actual = object.__send__(predicate)
    full_message = build_message(message,
                                 "<?>.? is false value expected but was\n" +
                                 "<?>",
                                 object,
                                 AssertionMessage.literal(predicate),
                                 actual)
    assert_block(full_message) do
      not actual
    end
  end
end

#assert_not_respond_to(object, method, message = "") ⇒ Object Also known as: refute_respond_to



364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
# File 'lib/test/unit/assertions.rb', line 364

def assert_not_respond_to(object, method, message="")
  _wrap_assertion do
    full_message = build_message(message,
                                 "<?>.kind_of\\?(Symbol) or\n" +
                                 "<?>.respond_to\\?(:to_str) expected",
                                 method, method)
    assert_block(full_message) do
      method.kind_of?(Symbol) or method.respond_to?(:to_str)
    end
    full_message = build_message(message,
                                 "!<?>.respond_to\\?(?) expected\n" +
                                 "(Class: <?>)",
                                 object, method, object.class)
    assert_block(full_message) {!object.respond_to?(method)}
  end
end

#assert_not_same(expected, actual, message = "") ⇒ Object Also known as: refute_same



498
499
500
501
502
503
504
505
506
# File 'lib/test/unit/assertions.rb', line 498

def assert_not_same(expected, actual, message="")
  full_message = build_message(message, <<EOT, expected, expected.__id__, actual, actual.__id__)
<?>
with id <?> expected to not be equal\\? to
<?>
with id <?>.
EOT
  assert_block(full_message) { !actual.equal?(expected) }
end

#assert_not_send(send_array, message = nil) ⇒ Object

Passes if the method send doesn’t return a true value.

send_array is composed of:

  • A receiver

  • A method

  • Arguments to the method

Example:

assert_not_send([[1, 2], :member?, 1]) # -> fail
assert_not_send([[1, 2], :member?, 4]) # -> pass


992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
# File 'lib/test/unit/assertions.rb', line 992

def assert_not_send(send_array, message=nil)
  _wrap_assertion do
    assert_instance_of(Array, send_array,
                       "assert_not_send requires an array " +
                       "of send information")
    assert_operator(send_array.size, :>=, 2,
                    "assert_not_send requires at least a receiver " +
                    "and a message name")
    format = <<EOT
<?> expected to respond to
<?(*?)> with not a true value but was
<?>.
EOT
    receiver, message_name, *arguments = send_array
    result = nil
    full_message =
      build_message(message,
                    format,
                    receiver,
                    AssertionMessage.literal(message_name.to_s),
                    arguments,
                    AssertionMessage.delayed_literal {result})
    assert_block(full_message) do
      result = receiver.__send__(message_name, *arguments)
      not result
    end
  end
end

#assert_nothing_raised(*args) ⇒ Object



456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
# File 'lib/test/unit/assertions.rb', line 456

def assert_nothing_raised(*args)
  _wrap_assertion do
    if args.last.is_a?(String)
      message = args.pop
    else
      message = ""
    end

    assert_exception_helper = AssertExceptionHelper.new(self, args)
    begin
      yield
    rescue Exception => e
      if ((args.empty? && !e.instance_of?(AssertionFailedError)) ||
          assert_exception_helper.expected?(e))
        failure_message = build_message(message, "Exception raised:\n?", e)
        assert_block(failure_message) {false}
      else
        raise
      end
    end
    nil
  end
end

#assert_nothing_thrown(message = "", &proc) ⇒ Object



654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
# File 'lib/test/unit/assertions.rb', line 654

def assert_nothing_thrown(message="", &proc)
  _wrap_assertion do
    assert(block_given?, "Should have passed a block to assert_nothing_thrown")
    begin
      proc.call
    rescue NameError, ArgumentError, ThreadError => error
      raise unless UncaughtThrow[error.class] =~ error.message
      tag = $1
      tag = tag[1..-1].intern if tag[0, 1] == ":"
      full_message = build_message(message,
                                   "<?> was thrown when nothing was expected",
                                   tag)
      flunk(full_message)
    end
    assert(true, "Expected nothing to be thrown")
  end
end

#assert_operator(object1, operator, object2, message = "") ⇒ Object



434
435
436
437
438
439
440
441
442
443
444
445
# File 'lib/test/unit/assertions.rb', line 434

def assert_operator(object1, operator, object2, message="")
  _wrap_assertion do
    full_message = build_message(nil, "<?>\ngiven as the operator for #assert_operator must be a Symbol or #respond_to\\?(:to_str).", operator)
    assert_block(full_message){operator.kind_of?(Symbol) || operator.respond_to?(:to_str)}
    full_message = build_message(message, <<EOT, object1, AssertionMessage.literal(operator), object2)
<?> expected to be
?
<?>.
EOT
    assert_block(full_message) { object1.__send__(operator, object2) }
  end
end

#assert_path_exist(path, message = nil) ⇒ Object

Passes if path exists.

Example:

assert_path_exist("/tmp")          # -> pass
assert_path_exist("/bin/sh")       # -> pass
assert_path_exist("/nonexistent")  # -> fail


1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
# File 'lib/test/unit/assertions.rb', line 1298

def assert_path_exist(path, message=nil)
  _wrap_assertion do
    failure_message = build_message(message,
                                    "<?> expected to exist",
                                    path)
    assert_block(failure_message) do
      File.exist?(path)
    end
  end
end

#assert_path_not_exist(path, message = nil) ⇒ Object

Passes if path doesn’t exist.

Example:

assert_path_not_exist("/nonexistent")  # -> pass
assert_path_not_exist("/tmp")          # -> fail
assert_path_not_exist("/bin/sh")       # -> fail


1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
# File 'lib/test/unit/assertions.rb', line 1316

def assert_path_not_exist(path, message=nil)
  _wrap_assertion do
    failure_message = build_message(message,
                                    "<?> expected to not exist",
                                    path)
    assert_block(failure_message) do
      not File.exist?(path)
    end
  end
end

#assert_predicate(object, predicate, message = nil) ⇒ Object

Passes if object.predicate is true.

Example:

assert_predicate([], :empty?)  # -> pass
assert_predicate([1], :empty?) # -> fail


1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
# File 'lib/test/unit/assertions.rb', line 1205

def assert_predicate(object, predicate, message=nil)
  _wrap_assertion do
    assert_respond_to(object, predicate, message)
    actual = object.__send__(predicate)
    full_message = build_message(message,
                                 "<?>.? is true value expected but was\n" +
                                 "<?>",
                                 object,
                                 AssertionMessage.literal(predicate),
                                 actual)
    assert_block(full_message) do
      actual
    end
  end
end

#assert_raise(*args, &block) ⇒ Object Also known as: assert_raises



185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
# File 'lib/test/unit/assertions.rb', line 185

def assert_raise(*args, &block)
  assert_expected_exception = Proc.new do |*_args|
    message, assert_exception_helper, actual_exception = _args
    expected = assert_exception_helper.expected_exceptions
    diff = AssertionMessage.delayed_diff(expected, actual_exception)
    full_message = build_message(message,
                                 "<?> exception expected but was\n<?>.?",
                                 expected, actual_exception, diff)
    begin
      assert_block(full_message) do
        expected == [] or
          assert_exception_helper.expected?(actual_exception)
      end
    rescue AssertionFailedError => failure
      _set_failed_information(failure, expected, actual_exception,
                              message)
      raise failure # For JRuby. :<
    end
  end
  _assert_raise(assert_expected_exception, *args, &block)
end

#assert_raise_kind_of(*args, &block) ⇒ Object

Passes if the block raises one of the given exceptions or sub exceptions of the given exceptions.

Example:

assert_raise_kind_of(SystemCallError) do
  raise Errno::EACCES
end


218
219
220
221
222
223
224
225
226
227
228
229
230
231
# File 'lib/test/unit/assertions.rb', line 218

def assert_raise_kind_of(*args, &block)
  assert_expected_exception = Proc.new do |*_args|
    message, assert_exception_helper, actual_exception = _args
    expected = assert_exception_helper.expected_exceptions
    full_message = build_message(message,
                                 "<?> family exception expected " +
                                 "but was\n<?>.",
                                 expected, actual_exception)
    assert_block(full_message) do
      assert_exception_helper.expected?(actual_exception, :kind_of?)
    end
  end
  _assert_raise(assert_expected_exception, *args, &block)
end

#assert_raise_message(expected, message = nil) ⇒ Object

Passes if an exception is raised in block and its message is expected.

Example:

assert_raise_message("exception") {raise "exception"}  # -> pass
assert_raise_message(/exc/i) {raise "exception"}       # -> pass
assert_raise_message("exception") {raise "EXCEPTION"}  # -> fail
assert_raise_message("exception") {}                   # -> fail


1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
# File 'lib/test/unit/assertions.rb', line 1133

def assert_raise_message(expected, message=nil)
  _wrap_assertion do
    full_message = build_message(message,
                                 "<?> exception message expected " +
                                 "but none was thrown.",
                                 expected)
    exception = nil
    assert_block(full_message) do
      begin
        yield
        false
      rescue Exception => exception
        true
      end
    end

    actual = exception.message
    diff = AssertionMessage.delayed_diff(expected, actual)
    full_message =
      build_message(message,
                    "<?> exception message expected but was\n" +
                    "<?>.?", expected, actual, diff)
    assert_block(full_message) do
      if expected.is_a?(Regexp)
        expected =~ actual
      else
        expected == actual
      end
    end
  end
end

#assert_respond_to(object, method, message = "") ⇒ Object



339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
# File 'lib/test/unit/assertions.rb', line 339

def assert_respond_to(object, method, message="")
  _wrap_assertion do
    full_message = build_message(message,
                                 "<?>.kind_of\\?(Symbol) or\n" +
                                 "<?>.respond_to\\?(:to_str) expected",
                                 method, method)
    assert_block(full_message) do
      method.kind_of?(Symbol) or method.respond_to?(:to_str)
    end
    full_message = build_message(message,
                                 "<?>.respond_to\\?(?) expected\n" +
                                 "(Class: <?>)",
                                 object, method, object.class)
    assert_block(full_message) {object.respond_to?(method)}
  end
end

#assert_same(expected, actual, message = "") ⇒ Object



415
416
417
418
419
420
421
422
423
# File 'lib/test/unit/assertions.rb', line 415

def assert_same(expected, actual, message="")
  full_message = build_message(message, <<EOT, expected, expected.__id__, actual, actual.__id__)
<?>
with id <?> expected to be equal\\? to
<?>
with id <?>.
EOT
  assert_block(full_message) { actual.equal?(expected) }
end

#assert_send(send_array, message = nil) ⇒ Object



952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
# File 'lib/test/unit/assertions.rb', line 952

def assert_send(send_array, message=nil)
  _wrap_assertion do
    assert_instance_of(Array, send_array,
                       "assert_send requires an array " +
                       "of send information")
    assert_operator(send_array.size, :>=, 2,
                    "assert_send requires at least a receiver " +
                    "and a message name")
    format = <<EOT
<?> expected to respond to
<?(*?)> with a true value but was
<?>.
EOT
    receiver, message_name, *arguments = send_array
    result = nil
    full_message =
      build_message(message,
                    format,
                    receiver,
                    AssertionMessage.literal(message_name.to_s),
                    arguments,
                    AssertionMessage.delayed_literal {result})
    assert_block(full_message) do
      result = receiver.__send__(message_name, *arguments)
      result
    end
  end
end

#assert_throw(expected_object, message = "", &proc) ⇒ Object Also known as: assert_throws



606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
# File 'lib/test/unit/assertions.rb', line 606

def assert_throw(expected_object, message="", &proc)
  _wrap_assertion do
    begin
      catch([]) {}
    rescue TypeError
      assert_instance_of(Symbol, expected_object,
                         "assert_throws expects the symbol that should be thrown for its first argument")
    end
    assert_block("Should have passed a block to assert_throw.") do
      block_given?
    end
    caught = true
    begin
      catch(expected_object) do
        proc.call
        caught = false
      end
      full_message = build_message(message,
                                   "<?> should have been thrown.",
                                   expected_object)
      assert_block(full_message) {caught}
    rescue NameError, ArgumentError, ThreadError => error
      raise unless UncaughtThrow[error.class] =~ error.message
      tag = $1
      tag = tag[1..-1].intern if tag[0, 1] == ":"
      full_message = build_message(message,
                                   "<?> expected to be thrown but\n" +
                                   "<?> was thrown.",
                                   expected_object, tag)
      flunk(full_message)
    end
  end
end

#assert_true(actual, message = nil) ⇒ Object

Passes if actual is true.

Example:

assert_true(true)  # -> pass
assert_true(:true) # -> fail


1043
1044
1045
1046
1047
1048
1049
1050
1051
# File 'lib/test/unit/assertions.rb', line 1043

def assert_true(actual, message=nil)
  _wrap_assertion do
    assert_block(build_message(message,
                               "<true> expected but was\n<?>",
                               actual)) do
      actual == true
    end
  end
end

#build_message(head, template = nil, *arguments) ⇒ Object



1427
1428
1429
1430
# File 'lib/test/unit/assertions.rb', line 1427

def build_message(head, template=nil, *arguments)
  template &&= template.chomp
  return AssertionMessage.new(head, template, arguments)
end

#flunk(message = "Flunked") ⇒ Object



487
488
489
# File 'lib/test/unit/assertions.rb', line 487

def flunk(message="Flunked")
  assert_block(build_message(message)){false}
end

#refute(object, message = nil) ⇒ void

Note:

Just for minitest compatibility. :<

This method returns an undefined value.

Asserts that object is false or nil.

Examples:

Pass patterns

refute(false)    # => pass
refute(nil)      # => pass

Fialure patterns

refute(true)     # => failure
refute("string") # => failure

Parameters:

  • object (Object)

    The object to be asserted.

Since:

  • 2.5.3



104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
# File 'lib/test/unit/assertions.rb', line 104

def refute(object, message=nil)
  _wrap_assertion do
    assertion_message = nil
    case message
    when nil, String, Proc
    when AssertionMessage
      assertion_message = message
    else
      error_message = "assertion message must be String, Proc or "
      error_message << "#{AssertionMessage}: "
      error_message << "<#{message.inspect}>(<#{message.class}>)"
      raise ArgumentError, error_message, filter_backtrace(caller)
    end
    assert_block("refute should not be called with a block.") do
      !block_given?
    end
    assertion_message ||= build_message(message,
                                        "<?> is neither nil or false.",
                                        object)
    assert_block(assertion_message) do
      not object
    end
  end
end