1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112
|
class Exception
# Is the exception an assertion error?
def assertion?
@assertion
end
# Set the the exception's assertion flag.
def set_assertion(boolean)
@assertion = boolean # ? true : false
end
# Set message.
# (not strictly needed here, but can be useful anyway).
#
# @todo Does the message have to be a string?
def set_message(msg)
@mesg = msg.to_str
end
# TODO: Consider assertion parameters for future vresion.
##
#def parameters
# @parameters
#end
#
## Set exception parameters. These are used to store specific information
## relavent to a particular exception or assertion. Unlike the message,
## which is a String, this is a Hash.
#def set_parameters(parameters)
# @parameters = parameters.to_hash
#end
end
module Kernel
# Track assertions counts.
$ASSERTION_COUNTS ||= Hash.new{ |h,k| h[k] = 0 }
#
# Universal assertion method.
#
def assert(truth, *raise_arguments)
$ASSERTION_COUNTS[:total] += 1
if truth
$ASSERTION_COUNTS[:pass] += 1
else
$ASSERTION_COUNTS[:fail] += 1
# if fail set assertion=true then just,
# fail *raise_arguments
# but alas ...
fail! *raise_arguments
end
end
module_function :assert
#
# Universal refutation method (opposite of `#assert`).
#
def refute(truth, *raise_arguments)
$ASSERTION_COUNTS[:total] += 1
if truth
$ASSERTION_COUNTS[:fail] += 1
# if fail set assertion=true then just,
# fail *raise_arguments
# but alas ...
fail! *raise_arguments
else
$ASSERTION_COUNTS[:pass] += 1
end
end
module_function :refute
#
# Alternate for #fail that also sets assertion flag to +true+.
#
def fail!(*raise_arguments)
backtrace = case raise_arguments.last
when Array
raise_arguments.pop
else
nil
end
exception = case raise_arguments.first
when Exception
raise_arguments.shift
when Class
raise ArgumentError unless Exception > raise_arguments.first
error_class = raise_arguments.shift
error_class.new(*raise_arguments)
else
error_class = $! || RuntimeError
error_class.new(*raise_arguments)
end
exception.set_backtrace(backtrace) if backtrace
exception.set_assertion(true)
fail exception
end
module_function :fail!
private :assert
private :refute
private :fail!
end
|