Skip to content

Instantly share code, notes, and snippets.

@zenspider
Last active November 6, 2025 05:45
Show Gist options
  • Save zenspider/984fdda33098be57bfafbc64f193379e to your computer and use it in GitHub Desktop.
Save zenspider/984fdda33098be57bfafbc64f193379e to your computer and use it in GitHub Desktop.
at_exit { exit Mini.autotest }
module Mini
def self.all_tests = Test.subklasses.flat_map { |k| k.tests.map { |m| [k, m] } }
def self.autotest = all_tests.shuffle.count { |k, m| k.run m }.zero?
class Test
@@subklasses = []
def self.subklasses = @@subklasses
def self.inherited(k) = subklasses << k
def self.tests = public_instance_methods(true).grep(/^test_/)
def self.run(m)
new.run m
nil
rescue Interrupt, NoMemoryError, SignalException, SystemExit
raise
rescue Assertion => e
puts "\nFailure: %s#%s: %s\n%s" % [self.class, m, e, e.backtrace.first]
rescue Exception => e
puts "\nError: %s#%s: %s\n%s" % [self.class, m, e, e.backtrace.first]
e
end
def run(m) = (setup; send m; teardown)
def setup = nil
def teardown = nil
def msg(m) = proc { m.to_s.empty? or m = "#{m}.\n" ; "#{m}#{yield}" }
def assert(test, msg=nil) = (test or raise Assertion, msg(nil) { msg || "failed assertion (no message given)" }.call)
def assert_equal(exp, act, msg=nil) = assert exp == act, msg(msg) { "Expected %p to be equal to %p" % [act, exp] }
def assert_in_delta(exp, act, delta, msg=nil) = assert (exp.to_f - act.to_f).abs <= delta.to_f, msg(msg) { "Expected %s to be within %s of %s" % [exp, delta, act] }
def assert_instance_of(cls, obj, msg=nil) = assert cls === obj, msg(msg) { "Expected %p to be a %s" % [obj, cls] }
def assert_kind_of(cls, obj, msg=nil) = assert obj.kind_of?(cls), msg(msg) { "Expected %p to be a kind of %s" % [obj, cls] }
def assert_match(exp, act, msg=nil) = assert act =~ exp, msg(msg) { "Expected %p to match %p" % [act, exp]}
def assert_nil(obj, msg=nil) = assert obj.nil?, msg(msg) { "Expected %p to be nil" % [obj] }
def assert_operator(o1, op, o2, msg="") = assert o1.__send__(op, o2), msg(msg) { "Expected %s.%s(%s)) to be true" % [o1, op, o2] }
def assert_same(exp, act, msg=nil) = assert exp.equal?(act), msg(msg) { "Expected %p to be the same as %p" % [act, exp] }
def refute_equal(exp, act, msg=nil) = assert exp != act, msg(msg) { "Expected %p to not be equal to %p" % [act, exp] }
def refute_nil(obj, msg=nil) = assert ! obj.nil?, msg(msg) { "Expected %p to not be nil" % [obj] }
def refute_same(exp, act, msg=nil) = assert ! exp.equal?(act), msg(msg) { "Expected %p to not be the same as %p" % [act, exp] }
def assert_raises(exp, m=nil)
yield
assert false, "Expected %s to be raised" % [exp]
rescue Exception => e
assert exp === e, msg(m) { "Expected %s to be raised, but got %p" % [exp, e] }
e
end
Assertion = Class.new Exception
end # class Test
end # module Mini
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment