Class: Util::Testing

Inherits:
Object
  • Object
show all
Defined in:
lib/util/test.rb

Overview

Class for some basic unit testing.

Examples:

class MyClass
  def self.function arg
    raise ArgumentError, 'Not an unsigned int.' unless arg.to_i >= 0
    -arg.to_i
  end
end

test = Util::Testing.new

test.register 'success', [-12, -42] do ||
  [MyClass.function('12'), MyClass.function(42.0)]
end

test.register 'success-with-implicit-result' do ||
  MyClass.function '12'
  true
end

test.register 'expected-fail', ArgumentError, 'unsigned' do ||
  MyClass.function -1
end

test.register 'wrong-reason', ArgumentError, 'unsigned' do ||
  MyClass.function
end

test.register 'wrong-exception', ArgumentError, 'unsigned' do ||
  MyOtherClass.function
end

test.run

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(logger = nil) ⇒ Testing

Create a new testing framework.

Parameters:

  • logger (#error & #normal & #ok) (defaults to: nil)
    nil

    logger used to

    express the results of the testing



50
51
52
53
54
55
56
57
# File 'lib/util/test.rb', line 50

def initialize logger=nil
  init_i18n
  init_logger logger
  init_tmp_path
  init_io
  @tests = []
  ObjectSpace.define_finalizer self, self.class.method(:finalize)
end

Class Method Details

.finalize(id) ⇒ Object

Do not document:



37
38
39
40
41
42
43
44
45
# File 'lib/util/test.rb', line 37

def self.finalize id
  obj = ObjectSpace._id2ref id
  begin
    File.delete obj.send(:stdout_path)
    File.delete obj.send(:stderr_path)
  rescue Exception => e
    puts e.message
  end
end

Instance Method Details

#register(name, expect = nil, with = '', &block) ⇒ Object

Add a test to the framework. If the test name is empty, the test will be run, but its results will not be displayed. Makes it possible to clean up between tests.

Parameters:

  • name (String)

    name of the test

  • expect (Object) (defaults to: nil)

    expected result \ (may be an Exception class)

  • with (String) (defaults to: '')

    optional string that must be found in the Exception message for it to be considered the expected result

  • block (Proc)

    test to perform



68
69
70
71
72
73
74
75
76
77
# File 'lib/util/test.rb', line 68

def register name, expect=nil, with='', &block
  return false unless block.respond_to? :call
  test = { :proc => block }

  test[:name] = name.to_s
  test[:expect] = expect unless expect.nil?
  test[:with] = with.to_s unless with.nil?

  @tests << test
end

#runObject

Run all the tests and express the results on the given logger.



80
81
82
83
84
85
86
# File 'lib/util/test.rb', line 80

def run
  @tests.each do |t|
    run_actual_test t
    run_determine_success t
    run_express_result t
  end
end